lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
bsd-2-clause
62102012f6672c4a98cf6921a77cfcd73a7f4ae5
0
ratan12/Atarashii,AnimeNeko/Atarashii,ratan12/Atarashii,AnimeNeko/Atarashii
package net.somethingdreadful.MAL; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.ColorStateList; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.freshdesk.mobihelp.Mobihelp; import com.squareup.picasso.Picasso; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.adapters.IGFPagerAdapter; import net.somethingdreadful.MAL.api.BaseModels.Profile; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.dialog.ChooseDialogFragment; import net.somethingdreadful.MAL.dialog.UpdateImageDialogFragment; import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener; import net.somethingdreadful.MAL.tasks.TaskJob; import net.somethingdreadful.MAL.tasks.UserNetworkTask; import butterknife.Bind; import butterknife.ButterKnife; public class Home extends AppCompatActivity implements ChooseDialogFragment.onClickListener, SwipeRefreshLayout.OnRefreshListener, IGF.IGFCallbackListener, APIAuthenticationErrorListener, View.OnClickListener, UserNetworkTask.UserNetworkTaskListener, ViewPager.OnPageChangeListener, NavigationView.OnNavigationItemSelectedListener { private IGF af; private IGF mf; private Menu menu; private Context context; private BroadcastReceiver networkReceiver; private String username; private boolean networkAvailable; private boolean myList = true; //tracks if the user is on 'My List' or not private int callbackCounter = 0; @Bind(R.id.navigationView) NavigationView navigationView; @Bind(R.id.drawerLayout) DrawerLayout drawerLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Initializing activity and application context = getApplicationContext(); Theme.context = context; if (AccountService.getAccount() != null) { //The following is state handling code networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true); if (savedInstanceState != null) myList = savedInstanceState.getBoolean("myList"); //Initializing Theme Theme.setTheme(this, R.layout.activity_home, false); //Initializing IGF Theme.setActionBar(this, new IGFPagerAdapter(getFragmentManager(), true)); getSupportActionBar(); //Initializing ButterKnife ButterKnife.bind(this); //setup navigation profile information username = AccountService.getUsername(); new UserNetworkTask(context, false, this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, username); //Initializing NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView); navigationView.setNavigationItemSelectedListener(this); navigationView.getMenu().findItem(R.id.nav_list).setChecked(true); ((TextView) navigationView.getHeaderView(0).findViewById(R.id.name)).setText(username); ((TextView) navigationView.getHeaderView(0).findViewById(R.id.siteName)).setText(getString(AccountService.isMAL() ? R.string.init_hint_myanimelist : R.string.init_hint_anilist)); //Initializing navigation toggle button drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, (Toolbar) findViewById(R.id.actionbar), R.string.drawer_open, R.string.drawer_close) { }; drawerLayout.setDrawerListener(drawerToggle); drawerToggle.syncState(); //Applying dark theme if (Theme.darkTheme) { int[][] states = new int[][]{ new int[]{-android.R.attr.state_checked}, // unchecked new int[]{android.R.attr.state_checked} // checked }; int[] colors = new int[]{ context.getResources().getColor(R.color.bg_light_card), context.getResources().getColor(R.color.primary) }; ColorStateList myList = new ColorStateList(states, colors); navigationView.setBackgroundColor(getResources().getColor(R.color.bg_dark)); navigationView.setItemTextColor(myList); navigationView.setItemIconTintList(myList); } networkReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkNetworkAndDisplayCrouton(); myListChanged(); } }; } else { Intent firstRunInit = new Intent(this, FirstTimeInit.class); startActivity(firstRunInit); finish(); } NfcHelper.disableBeam(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_home, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); ComponentName cn = new ComponentName(this, SearchActivity.class); searchView.setSearchableInfo(searchManager.getSearchableInfo(cn)); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.listType_all: getRecords(true, TaskJob.GETLIST, 0); setChecked(item); break; case R.id.listType_inprogress: getRecords(true, TaskJob.GETLIST, 1); setChecked(item); break; case R.id.listType_completed: getRecords(true, TaskJob.GETLIST, 2); setChecked(item); break; case R.id.listType_onhold: getRecords(true, TaskJob.GETLIST, 3); setChecked(item); break; case R.id.listType_dropped: getRecords(true, TaskJob.GETLIST, 4); setChecked(item); break; case R.id.listType_planned: getRecords(true, TaskJob.GETLIST, 5); setChecked(item); break; case R.id.listType_rewatching: getRecords(true, TaskJob.GETLIST, 6); setChecked(item); break; case R.id.forceSync: synctask(true); break; case R.id.menu_inverse: if (af != null && mf != null) { if (!AccountService.isMAL() && af.taskjob == TaskJob.GETMOSTPOPULAR) { af.toggleAiringTime(); } else { af.inverse(); mf.inverse(); } } break; } return super.onOptionsItemSelected(item); } private void getRecords(boolean clear, TaskJob task, int list) { if (af != null && mf != null) { af.getRecords(clear, task, list); mf.getRecords(clear, task, list); if (task == TaskJob.FORCESYNC) syncNotify(); } } @Override public void onResume() { super.onResume(); checkNetworkAndDisplayCrouton(); registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); } @SuppressLint("NewApi") @Override public void onPause() { super.onPause(); if (menu != null) menu.findItem(R.id.action_search).collapseActionView(); unregisterReceiver(networkReceiver); } private void synctask(boolean clear) { getRecords(clear, TaskJob.FORCESYNC, af.list); } @Override public void onSaveInstanceState(Bundle state) { //This is telling out future selves that we already have some things and not to do them state.putBoolean("networkAvailable", networkAvailable); state.putBoolean("myList", myList); super.onSaveInstanceState(state); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.menu = menu; if (af != null) { //All this is handling the ticks in the switch list menu switch (af.list) { case 0: setChecked(menu.findItem(R.id.listType_all)); break; case 1: setChecked(menu.findItem(R.id.listType_inprogress)); break; case 2: setChecked(menu.findItem(R.id.listType_completed)); break; case 3: setChecked(menu.findItem(R.id.listType_onhold)); break; case 4: setChecked(menu.findItem(R.id.listType_dropped)); break; case 5: setChecked(menu.findItem(R.id.listType_planned)); break; case 6: setChecked(menu.findItem(R.id.listType_rewatching)); break; } } return true; } private void setChecked(MenuItem item) { item.setChecked(true); } private void myListChanged() { if (menu != null) { menu.findItem(R.id.menu_listType).setVisible(myList); menu.findItem(R.id.menu_inverse).setVisible(myList || (!AccountService.isMAL() && af.taskjob == TaskJob.GETMOSTPOPULAR)); menu.findItem(R.id.forceSync).setVisible(myList && networkAvailable); menu.findItem(R.id.action_search).setVisible(networkAvailable); } } private void syncNotify() { Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder syncNotificationBuilder = new Notification.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.toast_info_SyncMessage)); Notification syncNotification; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { syncNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); } syncNotification = syncNotificationBuilder.build(); } else { syncNotification = syncNotificationBuilder.getNotification(); } nm.notify(R.id.notification_sync, syncNotification); } private void showLogoutDialog() { ChooseDialogFragment lcdf = new ChooseDialogFragment(); Bundle bundle = new Bundle(); bundle.putString("title", getString(R.string.dialog_title_restore)); bundle.putString("message", getString(R.string.dialog_message_logout)); bundle.putString("positive", getString(R.string.dialog_label_logout)); lcdf.setArguments(bundle); lcdf.setCallback(this); lcdf.show(getFragmentManager(), "fragment_LogoutConfirmationDialog"); } private void checkNetworkAndDisplayCrouton() { if (MALApi.isNetworkAvailable(context) && !networkAvailable) synctask(false); networkAvailable = MALApi.isNetworkAvailable(context); } @Override public void onRefresh() { if (networkAvailable) synctask(false); else { if (af != null && mf != null) { af.toggleSwipeRefreshAnimation(false); mf.toggleSwipeRefreshAnimation(false); } Theme.Snackbar(this, R.string.toast_error_noConnectivity); } } @Override public void onIGFReady(IGF igf) { igf.setUsername(AccountService.getUsername()); if (igf.listType.equals(MALApi.ListType.ANIME)) af = igf; else mf = igf; // do forced sync after FirstInit if (PrefManager.getForceSync()) { if (af != null && mf != null) { PrefManager.setForceSync(false); PrefManager.commitChanges(); synctask(true); } } else { if (igf.taskjob == null) { igf.getRecords(true, TaskJob.GETLIST, PrefManager.getDefaultList()); } } } @Override public void onRecordsLoadingFinished(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) { if (cancelled && !job.equals(TaskJob.FORCESYNC)) { return; } callbackCounter++; if (callbackCounter >= 2) { callbackCounter = 0; if (job.equals(TaskJob.FORCESYNC)) { NotificationManager nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(R.id.notification_sync); } } } @Override public void onItemClick(int id, MALApi.ListType listType, String username) { Intent startDetails = new Intent(context, DetailView.class); startDetails.putExtra("recordID", id); startDetails.putExtra("recordType", listType); startDetails.putExtra("username", username); startActivity(startDetails); } @Override public void onAPIAuthenticationError(MALApi.ListType type, TaskJob job) { startActivity(new Intent(this, Home.class).putExtra("updatePassword", true)); finish(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.Image: Intent Profile = new Intent(context, ProfileActivity.class); Profile.putExtra("username", username); startActivity(Profile); break; case R.id.NDimage: UpdateImageDialogFragment lcdf = new UpdateImageDialogFragment(); lcdf.show(getFragmentManager(), "fragment_NDImage"); break; } } @Override public void onUserNetworkTaskFinished(Profile result) { ImageView image = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.Image); ImageView image2 = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.NDimage); try { Picasso.with(context) .load(result.getImageUrl()) .transform(new RoundedTransformation(result.getUsername())) .into(image); if (PrefManager.getNavigationBackground() != null) Picasso.with(context) .load(PrefManager.getNavigationBackground()) .into(image2); image.setOnClickListener(this); image2.setOnClickListener(this); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "Home.onUserNetworkTaskFinished(): " + e.getMessage()); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (menu != null) menu.findItem(R.id.listType_rewatching).setTitle(getString(position == 0 ? R.string.listType_rewatching : R.string.listType_rereading)); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } @Override public void onPositiveButtonClicked() { AccountService.clearData(); startActivity(new Intent(this, FirstTimeInit.class)); System.exit(0); } @Override public boolean onNavigationItemSelected(MenuItem item) { // disable swipeRefresh for other lists af.setSwipeRefreshEnabled(myList); mf.setSwipeRefreshEnabled(myList); //Checking if the item should be checked & if the list status has been changed switch (item.getItemId()) { case R.id.nav_profile: case R.id.nav_friends: case R.id.nav_forum: case R.id.nav_settings: case R.id.nav_support: case R.id.nav_about: break; default: // Set the list tracker to false. It will be updated later in the code. myList = false; if (item.isChecked()) item.setChecked(false); else item.setChecked(true); break; } //Closing drawer on item click drawerLayout.closeDrawers(); //Performing the action switch (item.getItemId()) { case R.id.nav_list: getRecords(true, TaskJob.GETLIST, af.list); myList = true; break; case R.id.nav_profile: Intent Profile = new Intent(context, ProfileActivity.class); Profile.putExtra("username", username); startActivity(Profile); break; case R.id.nav_friends: Intent Friends = new Intent(context, ProfileActivity.class); Friends.putExtra("username", username); Friends.putExtra("friends", username); startActivity(Friends); break; case R.id.nav_forum: if (MALApi.isNetworkAvailable(this)) startActivity(new Intent(context, ForumActivity.class)); else Theme.Snackbar(this, R.string.toast_error_noConnectivity); break; case R.id.nav_rated: getRecords(true, TaskJob.GETTOPRATED, af.list); break; case R.id.nav_popular: getRecords(true, TaskJob.GETMOSTPOPULAR, af.list); break; case R.id.nav_added: getRecords(true, TaskJob.GETJUSTADDED, af.list); break; case R.id.nav_upcoming: getRecords(true, TaskJob.GETUPCOMING, af.list); break; case R.id.nav_logout: // Others subgroup showLogoutDialog(); break; case R.id.nav_settings: startActivity(new Intent(this, Settings.class)); break; case R.id.nav_support: Mobihelp.showSupport(this); break; case R.id.nav_about: startActivity(new Intent(this, AboutActivity.class)); break; } myListChanged(); return false; } }
Atarashii/src/net/somethingdreadful/MAL/Home.java
package net.somethingdreadful.MAL; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.ColorStateList; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.freshdesk.mobihelp.Mobihelp; import com.squareup.picasso.Picasso; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.adapters.IGFPagerAdapter; import net.somethingdreadful.MAL.api.BaseModels.Profile; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.dialog.ChooseDialogFragment; import net.somethingdreadful.MAL.dialog.UpdateImageDialogFragment; import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener; import net.somethingdreadful.MAL.tasks.TaskJob; import net.somethingdreadful.MAL.tasks.UserNetworkTask; import butterknife.Bind; import butterknife.ButterKnife; public class Home extends AppCompatActivity implements ChooseDialogFragment.onClickListener, SwipeRefreshLayout.OnRefreshListener, IGF.IGFCallbackListener, APIAuthenticationErrorListener, View.OnClickListener, UserNetworkTask.UserNetworkTaskListener, ViewPager.OnPageChangeListener, NavigationView.OnNavigationItemSelectedListener { private IGF af; private IGF mf; private Menu menu; private Context context; private BroadcastReceiver networkReceiver; private String username; private boolean networkAvailable; private boolean myList = true; //tracks if the user is on 'My List' or not private int callbackCounter = 0; @Bind(R.id.navigationView) NavigationView navigationView; @Bind(R.id.drawerLayout) DrawerLayout drawerLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Initializing activity and application context = getApplicationContext(); Theme.context = context; if (AccountService.getAccount() != null) { //The following is state handling code networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true); if (savedInstanceState != null) myList = savedInstanceState.getBoolean("myList"); //Initializing Theme Theme.setTheme(this, R.layout.activity_home, false); //Initializing IGF Theme.setActionBar(this, new IGFPagerAdapter(getFragmentManager(), true)); getSupportActionBar(); //Initializing ButterKnife ButterKnife.bind(this); //setup navigation profile information username = AccountService.getUsername(); new UserNetworkTask(context, false, this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, username); //Initializing NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView); navigationView.setNavigationItemSelectedListener(this); navigationView.getMenu().findItem(R.id.nav_list).setChecked(true); ((TextView) navigationView.getHeaderView(0).findViewById(R.id.name)).setText(username); ((TextView) navigationView.getHeaderView(0).findViewById(R.id.siteName)).setText(getString(AccountService.isMAL() ? R.string.init_hint_myanimelist : R.string.init_hint_anilist)); //Initializing navigation toggle button drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, (Toolbar) findViewById(R.id.actionbar), R.string.drawer_open, R.string.drawer_close) { }; drawerLayout.setDrawerListener(drawerToggle); drawerToggle.syncState(); //Applying dark theme if (Theme.darkTheme) { int[][] states = new int[][]{ new int[]{-android.R.attr.state_checked}, // unchecked new int[]{android.R.attr.state_checked} // checked }; int[] colors = new int[]{ context.getResources().getColor(R.color.bg_light_card), context.getResources().getColor(R.color.primary) }; ColorStateList myList = new ColorStateList(states, colors); navigationView.setBackgroundColor(getResources().getColor(R.color.bg_dark)); navigationView.setItemTextColor(myList); navigationView.setItemIconTintList(myList); } networkReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkNetworkAndDisplayCrouton(); myListChanged(); } }; } else { Intent firstRunInit = new Intent(this, FirstTimeInit.class); startActivity(firstRunInit); finish(); } NfcHelper.disableBeam(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_home, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); ComponentName cn = new ComponentName(this, SearchActivity.class); searchView.setSearchableInfo(searchManager.getSearchableInfo(cn)); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.listType_all: getRecords(true, TaskJob.GETLIST, 0); setChecked(item); break; case R.id.listType_inprogress: getRecords(true, TaskJob.GETLIST, 1); setChecked(item); break; case R.id.listType_completed: getRecords(true, TaskJob.GETLIST, 2); setChecked(item); break; case R.id.listType_onhold: getRecords(true, TaskJob.GETLIST, 3); setChecked(item); break; case R.id.listType_dropped: getRecords(true, TaskJob.GETLIST, 4); setChecked(item); break; case R.id.listType_planned: getRecords(true, TaskJob.GETLIST, 5); setChecked(item); break; case R.id.listType_rewatching: getRecords(true, TaskJob.GETLIST, 6); setChecked(item); break; case R.id.forceSync: synctask(true); break; case R.id.menu_inverse: if (af != null && mf != null) { if (!AccountService.isMAL() && af.taskjob == TaskJob.GETMOSTPOPULAR) { af.toggleAiringTime(); } else { af.inverse(); mf.inverse(); } } break; } return super.onOptionsItemSelected(item); } private void getRecords(boolean clear, TaskJob task, int list) { if (af != null && mf != null) { af.getRecords(clear, task, list); mf.getRecords(clear, task, list); if (task == TaskJob.FORCESYNC) syncNotify(); } } @Override public void onResume() { super.onResume(); checkNetworkAndDisplayCrouton(); registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); } @SuppressLint("NewApi") @Override public void onPause() { super.onPause(); if (menu != null) menu.findItem(R.id.action_search).collapseActionView(); unregisterReceiver(networkReceiver); } private void synctask(boolean clear) { getRecords(clear, TaskJob.FORCESYNC, af.list); } @Override public void onSaveInstanceState(Bundle state) { //This is telling out future selves that we already have some things and not to do them state.putBoolean("networkAvailable", networkAvailable); state.putBoolean("myList", myList); super.onSaveInstanceState(state); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.menu = menu; if (af != null) { //All this is handling the ticks in the switch list menu switch (af.list) { case 0: setChecked(menu.findItem(R.id.listType_all)); break; case 1: setChecked(menu.findItem(R.id.listType_inprogress)); break; case 2: setChecked(menu.findItem(R.id.listType_completed)); break; case 3: setChecked(menu.findItem(R.id.listType_onhold)); break; case 4: setChecked(menu.findItem(R.id.listType_dropped)); break; case 5: setChecked(menu.findItem(R.id.listType_planned)); break; case 6: setChecked(menu.findItem(R.id.listType_rewatching)); break; } } return true; } private void setChecked(MenuItem item) { item.setChecked(true); } private void myListChanged() { if (menu != null) { menu.findItem(R.id.menu_listType).setVisible(myList); menu.findItem(R.id.menu_inverse).setVisible(myList || (!AccountService.isMAL() && af.taskjob == TaskJob.GETMOSTPOPULAR)); menu.findItem(R.id.forceSync).setVisible(myList && networkAvailable); menu.findItem(R.id.action_search).setVisible(networkAvailable); } } private void syncNotify() { Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder syncNotificationBuilder = new Notification.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.toast_info_SyncMessage)); Notification syncNotification; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { syncNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); } syncNotification = syncNotificationBuilder.build(); } else { syncNotification = syncNotificationBuilder.getNotification(); } nm.notify(R.id.notification_sync, syncNotification); } private void showLogoutDialog() { ChooseDialogFragment lcdf = new ChooseDialogFragment(); Bundle bundle = new Bundle(); bundle.putString("title", getString(R.string.dialog_title_restore)); bundle.putString("message", getString(R.string.dialog_message_logout)); bundle.putString("positive", getString(R.string.dialog_label_logout)); lcdf.setArguments(bundle); lcdf.setCallback(this); lcdf.show(getFragmentManager(), "fragment_LogoutConfirmationDialog"); } private void checkNetworkAndDisplayCrouton() { if (MALApi.isNetworkAvailable(context) && !networkAvailable) synctask(false); networkAvailable = MALApi.isNetworkAvailable(context); } @Override public void onRefresh() { if (networkAvailable) synctask(false); else { if (af != null && mf != null) { af.toggleSwipeRefreshAnimation(false); mf.toggleSwipeRefreshAnimation(false); } Theme.Snackbar(this, R.string.toast_error_noConnectivity); } } @Override public void onIGFReady(IGF igf) { igf.setUsername(AccountService.getUsername()); if (igf.listType.equals(MALApi.ListType.ANIME)) af = igf; else mf = igf; // do forced sync after FirstInit if (PrefManager.getForceSync()) { if (af != null && mf != null) { PrefManager.setForceSync(false); PrefManager.commitChanges(); synctask(true); } } else { if (igf.taskjob == null) { igf.getRecords(true, TaskJob.GETLIST, PrefManager.getDefaultList()); } } } @Override public void onRecordsLoadingFinished(MALApi.ListType type, TaskJob job, boolean error, boolean resultEmpty, boolean cancelled) { if (cancelled && !job.equals(TaskJob.FORCESYNC)) { return; } callbackCounter++; if (callbackCounter >= 2) { callbackCounter = 0; if (job.equals(TaskJob.FORCESYNC)) { NotificationManager nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(R.id.notification_sync); } } } @Override public void onItemClick(int id, MALApi.ListType listType, String username) { Intent startDetails = new Intent(context, DetailView.class); startDetails.putExtra("recordID", id); startDetails.putExtra("recordType", listType); startDetails.putExtra("username", username); startActivity(startDetails); } @Override public void onAPIAuthenticationError(MALApi.ListType type, TaskJob job) { startActivity(new Intent(this, Home.class).putExtra("updatePassword", true)); finish(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.Image: Intent Profile = new Intent(context, ProfileActivity.class); Profile.putExtra("username", username); startActivity(Profile); break; case R.id.NDimage: UpdateImageDialogFragment lcdf = new UpdateImageDialogFragment(); lcdf.show(getFragmentManager(), "fragment_NDImage"); break; } } @Override public void onUserNetworkTaskFinished(Profile result) { ImageView image = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.Image); ImageView image2 = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.NDimage); try { Picasso.with(context) .load(result.getImageUrl()) .transform(new RoundedTransformation(result.getUsername())) .into(image); if (PrefManager.getNavigationBackground() != null) Picasso.with(context) .load(PrefManager.getNavigationBackground()) .into(image2); image.setOnClickListener(this); image2.setOnClickListener(this); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "Home.onUserNetworkTaskFinished(): " + e.getMessage()); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (menu != null) menu.findItem(R.id.listType_rewatching).setTitle(getString(position == 0 ? R.string.listType_rewatching : R.string.listType_rereading)); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } @Override public void onPositiveButtonClicked() { AccountService.clearData(); startActivity(new Intent(this, FirstTimeInit.class)); System.exit(0); } @Override public boolean onNavigationItemSelected(MenuItem item) { // disable swipeRefresh for other lists af.setSwipeRefreshEnabled(myList); mf.setSwipeRefreshEnabled(myList); //Checking if the item should be checked & if the list status has been changed switch (item.getItemId()) { case R.id.nav_profile: case R.id.nav_friends: case R.id.nav_forum: case R.id.nav_settings: case R.id.nav_support: case R.id.nav_about: break; default: // Set the list tracker to false. It will be updated later in the code. myList = false; if (item.isChecked()) item.setChecked(false); else item.setChecked(true); break; } //Closing drawer on item click drawerLayout.closeDrawers(); //Performing the action switch (item.getItemId()) { case R.id.nav_list: getRecords(true, TaskJob.GETLIST, af.list); myList = true; break; case R.id.nav_profile: Intent Profile = new Intent(context, ProfileActivity.class); Profile.putExtra("username", username); startActivity(Profile); break; case R.id.nav_friends: Intent Friends = new Intent(context, ProfileActivity.class); Friends.putExtra("username", username); Friends.putExtra("friends", username); startActivity(Friends); break; case R.id.nav_forum: Intent Forum = new Intent(context, ForumActivity.class); startActivity(Forum); break; case R.id.nav_rated: getRecords(true, TaskJob.GETTOPRATED, af.list); break; case R.id.nav_popular: getRecords(true, TaskJob.GETMOSTPOPULAR, af.list); break; case R.id.nav_added: getRecords(true, TaskJob.GETJUSTADDED, af.list); break; case R.id.nav_upcoming: getRecords(true, TaskJob.GETUPCOMING, af.list); break; case R.id.nav_logout: // Others subgroup showLogoutDialog(); break; case R.id.nav_settings: startActivity(new Intent(this, Settings.class)); break; case R.id.nav_support: Mobihelp.showSupport(this); break; case R.id.nav_about: startActivity(new Intent(this, AboutActivity.class)); break; } myListChanged(); return false; } }
Fix forum opening when there was no connection
Atarashii/src/net/somethingdreadful/MAL/Home.java
Fix forum opening when there was no connection
Java
bsd-2-clause
9fc0eb0b1f1906c7d49a6c9fca61c78be804478f
0
insideo/randomcoder-website,insideo/randomcoder-website,insideo/randomcoder-website
package com.randomcoder.security.userdetails.test; import static org.junit.Assert.*; import java.security.*; import java.util.*; import org.acegisecurity.*; import org.acegisecurity.userdetails.*; import org.apache.commons.codec.digest.DigestUtils; import org.junit.*; import org.springframework.core.io.*; import org.w3c.dom.*; import org.xml.sax.InputSource; import com.randomcoder.crypto.*; import com.randomcoder.saml.*; import com.randomcoder.security.cardspace.*; import com.randomcoder.security.userdetails.UserDetailsServiceImpl; import com.randomcoder.user.*; import com.randomcoder.user.User; import com.randomcoder.user.test.*; import com.randomcoder.xml.XmlUtils; import com.randomcoder.xml.security.XmlSecurityUtils; public class UserDetailsServiceImplTest { private static final String RES_ENCRYPTED = "/xmlsec/saml-encrypted.xml"; private static final String RES_ENCRYPTED2 = "/xmlsec/test-encrypted.xml"; private static final String RES_XMLSEC_PROPS = "/xmlsec/xmlsec.properties"; private UserDetailsServiceImpl svc = null; private CardSpaceTokenDaoMock cardSpaceTokenDao = null; private UserDaoMock userDao = null; private RoleDaoMock roleDao = null; private SamlAssertion existingUserAssertion = null; private SamlAssertion missingUserAssertion = null; private SamlAssertion missingPpidAssertion = null; private PublicKey existingUserKey = null; private PublicKey missingUserKey = null; private PublicKey missingPpidKey = null; private CardSpaceCredentials existingUserCredentials = null; private CardSpaceCredentials missingUserCredentials = null; private CardSpaceCredentials missingPpidCredentials = null; @Before public void setUp() throws Exception { cardSpaceTokenDao = new CardSpaceTokenDaoMock(); userDao = new UserDaoMock(); roleDao = new RoleDaoMock(); svc = new UserDetailsServiceImpl(); svc.setCardSpaceTokenDao(cardSpaceTokenDao); svc.setUserDao(userDao); Properties properties = new Properties(); properties.load(getClass().getResourceAsStream(RES_XMLSEC_PROPS)); KeystoreCertificateFactoryBean keystoreFactory = new KeystoreCertificateFactoryBean(); Resource keystoreLocation = new ClassPathResource(properties.getProperty("keystore.resource")); keystoreFactory.setKeystoreLocation(keystoreLocation); keystoreFactory.setKeystoreType(properties.getProperty("keystore.type")); keystoreFactory.setKeystorePassword(properties.getProperty("keystore.password")); keystoreFactory.setCertificateAlias(properties.getProperty("certificate.alias")); keystoreFactory.setCertificatePassword(properties.getProperty("certificate.password")); keystoreFactory.afterPropertiesSet(); CertificateContext certContext = (CertificateContext) keystoreFactory.getObject(); PrivateKey serverPrivateKey = certContext.getPrivateKey(); { Document doc = XmlUtils.parseXml(new InputSource(getClass().getResourceAsStream(RES_ENCRYPTED))); Element el = XmlSecurityUtils.findFirstEncryptedData(doc); XmlSecurityUtils.decrypt(doc, el, serverPrivateKey); Element sig = XmlSecurityUtils.findFirstSignature(doc); Element assertionEl = SamlUtils.findFirstSamlAssertion(doc); assertionEl.setIdAttribute("AssertionID", true); missingPpidKey = existingUserKey = XmlSecurityUtils.verifySignature(sig); existingUserAssertion = new SamlAssertion(assertionEl); NodeList atts = assertionEl.getElementsByTagNameNS(SamlUtils.SAML_10_NS, "Attribute"); for (int i = 0; i < atts.getLength(); i++) { Element att = (Element) atts.item(i); if ("privatepersonalidentifier".equals(att.getAttribute("AttributeName"))) att.getParentNode().removeChild(att); } missingPpidAssertion = new SamlAssertion(assertionEl); existingUserCredentials = new CardSpaceCredentials(existingUserAssertion, existingUserKey); missingPpidCredentials = new CardSpaceCredentials(missingPpidAssertion, missingPpidKey); } { Document doc = XmlUtils.parseXml(new InputSource(getClass().getResourceAsStream(RES_ENCRYPTED2))); Element el = XmlSecurityUtils.findFirstEncryptedData(doc); XmlSecurityUtils.decrypt(doc, el, serverPrivateKey); Element sig = XmlSecurityUtils.findFirstSignature(doc); Element assertionEl = SamlUtils.findFirstSamlAssertion(doc); assertionEl.setIdAttribute("AssertionID", true); missingUserKey = XmlSecurityUtils.verifySignature(sig); missingUserAssertion = new SamlAssertion(assertionEl); missingUserCredentials = new CardSpaceCredentials(missingUserAssertion, missingUserKey); } { Role role = new Role(); role.setName("ROLE_TEST"); role.setDescription("Test role"); roleDao.mockCreate(role); List<Role> roles = new ArrayList<Role>(); roles.add(role); User user = new User(); user.setUserName("test"); user.setEnabled(true); user.setPassword(User.hashPassword("Password1")); user.setEmailAddress("[email protected]"); user.setRoles(roles); userDao.create(user); CardSpaceToken token = new CardSpaceToken(); token.setPrivatePersonalIdentifier(existingUserCredentials.getPrivatePersonalIdentifier()); token.setIssuerHash(DigestUtils.shaHex(existingUserCredentials.getIssuerPublicKey())); token.setEmailAddress("[email protected]"); token.setCreationDate(new Date()); token.setUser(user); cardSpaceTokenDao.create(token); } { User user = new User(); user.setUserName("test-no-password"); user.setEnabled(true); user.setEmailAddress("[email protected]"); user.setRoles(new ArrayList<Role> ()); userDao.create(user); } } @After public void tearDown() throws Exception { svc = null; cardSpaceTokenDao = null; userDao = null; roleDao = null; existingUserAssertion = null; missingUserAssertion = null; missingPpidAssertion = null; existingUserKey = null; missingUserKey = null; missingPpidKey = null; existingUserCredentials = null; missingUserCredentials = null; missingPpidCredentials = null; } @Test public void testLoadUserByUsername() { UserDetails details = svc.loadUserByUsername("test"); assertNotNull(details); assertEquals("test", details.getUsername()); assertEquals(User.hashPassword("Password1"), details.getPassword()); GrantedAuthority[] authorities = details.getAuthorities(); assertNotNull(authorities); assertEquals(1, authorities.length); assertEquals("ROLE_TEST", authorities[0].getAuthority()); assertTrue(details.isAccountNonExpired()); assertTrue(details.isAccountNonLocked()); assertTrue(details.isCredentialsNonExpired()); assertTrue(details.isEnabled()); } @Test public void testLoadUserByUsernameDebug() { svc.setDebug(true); testLoadUserByUsername(); } @Test(expected=UsernameNotFoundException.class) public void testLoadUserByUsernameNotFound() throws Exception { svc.loadUserByUsername("bogus"); } @Test(expected=UsernameNotFoundException.class) public void testLoadUserByUsernameNoPassword() throws Exception { svc.loadUserByUsername("test-no-password"); } @Test public void testLoadUserByCardSpaceCredentials() { UserDetails details = svc.loadUserByCardSpaceCredentials(existingUserCredentials); assertNotNull(details); assertEquals("test", details.getUsername()); } @Test(expected=BadCredentialsException.class) public void testLoadUserByCardSpaceCredentialsNotFound() { svc.loadUserByCardSpaceCredentials(missingUserCredentials); } @Test(expected=InvalidCredentialsException.class) public void testLoadUserByCardSpaceCredentialsMissingPpid() { svc.loadUserByCardSpaceCredentials(missingPpidCredentials); } }
WEB-INF/src/com/randomcoder/security/userdetails/test/UserDetailsServiceImplTest.java
package com.randomcoder.security.userdetails.test; import static org.junit.Assert.*; import java.security.*; import java.util.*; import org.acegisecurity.BadCredentialsException; import org.acegisecurity.userdetails.*; import org.apache.commons.codec.digest.DigestUtils; import org.junit.*; import org.springframework.core.io.*; import org.w3c.dom.*; import org.xml.sax.InputSource; import com.randomcoder.crypto.*; import com.randomcoder.saml.*; import com.randomcoder.security.cardspace.*; import com.randomcoder.security.userdetails.UserDetailsServiceImpl; import com.randomcoder.user.*; import com.randomcoder.user.User; import com.randomcoder.user.test.*; import com.randomcoder.xml.XmlUtils; import com.randomcoder.xml.security.XmlSecurityUtils; public class UserDetailsServiceImplTest { private static final String RES_ENCRYPTED = "/xmlsec/saml-encrypted.xml"; private static final String RES_ENCRYPTED2 = "/xmlsec/test-encrypted.xml"; private static final String RES_XMLSEC_PROPS = "/xmlsec/xmlsec.properties"; private UserDetailsServiceImpl svc = null; private CardSpaceTokenDaoMock cardSpaceTokenDao = null; private UserDaoMock userDao = null; private SamlAssertion existingUserAssertion = null; private SamlAssertion missingUserAssertion = null; private SamlAssertion missingPpidAssertion = null; private PublicKey existingUserKey = null; private PublicKey missingUserKey = null; private PublicKey missingPpidKey = null; private CardSpaceCredentials existingUserCredentials = null; private CardSpaceCredentials missingUserCredentials = null; private CardSpaceCredentials missingPpidCredentials = null; @Before public void setUp() throws Exception { cardSpaceTokenDao = new CardSpaceTokenDaoMock(); userDao = new UserDaoMock(); svc = new UserDetailsServiceImpl(); svc.setCardSpaceTokenDao(cardSpaceTokenDao); svc.setUserDao(userDao); Properties properties = new Properties(); properties.load(getClass().getResourceAsStream(RES_XMLSEC_PROPS)); KeystoreCertificateFactoryBean keystoreFactory = new KeystoreCertificateFactoryBean(); Resource keystoreLocation = new ClassPathResource(properties.getProperty("keystore.resource")); keystoreFactory.setKeystoreLocation(keystoreLocation); keystoreFactory.setKeystoreType(properties.getProperty("keystore.type")); keystoreFactory.setKeystorePassword(properties.getProperty("keystore.password")); keystoreFactory.setCertificateAlias(properties.getProperty("certificate.alias")); keystoreFactory.setCertificatePassword(properties.getProperty("certificate.password")); keystoreFactory.afterPropertiesSet(); CertificateContext certContext = (CertificateContext) keystoreFactory.getObject(); PrivateKey serverPrivateKey = certContext.getPrivateKey(); { Document doc = XmlUtils.parseXml(new InputSource(getClass().getResourceAsStream(RES_ENCRYPTED))); Element el = XmlSecurityUtils.findFirstEncryptedData(doc); XmlSecurityUtils.decrypt(doc, el, serverPrivateKey); Element sig = XmlSecurityUtils.findFirstSignature(doc); Element assertionEl = SamlUtils.findFirstSamlAssertion(doc); assertionEl.setIdAttribute("AssertionID", true); missingPpidKey = existingUserKey = XmlSecurityUtils.verifySignature(sig); existingUserAssertion = new SamlAssertion(assertionEl); NodeList atts = assertionEl.getElementsByTagNameNS(SamlUtils.SAML_10_NS, "Attribute"); for (int i = 0; i < atts.getLength(); i++) { Element att = (Element) atts.item(i); if ("privatepersonalidentifier".equals(att.getAttribute("AttributeName"))) att.getParentNode().removeChild(att); } missingPpidAssertion = new SamlAssertion(assertionEl); existingUserCredentials = new CardSpaceCredentials(existingUserAssertion, existingUserKey); missingPpidCredentials = new CardSpaceCredentials(missingPpidAssertion, missingPpidKey); } { Document doc = XmlUtils.parseXml(new InputSource(getClass().getResourceAsStream(RES_ENCRYPTED2))); Element el = XmlSecurityUtils.findFirstEncryptedData(doc); XmlSecurityUtils.decrypt(doc, el, serverPrivateKey); Element sig = XmlSecurityUtils.findFirstSignature(doc); Element assertionEl = SamlUtils.findFirstSamlAssertion(doc); assertionEl.setIdAttribute("AssertionID", true); missingUserKey = XmlSecurityUtils.verifySignature(sig); missingUserAssertion = new SamlAssertion(assertionEl); missingUserCredentials = new CardSpaceCredentials(missingUserAssertion, missingUserKey); } { User user = new User(); user.setUserName("test"); user.setEnabled(true); user.setPassword(User.hashPassword("Password1")); user.setEmailAddress("[email protected]"); user.setRoles(new ArrayList<Role> ()); userDao.create(user); CardSpaceToken token = new CardSpaceToken(); token.setPrivatePersonalIdentifier(existingUserCredentials.getPrivatePersonalIdentifier()); token.setIssuerHash(DigestUtils.shaHex(existingUserCredentials.getIssuerPublicKey())); token.setEmailAddress("[email protected]"); token.setCreationDate(new Date()); token.setUser(user); cardSpaceTokenDao.create(token); } { User user = new User(); user.setUserName("test-no-password"); user.setEnabled(true); user.setEmailAddress("[email protected]"); user.setRoles(new ArrayList<Role> ()); userDao.create(user); } } @After public void tearDown() throws Exception { svc = null; cardSpaceTokenDao = null; userDao = null; existingUserAssertion = null; missingUserAssertion = null; missingPpidAssertion = null; existingUserKey = null; missingUserKey = null; missingPpidKey = null; existingUserCredentials = null; missingUserCredentials = null; missingPpidCredentials = null; } @Test public void testLoadUserByUsername() { UserDetails details = svc.loadUserByUsername("test"); assertNotNull(details); assertEquals("test", details.getUsername()); } @Test public void testLoadUserByUsernameDebug() { svc.setDebug(true); testLoadUserByUsername(); } @Test(expected=UsernameNotFoundException.class) public void testLoadUserByUsernameNotFound() throws Exception { svc.loadUserByUsername("bogus"); } @Test(expected=UsernameNotFoundException.class) public void testLoadUserByUsernameNoPassword() throws Exception { svc.loadUserByUsername("test-no-password"); } @Test public void testLoadUserByCardSpaceCredentials() { UserDetails details = svc.loadUserByCardSpaceCredentials(existingUserCredentials); assertNotNull(details); assertEquals("test", details.getUsername()); } @Test(expected=BadCredentialsException.class) public void testLoadUserByCardSpaceCredentialsNotFound() { svc.loadUserByCardSpaceCredentials(missingUserCredentials); } @Test(expected=InvalidCredentialsException.class) public void testLoadUserByCardSpaceCredentialsMissingPpid() { svc.loadUserByCardSpaceCredentials(missingPpidCredentials); } }
Expanded test coverage to include all UserDetailsImpl methods. git-svn-id: c54c250ef6781e452e8ba97060b13a35b2e33c47@354 5bee6cb3-3d18-0410-8c93-a642edd49b48
WEB-INF/src/com/randomcoder/security/userdetails/test/UserDetailsServiceImplTest.java
Expanded test coverage to include all UserDetailsImpl methods.
Java
bsd-3-clause
d400dd355b6888e0242f6ac3e307e61308551c31
0
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
/* * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.hotspot.replacements; import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.*; import sun.misc.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.replacements.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.Node.ConstantNodeParameter; import com.oracle.graal.graph.Node.NodeIntrinsic; import com.oracle.graal.hotspot.meta.*; import com.oracle.graal.hotspot.nodes.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.replacements.Snippet.Fold; import com.oracle.graal.word.*; /** * Substitutions for {@code com.sun.crypto.provider.CipherBlockChaining} methods. */ @ClassSubstitution(className = "com.sun.crypto.provider.CipherBlockChaining", optional = true) public class CipherBlockChainingSubstitutions { private static final long embeddedCipherOffset; private static final LocationIdentity embeddedCipherLocationIdentity; private static final long rOffset; private static final LocationIdentity rLocationIdentity; static { try { // Need to use launcher class path as com.sun.crypto.provider.AESCrypt // is normally not on the boot class path ClassLoader cl = Launcher.getLauncher().getClassLoader(); Class<?> feedbackCipherClass = Class.forName("com.sun.crypto.provider.FeedbackCipher", true, cl); embeddedCipherOffset = UnsafeAccess.unsafe.objectFieldOffset(feedbackCipherClass.getDeclaredField("embeddedCipher")); embeddedCipherLocationIdentity = HotSpotResolvedObjectType.fromClass(feedbackCipherClass).findInstanceFieldWithOffset(embeddedCipherOffset); Class<?> cipherBlockChainingClass = Class.forName("com.sun.crypto.provider.CipherBlockChaining", true, cl); rOffset = UnsafeAccess.unsafe.objectFieldOffset(cipherBlockChainingClass.getDeclaredField("r")); rLocationIdentity = HotSpotResolvedObjectType.fromClass(cipherBlockChainingClass).findInstanceFieldWithOffset(rOffset); } catch (Exception ex) { throw new GraalInternalError(ex); } } @Fold private static Class getAESCryptClass() { return AESCryptSubstitutions.AESCryptClass; } @MethodSubstitution(isStatic = false) static void encrypt(Object rcvr, byte[] in, int inOffset, int inLength, byte[] out, int outOffset) { Object embeddedCipher = UnsafeLoadNode.load(rcvr, embeddedCipherOffset, Kind.Object, embeddedCipherLocationIdentity); if (getAESCryptClass().isInstance(embeddedCipher)) { crypt(rcvr, in, inOffset, inLength, out, outOffset, embeddedCipher, true); } else { encrypt(rcvr, in, inOffset, inLength, out, outOffset); } } @MethodSubstitution(isStatic = false) static void decrypt(Object rcvr, byte[] in, int inOffset, int inLength, byte[] out, int outOffset) { Object embeddedCipher = UnsafeLoadNode.load(rcvr, embeddedCipherOffset, Kind.Object, embeddedCipherLocationIdentity); if (in != out && getAESCryptClass().isInstance(embeddedCipher)) { crypt(rcvr, in, inOffset, inLength, out, outOffset, embeddedCipher, false); } else { decrypt(rcvr, in, inOffset, inLength, out, outOffset); } } private static void crypt(Object rcvr, byte[] in, int inOffset, int inLength, byte[] out, int outOffset, Object embeddedCipher, boolean encrypt) { Object kObject = UnsafeLoadNode.load(embeddedCipher, AESCryptSubstitutions.kOffset, Kind.Object, AESCryptSubstitutions.kLocationIdentity); Object rObject = UnsafeLoadNode.load(rcvr, rOffset, Kind.Object, rLocationIdentity); Word kAddr = (Word) Word.fromObject(kObject).add(arrayBaseOffset(Kind.Byte)); Word rAddr = (Word) Word.fromObject(rObject).add(arrayBaseOffset(Kind.Byte)); Word inAddr = Word.unsigned(GetObjectAddressNode.get(in) + arrayBaseOffset(Kind.Byte) + inOffset); Word outAddr = Word.unsigned(GetObjectAddressNode.get(out) + arrayBaseOffset(Kind.Byte) + outOffset); if (encrypt) { encryptAESCryptStub(ENCRYPT, inAddr, outAddr, kAddr, rAddr, inLength); } else { decryptAESCryptStub(DECRYPT, inAddr, outAddr, kAddr, rAddr, inLength); } } public static final ForeignCallDescriptor ENCRYPT = new ForeignCallDescriptor("encrypt", void.class, Word.class, Word.class, Word.class, Word.class, int.class); public static final ForeignCallDescriptor DECRYPT = new ForeignCallDescriptor("decrypt", void.class, Word.class, Word.class, Word.class, Word.class, int.class); @NodeIntrinsic(ForeignCallNode.class) public static native void encryptAESCryptStub(@ConstantNodeParameter ForeignCallDescriptor descriptor, Word in, Word out, Word key, Word r, int inLength); @NodeIntrinsic(ForeignCallNode.class) public static native void decryptAESCryptStub(@ConstantNodeParameter ForeignCallDescriptor descriptor, Word in, Word out, Word key, Word r, int inLength); }
graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/replacements/CipherBlockChainingSubstitutions.java
/* * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.hotspot.replacements; import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.*; import sun.misc.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.replacements.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.Node.ConstantNodeParameter; import com.oracle.graal.graph.Node.NodeIntrinsic; import com.oracle.graal.hotspot.nodes.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.replacements.Snippet.Fold; import com.oracle.graal.word.*; /** * Substitutions for {@code com.sun.crypto.provider.CipherBlockChaining} methods. */ @ClassSubstitution(className = "com.sun.crypto.provider.CipherBlockChaining", optional = true) public class CipherBlockChainingSubstitutions { private static final long embeddedCipherOffset; private static final long rOffset; static { try { // Need to use launcher class path as com.sun.crypto.provider.AESCrypt // is normally not on the boot class path ClassLoader cl = Launcher.getLauncher().getClassLoader(); embeddedCipherOffset = UnsafeAccess.unsafe.objectFieldOffset(Class.forName("com.sun.crypto.provider.FeedbackCipher", true, cl).getDeclaredField("embeddedCipher")); rOffset = UnsafeAccess.unsafe.objectFieldOffset(Class.forName("com.sun.crypto.provider.CipherBlockChaining", true, cl).getDeclaredField("r")); } catch (Exception ex) { throw new GraalInternalError(ex); } } @Fold private static Class getAESCryptClass() { return AESCryptSubstitutions.AESCryptClass; } @MethodSubstitution(isStatic = false) static void encrypt(Object rcvr, byte[] in, int inOffset, int inLength, byte[] out, int outOffset) { Object embeddedCipher = UnsafeLoadNode.load(rcvr, embeddedCipherOffset, Kind.Object, LocationIdentity.ANY_LOCATION); if (getAESCryptClass().isInstance(embeddedCipher)) { crypt(rcvr, in, inOffset, inLength, out, outOffset, embeddedCipher, true); } else { encrypt(rcvr, in, inOffset, inLength, out, outOffset); } } @MethodSubstitution(isStatic = false) static void decrypt(Object rcvr, byte[] in, int inOffset, int inLength, byte[] out, int outOffset) { Object embeddedCipher = UnsafeLoadNode.load(rcvr, embeddedCipherOffset, Kind.Object, LocationIdentity.ANY_LOCATION); if (in != out && getAESCryptClass().isInstance(embeddedCipher)) { crypt(rcvr, in, inOffset, inLength, out, outOffset, embeddedCipher, false); } else { decrypt(rcvr, in, inOffset, inLength, out, outOffset); } } private static void crypt(Object rcvr, byte[] in, int inOffset, int inLength, byte[] out, int outOffset, Object embeddedCipher, boolean encrypt) { Object kObject = UnsafeLoadNode.load(embeddedCipher, AESCryptSubstitutions.kOffset, Kind.Object, AESCryptSubstitutions.kLocationIdentity); Object rObject = UnsafeLoadNode.load(rcvr, rOffset, Kind.Object, LocationIdentity.ANY_LOCATION); Word kAddr = (Word) Word.fromObject(kObject).add(arrayBaseOffset(Kind.Byte)); Word rAddr = (Word) Word.fromObject(rObject).add(arrayBaseOffset(Kind.Byte)); Word inAddr = Word.unsigned(GetObjectAddressNode.get(in) + arrayBaseOffset(Kind.Byte) + inOffset); Word outAddr = Word.unsigned(GetObjectAddressNode.get(out) + arrayBaseOffset(Kind.Byte) + outOffset); if (encrypt) { encryptAESCryptStub(ENCRYPT, inAddr, outAddr, kAddr, rAddr, inLength); } else { decryptAESCryptStub(DECRYPT, inAddr, outAddr, kAddr, rAddr, inLength); } } public static final ForeignCallDescriptor ENCRYPT = new ForeignCallDescriptor("encrypt", void.class, Word.class, Word.class, Word.class, Word.class, int.class); public static final ForeignCallDescriptor DECRYPT = new ForeignCallDescriptor("decrypt", void.class, Word.class, Word.class, Word.class, Word.class, int.class); @NodeIntrinsic(ForeignCallNode.class) public static native void encryptAESCryptStub(@ConstantNodeParameter ForeignCallDescriptor descriptor, Word in, Word out, Word key, Word r, int inLength); @NodeIntrinsic(ForeignCallNode.class) public static native void decryptAESCryptStub(@ConstantNodeParameter ForeignCallDescriptor descriptor, Word in, Word out, Word key, Word r, int inLength); }
CipherBlockChainingSubstitutions: use more precise location for embeddedCipher object and r array
graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/replacements/CipherBlockChainingSubstitutions.java
CipherBlockChainingSubstitutions: use more precise location for embeddedCipher object and r array
Java
bsd-3-clause
583f7671cd98cd631dc759fa2c1d593b5d798754
0
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.replacements; import java.lang.reflect.*; import java.util.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.replacements.*; import com.oracle.graal.graph.*; import com.oracle.graal.java.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.calc.*; import com.oracle.graal.nodes.java.*; import com.oracle.graal.nodes.java.MethodCallTargetNode.InvokeKind; import com.oracle.graal.phases.common.*; import com.oracle.graal.phases.common.inlining.*; import com.oracle.graal.phases.util.*; import com.oracle.graal.replacements.ReplacementsImpl.FrameStateProcessing; import com.oracle.graal.word.phases.*; /** * A utility for manually creating a graph. This will be expanded as necessary to support all * subsystems that employ manual graph creation (as opposed to {@linkplain GraphBuilderPhase * bytecode parsing} based graph creation). */ public class GraphKit { protected final Providers providers; protected final StructuredGraph graph; protected FixedWithNextNode lastFixedNode; private final List<Structure> structures; abstract static class Structure { } public GraphKit(StructuredGraph graph, Providers providers) { this.providers = providers; this.graph = graph; this.lastFixedNode = graph.start(); structures = new ArrayList<>(); /* Add a dummy element, so that the access of the last element never leads to an exception. */ structures.add(new Structure() { }); } public StructuredGraph getGraph() { return graph; } /** * Ensures a floating node is added to or already present in the graph via {@link Graph#unique}. * * @return a node similar to {@code node} if one exists, otherwise {@code node} */ public <T extends FloatingNode> T unique(T node) { return graph.unique(node); } /** * Appends a fixed node to the graph. */ public <T extends FixedNode> T append(T node) { T result = graph.add(node); assert lastFixedNode != null; assert result.predecessor() == null; graph.addAfterFixed(lastFixedNode, result); if (result instanceof FixedWithNextNode) { lastFixedNode = (FixedWithNextNode) result; } else { lastFixedNode = null; } return result; } public InvokeNode createInvoke(Class<?> declaringClass, String name, ValueNode... args) { return createInvoke(declaringClass, name, InvokeKind.Static, null, BytecodeFrame.UNKNOWN_BCI, args); } /** * Creates and appends an {@link InvokeNode} for a call to a given method with a given set of * arguments. The method is looked up via reflection based on the declaring class and name. * * @param declaringClass the class declaring the invoked method * @param name the name of the invoked method * @param args the arguments to the invocation */ public InvokeNode createInvoke(Class<?> declaringClass, String name, InvokeKind invokeKind, HIRFrameStateBuilder frameStateBuilder, int bci, ValueNode... args) { boolean isStatic = invokeKind == InvokeKind.Static; ResolvedJavaMethod method = null; for (Method m : declaringClass.getDeclaredMethods()) { if (Modifier.isStatic(m.getModifiers()) == isStatic && m.getName().equals(name)) { assert method == null : "found more than one method in " + declaringClass + " named " + name; method = providers.getMetaAccess().lookupJavaMethod(m); } } assert method != null : "did not find method in " + declaringClass + " named " + name; return createInvoke(method, invokeKind, frameStateBuilder, bci, args); } /** * Creates and appends an {@link InvokeNode} for a call to a given method with a given set of * arguments. */ public InvokeNode createInvoke(ResolvedJavaMethod method, InvokeKind invokeKind, HIRFrameStateBuilder frameStateBuilder, int bci, ValueNode... args) { assert method.isStatic() == (invokeKind == InvokeKind.Static); Signature signature = method.getSignature(); JavaType returnType = signature.getReturnType(null); assert checkArgs(method, args); MethodCallTargetNode callTarget = graph.add(createMethodCallTarget(invokeKind, method, args, returnType, bci)); InvokeNode invoke = append(new InvokeNode(callTarget, bci)); if (frameStateBuilder != null) { if (invoke.getKind() != Kind.Void) { frameStateBuilder.push(invoke.getKind(), invoke); } invoke.setStateAfter(frameStateBuilder.create(0)); if (invoke.getKind() != Kind.Void) { frameStateBuilder.pop(invoke.getKind()); } } return invoke; } protected MethodCallTargetNode createMethodCallTarget(InvokeKind invokeKind, ResolvedJavaMethod targetMethod, ValueNode[] args, JavaType returnType, @SuppressWarnings("unused") int bci) { return new MethodCallTargetNode(invokeKind, targetMethod, args, returnType); } /** * Determines if a given set of arguments is compatible with the signature of a given method. * * @return true if {@code args} are compatible with the signature if {@code method} * @throws AssertionError if {@code args} are not compatible with the signature if * {@code method} */ public boolean checkArgs(ResolvedJavaMethod method, ValueNode... args) { Signature signature = method.getSignature(); boolean isStatic = method.isStatic(); if (signature.getParameterCount(!isStatic) != args.length) { throw new AssertionError(graph + ": wrong number of arguments to " + method); } int paramNum = 0; for (int i = 0; i != args.length; i++) { Kind expected; if (i == 0 && !isStatic) { expected = Kind.Object; } else { expected = signature.getParameterKind(paramNum++).getStackKind(); } Kind actual = args[i].stamp().getStackKind(); if (expected != actual) { throw new AssertionError(graph + ": wrong kind of value for argument " + i + " of call to " + method + " [" + actual + " != " + expected + "]"); } } return true; } /** * Rewrite all word types in the graph. */ public void rewriteWordTypes(SnippetReflectionProvider snippetReflection) { new WordTypeRewriterPhase(providers.getMetaAccess(), snippetReflection, providers.getCodeCache().getTarget().wordKind).apply(graph); } /** * Recursively {@linkplain #inline inlines} all invocations currently in the graph. */ public void inlineInvokes(SnippetReflectionProvider snippetReflection) { while (!graph.getNodes().filter(InvokeNode.class).isEmpty()) { for (InvokeNode invoke : graph.getNodes().filter(InvokeNode.class).snapshot()) { inline(invoke, snippetReflection); } } // Clean up all code that is now dead after inlining. new DeadCodeEliminationPhase().apply(graph); } /** * Inlines a given invocation to a method. The graph of the inlined method is * {@linkplain ReplacementsImpl#makeGraph processed} in the same manner as for snippets and * method substitutions. */ public void inline(InvokeNode invoke, SnippetReflectionProvider snippetReflection) { ResolvedJavaMethod method = ((MethodCallTargetNode) invoke.callTarget()).targetMethod(); ReplacementsImpl repl = new ReplacementsImpl(providers, snippetReflection, new Assumptions(false), providers.getCodeCache().getTarget()); StructuredGraph calleeGraph = repl.makeGraph(method, null, method, null, FrameStateProcessing.CollapseFrameForSingleSideEffect); InliningUtil.inline(invoke, calleeGraph, false); } protected void pushStructure(Structure structure) { structures.add(structure); } protected <T extends Structure> T getTopStructure(Class<T> expectedClass) { return expectedClass.cast(structures.get(structures.size() - 1)); } protected void popStructure() { structures.remove(structures.size() - 1); } protected enum IfState { CONDITION, THEN_PART, ELSE_PART, FINISHED } static class IfStructure extends Structure { protected IfState state; protected FixedNode thenPart; protected FixedNode elsePart; } /** * Starts an if-block. This call can be followed by a call to {@link #thenPart} to start * emitting the code executed when the condition hold; and a call to {@link #elsePart} to start * emititng the code when the condition does not hold. It must be followed by a call to * {@link #endIf} to close the if-block. * * @param condition The condition for the if-block * @param trueProbability The estimated probability the the condition is true */ public void startIf(LogicNode condition, double trueProbability) { BeginNode thenSuccessor = graph.add(new BeginNode()); BeginNode elseSuccessor = graph.add(new BeginNode()); append(new IfNode(condition, thenSuccessor, elseSuccessor, trueProbability)); lastFixedNode = null; IfStructure s = new IfStructure(); s.state = IfState.CONDITION; s.thenPart = thenSuccessor; s.elsePart = elseSuccessor; pushStructure(s); } private IfStructure saveLastNode() { IfStructure s = getTopStructure(IfStructure.class); switch (s.state) { case CONDITION: assert lastFixedNode == null; break; case THEN_PART: s.thenPart = lastFixedNode; break; case ELSE_PART: s.elsePart = lastFixedNode; break; case FINISHED: assert false; break; } lastFixedNode = null; return s; } public void thenPart() { IfStructure s = saveLastNode(); lastFixedNode = (FixedWithNextNode) s.thenPart; s.state = IfState.THEN_PART; } public void elsePart() { IfStructure s = saveLastNode(); lastFixedNode = (FixedWithNextNode) s.elsePart; s.state = IfState.ELSE_PART; } public void endIf() { IfStructure s = saveLastNode(); FixedWithNextNode thenPart = s.thenPart instanceof FixedWithNextNode ? (FixedWithNextNode) s.thenPart : null; FixedWithNextNode elsePart = s.elsePart instanceof FixedWithNextNode ? (FixedWithNextNode) s.elsePart : null; if (thenPart != null && elsePart != null) { /* Both parts are alive, we need a real merge. */ EndNode thenEnd = graph.add(new EndNode()); graph.addAfterFixed(thenPart, thenEnd); EndNode elseEnd = graph.add(new EndNode()); graph.addAfterFixed(elsePart, elseEnd); MergeNode merge = graph.add(new MergeNode()); merge.addForwardEnd(thenEnd); merge.addForwardEnd(elseEnd); lastFixedNode = merge; } else if (thenPart != null) { /* elsePart ended with a control sink, so we can continue with thenPart. */ lastFixedNode = thenPart; } else if (elsePart != null) { /* thenPart ended with a control sink, so we can continue with elsePart. */ lastFixedNode = elsePart; } else { /* Both parts ended with a control sink, so no nodes can be added after the if. */ assert lastFixedNode == null; } s.state = IfState.FINISHED; popStructure(); } }
graal/com.oracle.graal.replacements/src/com/oracle/graal/replacements/GraphKit.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.replacements; import java.lang.reflect.*; import java.util.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.replacements.*; import com.oracle.graal.graph.*; import com.oracle.graal.java.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.calc.*; import com.oracle.graal.nodes.java.*; import com.oracle.graal.nodes.java.MethodCallTargetNode.InvokeKind; import com.oracle.graal.phases.common.*; import com.oracle.graal.phases.common.inlining.*; import com.oracle.graal.phases.util.*; import com.oracle.graal.replacements.ReplacementsImpl.FrameStateProcessing; import com.oracle.graal.word.phases.*; /** * A utility for manually creating a graph. This will be expanded as necessary to support all * subsystems that employ manual graph creation (as opposed to {@linkplain GraphBuilderPhase * bytecode parsing} based graph creation). */ public class GraphKit { protected final Providers providers; protected final StructuredGraph graph; protected FixedWithNextNode lastFixedNode; private final List<Structure> structures; abstract static class Structure { } public GraphKit(StructuredGraph graph, Providers providers) { this.providers = providers; this.graph = graph; this.lastFixedNode = graph.start(); structures = new ArrayList<>(); /* Add a dummy element, so that the access of the last element never leads to an exception. */ structures.add(new Structure() { }); } public StructuredGraph getGraph() { return graph; } /** * Ensures a floating node is added to or already present in the graph via {@link Graph#unique}. * * @return a node similar to {@code node} if one exists, otherwise {@code node} */ public <T extends FloatingNode> T unique(T node) { return graph.unique(node); } /** * Appends a fixed node to the graph. */ public <T extends FixedNode> T append(T node) { T result = graph.add(node); assert lastFixedNode != null; assert result.predecessor() == null; graph.addAfterFixed(lastFixedNode, result); if (result instanceof FixedWithNextNode) { lastFixedNode = (FixedWithNextNode) result; } else { lastFixedNode = null; } return result; } public InvokeNode createInvoke(Class<?> declaringClass, String name, ValueNode... args) { return createInvoke(declaringClass, name, InvokeKind.Static, null, BytecodeFrame.UNKNOWN_BCI, args); } /** * Creates and appends an {@link InvokeNode} for a call to a given method with a given set of * arguments. The method is looked up via reflection based on the declaring class and name. * * @param declaringClass the class declaring the invoked method * @param name the name of the invoked method * @param args the arguments to the invocation */ public InvokeNode createInvoke(Class<?> declaringClass, String name, InvokeKind invokeKind, HIRFrameStateBuilder frameStateBuilder, int bci, ValueNode... args) { boolean isStatic = invokeKind == InvokeKind.Static; ResolvedJavaMethod method = null; for (Method m : declaringClass.getDeclaredMethods()) { if (Modifier.isStatic(m.getModifiers()) == isStatic && m.getName().equals(name)) { assert method == null : "found more than one method in " + declaringClass + " named " + name; method = providers.getMetaAccess().lookupJavaMethod(m); } } assert method != null : "did not find method in " + declaringClass + " named " + name; return createInvoke(method, invokeKind, frameStateBuilder, bci, args); } /** * Creates and appends an {@link InvokeNode} for a call to a given method with a given set of * arguments. */ public InvokeNode createInvoke(ResolvedJavaMethod method, InvokeKind invokeKind, HIRFrameStateBuilder frameStateBuilder, int bci, ValueNode... args) { assert method.isStatic() == (invokeKind == InvokeKind.Static); Signature signature = method.getSignature(); JavaType returnType = signature.getReturnType(null); assert checkArgs(method, args); MethodCallTargetNode callTarget = graph.add(createMethodCallTarget(invokeKind, method, args, returnType, bci)); InvokeNode invoke = append(new InvokeNode(callTarget, bci)); if (frameStateBuilder != null) { if (invoke.getKind() != Kind.Void) { frameStateBuilder.push(invoke.getKind(), invoke); } invoke.setStateAfter(frameStateBuilder.create(0)); if (invoke.getKind() != Kind.Void) { frameStateBuilder.pop(invoke.getKind()); } } return invoke; } protected MethodCallTargetNode createMethodCallTarget(InvokeKind invokeKind, ResolvedJavaMethod targetMethod, ValueNode[] args, JavaType returnType, @SuppressWarnings("unused") int bci) { return new MethodCallTargetNode(invokeKind, targetMethod, args, returnType); } /** * Determines if a given set of arguments is compatible with the signature of a given method. * * @return true if {@code args} are compatible with the signature if {@code method} * @throws AssertionError if {@code args} are not compatible with the signature if * {@code method} */ public boolean checkArgs(ResolvedJavaMethod method, ValueNode... args) { Signature signature = method.getSignature(); boolean isStatic = method.isStatic(); if (signature.getParameterCount(!isStatic) != args.length) { throw new AssertionError(graph + ": wrong number of arguments to " + method); } int paramNum = 0; for (int i = 0; i != args.length; i++) { Kind expected; if (i == 0 && !isStatic) { expected = Kind.Object; } else { expected = signature.getParameterKind(paramNum++).getStackKind(); } Kind actual = args[i].stamp().getStackKind(); if (expected != actual) { throw new AssertionError(graph + ": wrong kind of value for argument " + i + " of call to " + method + " [" + actual + " != " + expected + "]"); } } return true; } /** * Rewrite all word types in the graph. */ public void rewriteWordTypes(SnippetReflectionProvider snippetReflection) { new WordTypeRewriterPhase(providers.getMetaAccess(), snippetReflection, providers.getCodeCache().getTarget().wordKind).apply(graph); } /** * {@linkplain #inline Inlines} all invocations currently in the graph. */ public void inlineInvokes(SnippetReflectionProvider snippetReflection) { for (InvokeNode invoke : graph.getNodes().filter(InvokeNode.class).snapshot()) { inline(invoke, snippetReflection); } // Clean up all code that is now dead after inlining. new DeadCodeEliminationPhase().apply(graph); assert graph.getNodes().filter(InvokeNode.class).isEmpty(); } /** * Inlines a given invocation to a method. The graph of the inlined method is * {@linkplain ReplacementsImpl#makeGraph processed} in the same manner as for snippets and * method substitutions. */ public void inline(InvokeNode invoke, SnippetReflectionProvider snippetReflection) { ResolvedJavaMethod method = ((MethodCallTargetNode) invoke.callTarget()).targetMethod(); ReplacementsImpl repl = new ReplacementsImpl(providers, snippetReflection, new Assumptions(false), providers.getCodeCache().getTarget()); StructuredGraph calleeGraph = repl.makeGraph(method, null, method, null, FrameStateProcessing.CollapseFrameForSingleSideEffect); InliningUtil.inline(invoke, calleeGraph, false); } protected void pushStructure(Structure structure) { structures.add(structure); } protected <T extends Structure> T getTopStructure(Class<T> expectedClass) { return expectedClass.cast(structures.get(structures.size() - 1)); } protected void popStructure() { structures.remove(structures.size() - 1); } protected enum IfState { CONDITION, THEN_PART, ELSE_PART, FINISHED } static class IfStructure extends Structure { protected IfState state; protected FixedNode thenPart; protected FixedNode elsePart; } /** * Starts an if-block. This call can be followed by a call to {@link #thenPart} to start * emitting the code executed when the condition hold; and a call to {@link #elsePart} to start * emititng the code when the condition does not hold. It must be followed by a call to * {@link #endIf} to close the if-block. * * @param condition The condition for the if-block * @param trueProbability The estimated probability the the condition is true */ public void startIf(LogicNode condition, double trueProbability) { BeginNode thenSuccessor = graph.add(new BeginNode()); BeginNode elseSuccessor = graph.add(new BeginNode()); append(new IfNode(condition, thenSuccessor, elseSuccessor, trueProbability)); lastFixedNode = null; IfStructure s = new IfStructure(); s.state = IfState.CONDITION; s.thenPart = thenSuccessor; s.elsePart = elseSuccessor; pushStructure(s); } private IfStructure saveLastNode() { IfStructure s = getTopStructure(IfStructure.class); switch (s.state) { case CONDITION: assert lastFixedNode == null; break; case THEN_PART: s.thenPart = lastFixedNode; break; case ELSE_PART: s.elsePart = lastFixedNode; break; case FINISHED: assert false; break; } lastFixedNode = null; return s; } public void thenPart() { IfStructure s = saveLastNode(); lastFixedNode = (FixedWithNextNode) s.thenPart; s.state = IfState.THEN_PART; } public void elsePart() { IfStructure s = saveLastNode(); lastFixedNode = (FixedWithNextNode) s.elsePart; s.state = IfState.ELSE_PART; } public void endIf() { IfStructure s = saveLastNode(); FixedWithNextNode thenPart = s.thenPart instanceof FixedWithNextNode ? (FixedWithNextNode) s.thenPart : null; FixedWithNextNode elsePart = s.elsePart instanceof FixedWithNextNode ? (FixedWithNextNode) s.elsePart : null; if (thenPart != null && elsePart != null) { /* Both parts are alive, we need a real merge. */ EndNode thenEnd = graph.add(new EndNode()); graph.addAfterFixed(thenPart, thenEnd); EndNode elseEnd = graph.add(new EndNode()); graph.addAfterFixed(elsePart, elseEnd); MergeNode merge = graph.add(new MergeNode()); merge.addForwardEnd(thenEnd); merge.addForwardEnd(elseEnd); lastFixedNode = merge; } else if (thenPart != null) { /* elsePart ended with a control sink, so we can continue with thenPart. */ lastFixedNode = thenPart; } else if (elsePart != null) { /* thenPart ended with a control sink, so we can continue with elsePart. */ lastFixedNode = elsePart; } else { /* Both parts ended with a control sink, so no nodes can be added after the if. */ assert lastFixedNode == null; } s.state = IfState.FINISHED; popStructure(); } }
made GraphKit.inlineInvoke recursively inline all invoke
graal/com.oracle.graal.replacements/src/com/oracle/graal/replacements/GraphKit.java
made GraphKit.inlineInvoke recursively inline all invoke
Java
mit
5d3c1db4dfb669a2cb50d45fd51b43c15ead4c27
0
Brightchu/JavaScriptAcquiring,Brightchu/JavaScriptAcquiring,Brightchu/JavaScriptAcquiring
public class Hello{ public static void main(String [] args){ System.out.println("Hello World!"); System.out.println("Hello!\nWorld!"); double a=0.0 ; a=(double) (1/3); System.out.println(a); //System.out.println("integrate the github with Sumblime text by Git plugin."); system.out.println("first git commit"); } }
dev/Hello.java
public class Hello{ public static void main(String [] args){ System.out.println("Hello World!"); System.out.println("Hello!\nWorld!"); double a=0.0 ; a=(double) (1/3); System.out.println(a); } }
fist git commit
dev/Hello.java
fist git commit
Java
mit
520c92a601bf3b9fdc4c1a004ac9a1f89b3e8b76
0
infinitemule/spring-espn-intg-test
package com.infinitemule.espn.api.test.now.spring; import static com.infinitemule.espn.common.lang.Console.printfn; import static com.infinitemule.espn.common.lang.Console.println; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.infinitemule.espn.api.now.Disable; import com.infinitemule.espn.api.now.Feed; import com.infinitemule.espn.api.now.NowApiRequest; import com.infinitemule.espn.api.now.NowApiResponse; import com.infinitemule.espn.api.now.NowApiService; import com.infinitemule.espn.api.now.NowLeague; import com.infinitemule.espn.api.test.AbstractApiServiceSpringIntgTest; import com.infinitemule.espn.common.api.Content; import com.infinitemule.espn.common.api.Image; import com.infinitemule.espn.common.api.Language; import com.infinitemule.espn.common.api.NewsCategory; import com.infinitemule.espn.common.api.Teams; import com.infinitemule.espn.common.api.Video; public class NowApiServiceSpringIntgTest extends AbstractApiServiceSpringIntgTest { @Autowired private NowApiService srv = null; @Test public void latest() { NowApiRequest request = new NowApiRequest() .latest(); output(srv.call(request)); } @Test public void top() { NowApiRequest request = new NowApiRequest() .top(); output(srv.call(request)); } @Test public void popular() { NowApiRequest request = new NowApiRequest() .popular(); output(srv.call(request)); } @Test public void limit() { NowApiRequest request = new NowApiRequest() .top() .limit(5); output(srv.call(request)); } @Test public void league() { NowApiRequest request = new NowApiRequest() .latest() .league(NowLeague.NFL); output(srv.call(request)); } @Test public void leagueTeam() { NowApiRequest request = new NowApiRequest() .latest() .league(NowLeague.MLB) .teams(Teams.MLB.BOS); output(srv.call(request)); } @Test public void language() { NowApiRequest request = new NowApiRequest() .latest() .language(Language.Spanish); output(srv.call(request)); } @Test public void content() { NowApiRequest request = new NowApiRequest() .latest() .content(Content.Blog, Content.Video); output(srv.call(request)); } @Test public void disable() { NowApiRequest request = new NowApiRequest() .latest() .disable(Disable.Categories); output(srv.call(request)); } private void output(NowApiResponse resp) { for(Feed breaking : resp.getBreakingNews()) { println("********** BREAKING NEWS **********"); printfn("%s (%s)", breaking.getHeadline(), breaking.getId()); println(" - Description:"); printfn(" %s - %s - %s", breaking.getPublished(), breaking.getType(), breaking.getSection()); printfn(" %s", breaking.getDescription()); println(); println(); } for(Feed feed : resp.getFeed()) { println("----------------------------------------"); printfn("%s (%s)", feed.getHeadline(), feed.getId()); println(" - Description:"); printfn(" %s - %s - %s", feed.getPublished(), feed.getType(), feed.getSection()); printfn(" %s", feed.getDescription()); println(" - Links:"); printfn(" Web: %s", feed.getLinks().getWebUrl()); printfn(" Mobile: %s", feed.getLinks().getMobileUrl()); println(" - Categories:"); for(NewsCategory cat : feed.getCategories()) { printfn(" %s (%s)", cat.getDescription(), cat.getType()); } println(" - Images:"); for(Image image : feed.getImages()) { printfn(" %s (%sx%s) - %s", image.getName(), image.getHeight(), image.getWidth(), image.getUrl()); } println(" - Videos:"); for(Video video : feed.getVideo()) { printfn(" %s - %s", video.getTitle(), video.getLinks().getWeb().getHref()); } println(); } printfn("Status: %s", resp.getStatus()); printfn("Timestamp: %s", resp.getTimestamp()); } }
src/test/java/com/infinitemule/espn/api/test/now/spring/NowApiServiceSpringIntgTest.java
package com.infinitemule.espn.api.test.now.spring; import static com.infinitemule.espn.common.lang.Console.printfn; import static com.infinitemule.espn.common.lang.Console.println; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.infinitemule.espn.api.now.Feed; import com.infinitemule.espn.api.now.NowApiRequest; import com.infinitemule.espn.api.now.NowApiResponse; import com.infinitemule.espn.api.now.NowApiService; import com.infinitemule.espn.api.now.NowLeague; import com.infinitemule.espn.api.test.AbstractApiServiceSpringIntgTest; import com.infinitemule.espn.common.api.Content; import com.infinitemule.espn.common.api.Image; import com.infinitemule.espn.common.api.Language; import com.infinitemule.espn.common.api.NewsCategory; import com.infinitemule.espn.common.api.Teams; import com.infinitemule.espn.common.api.Video; public class NowApiServiceSpringIntgTest extends AbstractApiServiceSpringIntgTest { @Autowired private NowApiService srv = null; @Test public void latest() { NowApiRequest request = new NowApiRequest() .latest(); output(srv.call(request)); } @Test public void top() { NowApiRequest request = new NowApiRequest() .top(); output(srv.call(request)); } @Test public void popular() { NowApiRequest request = new NowApiRequest() .popular(); output(srv.call(request)); } @Test public void limit() { NowApiRequest request = new NowApiRequest() .top() .limit(5); output(srv.call(request)); } @Test public void league() { NowApiRequest request = new NowApiRequest() .latest() .league(NowLeague.NFL); output(srv.call(request)); } @Test public void leagueTeam() { NowApiRequest request = new NowApiRequest() .latest() .league(NowLeague.MLB) .teams(Teams.MLB.BOS); output(srv.call(request)); } @Test public void language() { NowApiRequest request = new NowApiRequest() .latest() .language(Language.Spanish); output(srv.call(request)); } @Test public void content() { NowApiRequest request = new NowApiRequest() .latest() .content(Content.Blog, Content.Video); output(srv.call(request)); } private void output(NowApiResponse resp) { for(Feed breaking : resp.getBreakingNews()) { println("********** BREAKING NEWS **********"); printfn("%s (%s)", breaking.getHeadline(), breaking.getId()); println(" - Description:"); printfn(" %s - %s - %s", breaking.getPublished(), breaking.getType(), breaking.getSection()); printfn(" %s", breaking.getDescription()); println(); println(); } for(Feed feed : resp.getFeed()) { println("----------------------------------------"); printfn("%s (%s)", feed.getHeadline(), feed.getId()); println(" - Description:"); printfn(" %s - %s - %s", feed.getPublished(), feed.getType(), feed.getSection()); printfn(" %s", feed.getDescription()); println(" - Links:"); printfn(" Web: %s", feed.getLinks().getWebUrl()); printfn(" Mobile: %s", feed.getLinks().getMobileUrl()); println(" - Categories:"); for(NewsCategory cat : feed.getCategories()) { printfn(" %s (%s)", cat.getDescription(), cat.getType()); } println(" - Images:"); for(Image image : feed.getImages()) { printfn(" %s (%sx%s) - %s", image.getName(), image.getHeight(), image.getWidth(), image.getUrl()); } println(" - Videos:"); for(Video video : feed.getVideo()) { printfn(" %s - %s", video.getTitle(), video.getLinks().getWeb().getHref()); } println(); } printfn("Status: %s", resp.getStatus()); printfn("Timestamp: %s", resp.getTimestamp()); } }
Added disable test for Now API.
src/test/java/com/infinitemule/espn/api/test/now/spring/NowApiServiceSpringIntgTest.java
Added disable test for Now API.
Java
mit
f128dd4ffdc090dbddeb452ac9a5dd2365ebf087
0
mhogrefe/wheels
package mho.wheels.math; import mho.wheels.iterables.IterableUtils; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import java.math.BigInteger; import java.util.*; import java.util.function.Function; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; /** * Some mathematical utilities */ public final class MathUtils { /** * The size of {@link mho.wheels.math.MathUtils#PRIME_SIEVE}. Must be greater than or equal to * ⌈sqrt({@code Integer.MAX_VALUE})⌉ = 46,341 */ private static final int PRIME_SIEVE_SIZE = 1 << 16; /** * A cache of small primes, generated using the Sieve of Eratosthenes algorithm. */ private static final BitSet PRIME_SIEVE; static { PRIME_SIEVE = new BitSet(PRIME_SIEVE_SIZE); PRIME_SIEVE.set(2, PRIME_SIEVE_SIZE - 1); int multiple; for (multiple = 0; multiple < PRIME_SIEVE_SIZE; multiple++) { while (!PRIME_SIEVE.get(multiple) && multiple < PRIME_SIEVE_SIZE) multiple++; for (int i : rangeBy(multiple * 2, multiple, PRIME_SIEVE_SIZE - 1)) { PRIME_SIEVE.clear(i); } } } /** * Disallow instantiation */ private MathUtils() {} /** * The greatest common divisor of two {@link int}s. If both {@code x} and {@code y} are zero, the result is * undefined. Otherwise, the result is positive. * * <ul> * <li>{@code x} may be any {@code int}.</li> * <li>{@code y} may be any {@code int}.</li> * <li>{@code x} and {@code y} y may not both be zero.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first number * @param y the second number * @return gcd(x, y) */ public static int gcd(int x, int y) { if (x == 0 && y == 0) throw new ArithmeticException("cannot take gcd of 0 and 0"); return positiveGcd(Math.abs(x), Math.abs(y)); } /** * The greatest common divisor of two non-negative {@code int}s. * * <ul> * <li>{@code x} must be non-negative.</li> * <li>{@code y} must be non-negative.</li> * <li>{@code x} and {@code y} y may not both be zero.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first number * @param y the second number * @return gcd(x, y) */ private static int positiveGcd(int x, int y) { //noinspection SuspiciousNameCombination return y == 0 ? x : positiveGcd(y, x % y); } /** * The greatest common divisor of two {@link long}s. If both {@code x} and {@code y} are zero, the result is * undefined. Otherwise, the result is positive. * * <ul> * <li>{@code x} may be any {@code long}.</li> * <li>{@code y} may be any {@code long}.</li> * <li>{@code x} and {@code y} y may not both be zero.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first number * @param y the second number * @return gcd(x, y) */ public static long gcd(long x, long y) { if (x == 0 && y == 0) throw new ArithmeticException("cannot take gcd of 0 and 0"); return positiveGcd(Math.abs(x), Math.abs(y)); } /** * The greatest common divisor of two non-negative {@code long}s. * * <ul> * <li>{@code x} must be non-negative.</li> * <li>{@code y} must be non-negative.</li> * <li>{@code x} and {@code y} y may not both be zero.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first number * @param y the second number * @return gcd(x, y) */ private static long positiveGcd(long x, long y) { //noinspection SuspiciousNameCombination return y == 0 ? x : positiveGcd(y, x % y); } /** * Returns the bits of a non-negative {@code int}. The {@link Iterable} returned is little-endian; the least- * significant bits come first. Zero gives an empty {@code Iterable}. There are no trailing unset bits. Does not * support removal. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable}, containing no nulls. If it is non-empty, the last element is * {@code true}.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>2</sub>{@code n}⌋+1 otherwise * * @param n a number * @return {@code n}'s bits in little-endian order */ public static @NotNull Iterable<Boolean> bits(int n) { if (n < 0) throw new ArithmeticException("cannot get bits of a negative number"); return () -> new Iterator<Boolean>() { private int remaining = n; @Override public boolean hasNext() { return remaining != 0; } @Override public Boolean next() { boolean bit = (remaining & 1) == 1; remaining >>= 1; return bit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns the bits of a non-negative {@link BigInteger}. The {@code Iterable} returned is little-endian; the * least-significant bits come first. Zero gives an empty {@code Iterable}. There are no trailing unset bits. * Does not support removal. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable}, containing no nulls. If it is non-empty, the last element is * {@code true}.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>2</sub>{@code n}⌋+1 otherwise * * @param n a number * @return {@code n}'s bits in little-endian order */ public static @NotNull Iterable<Boolean> bits(@NotNull BigInteger n) { if (n.signum() == -1) throw new ArithmeticException("cannot get bits of a negative number"); return () -> new Iterator<Boolean>() { private BigInteger remaining = n; @Override public boolean hasNext() { return !remaining.equals(BigInteger.ZERO); } @Override public Boolean next() { boolean bit = remaining.testBit(0); remaining = remaining.shiftRight(1); return bit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns the lowest {@code n} bits of a non-negative {@code int}. The {@code Iterable} returned is little-endian * the least-significant bits come first. It is exactly {@code n} bits long, and right-padded with zeroes (falses) * if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} containing no nulls.</li> * </ul> * * Result length is {@code length} * * @param length the number of bits returned * @param n a number * @return {@code n}'s bits in little-endian order */ public static @NotNull Iterable<Boolean> bitsPadded(int length, int n) { if (length < 0) throw new ArithmeticException("cannot pad with a negative length"); return pad(false, length, bits(n)); } /** * Returns the lowest {@code n} bits of a non-negative {@code BigInteger}. The {@code Iterable} returned is little- * endian; the least-significant bits come first. It is exactly {@code n} bits long, and right-padded with zeroes * (falses) if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} containing no nulls.</li> * </ul> * * Result length is {@code length} * * @param length the number of bits returned * @param n a number * @return {@code n}'s bits in little-endian order */ public static @NotNull Iterable<Boolean> bitsPadded(int length, @NotNull BigInteger n) { if (length < 0) throw new ArithmeticException("cannot pad with a negative length"); return pad(false, length, bits(n)); } /** * Returns the bits of a non-negative {@code int}. The {@code Iterable} returned is big-endian; the most- * significant bits come first. Zero gives an empty {@code Iterable}. There are no leading unset bits. Does not * support removal. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable}, containing no nullsIf it is non-empty, the first element is * {@code true}.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>2</sub>{@code n}⌋+1 otherwise * * @param n a number * @return {@code n}'s bits in big-endian order */ public static @NotNull Iterable<Boolean> bigEndianBits(int n) { return reverse(bits(n)); } /** * Returns the bits of a non-negative {@code BigInteger}. The {@code Iterable} returned is big-endian; the most- * significant bits come first. Zero gives an empty {@code Iterable}. There are no leading unset bits. Does not * support removal. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable}, containing no nullsIf it is non-empty, the first element is * {@code true}.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>2</sub>{@code n}⌋+1 otherwise * * @param n a number * @return {@code n}'s bits in big-endian order */ public static @NotNull Iterable<Boolean> bigEndianBits(@NotNull BigInteger n) { return reverse(bits(n)); } /** * Returns the lowest {@code n} bits of a non-negative {@code int}. The {@code Iterable} returned is big-endian; * the most-significant bits come first. It is exactly {@code n} bits long, and left-padded with zeroes (falses) if * necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} containing no nulls.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param n a number * @return {@code n}'s bits in big-endian order */ public static @NotNull Iterable<Boolean> bigEndianBitsPadded(int length, int n) { return reverse(bitsPadded(length, n)); } /** * Returns the lowest {@code n} bits of a non-negative {@code BigInteger}. The {@code Iterable} returned is big- * endian; the most-significant bits come first. It is exactly {@code n} bits long, and left-padded with zeroes * (falses) if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} containing no nulls.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param n a number * @return {@code n}'s bits in big-endian order */ public static @NotNull Iterable<Boolean> bigEndianBitsPadded(int length, BigInteger n) { return reverse(bitsPadded(length, n)); } /** * Builds a {@code BigInteger} from an {@code Iterable} of bits in big-endian order (most significant bits first). * Leading zero (false) bits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code bits} must be finite and every element must be non-null.</li> * <li>The result is non-negative.</li> * </ul> * * @param bits an {@code Iterable} of bits in big-endian order * @return The {@code BigInteger} represented by {@code bits} */ public static @NotNull BigInteger fromBigEndianBits(@NotNull Iterable<Boolean> bits) { BigInteger n = BigInteger.ZERO; for (boolean bit : bits) { n = n.shiftLeft(1); if (bit) n = n.add(BigInteger.ONE); } return n; } /** * Builds a {@code BigInteger} from an {@code Iterable} of bits in little-endian order (least significant bits * first). Trailing zero (false) bits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code bits} must be finite and every element must be non-null.</li> * <li>The result is non-negative.</li> * </ul> * * @param bits an {@code Iterable} of bits in little-endian order * @return The {@code BigInteger} represented by {@code bits} */ public static @NotNull BigInteger fromBits(@NotNull Iterable<Boolean> bits) { return fromBigEndianBits(reverse(bits)); } /** * Returns the digits of a non-negative {@code int}. The {@code Iterable} returned is little-endian; the least- * significant digits come first. Zero gives an empty {@code Iterable}. There are no trailing zero digits. Does not * support removal. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and whose last element (if it * exists) is non-zero.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>{@code base}</sub>{@code n}⌋+1 otherwise * * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in little-endian order */ public static @NotNull Iterable<Integer> digits(int base, int n) { if (base < 2) throw new IllegalArgumentException("base must be at least 2"); if (n < 0) throw new ArithmeticException("cannot get digits of a negative number"); return () -> new Iterator<Integer>() { private int remaining = n; @Override public boolean hasNext() { return remaining != 0; } @Override public Integer next() { int digit = remaining % base; remaining /= base; return digit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns the digits of a non-negative {@code BigInteger}. The {@code Iterable} returned is little-endian; the * least-significant digits come first. Zero gives an empty {@code Iterable}. There are no trailing zero digits. * Does not support removal. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and whose last element (if it * exists) is non-zero.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>{@code base}</sub>{@code n}⌋+1 otherwise * * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in little-endian order */ public static @NotNull Iterable<BigInteger> digits(@NotNull BigInteger base, @NotNull final BigInteger n) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); if (n.signum() == -1) throw new ArithmeticException("cannot get digits of a negative number"); return () -> new Iterator<BigInteger>() { private BigInteger remaining = n; @Override public boolean hasNext() { return !remaining.equals(BigInteger.ZERO); } @Override public BigInteger next() { BigInteger digit = remaining.mod(base); remaining = remaining.divide(base); return digit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns the lowest {@code n} digits of a non-negative {@code int}. The {@code Iterable} returned is little- * endian; the least-significant digits come first. It is exactly {@code n} digits long, and left-padded with * zeroes if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and less than * 2<sup>31</sup>–1.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in little-endian order */ public static @NotNull Iterable<Integer> digitsPadded(int length, int base, int n) { return pad(0, length, digits(base, n)); } /** * Returns the lowest {@code n} digits of a non-negative {@code int}. The {@code Iterable} returned is little- * endian; the least-significant digits come first. It is exactly {@code n} digits long, and left-padded with * zeroes if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in little-endian order */ public static @NotNull Iterable<BigInteger> digitsPadded( @NotNull BigInteger length, @NotNull BigInteger base, @NotNull BigInteger n ) { return pad(BigInteger.ZERO, length, digits(base, n)); } /** * Returns the digits of a non-negative {@code int}. The {@code Iterable} returned is big-endian; the most- * significant digits come first. Zero gives an empty {@code Iterable}. There are no leading zero digits. Does not * support removal. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and whose first element (if it * exists) is non-zero.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>{@code base}</sub>{@code n}⌋ otherwise * * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in big-endian order */ public static @NotNull List<Integer> bigEndianDigits(int base, final int n) { return reverse(digits(base, n)); } /** * Returns the digits of a non-negative {@code BigInteger}. The {@code Iterable} returned is big-endian; the most- * significant digits come first. Zero gives an empty {@code Iterable}. There are no leading zero digits. Does not * support removal. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and whose first element (if it * exists) is non-zero.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>{@code base}</sub>{@code n}⌋ otherwise * * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in big-endian order */ public static @NotNull List<BigInteger> bigEndianDigits(@NotNull BigInteger base, final @NotNull BigInteger n) { return reverse(digits(base, n)); } /** * Returns the lowest {@code n} digits of a non-negative {@code int}. The {@code Iterable} returned is big-endian; * the least-significant digits come first. It is exactly {@code n} digits long, and right-padded with zeroes if * necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and less than * 2<sup>31</sup>–1.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in big-endian order */ public static @NotNull Iterable<Integer> bigEndianDigitsPadded(int length, int base, int n) { return reverse(digitsPadded(length, base, n)); } /** * Returns the lowest {@code n} digits of a non-negative {@code BigInteger}. The {@code Iterable} returned is big- * endian; the least-significant digits come first. It is exactly {@code n} digits long, and right-padded with * zeroes if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and less than * 2<sup>31</sup>–1.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in big-endian order */ public static @NotNull Iterable<BigInteger> bigEndianDigitsPadded( @NotNull BigInteger length, @NotNull BigInteger base, @NotNull BigInteger n ) { return reverse(digitsPadded(length, base, n)); } /** * Builds a {@code BigInteger} from an {@code Iterable} of digits in big-endian order (most-significant digits * first). Leading zero digits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code digits} must be finite, and each element must be non-negative.</li> * <li>Every element of {@code digits} must be less than {@code base}.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the input digits * @param digits an {@code Iterable} of digits in big-endian order * @return The {@code BigInteger} represented by {@code digits} */ public static @NotNull BigInteger fromBigEndianDigits(int base, @NotNull Iterable<Integer> digits) { if (base < 2) throw new IllegalArgumentException("base must be at least 2"); BigInteger n = BigInteger.ZERO; for (int digit : digits) { if (digit < 0 || digit >= base) throw new IllegalArgumentException("every digit must be at least zero and less than the base"); n = n.multiply(BigInteger.valueOf(base)).add(BigInteger.valueOf(digit)); } return n; } /** * Builds a {@code BigInteger} from an {@code Iterable} of digits in big-endian order (most-significant digits * first). Leading zero digits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code digits} must be finite, and each element must be non-negative.</li> * <li>Every element of {@code digits} must be less than {@code base}.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the input digits * @param digits an {@code Iterable} of digits in big-endian order * @return The {@code BigInteger} represented by {@code digits} */ public static @NotNull BigInteger fromBigEndianDigits( @NotNull BigInteger base, @NotNull Iterable<BigInteger> digits ) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); BigInteger n = BigInteger.ZERO; for (BigInteger digit : digits) { if (digit.signum() == -1 || ge(digit, base)) throw new IllegalArgumentException("every digit must be at least zero and less than the base"); n = n.multiply(base).add(digit); } return n; } /** * Builds a {@code BigInteger} from an {@code Iterable} of digits in little-endian order (least-significant digits * first). Trailing zero digits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code digits} must be finite, and each element must be non-negative.</li> * <li>Every element of {@code digits} must be less than {@code base}.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the input digits * @param digits an {@code Iterable} of digits in little-endian order * @return The {@code BigInteger} represented by {@code digits} */ public static @NotNull BigInteger fromDigits(int base, @NotNull Iterable<Integer> digits) { return fromBigEndianDigits(base, reverse(digits)); } /** * Builds a {@code BigInteger} from an {@code Iterable} of digits in little-endian order (least-significant digits * first). Trailing zero digits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code digits} must be finite, and each element must be non-negative.</li> * <li>Every element of {@code digits} must be less than {@code base}.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the input digits * @param digits an {@code Iterable} of digits in little-endian order * @return The {@code BigInteger} represented by {@code digits} */ public static @NotNull BigInteger fromDigits(@NotNull BigInteger base, @NotNull Iterable<BigInteger> digits) { return fromBigEndianDigits(base, reverse(digits)); } /** * Converts a digit to its {@code char} representation. The digits 0 through 9 and converted to '0' through '9', * and the digits 11 through 35 are converted to 'A' through 'Z'. * * <ul> * <li>{@code i} must be non-negative and less than 36.</li> * <li>The result is between '0' and '9', inclusive, or between 'A' and 'Z', inclusive.</li> * </ul> * * @param i the digit to be converted * @return the {@code char} representation of {@code i} */ public static char toDigit(int i) { if (i >= 0 && i <= 9) { return (char) ('0' + i); } else if (i >= 10 && i < 36) { return (char) ('A' + i - 10); } else { throw new IllegalArgumentException("digit value must be between 0 and 35, inclusive"); } } /** * Returns the digit corresponding to a {@code char}. The {@code char}s '0' through '9' are mapped to 0 through 9, * and the {@code char}s 'A' through 'Z' are mapped to 10 through 35. * * <ul> * <li>{@code c} must be between '0' and '9', inclusive, or between 'A' and 'Z', inclusive.</li> * <li>The result is non-negative and less than 36.</li> * </ul> * * @param c a {@code char} corresponding to a digit * @return the digit that {@code c} corresponds to */ public static int fromDigit(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'A' && c <= 'Z') { return c - 'A' + 10; } else { throw new IllegalArgumentException("char must be between '0' and '9' or between 'A' and 'Z'"); } } /** * Converts an {@code int} to a {@code String} in any base greater than 1. If the base is 36 or less, the digits * are '0' through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written in * decimal and each digit is surrounded by parentheses. Zero is represented by "0" if the base is 36 or less, or * "(0)" otherwise. In every other case there are no leading zeroes. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-null.</li> * <li>The result is a {@code String} which is nonempty and either composed of the characters '0'–'9' and 'A'–'Z' * (not starting with '0', unless that is the only character), or is the concatenation of some non-negative * numbers from 0 to 2<sup>31</sup>–1 surrounded by parentheses (not starting with "(0)", unless that is the only * number). In either case there may be an optional leading '-'.</li> * </ul> * * @param base the base of the output digits * @param n a number * @return a {@code String} representation of {@code n} in base {@code base} */ public static @NotNull String toStringBase(int base, int n) { if (base < 2) throw new IllegalArgumentException("base must be at least 2"); boolean bigBase = base > 36; if (n == 0) { return bigBase ? "(0)" : "0"; } boolean negative = n < 0; if (negative) n = -n; List<Integer> digits = bigEndianDigits(base, n); String absString; if (bigBase) { absString = concatStrings(map(d -> "(" + d + ")", digits)); } else { absString = charsToString(map(MathUtils::toDigit, digits)); } return negative ? cons('-', absString) : absString; } /** * Converts a {@code BigInteger} to a {@code String} in any base greater than 1. If the base is 36 or less, the * digits are '0' through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written * in decimal and each digit is surrounded by parentheses. Zero is represented by "0" if the base is 36 or less, or * "(0)" otherwise. In every other case there are no leading zeroes. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-null.</li> * <li>The result is a {@code String} which is nonempty and either composed of the characters '0'–'9' and 'A'–'Z' * (not starting with '0', unless that is the only character), or is the concatenation of some non-negative * numbers surrounded by parentheses (not starting with "(0)", unless that is the only number). In either case * there may be an optional leading '-'.</li> * </ul> * * @param base the base of the output digits * @param n a number * @return a {@code String} representation of {@code n} in base {@code base} */ public static @NotNull String toStringBase(@NotNull BigInteger base, @NotNull BigInteger n) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); boolean bigBase = gt(base, BigInteger.valueOf(36)); if (n.equals(BigInteger.ZERO)) { return bigBase ? "(0)" : "0"; } boolean negative = n.signum() == -1; if (negative) n = n.negate(); List<BigInteger> digits = bigEndianDigits(base, n); String absString; if (bigBase) { absString = concatStrings(map(d -> "(" + d + ")", digits)); } else { absString = charsToString(map(d -> toDigit(d.intValue()), digits)); } return negative ? cons('-', absString) : absString; } /** * Converts a {@code String} written in some base to a number. If the base is 36 or less, the digits are '0' * through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written in decimal and * each digit is surrounded by parentheses. The empty {@code String} represents 0. Leading zeroes are permitted. If * the {@code String} is invalid, an exception is thrown. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code s} must either be composed of the digits '0' through '9' and 'A' through 'Z', or a sequence of * non-negative decimal integers, each surrounded by parentheses. In either case there may be an optional leading * '-'. {@code s} may also be empty, but "-" is not permitted.</li> * <li>If {@code base} is between 2 and 36, {@code s} may only include the corresponding characters, and the * optional leading '-'. If {@code base} is greater than 36, {@code s} must be composed of decimal integers * surrounded by parentheses (with the optional leading '-'), each integer being non-negative and less than * {@code base}.</li> * <li>The result is non-null.</li> * </ul> * * @param base the base that the {@code s} is written in * @param s the input {@code String} * @return the number represented by {@code s} */ public static @NotNull BigInteger fromStringBase(int base, @NotNull String s) { if (base < 2) throw new IllegalArgumentException("base must be at least 2"); if (s.isEmpty()) return BigInteger.ZERO; boolean negative = false; if (head(s) == '-') { s = tail(s); if (s.isEmpty()) throw new IllegalArgumentException("improperly-formatted String"); negative = true; } List<Integer> digits; if (base <= 36) { digits = toList(map(MathUtils::fromDigit, fromString(s))); } else { if (head(s) != '(' || last(s) != ')') throw new IllegalArgumentException("improperly-formatted String"); s = tail(init(s)); digits = toList(map(Integer::parseInt, Arrays.asList(s.split("\\)\\(")))); } BigInteger result = fromBigEndianDigits(base, digits); return negative ? result.negate() : result; } /** * Converts a {@code String} written in some base to a number. If the base is 36 or less, the digits are '0' * through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written in decimal and * each digit is surrounded by parentheses. The empty {@code String} represents 0. Leading zeroes are permitted. If * the {@code String} is invalid, an exception is thrown. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code s} must either be composed of the digits '0' through '9' and 'A' through 'Z', or a sequence of * non-negative decimal integers, each surrounded by parentheses. In either case there may be an optional leading * '-'. {@code s} may also be empty, but "-" is not permitted.</li> * <li>If {@code base} is between 2 and 36, {@code s} may only include the corresponding characters, and the * optional leading '-'. If {@code base} is greater than 36, {@code s} must be composed of decimal integers * surrounded by parentheses (with the optional leading '-'), each integer being non-negative and less than * {@code base}.</li> * <li>The result is non-null.</li> * </ul> * * @param base the base that the {@code s} is written in * @param s the input {@code String} * @return the number represented by {@code s} */ public static @NotNull BigInteger fromStringBase(@NotNull BigInteger base, @NotNull String s) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); if (s.isEmpty()) return BigInteger.ZERO; boolean negative = false; if (head(s) == '-') { s = tail(s); if (s.isEmpty()) throw new IllegalArgumentException("improperly-formatted String"); negative = true; } List<BigInteger> digits; if (le(base, BigInteger.valueOf(36))) { digits = toList(map(c -> BigInteger.valueOf(fromDigit(c)), fromString(s))); } else { if (head(s) != '(' || last(s) != ')') throw new IllegalArgumentException("improperly-formatted String"); s = tail(init(s)); digits = toList(map(BigInteger::new, Arrays.asList(s.split("\\)\\(")))); } BigInteger result = fromBigEndianDigits(base, digits); return negative ? result.negate() : result; } /** * Bijectively maps two natural {@code BigInteger}s to one natural {@code BigInteger} in such a way that the result * is O({@code x}2<sup>{@code y}</sup>). In other words, the contribution of {@code x} is approximately the base-2 * log of the contribution of {@code y}. The inverse of this method is * {@link mho.wheels.math.MathUtils#logarithmicDemux}. * * <ul> * <li>{@code x} must be non-negative.</li> * <li>{@code y} must be non-negative.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first {@code BigInteger} * @param y the second {@code BigInteger} * @return a {@code BigInteger} generated bijectively from {@code x} and {@code y} */ public static @NotNull BigInteger logarithmicMux(@NotNull BigInteger x, @NotNull BigInteger y) { if (x.signum() == -1 || y.signum() == -1) throw new ArithmeticException("neither integer can be negative"); return x.shiftLeft(1).add(BigInteger.ONE).shiftLeft(y.intValueExact()).subtract(BigInteger.ONE); } /** * Bijectively maps one natural {@code BigInteger} to two natural {@code BigInteger}s in such a way that the second * is "typically" about the base-2 log of the first. More precisely, this method is the inverse of * {@link mho.wheels.math.MathUtils#logarithmicMux}. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is non-null and both of its elements are non-negative.</li> * </ul> * * @param n a {@code BigInteger} * @return a pair of {@code BigInteger}s generated bijectively from {@code n} */ public static @NotNull Pair<BigInteger, BigInteger> logarithmicDemux(@NotNull BigInteger n) { if (n.signum() == -1) throw new ArithmeticException("input cannot be negative"); n = n.add(BigInteger.ONE); int exp = n.getLowestSetBit(); return new Pair<>(n.shiftRight(exp + 1), BigInteger.valueOf(exp)); } /** * Bijectively maps two natural {@code BigInteger}s to one natural {@code BigInteger} in such a way that the result * is O({@code x}{@code y}<sup>2</sup>). In other words, the contribution of {@code x} is approximately the square * root of the contribution of {@code y}. The inverse of this method is * {@link mho.wheels.math.MathUtils#squareRootDemux}. * * <ul> * <li>{@code x} must be non-negative.</li> * <li>{@code y} must be non-negative.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first {@code BigInteger} * @param y the second {@code BigInteger} * @return a {@code BigInteger} generated bijectively from {@code x} and {@code y} */ public static @NotNull BigInteger squareRootMux(@NotNull BigInteger x, @NotNull BigInteger y) { List<Boolean> xBits = toList(bits(x)); List<Boolean> yBits = toList(bits(y)); int outputSize = max(xBits.size(), yBits.size()) * 3; Iterable<Iterable<Boolean>> xChunks = map(w -> w, chunk(2, concat(xBits, repeat(false)))); Iterable<Iterable<Boolean>> yChunks = map(Arrays::asList, concat(yBits, repeat(false))); return fromBits(take(outputSize, concat(IterableUtils.mux(Arrays.asList(yChunks, xChunks))))); } /** * Bijectively maps one natural {@code BigInteger} to two natural {@code BigInteger}s in such a way that the second * is "typically" about the square root of the first. More precisely, this method is the inverse of * {@link mho.wheels.math.MathUtils#squareRootMux}. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is non-null and both of its elements are non-negative.</li> * </ul> * * @param n a {@code BigInteger} * @return a pair of {@code BigInteger}s generated bijectively from {@code n} */ public static @NotNull Pair<BigInteger, BigInteger> squareRootDemux(@NotNull BigInteger n) { List<Boolean> bits = toList(bits(n)); Iterable<Boolean> xMask = cycle(Arrays.asList(false, true, true)); Iterable<Boolean> yMask = cycle(Arrays.asList(true, false, false)); return new Pair<>(fromBits(select(xMask, bits)), fromBits(select(yMask, bits))); } /** * Bijectively maps a list of natural {@code BigInteger}s to one natural {@code BigInteger} in such a way that the * result is O(max({@code xs})<sup>|{@code xs}|</sup>), so the contribution of each element of {@code xs} is * approximately equal. The bijection is between the naturals and list of a fixed size, not all lists. The empty * list maps to 0. The inverse of this method is {@link mho.wheels.math.MathUtils#demux}. * * <ul> * <li>Every element of {@code xs} must be non-negative.</li> * <li>The result is non-negative.</li> * </ul> * * @param xs the list of {@code BigInteger}s * @return a {@code BigInteger} generated bijectively from {@code xs} */ public static @NotNull BigInteger mux(@NotNull List<BigInteger> xs) { if (xs.isEmpty()) return BigInteger.ZERO; Iterable<Boolean> muxedBits = IterableUtils.mux(toList(map(x -> concat(bits(x), repeat(false)), reverse(xs)))); int outputSize = maximum(map(BigInteger::bitLength, xs)) * xs.size(); return fromBits(take(outputSize, muxedBits)); } /** * Bijectively maps one natural {@code BigInteger} to a list of natural {@code BigInteger}s in such a way that * every element of the list is "typically" about the same size. More precisely, this method is the inverse of * {@link mho.wheels.math.MathUtils#mux}. The bijection is between the naturals and list of a fixed size, not all * lists. If {@code lines} is 0, the only acceptable {@code n} is 0, which maps to the empty list. The inverse of * this method is {@link mho.wheels.math.MathUtils#mux}. * * <ul> * <li>{@code lines} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>If {@code lines} is 0, {@code n} must also be 0.</li> * <li>The result is non-null and all of its elements are non-negative.</li> * </ul> * * @param lines the number of {@code BigIntegers} to map {@code n} to * @param n a {@code BigInteger} * @return a list of {@code BigInteger}s generated bijectively from {@code n} */ public static @NotNull List<BigInteger> demux(int lines, @NotNull BigInteger n) { if (lines == 0 && !n.equals(BigInteger.ZERO)) throw new ArithmeticException("if muxing into 0 lines, n must also be 0"); if (lines < 0) throw new ArithmeticException("cannot demux into a negative number of lines"); if (n.equals(BigInteger.ZERO)) { return toList(replicate(lines, BigInteger.ZERO)); } return reverse(IterableUtils.map(MathUtils::fromBits, IterableUtils.demux(lines, bits(n)))); } public static boolean isAPowerOfTwo(@NotNull BigInteger n) { return n.getLowestSetBit() == n.bitLength() - 1; } public static @NotNull BigInteger fastGrowingCeilingInverse( @NotNull Function<BigInteger, BigInteger> f, @NotNull BigInteger y, @NotNull BigInteger min, @NotNull BigInteger max ) { for (BigInteger x : range(min, max)) { BigInteger j = f.apply(x); if (ge(j, y)) { return x; } } throw new IllegalArgumentException("inverse not found in range"); } public static @NotNull BigInteger ceilingLog(@NotNull BigInteger base, @NotNull BigInteger x) { //noinspection SuspiciousNameCombination return fastGrowingCeilingInverse( i -> base.pow(i.intValueExact()), x, BigInteger.ONE, x //very loose bound ); } public static @NotNull BigInteger ceilingInverse( @NotNull Function<BigInteger, BigInteger> f, @NotNull BigInteger y, @NotNull BigInteger min, @NotNull BigInteger max ) { while (true) { if (min.equals(max)) return max; BigInteger mid = min.add(max).shiftRight(1); BigInteger fMid = f.apply(mid); switch (compare(fMid, y)) { case GT: max = mid; break; case LT: min = mid.add(BigInteger.ONE); break; default: return mid; } } } public static @NotNull BigInteger ceilingRoot(@NotNull BigInteger r, @NotNull BigInteger x) { //noinspection SuspiciousNameCombination return ceilingInverse( i -> i.pow(r.intValueExact()), x, BigInteger.ZERO, x //very loose bound ); } public static int smallestPrimeFactor(int n) { if (n < 2) throw new IllegalArgumentException("argument must be at least 2"); if (n % 2 == 0) return 2; if (n < PRIME_SIEVE_SIZE && PRIME_SIEVE.get(n)) return n; for (int i = 3; ; i += 2) { int square = i * i; if (square > n || square < 0) break; if (PRIME_SIEVE.get(i) && n % i == 0) return i; } return n; } public static @NotNull BigInteger smallestPrimeFactor(@NotNull BigInteger n) { if (le(n, BigInteger.valueOf(Integer.MAX_VALUE))) { return BigInteger.valueOf(smallestPrimeFactor(n.intValueExact())); } if (!n.testBit(0)) return BigInteger.valueOf(2); for (int i = 3; i < PRIME_SIEVE_SIZE; i += 2) { BigInteger bi = BigInteger.valueOf(i); if (gt(bi.pow(2), n)) return n; if (PRIME_SIEVE.get(i) && n.mod(bi).equals(BigInteger.ZERO)) return bi; } BigInteger limit = ceilingRoot(BigInteger.valueOf(2), n); Iterable<BigInteger> candidates = concatMap( i -> { BigInteger sixI = i.multiply(BigInteger.valueOf(6)); return Arrays.asList(sixI.subtract(BigInteger.ONE), sixI.add(BigInteger.ONE)); }, range(BigInteger.valueOf(PRIME_SIEVE_SIZE / 6)) ); for (BigInteger candidate : takeWhile(i -> le(i, limit), candidates)) { if (n.mod(candidate).equals(BigInteger.ZERO)) return candidate; } return n; } public static boolean isPrime(int n) { return smallestPrimeFactor(n) == n; } public static boolean isPrime(@NotNull BigInteger n) { return smallestPrimeFactor(n).equals(n); } public static @NotNull Iterable<Integer> primeFactors(int n) { return unfoldr( i -> { if (i == 1) return Optional.empty(); int spf = smallestPrimeFactor(i); return Optional.of(new Pair<>(spf, i / spf)); }, n ); } public static @NotNull Iterable<BigInteger> primeFactors(@NotNull BigInteger n) { return unfoldr( i -> { if (i.equals(BigInteger.ONE)) return Optional.empty(); BigInteger spf = smallestPrimeFactor(i); return Optional.of(new Pair<>(spf, i.divide(spf))); }, n ); } public static @NotNull Iterable<Pair<Integer, Integer>> compactPrimeFactors(int n) { return countAdjacent(primeFactors(n)); } public static @NotNull Iterable<Pair<BigInteger, Integer>> compactPrimeFactors(@NotNull BigInteger n) { return countAdjacent(primeFactors(n)); } public static @NotNull List<Integer> factors(int n) { List<Pair<Integer, Integer>> cpf = toList(compactPrimeFactors(n)); Iterable<List<Integer>> possibleExponents = Combinatorics.controlledListsIncreasing( toList(map(p -> range(0, p.b), cpf)) ); Function<List<Integer>, Integer> f = exponents -> productInteger( zipWith(p -> BigInteger.valueOf(p.a).pow(p.b).intValueExact(), map(q -> q.a, cpf), exponents) ); return sort(map(f, possibleExponents)); } public static @NotNull List<BigInteger> factors(@NotNull BigInteger n) { List<Pair<BigInteger, Integer>> cpf = toList(compactPrimeFactors(n)); Iterable<List<Integer>> possibleExponents = Combinatorics.controlledListsIncreasing( toList(map(p -> range(0, p.b), cpf)) ); Function<List<Integer>, BigInteger> f = exponents -> productBigInteger( zipWith(p -> { assert p.a != null; assert p.b != null; return p.a.pow(p.b); }, map(q -> q.a, cpf), exponents) ); return sort(map(f, possibleExponents)); } public static @NotNull Iterable<Integer> intPrimes() { int start = (PRIME_SIEVE_SIZE & 1) == 0 ? PRIME_SIEVE_SIZE + 1 : PRIME_SIEVE_SIZE; return concat( filter(PRIME_SIEVE::get, range(2, PRIME_SIEVE_SIZE - 1)), filter(MathUtils::isPrime, rangeBy(start, 2)) ); } public static @NotNull Iterable<BigInteger> primes() { Iterable<BigInteger> candidates = concatMap( i -> { BigInteger sixI = i.multiply(BigInteger.valueOf(6)); return Arrays.asList(sixI.subtract(BigInteger.ONE), sixI.add(BigInteger.ONE)); }, range(BigInteger.valueOf(PRIME_SIEVE_SIZE / 6)) ); return concat(map(i -> BigInteger.valueOf(i), intPrimes()), filter(MathUtils::isPrime, candidates)); } }
src/main/java/mho/wheels/math/MathUtils.java
package mho.wheels.math; import mho.wheels.iterables.IterableUtils; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import java.math.BigInteger; import java.util.*; import java.util.function.Function; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; /** * Some mathematical utilities */ public final class MathUtils { /** * The size of {@link mho.wheels.math.MathUtils#PRIME_SIEVE}. Must be greater than or equal to * ⌈sqrt({@code Integer.MAX_VALUE})⌉ = 46,341 */ private static final int PRIME_SIEVE_SIZE = 1 << 16; /** * A cache of small primes, generated using the Sieve of Eratosthenes algorithm. */ private static final BitSet PRIME_SIEVE; static { PRIME_SIEVE = new BitSet(PRIME_SIEVE_SIZE); PRIME_SIEVE.set(2, PRIME_SIEVE_SIZE - 1); int multiple; for (multiple = 0; multiple < PRIME_SIEVE_SIZE; multiple++) { while (!PRIME_SIEVE.get(multiple) && multiple < PRIME_SIEVE_SIZE) multiple++; for (int i : rangeBy(multiple * 2, multiple, PRIME_SIEVE_SIZE - 1)) { PRIME_SIEVE.clear(i); } } } /** * Disallow instantiation */ private MathUtils() {} /** * The greatest common divisor of two {@link int}s. If both {@code x} and {@code y} are zero, the result is * undefined. Otherwise, the result is positive. * * <ul> * <li>{@code x} may be any {@code int}.</li> * <li>{@code y} may be any {@code int}.</li> * <li>{@code x} and {@code y} y may not both be zero.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first number * @param y the second number * @return gcd(x, y) */ public static int gcd(int x, int y) { if (x == 0 && y == 0) throw new ArithmeticException("cannot take gcd of 0 and 0"); return positiveGcd(Math.abs(x), Math.abs(y)); } /** * The greatest common divisor of two non-negative {@code int}s. * * <ul> * <li>{@code x} must be non-negative.</li> * <li>{@code y} must be non-negative.</li> * <li>{@code x} and {@code y} y may not both be zero.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first number * @param y the second number * @return gcd(x, y) */ private static int positiveGcd(int x, int y) { //noinspection SuspiciousNameCombination return y == 0 ? x : positiveGcd(y, x % y); } /** * The greatest common divisor of two {@link long}s. If both {@code x} and {@code y} are zero, the result is * undefined. Otherwise, the result is positive. * * <ul> * <li>{@code x} may be any {@code long}.</li> * <li>{@code y} may be any {@code long}.</li> * <li>{@code x} and {@code y} y may not both be zero.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first number * @param y the second number * @return gcd(x, y) */ public static long gcd(long x, long y) { if (x == 0 && y == 0) throw new ArithmeticException("cannot take gcd of 0 and 0"); return positiveGcd(Math.abs(x), Math.abs(y)); } /** * The greatest common divisor of two non-negative {@code long}s. * * <ul> * <li>{@code x} must be non-negative.</li> * <li>{@code y} must be non-negative.</li> * <li>{@code x} and {@code y} y may not both be zero.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first number * @param y the second number * @return gcd(x, y) */ private static long positiveGcd(long x, long y) { //noinspection SuspiciousNameCombination return y == 0 ? x : positiveGcd(y, x % y); } /** * Returns the bits of a non-negative {@code int}. The {@link Iterable} returned is little-endian; the least- * significant bits come first. Zero gives an empty {@code Iterable}. There are no trailing unset bits. Does not * support removal. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable}, containing no nulls, ending with {@code true}.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>2</sub>{@code n}⌋+1 otherwise * * @param n a number * @return {@code n}'s bits in little-endian order */ public static @NotNull Iterable<Boolean> bits(int n) { if (n < 0) throw new ArithmeticException("cannot get bits of a negative number"); return () -> new Iterator<Boolean>() { private int remaining = n; @Override public boolean hasNext() { return remaining != 0; } @Override public Boolean next() { boolean bit = (remaining & 1) == 1; remaining >>= 1; return bit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns the bits of a non-negative {@link BigInteger}. The {@code Iterable} returned is little-endian; the * least-significant bits come first. Zero gives an empty {@code Iterable}. There are no trailing unset bits. * Does not support removal. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable}, containing no nulls, ending with {@code true}.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>2</sub>{@code n}⌋+1 otherwise * * @param n a number * @return {@code n}'s bits in little-endian order */ public static @NotNull Iterable<Boolean> bits(@NotNull BigInteger n) { if (n.signum() == -1) throw new ArithmeticException("cannot get bits of a negative number"); return () -> new Iterator<Boolean>() { private BigInteger remaining = n; @Override public boolean hasNext() { return !remaining.equals(BigInteger.ZERO); } @Override public Boolean next() { boolean bit = remaining.testBit(0); remaining = remaining.shiftRight(1); return bit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns the lowest {@code n} bits of a non-negative {@code int}. The {@code Iterable} returned is little-endian * the least-significant bits come first. It is exactly {@code n} bits long, and right-padded with zeroes (falses) * if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} containing no nulls.</li> * </ul> * * Result length is {@code length} * * @param length the number of bits returned * @param n a number * @return {@code n}'s bits in little-endian order */ public static @NotNull Iterable<Boolean> bitsPadded(int length, int n) { if (length < 0) throw new ArithmeticException("cannot pad with a negative length"); return pad(false, length, bits(n)); } /** * Returns the lowest {@code n} bits of a non-negative {@code BigInteger}. The {@code Iterable} returned is little- * endian; the least-significant bits come first. It is exactly {@code n} bits long, and right-padded with zeroes * (falses) if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} containing no nulls.</li> * </ul> * * Result length is {@code length} * * @param length the number of bits returned * @param n a number * @return {@code n}'s bits in little-endian order */ public static @NotNull Iterable<Boolean> bitsPadded(int length, @NotNull BigInteger n) { if (length < 0) throw new ArithmeticException("cannot pad with a negative length"); return pad(false, length, bits(n)); } /** * Returns the bits of a non-negative {@code int}. The {@code Iterable} returned is big-endian; the most- * significant bits come first. Zero gives an empty {@code Iterable}. There are no leading unset bits. Does not * support removal. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable}, containing no nulls, beginning with {@code true}.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>2</sub>{@code n}⌋+1 otherwise * * @param n a number * @return {@code n}'s bits in big-endian order */ public static @NotNull Iterable<Boolean> bigEndianBits(int n) { return reverse(bits(n)); } /** * Returns the bits of a non-negative {@code BigInteger}. The {@code Iterable} returned is big-endian; the most- * significant bits come first. Zero gives an empty {@code Iterable}. There are no leading unset bits. Does not * support removal. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable}, containing no nulls, beginning with {@code true}.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>2</sub>{@code n}⌋+1 otherwise * * @param n a number * @return {@code n}'s bits in big-endian order */ public static @NotNull Iterable<Boolean> bigEndianBits(@NotNull BigInteger n) { return reverse(bits(n)); } /** * Returns the lowest {@code n} bits of a non-negative {@code int}. The {@code Iterable} returned is big-endian; * the most-significant bits come first. It is exactly {@code n} bits long, and left-padded with zeroes (falses) if * necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} containing no nulls.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param n a number * @return {@code n}'s bits in big-endian order */ public static @NotNull Iterable<Boolean> bigEndianBitsPadded(int length, int n) { return reverse(bitsPadded(length, n)); } /** * Returns the lowest {@code n} bits of a non-negative {@code BigInteger}. The {@code Iterable} returned is big- * endian; the most-significant bits come first. It is exactly {@code n} bits long, and left-padded with zeroes * (falses) if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} containing no nulls.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param n a number * @return {@code n}'s bits in big-endian order */ public static @NotNull Iterable<Boolean> bigEndianBitsPadded(int length, BigInteger n) { return reverse(bitsPadded(length, n)); } /** * Builds a {@code BigInteger} from an {@code Iterable} of bits in big-endian order (most significant bits first). * Leading zero (false) bits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code bits} must be finite and every element must be non-null.</li> * <li>The result is non-negative.</li> * </ul> * * @param bits an {@code Iterable} of bits in big-endian order * @return The {@code BigInteger} represented by {@code bits} */ public static @NotNull BigInteger fromBigEndianBits(@NotNull Iterable<Boolean> bits) { BigInteger n = BigInteger.ZERO; for (boolean bit : bits) { n = n.shiftLeft(1); if (bit) n = n.add(BigInteger.ONE); } return n; } /** * Builds a {@code BigInteger} from an {@code Iterable} of bits in little-endian order (least significant bits * first). Trailing zero (false) bits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code bits} must be finite and every element must be non-null.</li> * <li>The result is non-negative.</li> * </ul> * * @param bits an {@code Iterable} of bits in little-endian order * @return The {@code BigInteger} represented by {@code bits} */ public static @NotNull BigInteger fromBits(@NotNull Iterable<Boolean> bits) { return fromBigEndianBits(reverse(bits)); } /** * Returns the digits of a non-negative {@code int}. The {@code Iterable} returned is little-endian; the least- * significant digits come first. Zero gives an empty {@code Iterable}. There are no trailing zero digits. Does not * support removal. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and whose last element is greater * than zero.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>{@code base}</sub>{@code n}⌋+1 otherwise * * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in little-endian order */ public static @NotNull Iterable<Integer> digits(int base, int n) { if (base < 2) throw new IllegalArgumentException("base must be at least 2"); if (n < 0) throw new ArithmeticException("cannot get digits of a negative number"); return () -> new Iterator<Integer>() { private int remaining = n; @Override public boolean hasNext() { return remaining != 0; } @Override public Integer next() { int digit = remaining % base; remaining /= base; return digit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns the digits of a non-negative {@code BigInteger}. The {@code Iterable} returned is little-endian; the * least-significant digits come first. Zero gives an empty {@code Iterable}. There are no trailing zero digits. * Does not support removal. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and whose last element is non- * zero.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>{@code base}</sub>{@code n}⌋+1 otherwise * * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in little-endian order */ public static @NotNull Iterable<BigInteger> digits(@NotNull BigInteger base, @NotNull final BigInteger n) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); if (n.signum() == -1) throw new ArithmeticException("cannot get digits of a negative number"); return () -> new Iterator<BigInteger>() { private BigInteger remaining = n; @Override public boolean hasNext() { return !remaining.equals(BigInteger.ZERO); } @Override public BigInteger next() { BigInteger digit = remaining.mod(base); remaining = remaining.divide(base); return digit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns the lowest {@code n} digits of a non-negative {@code int}. The {@code Iterable} returned is little- * endian; the least-significant digits come first. It is exactly {@code n} digits long, and left-padded with * zeroes if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and less than * 2<sup>31</sup>–1.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in little-endian order */ public static @NotNull Iterable<Integer> digitsPadded(int length, int base, int n) { return pad(0, length, digits(base, n)); } /** * Returns the lowest {@code n} digits of a non-negative {@code int}. The {@code Iterable} returned is little- * endian; the least-significant digits come first. It is exactly {@code n} digits long, and left-padded with * zeroes if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in little-endian order */ public static @NotNull Iterable<BigInteger> digitsPadded( @NotNull BigInteger length, @NotNull BigInteger base, @NotNull BigInteger n ) { return pad(BigInteger.ZERO, length, digits(base, n)); } /** * Returns the digits of a non-negative {@code int}. The {@code Iterable} returned is big-endian; the most- * significant digits come first. Zero gives an empty {@code Iterable}. There are no leading zero digits. Does not * support removal. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and whose first element is greater * than zero.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>{@code base}</sub>{@code n}⌋ otherwise * * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in big-endian order */ public static @NotNull List<Integer> bigEndianDigits(int base, final int n) { return reverse(digits(base, n)); } /** * Returns the digits of a non-negative {@code BigInteger}. The {@code Iterable} returned is big-endian; the most- * significant digits come first. Zero gives an empty {@code Iterable}. There are no leading zero digits. Does not * support removal. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and whose first element is greater * than zero.</li> * </ul> * * Result length is 0 if {@code n} is 0, or ⌊log<sub>{@code base}</sub>{@code n}⌋ otherwise * * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in big-endian order */ public static @NotNull List<BigInteger> bigEndianDigits(@NotNull BigInteger base, final @NotNull BigInteger n) { return reverse(digits(base, n)); } /** * Returns the lowest {@code n} digits of a non-negative {@code int}. The {@code Iterable} returned is big-endian; * the least-significant digits come first. It is exactly {@code n} digits long, and right-padded with zeroes if * necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and less than * 2<sup>31</sup>–1.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in big-endian order */ public static @NotNull Iterable<Integer> bigEndianDigitsPadded(int length, int base, int n) { return reverse(digitsPadded(length, base, n)); } /** * Returns the lowest {@code n} digits of a non-negative {@code BigInteger}. The {@code Iterable} returned is big- * endian; the least-significant digits come first. It is exactly {@code n} digits long, and right-padded with * zeroes if necessary. Does not support removal. * * <ul> * <li>{@code length} must be non-negative.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-negative.</li> * <li>The result is a finite {@code Iterable} whose elements are non-negative and less than * 2<sup>31</sup>–1.</li> * </ul> * * Result length is {@code length} * * @param length the number of digits returned * @param base the base of the output digits * @param n a number * @return {@code n}'s digits in big-endian order */ public static @NotNull Iterable<BigInteger> bigEndianDigitsPadded( @NotNull BigInteger length, @NotNull BigInteger base, @NotNull BigInteger n ) { return reverse(digitsPadded(length, base, n)); } /** * Builds a {@code BigInteger} from an {@code Iterable} of digits in big-endian order (most-significant digits * first). Leading zero digits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code digits} must be finite, and each element must be non-negative.</li> * <li>Every element of {@code digits} must be less than {@code base}.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the input digits * @param digits an {@code Iterable} of digits in big-endian order * @return The {@code BigInteger} represented by {@code digits} */ public static @NotNull BigInteger fromBigEndianDigits(int base, @NotNull Iterable<Integer> digits) { if (base < 2) throw new IllegalArgumentException("base must be at least 2"); BigInteger n = BigInteger.ZERO; for (int digit : digits) { if (digit < 0 || digit >= base) throw new IllegalArgumentException("every digit must be at least zero and less than the base"); n = n.multiply(BigInteger.valueOf(base)).add(BigInteger.valueOf(digit)); } return n; } /** * Builds a {@code BigInteger} from an {@code Iterable} of digits in big-endian order (most-significant digits * first). Leading zero digits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code digits} must be finite, and each element must be non-negative.</li> * <li>Every element of {@code digits} must be less than {@code base}.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the input digits * @param digits an {@code Iterable} of digits in big-endian order * @return The {@code BigInteger} represented by {@code digits} */ public static @NotNull BigInteger fromBigEndianDigits( @NotNull BigInteger base, @NotNull Iterable<BigInteger> digits ) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); BigInteger n = BigInteger.ZERO; for (BigInteger digit : digits) { if (digit.signum() == -1 || ge(digit, base)) throw new IllegalArgumentException("every digit must be at least zero and less than the base"); n = n.multiply(base).add(digit); } return n; } /** * Builds a {@code BigInteger} from an {@code Iterable} of digits in little-endian order (least-significant digits * first). Trailing zero digits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code digits} must be finite, and each element must be non-negative.</li> * <li>Every element of {@code digits} must be less than {@code base}.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the input digits * @param digits an {@code Iterable} of digits in little-endian order * @return The {@code BigInteger} represented by {@code digits} */ public static @NotNull BigInteger fromDigits(int base, @NotNull Iterable<Integer> digits) { return fromBigEndianDigits(base, reverse(digits)); } /** * Builds a {@code BigInteger} from an {@code Iterable} of digits in little-endian order (least-significant digits * first). Trailing zero digits are permitted. Zero may be represented by an empty {@code Iterable}. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code digits} must be finite, and each element must be non-negative.</li> * <li>Every element of {@code digits} must be less than {@code base}.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the input digits * @param digits an {@code Iterable} of digits in little-endian order * @return The {@code BigInteger} represented by {@code digits} */ public static @NotNull BigInteger fromDigits(@NotNull BigInteger base, @NotNull Iterable<BigInteger> digits) { return fromBigEndianDigits(base, reverse(digits)); } /** * Converts a digit to its {@code char} representation. The digits 0 through 9 and converted to '0' through '9', * and the digits 11 through 35 are converted to 'A' through 'Z'. * * <ul> * <li>{@code i} must be non-negative and less than 36.</li> * <li>The result is between '0' and '9', inclusive, or between 'A' and 'Z', inclusive.</li> * </ul> * * @param i the digit to be converted * @return the {@code char} representation of {@code i} */ public static char toDigit(int i) { if (i >= 0 && i <= 9) { return (char) ('0' + i); } else if (i >= 10 && i < 36) { return (char) ('A' + i - 10); } else { throw new IllegalArgumentException("digit value must be between 0 and 35, inclusive"); } } /** * Returns the digit corresponding to a {@code char}. The {@code char}s '0' through '9' are mapped to 0 through 9, * and the {@code char}s 'A' through 'Z' are mapped to 10 through 35. * * <ul> * <li>{@code c} must be between '0' and '9', inclusive, or between 'A' and 'Z', inclusive.</li> * <li>The result is non-negative and less than 36.</li> * </ul> * * @param c a {@code char} corresponding to a digit * @return the digit that {@code c} corresponds to */ public static int fromDigit(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'A' && c <= 'Z') { return c - 'A' + 10; } else { throw new IllegalArgumentException("char must be between '0' and '9' or between 'A' and 'Z'"); } } /** * Converts an {@code int} to a {@code String} in any base greater than 1. If the base is 36 or less, the digits * are '0' through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written in * decimal and each digit is surrounded by parentheses. Zero is represented by "0" if the base is 36 or less, or * "(0)" otherwise. In every other case there are no leading zeroes. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-null.</li> * <li>The result is a {@code String} which is nonempty and either composed of the characters '0'–'9' and 'A'–'Z' * (not starting with '0', unless that is the only character), or is the concatenation of some non-negative * numbers from 0 to 2<sup>31</sup>–1 surrounded by parentheses (not starting with "(0)", unless that is the only * number). In either case there may be an optional leading '-'.</li> * </ul> * * @param base the base of the output digits * @param n a number * @return a {@code String} representation of {@code n} in base {@code base} */ public static @NotNull String toStringBase(int base, int n) { if (base < 2) throw new IllegalArgumentException("base must be at least 2"); boolean bigBase = base > 36; if (n == 0) { return bigBase ? "(0)" : "0"; } boolean negative = n < 0; if (negative) n = -n; List<Integer> digits = bigEndianDigits(base, n); String absString; if (bigBase) { absString = concatStrings(map(d -> "(" + d + ")", digits)); } else { absString = charsToString(map(MathUtils::toDigit, digits)); } return negative ? cons('-', absString) : absString; } /** * Converts a {@code BigInteger} to a {@code String} in any base greater than 1. If the base is 36 or less, the * digits are '0' through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written * in decimal and each digit is surrounded by parentheses. Zero is represented by "0" if the base is 36 or less, or * "(0)" otherwise. In every other case there are no leading zeroes. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code n} must be non-null.</li> * <li>The result is a {@code String} which is nonempty and either composed of the characters '0'–'9' and 'A'–'Z' * (not starting with '0', unless that is the only character), or is the concatenation of some non-negative * numbers surrounded by parentheses (not starting with "(0)", unless that is the only number). In either case * there may be an optional leading '-'.</li> * </ul> * * @param base the base of the output digits * @param n a number * @return a {@code String} representation of {@code n} in base {@code base} */ public static @NotNull String toStringBase(@NotNull BigInteger base, @NotNull BigInteger n) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); boolean bigBase = gt(base, BigInteger.valueOf(36)); if (n.equals(BigInteger.ZERO)) { return bigBase ? "(0)" : "0"; } boolean negative = n.signum() == -1; if (negative) n = n.negate(); List<BigInteger> digits = bigEndianDigits(base, n); String absString; if (bigBase) { absString = concatStrings(map(d -> "(" + d + ")", digits)); } else { absString = charsToString(map(d -> toDigit(d.intValue()), digits)); } return negative ? cons('-', absString) : absString; } /** * Converts a {@code String} written in some base to a number. If the base is 36 or less, the digits are '0' * through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written in decimal and * each digit is surrounded by parentheses. The empty {@code String} represents 0. Leading zeroes are permitted. If * the {@code String} is invalid, an exception is thrown. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code s} must either be composed of the digits '0' through '9' and 'A' through 'Z', or a sequence of * non-negative decimal integers, each surrounded by parentheses. In either case there may be an optional leading * '-'. {@code s} may also be empty, but "-" is not permitted.</li> * <li>If {@code base} is between 2 and 36, {@code s} may only include the corresponding characters, and the * optional leading '-'. If {@code base} is greater than 36, {@code s} must be composed of decimal integers * surrounded by parentheses (with the optional leading '-'), each integer being non-negative and less than * {@code base}.</li> * <li>The result is non-null.</li> * </ul> * * @param base the base that the {@code s} is written in * @param s the input {@code String} * @return the number represented by {@code s} */ public static @NotNull BigInteger fromStringBase(int base, @NotNull String s) { if (base < 2) throw new IllegalArgumentException("base must be at least 2"); if (s.isEmpty()) return BigInteger.ZERO; boolean negative = false; if (head(s) == '-') { s = tail(s); if (s.isEmpty()) throw new IllegalArgumentException("improperly-formatted String"); negative = true; } List<Integer> digits; if (base <= 36) { digits = toList(map(MathUtils::fromDigit, fromString(s))); } else { if (head(s) != '(' || last(s) != ')') throw new IllegalArgumentException("improperly-formatted String"); s = tail(init(s)); digits = toList(map(Integer::parseInt, Arrays.asList(s.split("\\)\\(")))); } BigInteger result = fromBigEndianDigits(base, digits); return negative ? result.negate() : result; } /** * Converts a {@code String} written in some base to a number. If the base is 36 or less, the digits are '0' * through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written in decimal and * each digit is surrounded by parentheses. The empty {@code String} represents 0. Leading zeroes are permitted. If * the {@code String} is invalid, an exception is thrown. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code s} must either be composed of the digits '0' through '9' and 'A' through 'Z', or a sequence of * non-negative decimal integers, each surrounded by parentheses. In either case there may be an optional leading * '-'. {@code s} may also be empty, but "-" is not permitted.</li> * <li>If {@code base} is between 2 and 36, {@code s} may only include the corresponding characters, and the * optional leading '-'. If {@code base} is greater than 36, {@code s} must be composed of decimal integers * surrounded by parentheses (with the optional leading '-'), each integer being non-negative and less than * {@code base}.</li> * <li>The result is non-null.</li> * </ul> * * @param base the base that the {@code s} is written in * @param s the input {@code String} * @return the number represented by {@code s} */ public static @NotNull BigInteger fromStringBase(@NotNull BigInteger base, @NotNull String s) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); if (s.isEmpty()) return BigInteger.ZERO; boolean negative = false; if (head(s) == '-') { s = tail(s); if (s.isEmpty()) throw new IllegalArgumentException("improperly-formatted String"); negative = true; } List<BigInteger> digits; if (le(base, BigInteger.valueOf(36))) { digits = toList(map(c -> BigInteger.valueOf(fromDigit(c)), fromString(s))); } else { if (head(s) != '(' || last(s) != ')') throw new IllegalArgumentException("improperly-formatted String"); s = tail(init(s)); digits = toList(map(BigInteger::new, Arrays.asList(s.split("\\)\\(")))); } BigInteger result = fromBigEndianDigits(base, digits); return negative ? result.negate() : result; } /** * Bijectively maps two natural {@code BigInteger}s to one natural {@code BigInteger} in such a way that the result * is O({@code x}2<sup>{@code y}</sup>). In other words, the contribution of {@code x} is approximately the base-2 * log of the contribution of {@code y}. The inverse of this method is * {@link mho.wheels.math.MathUtils#logarithmicDemux}. * * <ul> * <li>{@code x} must be non-negative.</li> * <li>{@code y} must be non-negative.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first {@code BigInteger} * @param y the second {@code BigInteger} * @return a {@code BigInteger} generated bijectively from {@code x} and {@code y} */ public static @NotNull BigInteger logarithmicMux(@NotNull BigInteger x, @NotNull BigInteger y) { if (x.signum() == -1 || y.signum() == -1) throw new ArithmeticException("neither integer can be negative"); return x.shiftLeft(1).add(BigInteger.ONE).shiftLeft(y.intValueExact()).subtract(BigInteger.ONE); } /** * Bijectively maps one natural {@code BigInteger} to two natural {@code BigInteger}s in such a way that the second * is "typically" about the base-2 log of the first. More precisely, this method is the inverse of * {@link mho.wheels.math.MathUtils#logarithmicMux}. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is non-null and both of its elements are non-negative.</li> * </ul> * * @param n a {@code BigInteger} * @return a pair of {@code BigInteger}s generated bijectively from {@code n} */ public static @NotNull Pair<BigInteger, BigInteger> logarithmicDemux(@NotNull BigInteger n) { if (n.signum() == -1) throw new ArithmeticException("input cannot be negative"); n = n.add(BigInteger.ONE); int exp = n.getLowestSetBit(); return new Pair<>(n.shiftRight(exp + 1), BigInteger.valueOf(exp)); } /** * Bijectively maps two natural {@code BigInteger}s to one natural {@code BigInteger} in such a way that the result * is O({@code x}{@code y}<sup>2</sup>). In other words, the contribution of {@code x} is approximately the square * root of the contribution of {@code y}. The inverse of this method is * {@link mho.wheels.math.MathUtils#squareRootDemux}. * * <ul> * <li>{@code x} must be non-negative.</li> * <li>{@code y} must be non-negative.</li> * <li>The result is non-negative.</li> * </ul> * * @param x the first {@code BigInteger} * @param y the second {@code BigInteger} * @return a {@code BigInteger} generated bijectively from {@code x} and {@code y} */ public static @NotNull BigInteger squareRootMux(@NotNull BigInteger x, @NotNull BigInteger y) { List<Boolean> xBits = toList(bits(x)); List<Boolean> yBits = toList(bits(y)); int outputSize = max(xBits.size(), yBits.size()) * 3; Iterable<Iterable<Boolean>> xChunks = map(w -> w, chunk(2, concat(xBits, repeat(false)))); Iterable<Iterable<Boolean>> yChunks = map(Arrays::asList, concat(yBits, repeat(false))); return fromBits(take(outputSize, concat(IterableUtils.mux(Arrays.asList(yChunks, xChunks))))); } /** * Bijectively maps one natural {@code BigInteger} to two natural {@code BigInteger}s in such a way that the second * is "typically" about the square root of the first. More precisely, this method is the inverse of * {@link mho.wheels.math.MathUtils#squareRootMux}. * * <ul> * <li>{@code n} must be non-negative.</li> * <li>The result is non-null and both of its elements are non-negative.</li> * </ul> * * @param n a {@code BigInteger} * @return a pair of {@code BigInteger}s generated bijectively from {@code n} */ public static @NotNull Pair<BigInteger, BigInteger> squareRootDemux(@NotNull BigInteger n) { List<Boolean> bits = toList(bits(n)); Iterable<Boolean> xMask = cycle(Arrays.asList(false, true, true)); Iterable<Boolean> yMask = cycle(Arrays.asList(true, false, false)); return new Pair<>(fromBits(select(xMask, bits)), fromBits(select(yMask, bits))); } /** * Bijectively maps a list of natural {@code BigInteger}s to one natural {@code BigInteger} in such a way that the * result is O(max({@code xs})<sup>|{@code xs}|</sup>), so the contribution of each element of {@code xs} is * approximately equal. The bijection is between the naturals and list of a fixed size, not all lists. The empty * list maps to 0. The inverse of this method is {@link mho.wheels.math.MathUtils#demux}. * * <ul> * <li>Every element of {@code xs} must be non-negative.</li> * <li>The result is non-negative.</li> * </ul> * * @param xs the list of {@code BigInteger}s * @return a {@code BigInteger} generated bijectively from {@code xs} */ public static @NotNull BigInteger mux(@NotNull List<BigInteger> xs) { if (xs.isEmpty()) return BigInteger.ZERO; Iterable<Boolean> muxedBits = IterableUtils.mux(toList(map(x -> concat(bits(x), repeat(false)), reverse(xs)))); int outputSize = maximum(map(BigInteger::bitLength, xs)) * xs.size(); return fromBits(take(outputSize, muxedBits)); } /** * Bijectively maps one natural {@code BigInteger} to a list of natural {@code BigInteger}s in such a way that * every element of the list is "typically" about the same size. More precisely, this method is the inverse of * {@link mho.wheels.math.MathUtils#mux}. The bijection is between the naturals and list of a fixed size, not all * lists. If {@code lines} is 0, the only acceptable {@code n} is 0, which maps to the empty list. The inverse of * this method is {@link mho.wheels.math.MathUtils#mux}. * * <ul> * <li>{@code lines} must be non-negative.</li> * <li>{@code n} must be non-negative.</li> * <li>If {@code lines} is 0, {@code n} must also be 0.</li> * <li>The result is non-null and all of its elements are non-negative.</li> * </ul> * * @param lines the number of {@code BigIntegers} to map {@code n} to * @param n a {@code BigInteger} * @return a list of {@code BigInteger}s generated bijectively from {@code n} */ public static @NotNull List<BigInteger> demux(int lines, @NotNull BigInteger n) { if (lines == 0 && !n.equals(BigInteger.ZERO)) throw new ArithmeticException("if muxing into 0 lines, n must also be 0"); if (lines < 0) throw new ArithmeticException("cannot demux into a negative number of lines"); if (n.equals(BigInteger.ZERO)) { return toList(replicate(lines, BigInteger.ZERO)); } return reverse(IterableUtils.map(MathUtils::fromBits, IterableUtils.demux(lines, bits(n)))); } public static boolean isAPowerOfTwo(@NotNull BigInteger n) { return n.getLowestSetBit() == n.bitLength() - 1; } public static @NotNull BigInteger fastGrowingCeilingInverse( @NotNull Function<BigInteger, BigInteger> f, @NotNull BigInteger y, @NotNull BigInteger min, @NotNull BigInteger max ) { for (BigInteger x : range(min, max)) { BigInteger j = f.apply(x); if (ge(j, y)) { return x; } } throw new IllegalArgumentException("inverse not found in range"); } public static @NotNull BigInteger ceilingLog(@NotNull BigInteger base, @NotNull BigInteger x) { //noinspection SuspiciousNameCombination return fastGrowingCeilingInverse( i -> base.pow(i.intValueExact()), x, BigInteger.ONE, x //very loose bound ); } public static @NotNull BigInteger ceilingInverse( @NotNull Function<BigInteger, BigInteger> f, @NotNull BigInteger y, @NotNull BigInteger min, @NotNull BigInteger max ) { while (true) { if (min.equals(max)) return max; BigInteger mid = min.add(max).shiftRight(1); BigInteger fMid = f.apply(mid); switch (compare(fMid, y)) { case GT: max = mid; break; case LT: min = mid.add(BigInteger.ONE); break; default: return mid; } } } public static @NotNull BigInteger ceilingRoot(@NotNull BigInteger r, @NotNull BigInteger x) { //noinspection SuspiciousNameCombination return ceilingInverse( i -> i.pow(r.intValueExact()), x, BigInteger.ZERO, x //very loose bound ); } public static int smallestPrimeFactor(int n) { if (n < 2) throw new IllegalArgumentException("argument must be at least 2"); if (n % 2 == 0) return 2; if (n < PRIME_SIEVE_SIZE && PRIME_SIEVE.get(n)) return n; for (int i = 3; ; i += 2) { int square = i * i; if (square > n || square < 0) break; if (PRIME_SIEVE.get(i) && n % i == 0) return i; } return n; } public static @NotNull BigInteger smallestPrimeFactor(@NotNull BigInteger n) { if (le(n, BigInteger.valueOf(Integer.MAX_VALUE))) { return BigInteger.valueOf(smallestPrimeFactor(n.intValueExact())); } if (!n.testBit(0)) return BigInteger.valueOf(2); for (int i = 3; i < PRIME_SIEVE_SIZE; i += 2) { BigInteger bi = BigInteger.valueOf(i); if (gt(bi.pow(2), n)) return n; if (PRIME_SIEVE.get(i) && n.mod(bi).equals(BigInteger.ZERO)) return bi; } BigInteger limit = ceilingRoot(BigInteger.valueOf(2), n); Iterable<BigInteger> candidates = concatMap( i -> { BigInteger sixI = i.multiply(BigInteger.valueOf(6)); return Arrays.asList(sixI.subtract(BigInteger.ONE), sixI.add(BigInteger.ONE)); }, range(BigInteger.valueOf(PRIME_SIEVE_SIZE / 6)) ); for (BigInteger candidate : takeWhile(i -> le(i, limit), candidates)) { if (n.mod(candidate).equals(BigInteger.ZERO)) return candidate; } return n; } public static boolean isPrime(int n) { return smallestPrimeFactor(n) == n; } public static boolean isPrime(@NotNull BigInteger n) { return smallestPrimeFactor(n).equals(n); } public static @NotNull Iterable<Integer> primeFactors(int n) { return unfoldr( i -> { if (i == 1) return Optional.empty(); int spf = smallestPrimeFactor(i); return Optional.of(new Pair<>(spf, i / spf)); }, n ); } public static @NotNull Iterable<BigInteger> primeFactors(@NotNull BigInteger n) { return unfoldr( i -> { if (i.equals(BigInteger.ONE)) return Optional.empty(); BigInteger spf = smallestPrimeFactor(i); return Optional.of(new Pair<>(spf, i.divide(spf))); }, n ); } public static @NotNull Iterable<Pair<Integer, Integer>> compactPrimeFactors(int n) { return countAdjacent(primeFactors(n)); } public static @NotNull Iterable<Pair<BigInteger, Integer>> compactPrimeFactors(@NotNull BigInteger n) { return countAdjacent(primeFactors(n)); } public static @NotNull List<Integer> factors(int n) { List<Pair<Integer, Integer>> cpf = toList(compactPrimeFactors(n)); Iterable<List<Integer>> possibleExponents = Combinatorics.controlledListsIncreasing( toList(map(p -> range(0, p.b), cpf)) ); Function<List<Integer>, Integer> f = exponents -> productInteger( zipWith(p -> BigInteger.valueOf(p.a).pow(p.b).intValueExact(), map(q -> q.a, cpf), exponents) ); return sort(map(f, possibleExponents)); } public static @NotNull List<BigInteger> factors(@NotNull BigInteger n) { List<Pair<BigInteger, Integer>> cpf = toList(compactPrimeFactors(n)); Iterable<List<Integer>> possibleExponents = Combinatorics.controlledListsIncreasing( toList(map(p -> range(0, p.b), cpf)) ); Function<List<Integer>, BigInteger> f = exponents -> productBigInteger( zipWith(p -> { assert p.a != null; assert p.b != null; return p.a.pow(p.b); }, map(q -> q.a, cpf), exponents) ); return sort(map(f, possibleExponents)); } public static @NotNull Iterable<Integer> intPrimes() { int start = (PRIME_SIEVE_SIZE & 1) == 0 ? PRIME_SIEVE_SIZE + 1 : PRIME_SIEVE_SIZE; return concat( filter(PRIME_SIEVE::get, range(2, PRIME_SIEVE_SIZE - 1)), filter(MathUtils::isPrime, rangeBy(start, 2)) ); } public static @NotNull Iterable<BigInteger> primes() { Iterable<BigInteger> candidates = concatMap( i -> { BigInteger sixI = i.multiply(BigInteger.valueOf(6)); return Arrays.asList(sixI.subtract(BigInteger.ONE), sixI.add(BigInteger.ONE)); }, range(BigInteger.valueOf(PRIME_SIEVE_SIZE / 6)) ); return concat(map(i -> BigInteger.valueOf(i), intPrimes()), filter(MathUtils::isPrime, candidates)); } }
clarify bits/digits docs
src/main/java/mho/wheels/math/MathUtils.java
clarify bits/digits docs
Java
mit
de6dec3ed5aa9d8abafbcc1014546ca4ce6f3f86
0
diachron/quality
/** * */ package eu.diachron.qualitymetrics.utilities; import java.io.StringReader; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.io.output.StringBuilderWriter; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFDataMgr; import org.mapdb.HTreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import EDU.oswego.cs.dl.util.concurrent.TimeoutException; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.query.DatasetFactory; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.util.iterator.Filter; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import de.unibonn.iai.eis.diachron.mapdb.MapDbFactory; import de.unibonn.iai.eis.luzzu.semantics.utilities.Commons; import eu.diachron.qualitymetrics.cache.CachedVocabulary; import eu.diachron.qualitymetrics.cache.DiachronCacheManager; /** * @author Jeremy Debattista * * This helper class loads known vocabularies * into a Jena dataset. * * In this package, we provide 53 non-propriatary * vocabularies that are used by at least 1% of * the whole LOD Cloud. This list is compiled from * http://linkeddatacatalog.dws.informatik.uni-mannheim.de/state/#toc6 * */ public class VocabularyLoader { private static Logger logger = LoggerFactory.getLogger(VocabularyLoader.class); private static DiachronCacheManager dcm = DiachronCacheManager.getInstance(); private static Dataset dataset = DatasetFactory.createMem(); private static ConcurrentMap<String, String> knownDatasets = new ConcurrentHashMap<String,String>(); static { knownDatasets.put("http://dbpedia.org/ontology/","dbpedia.nt"); knownDatasets.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#","rdf.rdf"); knownDatasets.put("http://www.w3.org/2000/01/rdf-schema#","rdfs.rdf"); knownDatasets.put("http://xmlns.com/foaf/0.1/","foaf.rdf"); knownDatasets.put("http://purl.org/dc/terms/","dcterm.rdf"); knownDatasets.put("http://www.w3.org/2002/07/owl#","owl.rdf"); knownDatasets.put("http://www.w3.org/2003/01/geo/wgs84_pos#","pos.rdf"); knownDatasets.put("http://rdfs.org/sioc/ns#","sioc.rdf"); // knownDatasets.put("http://webns.net/mvcb/","admin.rdf"); knownDatasets.put("http://www.w3.org/2004/02/skos/core#","skos.rdf"); knownDatasets.put("http://rdfs.org/ns/void#","void.rdf"); //TODO update new namespace knownDatasets.put("http://purl.org/vocab/bio/0.1/","bio.rdf"); knownDatasets.put("http://purl.org/linked-data/cube#","cube.ttl"); knownDatasets.put("http://purl.org/rss/1.0/","rss.rdf"); knownDatasets.put("http://www.w3.org/2000/10/swap/pim/contact#","w3con.rdf"); knownDatasets.put("http://usefulinc.com/ns/doap#","doap.rdf"); knownDatasets.put("http://purl.org/ontology/bibo/","bibo.rdf"); knownDatasets.put("http://www.w3.org/ns/dcat#","dcat.rdf"); knownDatasets.put("http://www.w3.org/ns/auth/cert#","cert.rdf"); knownDatasets.put("http://purl.org/linked-data/sdmx/2009/dimension#","sdmxd.ttl"); knownDatasets.put("http://www.daml.org/2001/10/html/airport-ont#","airport.rdf"); knownDatasets.put("http://xmlns.com/wot/0.1/","wot.rdf"); // knownDatasets.put("http://purl.org/rss/1.0/modules/content/","content.rdf"); knownDatasets.put("http://creativecommons.org/ns#","cc.rdf"); knownDatasets.put("http://purl.org/vocab/relationship/","ref.rdf"); // knownDatasets.put("http://xmlns.com/wordnet/1.6/","wn.rdf"); knownDatasets.put("http://rdfs.org/sioc/types#","tsioc.rdf"); knownDatasets.put("http://www.w3.org/2006/vcard/ns#","vcard2006.rdf"); knownDatasets.put("http://purl.org/linked-data/sdmx/2009/attribute#","sdmxa.ttl"); knownDatasets.put("http://www.geonames.org/ontology#","gn.rdf"); knownDatasets.put("http://data.semanticweb.org/ns/swc/ontology#","swc.rdf"); knownDatasets.put("http://purl.org/dc/dcmitype/","dctypes.rdf"); knownDatasets.put("http://purl.org/net/provenance/ns#","hartigprov.rdf"); knownDatasets.put("http://www.w3.org/ns/sparql-service-description#","sd.rdf"); knownDatasets.put("http://open.vocab.org/terms/","open.ttl"); knownDatasets.put("http://www.w3.org/ns/prov#","prov.rdf"); knownDatasets.put("http://purl.org/vocab/resourcelist/schema#","resource.rdf"); knownDatasets.put("http://rdvocab.info/elements/","rda.rdf"); knownDatasets.put("http://purl.org/net/provenance/types#","prvt.rdf"); knownDatasets.put("http://purl.org/NET/c4dm/event.owl#","c4dm.rdf"); knownDatasets.put("http://purl.org/goodrelations/v1#","gr.rdf"); knownDatasets.put("http://www.w3.org/ns/auth/rsa#","rsa.rdf"); knownDatasets.put("http://purl.org/vocab/aiiso/schema#","aiiso.rdf"); knownDatasets.put("http://purl.org/net/pingback/","pingback.rdf"); knownDatasets.put("http://www.w3.org/2006/time#","time.rdf"); knownDatasets.put("http://www.w3.org/ns/org#","org.rdf"); knownDatasets.put("http://www.w3.org/2007/05/powder-s#","wdrs.rdf"); knownDatasets.put("http://www.w3.org/2003/06/sw-vocab-status/ns#","vs.rdf"); knownDatasets.put("http://purl.org/vocab/vann/","vann.rdf"); knownDatasets.put("http://www.w3.org/2002/12/cal/icaltzd#","icaltzd.rdf"); knownDatasets.put("http://purl.org/vocab/frbr/core#","frbrcore.rdf"); knownDatasets.put("http://www.w3.org/1999/xhtml/vocab#","xhv.rdf"); knownDatasets.put("http://purl.org/vocab/lifecycle/schema#","lcy.rdf"); knownDatasets.put("http://www.w3.org/2004/03/trix/rdfg-1/","rdfg.rdf"); knownDatasets.put("http://schema.org/", "schema.rdf"); //added schema.org since it does not allow content negotiation } /** * Checks if a term (Class or Property) exists in a vocabulary * * @param term: Class or Property resource */ public static boolean checkTerm(Node term){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); return termExists(ns, term); } public static void loadVocabulary(String vocabURI){ if(!(dataset.containsNamedModel(vocabURI))) loadNStoDataset(vocabURI); } private static void loadNStoDataset(String ns){ if (knownDatasets.containsKey(ns)){ //String filepath = VocabularyLoader.class.getClassLoader().getResource("vocabs/"+knownDatasets.get(ns)).getPath(); Model m = RDFDataMgr.loadModel("vocabs/" + knownDatasets.get(ns)); dataset.addNamedModel(ns, m); } else { //download and store in cache if (dcm.existsInCache(DiachronCacheManager.VOCABULARY_CACHE, ns)){ try{ CachedVocabulary cv = (CachedVocabulary) dcm.getFromCache(DiachronCacheManager.VOCABULARY_CACHE, ns); StringReader reader = new StringReader(cv.getTextualContent()); Model m = ModelFactory.createDefaultModel(); m.read(reader, ns, cv.getLanguage()); dataset.addNamedModel(ns, m); }catch (ClassCastException cce){ logger.error("Cannot cast {} " + ns); } } else { downloadAndLoadVocab(ns); } } } private static void downloadAndLoadVocab(final String ns) { try{ ExecutorService executor = Executors.newSingleThreadExecutor(); Model m = null; final Future<Model> handler = executor.submit(new Callable<Model>() { @Override public Model call() throws Exception { Model m = RDFDataMgr.loadModel(ns,Lang.RDFXML); return m; } }); try { m = handler.get(5, TimeUnit.SECONDS); dataset.addNamedModel(ns, m); StringBuilderWriter writer = new StringBuilderWriter(); m.write(writer, "TURTLE"); CachedVocabulary cv = new CachedVocabulary(); cv.setLanguage("TURTLE"); cv.setNs(ns); cv.setTextualContent(writer.toString()); dcm.addToCache(DiachronCacheManager.VOCABULARY_CACHE, ns, cv); } catch (TimeoutException e) { handler.cancel(true); } } catch (Exception e){ logger.error("Vocabulary {} could not be accessed.",ns); // throw new VocabularyUnreachableException("The vocabulary <"+ns+"> cannot be accessed. Error thrown: "+e.getMessage()); } } private static Boolean termExists(String ns, Node term){ Model m = dataset.getNamedModel(ns); if ((term.getNameSpace().startsWith(RDF.getURI())) && (term.getURI().matches(RDF.getURI()+"_[0-9]+"))){ return true; } if (term.isURI()) { Resource r = m.createResource(term.getURI()); return m.containsResource(r); } return null; } public static void clearDataset(){ dataset.close(); dataset = DatasetFactory.createMem(); } public static Boolean knownVocabulary(String uri){ return (knownDatasets.containsKey(uri) || dataset.containsNamedModel(uri)); } public static Model getModelForVocabulary(String ns){ if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); return dataset.getNamedModel(ns); } public static boolean isProperty(Node term){ String ns = term.getNameSpace(); Model m = getModelForVocabulary(ns); return (m.contains(m.createResource(term.getURI()), RDF.type, RDF.Property) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.DatatypeProperty) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.ObjectProperty) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.OntologyProperty)); } public static boolean isClass(Node term){ String ns = term.getNameSpace(); Model m = getModelForVocabulary(ns); return (m.contains(m.createResource(term.getURI()), RDF.type, RDFS.Class) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.Class)) ; } public static Filter<RDFNode> deprecatedfilter = new Filter<RDFNode>() { @Override public boolean accept(RDFNode node) { return ((node.equals(OWL.DeprecatedClass)) || (node.equals(OWL.DeprecatedProperty))); } }; private static HTreeMap<String, Boolean> checkedDeprecatedTerm = MapDbFactory.createFilesystemDB().createHashMap("deprecated-terms").make(); public static boolean isDeprecatedTerm(Node term){ if (checkedDeprecatedTerm.containsKey(term.getURI())) return checkedDeprecatedTerm.get(term.getURI()); String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); Model m = dataset.getNamedModel(ns); Resource r = Commons.asRDFNode(term).asResource(); boolean isDeprecated = m.listObjectsOfProperty(r, RDF.type).filterKeep(deprecatedfilter).hasNext(); checkedDeprecatedTerm.put(term.getURI(), isDeprecated); return isDeprecated; } public static Set<RDFNode> getPropertyDomain(Node term){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); Model m = dataset.getNamedModel(ns); Resource s = Commons.asRDFNode(term).asResource(); Set<RDFNode> set = m.listObjectsOfProperty(s, RDFS.domain).toSet(); // set.addAll(inferParent(term,m,true)); return set; } public static Set<RDFNode> getPropertyRange(Node term){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); Model m = dataset.getNamedModel(ns); Resource s = Commons.asRDFNode(term).asResource(); Set<RDFNode> set = m.listObjectsOfProperty(s, RDFS.range).toSet(); // set.addAll(inferParent(term,m,false)); if (set.contains(RDFS.Literal)){ set.add(XSD.xfloat); set.add(XSD.xdouble); set.add(XSD.xint); set.add(XSD.xlong); set.add(XSD.xshort); set.add(XSD.xbyte); set.add(XSD.xboolean); set.add(XSD.xstring); set.add(XSD.unsignedByte); set.add(XSD.unsignedShort); set.add(XSD.unsignedInt); set.add(XSD.unsignedLong); set.add(XSD.decimal); set.add(XSD.integer); set.add(XSD.nonPositiveInteger); set.add(XSD.nonNegativeInteger); set.add(XSD.positiveInteger); set.add(XSD.negativeInteger); set.add(XSD.normalizedString); } return set; } private static Map<Node, Set<RDFNode>> infParent = new HashMap<Node,Set<RDFNode>>(); //TODO: Fix public static Set<RDFNode> inferParent(Node term, Model m, boolean isSuperClass){ if (infParent.containsKey(term)) return infParent.get(term); String query; Model _mdl = m; if (_mdl == null){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); _mdl = dataset.getNamedModel(ns); } if (isSuperClass) query = "SELECT ?super { <"+term.getURI()+"> <"+RDFS.subClassOf.getURI()+">* ?super }"; else query = "SELECT ?super { <"+term.getURI()+"> <"+RDFS.subPropertyOf.getURI()+">* ?super }"; QueryExecution q = QueryExecutionFactory.create(query,_mdl); ResultSet rs = q.execSelect(); Set<RDFNode> set = new LinkedHashSet<RDFNode>(); while(rs.hasNext()) set.add(rs.next().get("super")); set.add(OWL.Thing); infParent.put(term, set); return set; } public static Set<RDFNode> inferChildren(Node term, Model m, boolean isSuperClass){ String query; Model _mdl = m; if (_mdl == null){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); _mdl = dataset.getNamedModel(ns); } if (isSuperClass) query = "SELECT ?child { ?child <"+RDFS.subClassOf.getURI()+">* <"+term.getURI()+"> }"; else query = "SELECT ?child { ?child <"+RDFS.subPropertyOf.getURI()+">* <"+term.getURI()+"> }"; QueryExecution q = QueryExecutionFactory.create(query,_mdl); ResultSet rs = q.execSelect(); Set<RDFNode> set = new HashSet<RDFNode>(); while(rs.hasNext()) set.add(rs.next().get("child")); return set; } public static boolean isInverseFunctionalProperty(Node term){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); Model m = dataset.getNamedModel(ns); Resource r = Commons.asRDFNode(term).asResource(); Filter<RDFNode> filter = new Filter<RDFNode>() { @Override public boolean accept(RDFNode node) { return ((node.equals(OWL.InverseFunctionalProperty))); } }; return m.listObjectsOfProperty(r, RDF.type).filterKeep(filter).hasNext(); } public static Model getClassModelNoLiterals(Node term, Model m){ String query = "SELECT * { <"+term.getURI()+"> ?p ?o }"; Model _mdl = m; Model _ret = ModelFactory.createDefaultModel(); if (_mdl == null){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); _mdl = dataset.getNamedModel(ns); } QueryExecution q = QueryExecutionFactory.create(query,_mdl); ResultSet rs = q.execSelect(); while(rs.hasNext()) { QuerySolution qs = rs.next(); if (qs.get("o").isLiteral()) continue; else { Resource prop = qs.get("p").asResource(); Resource obj = qs.getResource("o"); _ret.add(Commons.asRDFNode(term).asResource(), _ret.createProperty(prop.getURI()), obj); } } return _ret; } public static Model inferAncDec(Node term, Model m){ Model _mdl = m; Model _ret = ModelFactory.createDefaultModel(); if (_mdl == null){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); _mdl = dataset.getNamedModel(ns); } String query = "SELECT ?super ?type { <"+term.getURI()+"> <"+RDFS.subClassOf.getURI()+"> ?super . ?super a ?type .}"; QueryExecution q = QueryExecutionFactory.create(query,_mdl); ResultSet rs = q.execSelect(); while(rs.hasNext()) { QuerySolution sol = rs.next(); _ret.add(Commons.asRDFNode(term).asResource(), RDFS.subClassOf, sol.get("super")); _ret.add(sol.get("super").asResource(), RDF.type, sol.get("type")); } query = "SELECT ?child ?type { ?child <"+RDFS.subClassOf.getURI()+"> <"+term.getURI()+"> . ?child a ?type . }"; q = QueryExecutionFactory.create(query,_mdl); rs = q.execSelect(); while(rs.hasNext()) { QuerySolution sol = rs.next(); _ret.add(sol.get("child").asResource(), RDFS.subClassOf,Commons.asRDFNode(term).asResource()); _ret.add(sol.get("child").asResource(), RDF.type, sol.get("type")); } return _ret; } }
metric-utilities/src/main/java/eu/diachron/qualitymetrics/utilities/VocabularyLoader.java
/** * */ package eu.diachron.qualitymetrics.utilities; import java.io.StringReader; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.io.output.StringBuilderWriter; import org.apache.jena.atlas.web.HttpException; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.riot.RiotException; import org.mapdb.HTreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.query.DatasetFactory; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.util.iterator.Filter; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import de.unibonn.iai.eis.diachron.mapdb.MapDbFactory; import de.unibonn.iai.eis.luzzu.semantics.utilities.Commons; import eu.diachron.qualitymetrics.cache.CachedVocabulary; import eu.diachron.qualitymetrics.cache.DiachronCacheManager; /** * @author Jeremy Debattista * * This helper class loads known vocabularies * into a Jena dataset. * * In this package, we provide 53 non-propriatary * vocabularies that are used by at least 1% of * the whole LOD Cloud. This list is compiled from * http://linkeddatacatalog.dws.informatik.uni-mannheim.de/state/#toc6 * */ public class VocabularyLoader { private static Logger logger = LoggerFactory.getLogger(VocabularyLoader.class); private static DiachronCacheManager dcm = DiachronCacheManager.getInstance(); private static Dataset dataset = DatasetFactory.createMem(); private static ConcurrentMap<String, String> knownDatasets = new ConcurrentHashMap<String,String>(); static { knownDatasets.put("http://dbpedia.org/ontology/","dbpedia.nt"); knownDatasets.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#","rdf.rdf"); knownDatasets.put("http://www.w3.org/2000/01/rdf-schema#","rdfs.rdf"); knownDatasets.put("http://xmlns.com/foaf/0.1/","foaf.rdf"); knownDatasets.put("http://purl.org/dc/terms/","dcterm.rdf"); knownDatasets.put("http://www.w3.org/2002/07/owl#","owl.rdf"); knownDatasets.put("http://www.w3.org/2003/01/geo/wgs84_pos#","pos.rdf"); knownDatasets.put("http://rdfs.org/sioc/ns#","sioc.rdf"); // knownDatasets.put("http://webns.net/mvcb/","admin.rdf"); knownDatasets.put("http://www.w3.org/2004/02/skos/core#","skos.rdf"); knownDatasets.put("http://rdfs.org/ns/void#","void.rdf"); //TODO update new namespace knownDatasets.put("http://purl.org/vocab/bio/0.1/","bio.rdf"); knownDatasets.put("http://purl.org/linked-data/cube#","cube.ttl"); knownDatasets.put("http://purl.org/rss/1.0/","rss.rdf"); knownDatasets.put("http://www.w3.org/2000/10/swap/pim/contact#","w3con.rdf"); knownDatasets.put("http://usefulinc.com/ns/doap#","doap.rdf"); knownDatasets.put("http://purl.org/ontology/bibo/","bibo.rdf"); knownDatasets.put("http://www.w3.org/ns/dcat#","dcat.rdf"); knownDatasets.put("http://www.w3.org/ns/auth/cert#","cert.rdf"); knownDatasets.put("http://purl.org/linked-data/sdmx/2009/dimension#","sdmxd.ttl"); knownDatasets.put("http://www.daml.org/2001/10/html/airport-ont#","airport.rdf"); knownDatasets.put("http://xmlns.com/wot/0.1/","wot.rdf"); // knownDatasets.put("http://purl.org/rss/1.0/modules/content/","content.rdf"); knownDatasets.put("http://creativecommons.org/ns#","cc.rdf"); knownDatasets.put("http://purl.org/vocab/relationship/","ref.rdf"); // knownDatasets.put("http://xmlns.com/wordnet/1.6/","wn.rdf"); knownDatasets.put("http://rdfs.org/sioc/types#","tsioc.rdf"); knownDatasets.put("http://www.w3.org/2006/vcard/ns#","vcard2006.rdf"); knownDatasets.put("http://purl.org/linked-data/sdmx/2009/attribute#","sdmxa.ttl"); knownDatasets.put("http://www.geonames.org/ontology#","gn.rdf"); knownDatasets.put("http://data.semanticweb.org/ns/swc/ontology#","swc.rdf"); knownDatasets.put("http://purl.org/dc/dcmitype/","dctypes.rdf"); knownDatasets.put("http://purl.org/net/provenance/ns#","hartigprov.rdf"); knownDatasets.put("http://www.w3.org/ns/sparql-service-description#","sd.rdf"); knownDatasets.put("http://open.vocab.org/terms/","open.ttl"); knownDatasets.put("http://www.w3.org/ns/prov#","prov.rdf"); knownDatasets.put("http://purl.org/vocab/resourcelist/schema#","resource.rdf"); knownDatasets.put("http://rdvocab.info/elements/","rda.rdf"); knownDatasets.put("http://purl.org/net/provenance/types#","prvt.rdf"); knownDatasets.put("http://purl.org/NET/c4dm/event.owl#","c4dm.rdf"); knownDatasets.put("http://purl.org/goodrelations/v1#","gr.rdf"); knownDatasets.put("http://www.w3.org/ns/auth/rsa#","rsa.rdf"); knownDatasets.put("http://purl.org/vocab/aiiso/schema#","aiiso.rdf"); knownDatasets.put("http://purl.org/net/pingback/","pingback.rdf"); knownDatasets.put("http://www.w3.org/2006/time#","time.rdf"); knownDatasets.put("http://www.w3.org/ns/org#","org.rdf"); knownDatasets.put("http://www.w3.org/2007/05/powder-s#","wdrs.rdf"); knownDatasets.put("http://www.w3.org/2003/06/sw-vocab-status/ns#","vs.rdf"); knownDatasets.put("http://purl.org/vocab/vann/","vann.rdf"); knownDatasets.put("http://www.w3.org/2002/12/cal/icaltzd#","icaltzd.rdf"); knownDatasets.put("http://purl.org/vocab/frbr/core#","frbrcore.rdf"); knownDatasets.put("http://www.w3.org/1999/xhtml/vocab#","xhv.rdf"); knownDatasets.put("http://purl.org/vocab/lifecycle/schema#","lcy.rdf"); knownDatasets.put("http://www.w3.org/2004/03/trix/rdfg-1/","rdfg.rdf"); knownDatasets.put("http://schema.org/", "schema.rdf"); //added schema.org since it does not allow content negotiation } /** * Checks if a term (Class or Property) exists in a vocabulary * * @param term: Class or Property resource */ public static boolean checkTerm(Node term){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); return termExists(ns, term); } public static void loadVocabulary(String vocabURI){ if(!(dataset.containsNamedModel(vocabURI))) loadNStoDataset(vocabURI); } private static void loadNStoDataset(String ns){ if (knownDatasets.containsKey(ns)){ //String filepath = VocabularyLoader.class.getClassLoader().getResource("vocabs/"+knownDatasets.get(ns)).getPath(); Model m = RDFDataMgr.loadModel("vocabs/" + knownDatasets.get(ns)); dataset.addNamedModel(ns, m); } else { //download and store in cache if (dcm.existsInCache(DiachronCacheManager.VOCABULARY_CACHE, ns)){ try{ CachedVocabulary cv = (CachedVocabulary) dcm.getFromCache(DiachronCacheManager.VOCABULARY_CACHE, ns); StringReader reader = new StringReader(cv.getTextualContent()); Model m = ModelFactory.createDefaultModel(); m.read(reader, ns, cv.getLanguage()); dataset.addNamedModel(ns, m); }catch (ClassCastException cce){ logger.error("Cannot cast {} " + ns); } } else { downloadAndLoadVocab(ns); } } } private static void downloadAndLoadVocab(String ns) { try{ Model m = RDFDataMgr.loadModel(ns,Lang.RDFXML); dataset.addNamedModel(ns, m); StringBuilderWriter writer = new StringBuilderWriter(); m.write(writer, "TURTLE"); CachedVocabulary cv = new CachedVocabulary(); cv.setLanguage("TURTLE"); cv.setNs(ns); cv.setTextualContent(writer.toString()); dcm.addToCache(DiachronCacheManager.VOCABULARY_CACHE, ns, cv); } catch (RiotException | HttpException e){ logger.error("Vocabulary {} could not be accessed.",ns); // throw new VocabularyUnreachableException("The vocabulary <"+ns+"> cannot be accessed. Error thrown: "+e.getMessage()); } } private static Boolean termExists(String ns, Node term){ Model m = dataset.getNamedModel(ns); if ((term.getNameSpace().startsWith(RDF.getURI())) && (term.getURI().matches(RDF.getURI()+"_[0-9]+"))){ return true; } if (term.isURI()) { Resource r = m.createResource(term.getURI()); return m.containsResource(r); } return null; } public static void clearDataset(){ dataset.close(); dataset = DatasetFactory.createMem(); } public static Boolean knownVocabulary(String uri){ return (knownDatasets.containsKey(uri) || dataset.containsNamedModel(uri)); } public static Model getModelForVocabulary(String ns){ if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); return dataset.getNamedModel(ns); } public static boolean isProperty(Node term){ String ns = term.getNameSpace(); Model m = getModelForVocabulary(ns); return (m.contains(m.createResource(term.getURI()), RDF.type, RDF.Property) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.DatatypeProperty) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.ObjectProperty)); } public static boolean isClass(Node term){ String ns = term.getNameSpace(); Model m = getModelForVocabulary(ns); return (m.contains(m.createResource(term.getURI()), RDF.type, RDFS.Class) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.Class)) ; } public static Boolean checkTerm(Node term, boolean useCache){ if (useCache) return checkTerm(term); else{ Model m = null; try { m = RDFDataMgr.loadModel(term.getURI()); } catch (Exception e){ System.out.println(term.getURI() + " " + e.getLocalizedMessage()); return false; } if ((term.getNameSpace().startsWith(RDF.getURI())) && (term.getURI().matches(RDF.getURI()+"_[0-9]+"))){ return true; } if (term.isURI()) { Resource r = m.createResource(term.getURI()); return m.containsResource(r); } return null; } } public static boolean isProperty(Node term, boolean useCache){ if (useCache) return isProperty(term); else{ Model m = null; try { m = RDFDataMgr.loadModel(term.getURI()); } catch (Exception e){ System.out.println(term.getURI() + " " + e.getLocalizedMessage()); return false; } return (m.contains(m.createResource(term.getURI()), RDF.type, RDF.Property) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.DatatypeProperty) || m.contains(m.createResource(term.getURI()), RDF.type, OWL.ObjectProperty)); } } public static Filter<RDFNode> deprecatedfilter = new Filter<RDFNode>() { @Override public boolean accept(RDFNode node) { return ((node.equals(OWL.DeprecatedClass)) || (node.equals(OWL.DeprecatedProperty))); } }; private static HTreeMap<String, Boolean> checkedDeprecatedTerm = MapDbFactory.createFilesystemDB().createHashMap("deprecated-terms").make(); public static boolean isDeprecatedTerm(Node term){ if (checkedDeprecatedTerm.containsKey(term.getURI())) return checkedDeprecatedTerm.get(term.getURI()); String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); Model m = dataset.getNamedModel(ns); Resource r = Commons.asRDFNode(term).asResource(); boolean isDeprecated = m.listObjectsOfProperty(r, RDF.type).filterKeep(deprecatedfilter).hasNext(); checkedDeprecatedTerm.put(term.getURI(), isDeprecated); return isDeprecated; } public static Set<RDFNode> getPropertyDomain(Node term){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); Model m = dataset.getNamedModel(ns); Resource s = Commons.asRDFNode(term).asResource(); Set<RDFNode> set = m.listObjectsOfProperty(s, RDFS.domain).toSet(); // set.addAll(inferParent(term,m,true)); return set; } public static Set<RDFNode> getPropertyRange(Node term){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); Model m = dataset.getNamedModel(ns); Resource s = Commons.asRDFNode(term).asResource(); Set<RDFNode> set = m.listObjectsOfProperty(s, RDFS.range).toSet(); // set.addAll(inferParent(term,m,false)); if (set.contains(RDFS.Literal)){ set.add(XSD.xfloat); set.add(XSD.xdouble); set.add(XSD.xint); set.add(XSD.xlong); set.add(XSD.xshort); set.add(XSD.xbyte); set.add(XSD.xboolean); set.add(XSD.xstring); set.add(XSD.unsignedByte); set.add(XSD.unsignedShort); set.add(XSD.unsignedInt); set.add(XSD.unsignedLong); set.add(XSD.decimal); set.add(XSD.integer); set.add(XSD.nonPositiveInteger); set.add(XSD.nonNegativeInteger); set.add(XSD.positiveInteger); set.add(XSD.negativeInteger); set.add(XSD.normalizedString); } return set; } private static Map<Node, Set<RDFNode>> infParent = new HashMap<Node,Set<RDFNode>>(); //TODO: Fix public static Set<RDFNode> inferParent(Node term, Model m, boolean isSuperClass){ if (infParent.containsKey(term)) return infParent.get(term); String query; Model _mdl = m; if (_mdl == null){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); _mdl = dataset.getNamedModel(ns); } if (isSuperClass) query = "SELECT ?super { <"+term.getURI()+"> <"+RDFS.subClassOf.getURI()+">* ?super }"; else query = "SELECT ?super { <"+term.getURI()+"> <"+RDFS.subPropertyOf.getURI()+">* ?super }"; QueryExecution q = QueryExecutionFactory.create(query,_mdl); ResultSet rs = q.execSelect(); Set<RDFNode> set = new LinkedHashSet<RDFNode>(); while(rs.hasNext()) set.add(rs.next().get("super")); set.add(OWL.Thing); infParent.put(term, set); return set; } public static Set<RDFNode> inferChildren(Node term, Model m, boolean isSuperClass){ String query; Model _mdl = m; if (_mdl == null){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); _mdl = dataset.getNamedModel(ns); } if (isSuperClass) query = "SELECT ?child { ?child <"+RDFS.subClassOf.getURI()+">* <"+term.getURI()+"> }"; else query = "SELECT ?child { ?child <"+RDFS.subPropertyOf.getURI()+">* <"+term.getURI()+"> }"; QueryExecution q = QueryExecutionFactory.create(query,_mdl); ResultSet rs = q.execSelect(); Set<RDFNode> set = new HashSet<RDFNode>(); while(rs.hasNext()) set.add(rs.next().get("child")); return set; } public static boolean isInverseFunctionalProperty(Node term){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); Model m = dataset.getNamedModel(ns); Resource r = Commons.asRDFNode(term).asResource(); Filter<RDFNode> filter = new Filter<RDFNode>() { @Override public boolean accept(RDFNode node) { return ((node.equals(OWL.InverseFunctionalProperty))); } }; return m.listObjectsOfProperty(r, RDF.type).filterKeep(filter).hasNext(); } public static Model getClassModelNoLiterals(Node term, Model m){ String query = "SELECT * { <"+term.getURI()+"> ?p ?o }"; Model _mdl = m; Model _ret = ModelFactory.createDefaultModel(); if (_mdl == null){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); _mdl = dataset.getNamedModel(ns); } QueryExecution q = QueryExecutionFactory.create(query,_mdl); ResultSet rs = q.execSelect(); while(rs.hasNext()) { QuerySolution qs = rs.next(); if (qs.get("o").isLiteral()) continue; else { Resource prop = qs.get("p").asResource(); Resource obj = qs.getResource("o"); _ret.add(Commons.asRDFNode(term).asResource(), _ret.createProperty(prop.getURI()), obj); } } return _ret; } public static Model inferAncDec(Node term, Model m){ Model _mdl = m; Model _ret = ModelFactory.createDefaultModel(); if (_mdl == null){ String ns = term.getNameSpace(); if(!(dataset.containsNamedModel(ns))) loadNStoDataset(ns); _mdl = dataset.getNamedModel(ns); } String query = "SELECT ?super ?type { <"+term.getURI()+"> <"+RDFS.subClassOf.getURI()+"> ?super . ?super a ?type .}"; QueryExecution q = QueryExecutionFactory.create(query,_mdl); ResultSet rs = q.execSelect(); while(rs.hasNext()) { QuerySolution sol = rs.next(); _ret.add(Commons.asRDFNode(term).asResource(), RDFS.subClassOf, sol.get("super")); _ret.add(sol.get("super").asResource(), RDF.type, sol.get("type")); } query = "SELECT ?child ?type { ?child <"+RDFS.subClassOf.getURI()+"> <"+term.getURI()+"> . ?child a ?type . }"; q = QueryExecutionFactory.create(query,_mdl); rs = q.execSelect(); while(rs.hasNext()) { QuerySolution sol = rs.next(); _ret.add(sol.get("child").asResource(), RDFS.subClassOf,Commons.asRDFNode(term).asResource()); _ret.add(sol.get("child").asResource(), RDF.type, sol.get("type")); } return _ret; } }
added 5 second timeout to vocab downloader
metric-utilities/src/main/java/eu/diachron/qualitymetrics/utilities/VocabularyLoader.java
added 5 second timeout to vocab downloader
Java
mit
b3fd9ca6a1fd35b6c5be40bc65812fee30854235
0
flintproject/Flint,flintproject/Flint
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */ package jp.oist.flint.form.job; import jp.oist.flint.form.sub.JobWindow; import jp.oist.flint.garuda.GarudaClient; import jp.oist.flint.job.Job; import jp.oist.flint.job.Progress; import jp.oist.flint.util.DurationFormat; import jp.oist.flint.util.PeriodFormat; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.SwingConstants; import javax.swing.UIManager; public class JobCell extends JPanel { private final JobWindow mJobWindow; private final int mIndex; private Number[] mCombination; private boolean mIsCancelled = false; public JobCell(JobWindow jobWindow, int index) { mJobWindow = jobWindow; mIndex = index; initComponents(); setBackground(UIManager.getColor("List.background")); if (!GarudaClient.isRunning()) { btn_SendViaGaruda.setEnabled(false); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnl_Top = new JPanel(); lbl_Title = new JLabel(); pnl_Middle = new JPanel(); jPanel2 = new JPanel(); mProgressBar = new JProgressBar(); btn_Cancel = new JButton(); pnl_Bottom = new JPanel(); lbl_Detail = new JLabel(); jPanel4 = new JPanel(); btn_SendViaGaruda = new JButton(); btn_Export = new JButton(); btn_View = new JButton(); setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); setMinimumSize(new Dimension(0, 70)); setPreferredSize(new Dimension(200, 70)); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); pnl_Top.setMaximumSize(new Dimension(32767, 20)); pnl_Top.setOpaque(false); pnl_Top.setPreferredSize(new Dimension(800, 20)); pnl_Top.setLayout(new BorderLayout()); pnl_Top.add(lbl_Title, BorderLayout.CENTER); add(pnl_Top); pnl_Middle.setMinimumSize(new Dimension(0, 0)); pnl_Middle.setOpaque(false); pnl_Middle.setPreferredSize(new Dimension(800, 20)); pnl_Middle.setLayout(new BoxLayout(pnl_Middle, BoxLayout.LINE_AXIS)); jPanel2.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); jPanel2.setMinimumSize(new Dimension(0, 20)); jPanel2.setOpaque(false); jPanel2.setPreferredSize(new Dimension(0, 23)); jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.LINE_AXIS)); mProgressBar.setMinimumSize(new Dimension(0, 20)); mProgressBar.setPreferredSize(new Dimension(0, 20)); mProgressBar.setStringPainted(true); jPanel2.add(mProgressBar); pnl_Middle.add(jPanel2); btn_Cancel.setIcon(new ImageIcon(getClass().getResource("/jp/oist/flint/image/cancel.png"))); // NOI18N btn_Cancel.setActionCommand("jobcell.action.cancel"); btn_Cancel.setIconTextGap(0); btn_Cancel.setMaximumSize(new Dimension(20, 20)); btn_Cancel.setMinimumSize(new Dimension(20, 20)); btn_Cancel.setPreferredSize(new Dimension(20, 20)); btn_Cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_CancelActionPerformed(evt); } }); pnl_Middle.add(btn_Cancel); add(pnl_Middle); pnl_Bottom.setMaximumSize(new Dimension(65534, 30)); pnl_Bottom.setMinimumSize(new Dimension(0, 30)); pnl_Bottom.setOpaque(false); pnl_Bottom.setPreferredSize(new Dimension(800, 30)); pnl_Bottom.setLayout(new BoxLayout(pnl_Bottom, BoxLayout.LINE_AXIS)); lbl_Detail.setFont(new Font("Lucida Grande", 0, 12)); // NOI18N lbl_Detail.setForeground(Color.gray); lbl_Detail.setVerticalAlignment(SwingConstants.TOP); lbl_Detail.setMaximumSize(new Dimension(32333, 20)); lbl_Detail.setMinimumSize(new Dimension(0, 20)); lbl_Detail.setPreferredSize(new Dimension(600, 20)); pnl_Bottom.add(lbl_Detail); jPanel4.setMaximumSize(new Dimension(250, 20)); jPanel4.setMinimumSize(new Dimension(250, 30)); jPanel4.setOpaque(false); jPanel4.setPreferredSize(new Dimension(400, 30)); FlowLayout flowLayout1 = new FlowLayout(FlowLayout.RIGHT, 2, 0); flowLayout1.setAlignOnBaseline(true); jPanel4.setLayout(flowLayout1); btn_SendViaGaruda.setText("Send via Garuda"); btn_SendViaGaruda.setActionCommand("jobcell.action.sendviagaruda"); btn_SendViaGaruda.setMaximumSize(new Dimension(110, 20)); btn_SendViaGaruda.setMinimumSize(new Dimension(110, 20)); btn_SendViaGaruda.setPreferredSize(new Dimension(130, 20)); btn_SendViaGaruda.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_SendViaGarudaActionPerformed(evt); } }); jPanel4.add(btn_SendViaGaruda); btn_Export.setText("Export"); btn_Export.setActionCommand("jobcell.action.export"); btn_Export.setMaximumSize(new Dimension(75, 20)); btn_Export.setMinimumSize(new Dimension(75, 20)); btn_Export.setPreferredSize(new Dimension(75, 20)); btn_Export.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_ExportActionPerformed(evt); } }); jPanel4.add(btn_Export); btn_View.setText("View"); btn_View.setActionCommand("jobcell.action.view"); btn_View.setMaximumSize(new Dimension(75, 20)); btn_View.setMinimumSize(new Dimension(75, 20)); btn_View.setPreferredSize(new Dimension(75, 20)); btn_View.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_ViewActionPerformed(evt); } }); jPanel4.add(btn_View); pnl_Bottom.add(jPanel4); add(pnl_Bottom); }// </editor-fold>//GEN-END:initComponents private void btn_CancelActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btn_CancelActionPerformed mJobWindow.cancelJobPerformed(mIndex); }//GEN-LAST:event_btn_CancelActionPerformed private void btn_ExportActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btn_ExportActionPerformed mJobWindow.exportPerformed(mIndex); }//GEN-LAST:event_btn_ExportActionPerformed private void btn_SendViaGarudaActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btn_SendViaGarudaActionPerformed mJobWindow.sendViaGarudaPerformed(mIndex); }//GEN-LAST:event_btn_SendViaGarudaActionPerformed private void btn_ViewActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btn_ViewActionPerformed mJobWindow.plotPerformed(mIndex); }//GEN-LAST:event_btn_ViewActionPerformed public void setCombination (Number[] combination) { mCombination = combination; } public Number[] getCombination () { return mCombination; } public void setDetail (String detail) { lbl_Detail.setText(detail); } public void setValueIsAdjusting (boolean isAdjusting) { mProgressBar.getModel().setValueIsAdjusting(isAdjusting); } public boolean getValueIsAdjusting () { return mProgressBar.getModel().getValueIsAdjusting(); } public void setProgress(Job job) { Progress progress = job.getProgress(); int percent = progress.getPercent(); mProgressBar.setValue(percent); StringBuilder sb = new StringBuilder(); if (isCancelled()) { sb.append("cancelled | "); } sb.append(String.format("%1$3d", percent)); sb.append(" % | "); sb.append(PeriodFormat.fromTo(progress.getStarted(), progress.getLastUpdated())); sb.append(" ("); sb.append(DurationFormat.fromMillis(progress.getElapsedMillis())); sb.append(")"); if (isFinished()) { btn_Cancel.setEnabled(false); } mProgressBar.setString(sb.toString()); mProgressBar.repaint(); if (lbl_Detail.getText().isEmpty()) { try { lbl_Detail.setText(job.getParameterDescription()); } catch (IOException ex) { // give up } } } public int getProgress () { return mProgressBar.getValue(); } public boolean isCancelled() { return mIsCancelled; } public void setCancelled(boolean cancelled) { mIsCancelled = cancelled; btn_Cancel.setEnabled(!cancelled); } private boolean isFinished () { return isCancelled() || isCompleted(); } private boolean isCompleted () { return mProgressBar.getMaximum() == mProgressBar.getValue(); } // Variables declaration - do not modify//GEN-BEGIN:variables private JButton btn_Cancel; private JButton btn_Export; private JButton btn_SendViaGaruda; private JButton btn_View; private JPanel jPanel2; private JPanel jPanel4; private JLabel lbl_Detail; private JLabel lbl_Title; private JProgressBar mProgressBar; private JPanel pnl_Bottom; private JPanel pnl_Middle; private JPanel pnl_Top; // End of variables declaration//GEN-END:variables }
flint/src/jp/oist/flint/form/job/JobCell.java
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */ package jp.oist.flint.form.job; import jp.oist.flint.form.sub.JobWindow; import jp.oist.flint.garuda.GarudaClient; import jp.oist.flint.job.Job; import jp.oist.flint.job.Progress; import jp.oist.flint.util.DurationFormat; import jp.oist.flint.util.PeriodFormat; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.SwingConstants; import javax.swing.UIManager; public class JobCell extends JPanel { public final static String ACTION_EXPORT = "jobcell.action.export"; public final static String ACTION_SENDVIAGARUDA = "jobcell.action.sendviagaruda"; public final static String ACTION_VIEW = "jobcell.action.view"; public final static String ACTION_CANCEL = "jobcell.action.cancel"; private final JobWindow mJobWindow; private final int mIndex; private Number[] mCombination; private boolean mIsCancelled = false; public JobCell(JobWindow jobWindow, int index) { mJobWindow = jobWindow; mIndex = index; initComponents(); setBackground(UIManager.getColor("List.background")); if (!GarudaClient.isRunning()) { btn_SendViaGaruda.setEnabled(false); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnl_Top = new JPanel(); lbl_Title = new JLabel(); pnl_Middle = new JPanel(); jPanel2 = new JPanel(); mProgressBar = new JProgressBar(); btn_Cancel = new JButton(); pnl_Bottom = new JPanel(); lbl_Detail = new JLabel(); jPanel4 = new JPanel(); btn_SendViaGaruda = new JButton(); btn_Export = new JButton(); btn_View = new JButton(); setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); setMinimumSize(new Dimension(0, 70)); setPreferredSize(new Dimension(200, 70)); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); pnl_Top.setMaximumSize(new Dimension(32767, 20)); pnl_Top.setOpaque(false); pnl_Top.setPreferredSize(new Dimension(800, 20)); pnl_Top.setLayout(new BorderLayout()); pnl_Top.add(lbl_Title, BorderLayout.CENTER); add(pnl_Top); pnl_Middle.setMinimumSize(new Dimension(0, 0)); pnl_Middle.setOpaque(false); pnl_Middle.setPreferredSize(new Dimension(800, 20)); pnl_Middle.setLayout(new BoxLayout(pnl_Middle, BoxLayout.LINE_AXIS)); jPanel2.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); jPanel2.setMinimumSize(new Dimension(0, 20)); jPanel2.setOpaque(false); jPanel2.setPreferredSize(new Dimension(0, 23)); jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.LINE_AXIS)); mProgressBar.setMinimumSize(new Dimension(0, 20)); mProgressBar.setPreferredSize(new Dimension(0, 20)); mProgressBar.setStringPainted(true); jPanel2.add(mProgressBar); pnl_Middle.add(jPanel2); btn_Cancel.setIcon(new ImageIcon(getClass().getResource("/jp/oist/flint/image/cancel.png"))); // NOI18N btn_Cancel.setActionCommand("jobcell.action.cancel"); btn_Cancel.setIconTextGap(0); btn_Cancel.setMaximumSize(new Dimension(20, 20)); btn_Cancel.setMinimumSize(new Dimension(20, 20)); btn_Cancel.setPreferredSize(new Dimension(20, 20)); btn_Cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_CancelActionPerformed(evt); } }); pnl_Middle.add(btn_Cancel); add(pnl_Middle); pnl_Bottom.setMaximumSize(new Dimension(65534, 30)); pnl_Bottom.setMinimumSize(new Dimension(0, 30)); pnl_Bottom.setOpaque(false); pnl_Bottom.setPreferredSize(new Dimension(800, 30)); pnl_Bottom.setLayout(new BoxLayout(pnl_Bottom, BoxLayout.LINE_AXIS)); lbl_Detail.setFont(new Font("Lucida Grande", 0, 12)); // NOI18N lbl_Detail.setForeground(Color.gray); lbl_Detail.setVerticalAlignment(SwingConstants.TOP); lbl_Detail.setMaximumSize(new Dimension(32333, 20)); lbl_Detail.setMinimumSize(new Dimension(0, 20)); lbl_Detail.setPreferredSize(new Dimension(600, 20)); pnl_Bottom.add(lbl_Detail); jPanel4.setMaximumSize(new Dimension(250, 20)); jPanel4.setMinimumSize(new Dimension(250, 30)); jPanel4.setOpaque(false); jPanel4.setPreferredSize(new Dimension(400, 30)); FlowLayout flowLayout1 = new FlowLayout(FlowLayout.RIGHT, 2, 0); flowLayout1.setAlignOnBaseline(true); jPanel4.setLayout(flowLayout1); btn_SendViaGaruda.setText("Send via Garuda"); btn_SendViaGaruda.setActionCommand("jobcell.action.sendviagaruda"); btn_SendViaGaruda.setMaximumSize(new Dimension(110, 20)); btn_SendViaGaruda.setMinimumSize(new Dimension(110, 20)); btn_SendViaGaruda.setPreferredSize(new Dimension(130, 20)); btn_SendViaGaruda.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_SendViaGarudaActionPerformed(evt); } }); jPanel4.add(btn_SendViaGaruda); btn_Export.setText("Export"); btn_Export.setActionCommand("jobcell.action.export"); btn_Export.setMaximumSize(new Dimension(75, 20)); btn_Export.setMinimumSize(new Dimension(75, 20)); btn_Export.setPreferredSize(new Dimension(75, 20)); btn_Export.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_ExportActionPerformed(evt); } }); jPanel4.add(btn_Export); btn_View.setText("View"); btn_View.setActionCommand("jobcell.action.view"); btn_View.setMaximumSize(new Dimension(75, 20)); btn_View.setMinimumSize(new Dimension(75, 20)); btn_View.setPreferredSize(new Dimension(75, 20)); btn_View.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_ViewActionPerformed(evt); } }); jPanel4.add(btn_View); pnl_Bottom.add(jPanel4); add(pnl_Bottom); }// </editor-fold>//GEN-END:initComponents private void btn_CancelActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btn_CancelActionPerformed mJobWindow.cancelJobPerformed(mIndex); }//GEN-LAST:event_btn_CancelActionPerformed private void btn_ExportActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btn_ExportActionPerformed mJobWindow.exportPerformed(mIndex); }//GEN-LAST:event_btn_ExportActionPerformed private void btn_SendViaGarudaActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btn_SendViaGarudaActionPerformed mJobWindow.sendViaGarudaPerformed(mIndex); }//GEN-LAST:event_btn_SendViaGarudaActionPerformed private void btn_ViewActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btn_ViewActionPerformed mJobWindow.plotPerformed(mIndex); }//GEN-LAST:event_btn_ViewActionPerformed public void setCombination (Number[] combination) { mCombination = combination; } public Number[] getCombination () { return mCombination; } public void setDetail (String detail) { lbl_Detail.setText(detail); } public void setValueIsAdjusting (boolean isAdjusting) { mProgressBar.getModel().setValueIsAdjusting(isAdjusting); } public boolean getValueIsAdjusting () { return mProgressBar.getModel().getValueIsAdjusting(); } public void setProgress(Job job) { Progress progress = job.getProgress(); int percent = progress.getPercent(); mProgressBar.setValue(percent); StringBuilder sb = new StringBuilder(); if (isCancelled()) { sb.append("cancelled | "); } sb.append(String.format("%1$3d", percent)); sb.append(" % | "); sb.append(PeriodFormat.fromTo(progress.getStarted(), progress.getLastUpdated())); sb.append(" ("); sb.append(DurationFormat.fromMillis(progress.getElapsedMillis())); sb.append(")"); if (isFinished()) { btn_Cancel.setEnabled(false); } mProgressBar.setString(sb.toString()); mProgressBar.repaint(); if (lbl_Detail.getText().isEmpty()) { try { lbl_Detail.setText(job.getParameterDescription()); } catch (IOException ex) { // give up } } } public int getProgress () { return mProgressBar.getValue(); } public boolean isCancelled() { return mIsCancelled; } public void setCancelled(boolean cancelled) { mIsCancelled = cancelled; btn_Cancel.setEnabled(!cancelled); } private boolean isFinished () { return isCancelled() || isCompleted(); } private boolean isCompleted () { return mProgressBar.getMaximum() == mProgressBar.getValue(); } // Variables declaration - do not modify//GEN-BEGIN:variables private JButton btn_Cancel; private JButton btn_Export; private JButton btn_SendViaGaruda; private JButton btn_View; private JPanel jPanel2; private JPanel jPanel4; private JLabel lbl_Detail; private JLabel lbl_Title; private JProgressBar mProgressBar; private JPanel pnl_Bottom; private JPanel pnl_Middle; private JPanel pnl_Top; // End of variables declaration//GEN-END:variables }
Drop unused constants
flint/src/jp/oist/flint/form/job/JobCell.java
Drop unused constants
Java
mit
a6f4b34d016d9c2b590d981ca5fd14bd3521986f
0
dreamhead/moco,dreamhead/moco
package com.github.dreamhead.moco.runner.watcher; import com.github.dreamhead.moco.MocoException; import com.github.dreamhead.moco.internal.MocoServer; import com.google.common.base.Optional; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.google.common.io.CharSource.wrap; import static io.netty.channel.ChannelHandler.Sharable; public class ShutdownMocoRunnerWatcher implements Watcher { private static Logger logger = LoggerFactory.getLogger(ShutdownMocoRunnerWatcher.class); private final MocoServer server = new MocoServer(); private final Optional<Integer> shutdownPort; private final String shutdownKey; private final ShutdownListener shutdownListener; private int port; public ShutdownMocoRunnerWatcher(final Optional<Integer> shutdownPort, final String shutdownKey, final ShutdownListener shutdownListener) { this.shutdownPort = shutdownPort; this.shutdownKey = shutdownKey; this.shutdownListener = shutdownListener; } public void start() { int actualPort = server.start(this.shutdownPort.or(0), new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("handler", new ShutdownHandler()); } }); this.port = actualPort; logger.info("Shutdown port is {}", actualPort); } public void stop() { server.stop(); } public int port() { return port; } @Sharable private class ShutdownHandler extends SimpleChannelInboundHandler<String> { private final ExecutorService service = Executors.newCachedThreadPool(); @Override protected void channelRead0(final ChannelHandlerContext ctx, final String msg) throws Exception { if (shouldShutdown(msg)) { shutdownListener.onShutdown(); shutdownMonitorSelf(); } } private void shutdownMonitorSelf() { service.execute(new Runnable() { @Override public void run() { stop(); } }); } private boolean shouldShutdown(final String message) { try { return shutdownKey.equals(wrap(message).readFirstLine()); } catch (IOException e) { throw new MocoException(e); } } } }
moco-runner/src/main/java/com/github/dreamhead/moco/runner/watcher/ShutdownMocoRunnerWatcher.java
package com.github.dreamhead.moco.runner.watcher; import com.github.dreamhead.moco.internal.MocoServer; import com.google.common.base.Optional; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.google.common.io.CharSource.wrap; import static io.netty.channel.ChannelHandler.Sharable; public class ShutdownMocoRunnerWatcher implements Watcher { private static Logger logger = LoggerFactory.getLogger(ShutdownMocoRunnerWatcher.class); private final MocoServer server = new MocoServer(); private final Optional<Integer> shutdownPort; private final String shutdownKey; private final ShutdownListener shutdownListener; private int port; public ShutdownMocoRunnerWatcher(final Optional<Integer> shutdownPort, final String shutdownKey, final ShutdownListener shutdownListener) { this.shutdownPort = shutdownPort; this.shutdownKey = shutdownKey; this.shutdownListener = shutdownListener; } public void start() { int actualPort = server.start(this.shutdownPort.or(0), new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("handler", new ShutdownHandler()); } }); this.port = actualPort; logger.info("Shutdown port is {}", actualPort); } public void stop() { server.stop(); } public int port() { return port; } @Sharable private class ShutdownHandler extends SimpleChannelInboundHandler<String> { private final ExecutorService service = Executors.newCachedThreadPool(); @Override protected void channelRead0(final ChannelHandlerContext ctx, final String msg) throws Exception { if (shouldShutdown(msg)) { shutdownListener.onShutdown(); shutdownMonitorSelf(); } } private void shutdownMonitorSelf() { service.execute(new Runnable() { @Override public void run() { stop(); } }); } private boolean shouldShutdown(final String message) { try { return shutdownKey.equals(wrap(message).readFirstLine()); } catch (IOException e) { throw new RuntimeException(e); } } } }
replaced runtime exception with moco exception in shutdown watcher
moco-runner/src/main/java/com/github/dreamhead/moco/runner/watcher/ShutdownMocoRunnerWatcher.java
replaced runtime exception with moco exception in shutdown watcher
Java
mit
9143dcb974103e19ed42beaa022aebbbc91990ec
0
RoboEagles4828/2017Robot,RoboEagles4828/ACE
package org.usfirst.frc.team4828; import com.ctre.CANTalon; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.Timer; import org.usfirst.frc.team4828.Vision.PixyThread; public class DriveTrain { private CANTalon frontLeft; private CANTalon frontRight; private CANTalon backLeft; private CANTalon backRight; private AHRS navx; private static final double TWIST_THRESHOLD = 0.15; private static final double DIST_TO_ENC = 4000.0; //todo: determine conversion factor private static final double AUTON_SPEED = 0.3; //todo: calibrate speed private static final double TURN_DEADZONE = 1; private static final double TURN_SPEED = .25; private static final double VISION_DEADZONE = 0.5; private static final double PLACING_DIST = -3; //todo: determine distance from the wall to stop when placing gear /** * Create drive train object containing mecanum motor functionality. * * @param frontLeftPort port of the front left motor * @param backLeftPort port of the back left motor * @param frontRightPort port of the front right motor * @param backRightPort port of the back right motor */ public DriveTrain(int frontLeftPort, int backLeftPort, int frontRightPort, int backRightPort) { frontLeft = new CANTalon(frontLeftPort); frontRight = new CANTalon(frontRightPort); backLeft = new CANTalon(backLeftPort); backRight = new CANTalon(backRightPort); navx = new AHRS(SPI.Port.kMXP); } /** * Test drive train object. */ public DriveTrain(boolean gyro) { if (gyro) { navx = new AHRS(SPI.Port.kMXP); } System.out.println("Created dummy drivetrain"); } /** * Ensure that wheel speeds are valid numbers. * * @param wheelSpeeds wheel speeds */ public static void normalize(double[] wheelSpeeds) { double maxMagnitude = Math.abs(wheelSpeeds[0]); for (int i = 1; i < 4; i++) { double temp = Math.abs(wheelSpeeds[i]); if (maxMagnitude < temp) { maxMagnitude = temp; } } if (maxMagnitude > 1.0) { for (int i = 0; i < 4; i++) { wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude; } } } /** * Rotate a vector in Cartesian space. * * @param xcomponent X component of the vector * @param ycomponent Y component of the vector * @return the resultant vector as a double[2] */ public double[] rotateVector(double xcomponent, double ycomponent) { double angle = navx.getAngle(); double cosA = Math.cos(angle * (3.14159 / 180.0)); double sinA = Math.sin(angle * (3.14159 / 180.0)); double[] out = new double[2]; out[0] = xcomponent * cosA - ycomponent * sinA; out[1] = xcomponent * sinA + ycomponent * cosA; return out; } /** * Adjust motor speeds according to joystick input. * * @param xcomponent x component of the joystick * @param ycomponent y component of the joystick * @param rotation rotation of the joystick */ public void mecanumDriveAbsolute(double xcomponent, double ycomponent, double rotation) { if (Math.abs(rotation) <= TWIST_THRESHOLD) { rotation = 0.0; } // Negate y for the joystick. ycomponent = -ycomponent; double[] wheelSpeeds = new double[4]; wheelSpeeds[0] = xcomponent + ycomponent + rotation; wheelSpeeds[1] = -xcomponent + ycomponent - rotation; wheelSpeeds[2] = -xcomponent + ycomponent + rotation; wheelSpeeds[3] = xcomponent + ycomponent - rotation; normalize(wheelSpeeds); frontLeft.set(wheelSpeeds[0]); frontRight.set(wheelSpeeds[1]); backLeft.set(wheelSpeeds[2]); backRight.set(wheelSpeeds[3]); } /** * Adjust motor speeds according to heading and joystick input. * Uses input from the gyroscope to determine field orientation. * * @param xcomponent x component of the joystick * @param ycomponent y component of the joystick * @param rotation rotation of the joystick */ public void mecanumDrive(double xcomponent, double ycomponent, double rotation) { // Ignore tiny inadvertent joystick rotations if (Math.abs(rotation) <= TWIST_THRESHOLD) { rotation = 0.0; } // Negate y for the joystick. ycomponent = -ycomponent; // Compensate for gyro angle. double[] rotated = rotateVector(xcomponent, ycomponent); xcomponent = rotated[0]; ycomponent = rotated[1]; double[] wheelSpeeds = new double[4]; wheelSpeeds[0] = xcomponent + ycomponent + rotation; wheelSpeeds[1] = -xcomponent + ycomponent - rotation; wheelSpeeds[2] = -xcomponent + ycomponent + rotation; wheelSpeeds[3] = xcomponent + ycomponent - rotation; normalize(wheelSpeeds); frontLeft.set(wheelSpeeds[0]); frontRight.set(wheelSpeeds[1]); backLeft.set(wheelSpeeds[2]); backRight.set(wheelSpeeds[3]); } /** * Move motors a certain distance. * * @param dist distance */ public void moveDistance(double dist) { double encoderChange = Math.abs(dist * DIST_TO_ENC); int dir = 1; frontLeft.setEncPosition(0); if (dist < 0) { dir = -1; } while (frontLeft.getEncPosition() < encoderChange) { mecanumDrive(0, AUTON_SPEED * dir, 0); } brake(); } /** * @param pos 1 = Right, 2 = Middle, 3 = Right * @param pixy */ public void placeGear(int pos, PixyThread pixy, GearGobbler gobbler) { //todo: confirm angles for each side if (pixy.isBlocksDetected()) { if (pos == 1) { turnDegrees(-30); } else if (pos == 2) { turnDegrees(-90); } else if (pos == 3) { turnDegrees(-150); } else { turnDegrees(0); } int dir; while (Math.abs(pixy.horizontalOffset()) > VISION_DEADZONE) { dir = 1; if (pixy.horizontalOffset() < 0) { dir = -1; } // center relative to the target mecanumDriveAbsolute(0, AUTON_SPEED * dir, 0); } while (pixy.distanceFromLift() >= PLACING_DIST) { // approach the target dir = 1; if (pixy.horizontalOffset() < 0) { dir = -1; } mecanumDriveAbsolute(AUTON_SPEED, AUTON_SPEED * dir, 0); } brake(); gobbler.open(); Timer.delay(.5); gobbler.close(); } } /** * Teleop version finds nearest angle before starting. * * @param pixy */ public void placeGear(PixyThread pixy, GearGobbler gobbler) { //todo: round to nearest angle double angle = navx.getAngle(); if (angle > 0 && angle < 60) { placeGear(1, pixy, gobbler); } } /** * Turn all wheels slowly for testing purposes. */ public void testMotors() { frontLeft.set(.2); frontRight.set(.2); backLeft.set(.2); backRight.set(.2); } /** * Turns at a certain speed * * @param speed double -1-1 */ public void turn(double speed) { mecanumDrive(0, 0, speed); } /** * Turn a certain amount of degrees * * @param degrees target degrees */ public void turnDegrees(double degrees) { int dir = getOptimalDirection(getTrueAngle(), degrees); while (getTrueAngle() - TURN_DEADZONE > degrees || getTrueAngle() + TURN_DEADZONE < degrees) { turn(TURN_SPEED * dir); } brake(); } /** * Get the true navx angle * * @return 0 <= angle < 360 */ public double getTrueAngle() { double angle = navx.getAngle() % 360; if (angle < 0) { return 360 + angle; } return angle; } /** * Get the best direction to turn * * @param current current angle * @param target target angle * @return -1 = left, 1 = right */ public int getOptimalDirection(double current, double target) { if (Math.abs(current - target) <= 180) { if (current > target) { return -1; } return 1; } if (current > target) { return 1; } return -1; } /** * Turn all wheels at set speeds. * * @param fl speed for front left wheel * @param fr speed for front right wheel * @param bl speed for back left wheel * @param br speed for back right wheel */ public void testMotors(int fl, int fr, int bl, int br) { frontLeft.set(fl); frontRight.set(fr); backLeft.set(bl); backRight.set(br); } /** * Stop all motors. */ public void brake() { frontLeft.set(0); frontRight.set(0); backRight.set(0); backLeft.set(0); } /** * @return the current gyro heading */ public String toString() { return Double.toString(navx.getAngle()); } /** * Prints current average encoder values. */ public void debugEncoders() { System.out.println("bl " + backLeft.getPosition() + " br " + backRight.getPosition() + " fl " + frontLeft.getPosition() + " fr " + frontRight.getPosition()); } /** * Zero the gyro. */ public void reset() { navx.reset(); } }
src/main/java/org/usfirst/frc/team4828/DriveTrain.java
package org.usfirst.frc.team4828; import com.ctre.CANTalon; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.Timer; import org.usfirst.frc.team4828.Vision.PixyThread; public class DriveTrain { private CANTalon frontLeft; private CANTalon frontRight; private CANTalon backLeft; private CANTalon backRight; private AHRS navx; private static final double TWIST_THRESHOLD = 0.15; private static final double DIST_TO_ENC = 4000.0; //todo: determine conversion factor private static final double AUTON_SPEED = 0.3; //todo: calibrate speed private static final double TURN_DEADZONE = 1; private static final double TURN_SPEED = .25; private static final double VISION_DEADZONE = 0.5; private static final double PLACING_DIST = -3; //todo: determine distance from the wall to stop when placing gear /** * Create drive train object containing mecanum motor functionality. * * @param frontLeftPort port of the front left motor * @param backLeftPort port of the back left motor * @param frontRightPort port of the front right motor * @param backRightPort port of the back right motor */ public DriveTrain(int frontLeftPort, int backLeftPort, int frontRightPort, int backRightPort) { frontLeft = new CANTalon(frontLeftPort); frontRight = new CANTalon(frontRightPort); backLeft = new CANTalon(backLeftPort); backRight = new CANTalon(backRightPort); navx = new AHRS(SPI.Port.kMXP); } /** * Test drive train object. */ public DriveTrain(boolean gyro) { if (gyro) { navx = new AHRS(SPI.Port.kMXP); } System.out.println("Created dummy drivetrain"); } /** * Ensure that wheel speeds are valid numbers. * * @param wheelSpeeds wheel speeds */ public static void normalize(double[] wheelSpeeds) { double maxMagnitude = Math.abs(wheelSpeeds[0]); for (int i = 1; i < 4; i++) { double temp = Math.abs(wheelSpeeds[i]); if (maxMagnitude < temp) { maxMagnitude = temp; } } if (maxMagnitude > 1.0) { for (int i = 0; i < 4; i++) { wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude; } } } /** * Rotate a vector in Cartesian space. * * @param xcomponent X component of the vector * @param ycomponent Y component of the vector * @return the resultant vector as a double[2] */ public double[] rotateVector(double xcomponent, double ycomponent) { double angle = navx.getAngle(); double cosA = Math.cos(angle * (3.14159 / 180.0)); double sinA = Math.sin(angle * (3.14159 / 180.0)); double[] out = new double[2]; out[0] = xcomponent * cosA - ycomponent * sinA; out[1] = xcomponent * sinA + ycomponent * cosA; return out; } /** * Adjust motor speeds according to joystick input. * * @param xcomponent x component of the joystick * @param ycomponent y component of the joystick * @param rotation rotation of the joystick */ public void mecanumDriveAbsolute(double xcomponent, double ycomponent, double rotation) { if (Math.abs(rotation) <= TWIST_THRESHOLD) { rotation = 0.0; } // Negate y for the joystick. ycomponent = -ycomponent; double[] wheelSpeeds = new double[4]; wheelSpeeds[0] = xcomponent + ycomponent + rotation; wheelSpeeds[1] = -xcomponent + ycomponent - rotation; wheelSpeeds[2] = -xcomponent + ycomponent + rotation; wheelSpeeds[3] = xcomponent + ycomponent - rotation; normalize(wheelSpeeds); frontLeft.set(wheelSpeeds[0]); frontRight.set(wheelSpeeds[1]); backLeft.set(wheelSpeeds[2]); backRight.set(wheelSpeeds[3]); } /** * Adjust motor speeds according to heading and joystick input. * Uses input from the gyroscope to determine field orientation. * * @param xcomponent x component of the joystick * @param ycomponent y component of the joystick * @param rotation rotation of the joystick */ public void mecanumDrive(double xcomponent, double ycomponent, double rotation) { // Ignore tiny inadvertent joystick rotations if (Math.abs(rotation) <= TWIST_THRESHOLD) { rotation = 0.0; } // Negate y for the joystick. ycomponent = -ycomponent; // Compensate for gyro angle. double[] rotated = rotateVector(xcomponent, ycomponent); xcomponent = rotated[0]; ycomponent = rotated[1]; double[] wheelSpeeds = new double[4]; wheelSpeeds[0] = xcomponent + ycomponent + rotation; wheelSpeeds[1] = -xcomponent + ycomponent - rotation; wheelSpeeds[2] = -xcomponent + ycomponent + rotation; wheelSpeeds[3] = xcomponent + ycomponent - rotation; normalize(wheelSpeeds); frontLeft.set(wheelSpeeds[0]); frontRight.set(wheelSpeeds[1]); backLeft.set(wheelSpeeds[2]); backRight.set(wheelSpeeds[3]); } /** * Move motors a certain distance. * * @param dist distance */ public void moveDistance(double dist) { double encoderChange = Math.abs(dist * DIST_TO_ENC); int dir = 1; frontLeft.setEncPosition(0); if (dist < 0) { dir = -1; } while (frontLeft.getEncPosition() < encoderChange) { mecanumDrive(0, AUTON_SPEED * dir, 0); } brake(); } /** * @param pos 1 = Right, 2 = Middle, 3 = Right * @param pixy */ public void placeGear(int pos, PixyThread pixy, GearGobbler gobbler) { //todo: confirm angles for each side if (pixy.isBlocksDetected()) { if (pos == 1) { turnDegrees(-30); } else if (pos == 2) { turnDegrees(-90); } else if (pos == 3) { turnDegrees(-150); } else { turnDegrees(0); } int dir; while (Math.abs(pixy.horizontalOffset()) > VISION_DEADZONE) { dir = 1; if (pixy.horizontalOffset() < 0) { dir = -1; } // center relative to the target mecanumDrive(0, AUTON_SPEED * dir, 0); } while (pixy.distanceFromLift() >= PLACING_DIST) { // approach the target dir = 1; if (pixy.horizontalOffset() < 0) { dir = -1; } mecanumDrive(AUTON_SPEED, AUTON_SPEED * dir, 0); } brake(); gobbler.open(); Timer.delay(.5); gobbler.close(); } } /** * Teleop version finds nearest angle before starting. * * @param pixy */ public void placeGear(PixyThread pixy, GearGobbler gobbler) { //todo: round to nearest angle double angle = navx.getAngle(); if (angle > 0 && angle < 60) { placeGear(1, pixy, gobbler); } } /** * Turn all wheels slowly for testing purposes. */ public void testMotors() { frontLeft.set(.2); frontRight.set(.2); backLeft.set(.2); backRight.set(.2); } /** * Turns at a certain speed * * @param speed double -1-1 */ public void turn(double speed) { frontLeft.set(-speed); backLeft.set(-speed); frontRight.set(speed); backRight.set(speed); } /** * Turn a certain amount of degrees * * @param degrees target degrees */ public void turnDegrees(double degrees) { int dir = getOptimalDirection(getTrueAngle(), degrees); while (getTrueAngle() - TURN_DEADZONE > degrees || getTrueAngle() + TURN_DEADZONE < degrees) { turn(TURN_SPEED * dir); } brake(); } /** * Get the true navx angle * * @return 0 <= angle < 360 */ public double getTrueAngle() { double angle = navx.getAngle() % 360; if (angle < 0) { return 360 + angle; } return angle; } /** * Get the best direction to turn * * @param current current angle * @param target target angle * @return -1 = left, 1 = right */ public int getOptimalDirection(double current, double target) { if (Math.abs(current - target) <= 180) { if (current > target) { return -1; } return 1; } if (current > target) { return 1; } return -1; } /** * Turn all wheels at set speeds. * * @param fl speed for front left wheel * @param fr speed for front right wheel * @param bl speed for back left wheel * @param br speed for back right wheel */ public void testMotors(int fl, int fr, int bl, int br) { frontLeft.set(fl); frontRight.set(fr); backLeft.set(bl); backRight.set(br); } /** * Stop all motors. */ public void brake() { frontLeft.set(0); frontRight.set(0); backRight.set(0); backLeft.set(0); } /** * @return the current gyro heading */ public String toString() { return Double.toString(navx.getAngle()); } /** * Prints current average encoder values. */ public void debugEncoders() { System.out.println("bl " + backLeft.getPosition() + " br " + backRight.getPosition() + " fl " + frontLeft.getPosition() + " fr " + frontRight.getPosition()); } /** * Zero the gyro. */ public void reset() { navx.reset(); } }
Clean up turning to use mecanum drive and make the auton routine use absolute directions
src/main/java/org/usfirst/frc/team4828/DriveTrain.java
Clean up turning to use mecanum drive
Java
epl-1.0
d9243f6c8f63fcf52585a6687be162756e4f55e9
0
smeup/asup,smeup/asup,smeup/asup
/** * Copyright (c) 2012, 2015 Sme.UP and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * * Contributors: * Mattia Rocchi - Initial API and implementation */ package org.smeup.sys.db.syntax.db2; import org.eclipse.datatools.modelbase.sql.constraints.Index; import org.eclipse.datatools.modelbase.sql.schema.Schema; import org.eclipse.datatools.modelbase.sql.schema.helper.SQLObjectNameHelper; import org.eclipse.datatools.modelbase.sql.schema.impl.SchemaImpl; import org.eclipse.datatools.modelbase.sql.tables.Table; import org.eclipse.datatools.modelbase.sql.tables.impl.TableImpl; import org.smeup.sys.db.core.OrderingType; import org.smeup.sys.db.core.QIndexColumnDef; import org.smeup.sys.db.core.QIndexDef; import org.smeup.sys.db.core.QSchemaDef; import org.smeup.sys.db.core.QTableColumnDef; import org.smeup.sys.db.core.QTableDef; import org.smeup.sys.db.syntax.base.BaseDefinitionWriterImpl; import org.smeup.sys.il.data.def.QCharacterDef; import org.smeup.sys.il.data.def.QDataDef; import org.smeup.sys.il.data.def.QDecimalDef; public class DB2DefinitionWriterImpl extends BaseDefinitionWriterImpl { public DB2DefinitionWriterImpl() { super(new SQLObjectNameHelper()); } @Override public String dropSchema(Schema schema) { return dropSchema(schema, false); } @Override public String createTable(Schema schema, String name, QTableDef table) { StringBuffer result = new StringBuffer("CREATE TABLE "); result.append(getNameInSQLFormat(schema) + "." + getNameInSQLFormat(name) + " ("); String pkey_name = null; boolean first = true; for (QTableColumnDef column : table.getColumns()) { if (!first) result.append(", "); else first = false; QDataDef<?> columnDef = column.getDefinition(); switch (columnDef.getDataDefType()) { case IDENTITY: result.append(getNameInSQLFormat(column) + " INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)"); pkey_name = getNameInSQLFormat(column); break; case CHARACTER: QCharacterDef characterDef = (QCharacterDef)columnDef; if(characterDef.isVarying()) result.append(getNameInSQLFormat(column) + " VARCHAR(" + characterDef.getLength() + ")"); else if (characterDef.getLength() <= 254) result.append(getNameInSQLFormat(column) + " CHAR(" + characterDef.getLength() + ")"); else result.append(getNameInSQLFormat(column) + " VARCHAR(" + characterDef.getLength() + ")"); break; case DECIMAL: QDecimalDef decimalDef = (QDecimalDef)columnDef; if (decimalDef.getLength() > 31) result.append(getNameInSQLFormat(column) + " DECFLOAT(34)"); else if (decimalDef.getScale() != 0) result.append(getNameInSQLFormat(column) + " DECIMAL(" + decimalDef.getLength() + ", " + decimalDef.getScale() + ")"); else result.append(getNameInSQLFormat(column) + " DECIMAL(" + decimalDef.getLength() + ", 0)"); break; default: result.append(getNameInSQLFormat(column) + " " + columnDef.getDataDefType().getName().toUpperCase()); } } if (pkey_name != null) result.append(", PRIMARY KEY (" + pkey_name + ")"); result.append(")"); return result.toString(); } public String createIndex(Table table, String indexName, QIndexDef index) { StringBuffer result = new StringBuffer("CREATE "); if (index.isUnique()) result.append("UNIQUE "); result.append("INDEX " + getQualifiedNameInSQLFormat(asTable(table.getSchema().getName(), indexName))); result.append(" ON " + getQualifiedNameInSQLFormat(table) + " ("); boolean first = true; for (QIndexColumnDef column : index.getColumns()) { if (!first) result.append(", "); result.append(getNameInSQLFormat(column)); if (column.getOrdering() == OrderingType.DESCEND) result.append(" DESC"); first = false; } result.append(")"); return result.toString(); } // TODO ?!? private Table asTable(final String schemaName, final String indexName) { return new TableImpl() { public Schema getSchema() { return new SchemaImpl() { public String getName() { return schemaName; } }; } public String getName() { return indexName; } }; } @Override public String dropIndex(Index index) { return "DROP INDEX " + getQualifiedNameInSQLFormat(asTable(index.getSchema().getName(), index.getName())); } @Override public String dropSchema(Schema schema, boolean ignoreFailOnNonEmpty) { if (!ignoreFailOnNonEmpty) return "DROP SCHEMA " + getNameInSQLFormat(schema) + " RESTRICT"; else { String sql = "begin " + " declare l_errschema varchar(128) default 'ERRORSCHEMA';" + " declare l_errtab varchar(128) default 'ERRORTABLE';" + " CALL SYSPROC.ADMIN_DROP_SCHEMA('" + schema.getName() + "', NULL, l_errschema, l_errtab);" + " end"; return sql; } } @Override public String createLabel(String name, QSchemaDef schema) { return null; /* String label = schema.getLabel(); if (label != null && label.trim() != "") return "COMMENT ON SCHEMA " + name + " IS " + getNameInSQLFormat(label); else return null;*/ } @Override public String createLabel(Schema schema, String name, QTableDef table) { String label = schema.getLabel(); if (label != null && label.trim() != "") { return "COMMENT ON TABLE " + getNameInSQLFormat(schema) + "." + getNameInSQLFormat(name) + " IS " + getNameInSQLFormat(label); } else { return null; } } @Override public String createLabelForFields(Schema schema, String name, QTableDef table) { StringBuffer result = new StringBuffer(); for (QTableColumnDef column : table.getColumns()) { String label = column.getLabel(); if (label != null && label.trim() != "") { if (result.length() > 0) result.append(", "); result.append(getNameInSQLFormat(column)) .append(" IS ") .append(getNameInSQLFormat(label)); } } if (result.length() > 0) { return "COMMENT ON " + getNameInSQLFormat(schema) + "." + getNameInSQLFormat(name) + "(" + result.toString() + ")"; } else { return null; } } }
org.smeup.sys.db.syntax.db2/src/org/smeup/sys/db/syntax/db2/DB2DefinitionWriterImpl.java
/** * Copyright (c) 2012, 2015 Sme.UP and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * * Contributors: * Mattia Rocchi - Initial API and implementation */ package org.smeup.sys.db.syntax.db2; import org.eclipse.datatools.modelbase.sql.constraints.Index; import org.eclipse.datatools.modelbase.sql.schema.Schema; import org.eclipse.datatools.modelbase.sql.schema.helper.SQLObjectNameHelper; import org.eclipse.datatools.modelbase.sql.schema.impl.SchemaImpl; import org.eclipse.datatools.modelbase.sql.tables.Table; import org.eclipse.datatools.modelbase.sql.tables.impl.TableImpl; import org.smeup.sys.db.core.OrderingType; import org.smeup.sys.db.core.QIndexColumnDef; import org.smeup.sys.db.core.QIndexDef; import org.smeup.sys.db.core.QSchemaDef; import org.smeup.sys.db.core.QTableColumnDef; import org.smeup.sys.db.core.QTableDef; import org.smeup.sys.db.syntax.base.BaseDefinitionWriterImpl; import org.smeup.sys.il.data.def.QCharacterDef; import org.smeup.sys.il.data.def.QDataDef; import org.smeup.sys.il.data.def.QDecimalDef; public class DB2DefinitionWriterImpl extends BaseDefinitionWriterImpl { public DB2DefinitionWriterImpl() { super(new SQLObjectNameHelper()); } @Override public String dropSchema(Schema schema) { return dropSchema(schema, false); } @Override public String createTable(Schema schema, String name, QTableDef table) { StringBuffer result = new StringBuffer("CREATE TABLE "); result.append(getNameInSQLFormat(schema) + "." + getNameInSQLFormat(name) + " ("); String pkey_name = null; boolean first = true; for (QTableColumnDef column : table.getColumns()) { if (!first) result.append(", "); else first = false; QDataDef<?> columnDef = column.getDefinition(); switch (columnDef.getDataDefType()) { case IDENTITY: result.append(getNameInSQLFormat(column) + " INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)"); pkey_name = getNameInSQLFormat(column); break; case CHARACTER: QCharacterDef characterDef = (QCharacterDef)columnDef; if(characterDef.isVarying()) result.append(getNameInSQLFormat(column) + " VARCHAR(" + characterDef.getLength() + ")"); else if (characterDef.getLength() <= 254) result.append(getNameInSQLFormat(column) + " CHAR(" + characterDef.getLength() + ")"); else result.append(getNameInSQLFormat(column) + " VARCHAR(" + characterDef.getLength() + ")"); break; case DECIMAL: QDecimalDef decimalDef = (QDecimalDef)columnDef; if (decimalDef.getLength() > 31) result.append(getNameInSQLFormat(column) + " DECFLOAT(34)"); else if (decimalDef.getScale() != 0) result.append(getNameInSQLFormat(column) + " DECIMAL(" + decimalDef.getLength() + ", " + decimalDef.getScale() + ")"); else result.append(getNameInSQLFormat(column) + " DECIMAL(" + decimalDef.getLength() + ", 0)"); break; default: result.append(getNameInSQLFormat(column) + " " + columnDef.getDataDefType().getName().toUpperCase()); } } if (pkey_name != null) result.append(", PRIMARY KEY (" + pkey_name + ")"); result.append(")"); return result.toString(); } public String createIndex(Table table, String indexName, QIndexDef index) { StringBuffer result = new StringBuffer("CREATE "); if (index.isUnique()) result.append("UNIQUE "); result.append("INDEX " + getQualifiedNameInSQLFormat(asTable(table.getSchema().getName(), indexName))); result.append(" ON " + getQualifiedNameInSQLFormat(table) + " ("); boolean first = true; for (QIndexColumnDef column : index.getColumns()) { if (!first) result.append(", "); result.append(getNameInSQLFormat(column)); if (column.getOrdering() == OrderingType.DESCEND) result.append(" DESC"); first = false; } result.append(")"); return result.toString(); } // TODO ?!? private Table asTable(final String schemaName, final String indexName) { return new TableImpl() { public Schema getSchema() { return new SchemaImpl() { public String getName() { return schemaName; } }; } public String getName() { return indexName; } }; } @Override public String dropIndex(Index index) { return "DROP INDEX " + getQualifiedNameInSQLFormat(asTable(index.getSchema().getName(), index.getName())); } @Override public String dropSchema(Schema schema, boolean ignoreFailOnNonEmpty) { if (!ignoreFailOnNonEmpty) return "DROP SCHEMA " + getNameInSQLFormat(schema) + " RESTRICT"; else { String sql = "begin " + " declare l_errschema varchar(128) default 'ERRORSCHEMA';" + " declare l_errtab varchar(128) default 'ERRORTABLE';" + " CALL SYSPROC.ADMIN_DROP_SCHEMA('" + schema.getName() + "', NULL, l_errschema, l_errtab);" + " end"; return sql; } } @Override public String createLabel(String name, QSchemaDef schema) { return null; /* String label = schema.getLabel(); if (label != null && label.trim() != "") return "COMMENT ON SCHEMA " + name + " IS " + getNameInSQLFormat(label); else return null;*/ } @Override public String createLabel(Schema schema, String name, QTableDef table) { return null; // String label = schema.getLabel(); // if (label != null && label.trim() != "") { // return "COMMENT ON TABLE " + getNameInSQLFormat(schema) + "." + getNameInSQLFormat(name) + " IS " + getNameInSQLFormat(label); // } else { // return null; // } } @Override public String createLabelForFields(Schema schema, String name, QTableDef table) { return null; // StringBuffer result = new StringBuffer(); // for (QTableColumnDef column : table.getColumns()) { // String label = column.getLabel(); // if (label != null && label.trim() != "") { // if (result.length() > 0) // result.append(", "); // result.append(getNameInSQLFormat(column)) // .append(" IS ") // .append(getNameInSQLFormat(label)); // } // } // // if (result.length() > 0) { // return "COMMENT ON " + getNameInSQLFormat(schema) + "." + getNameInSQLFormat(name) + "(" + result.toString() + ")"; // } else { // return null; // } } }
Modifica per gestione label
org.smeup.sys.db.syntax.db2/src/org/smeup/sys/db/syntax/db2/DB2DefinitionWriterImpl.java
Modifica per gestione label
Java
epl-1.0
2964fd6460a2ada777bf85b79f32d082ccfa0933
0
jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2012-2014 Chuck Ritola * Part of the jTRFP.org project * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl.core; import java.util.concurrent.Callable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.SwingUtilities; import org.jtrfp.trcl.gpu.CanvasProvider; import org.jtrfp.trcl.gpu.GLExecutor; import org.springframework.stereotype.Component; @Component public class RootWindow extends JFrame implements GLExecutor, CanvasProvider { /** * */ private static final long serialVersionUID = -2412572500302248185L; static {GLProfile.initSingleton();} private final GLProfile glProfile = GLProfile.get(GLProfile.GL2GL3); private final GLCapabilities capabilities = new GLCapabilities(glProfile); private final GLCanvas canvas = new GLCanvas(capabilities); public RootWindow(){ this("Terminal Recall"); } public RootWindow(final String title) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { setVisible(false); canvas.setFocusTraversalKeysEnabled(false); getContentPane().add(canvas); setSize(800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setFocusTraversalKeysEnabled(false); setJMenuBar(new JMenuBar()); setTitle(title); setVisible(true); } }); } catch (Exception e) { e.printStackTrace(); }//end try/catch Exception }//end constructor public GLCanvas getCanvas() { return canvas; } public <T> GLFutureTask<T> submitToGL(Callable<T> c){ final GLCanvas canvas = getCanvas(); final GLContext context = canvas.getContext(); final GLFutureTask<T> result = new GLFutureTask<T>(canvas,c); if(context.isCurrent()) if(context.isCurrent()){ result.run(); return result; }else{ context.makeCurrent(); result.run(); context.release(); } result.enqueue(); return result; }//end submitToGL(...) }// end RootWindow
src/main/java/org/jtrfp/trcl/core/RootWindow.java
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2012-2014 Chuck Ritola * Part of the jTRFP.org project * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl.core; import java.util.concurrent.Callable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.jtrfp.trcl.gpu.CanvasProvider; import org.jtrfp.trcl.gpu.GLExecutor; import org.springframework.stereotype.Component; @Component public class RootWindow extends JFrame implements GLExecutor, CanvasProvider { /** * */ private static final long serialVersionUID = -2412572500302248185L; static {GLProfile.initSingleton();} private final GLProfile glProfile = GLProfile.get(GLProfile.GL2GL3); private final GLCapabilities capabilities = new GLCapabilities(glProfile); private final GLCanvas canvas = new GLCanvas(capabilities); public RootWindow(){ this("Terminal Recall"); } public RootWindow(String title) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { canvas.setFocusTraversalKeysEnabled(false); getContentPane().add(canvas); setVisible(true); setSize(800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setFocusTraversalKeysEnabled(false); } }); } catch (Exception e) { e.printStackTrace(); }//end try/catch Exception setTitle(title); }//end constructor public GLCanvas getCanvas() { return canvas; } public <T> GLFutureTask<T> submitToGL(Callable<T> c){ final GLCanvas canvas = getCanvas(); final GLContext context = canvas.getContext(); final GLFutureTask<T> result = new GLFutureTask<T>(canvas,c); if(context.isCurrent()) if(context.isCurrent()){ result.run(); return result; }else{ context.makeCurrent(); result.run(); context.release(); } result.enqueue(); return result; }//end submitToGL(...) }// end RootWindow
Change setTitle(..) ordering in RootWindow.
src/main/java/org/jtrfp/trcl/core/RootWindow.java
Change setTitle(..) ordering in RootWindow.
Java
mpl-2.0
dfeb4f3ad9b0d1c16c7fa8247c4bc1289410b064
0
jflory7/RIT-ISTE121-2155-MiniProject1
import javax.swing.*; import java.awt.*; import java.awt.Color.*; import java.awt.event.*; import javax.swing.event.*; import java.util.Random; /* * Timothy Endersby * ISTE 121 * Homework 2 - "GUI from Hell" */ public class GUIFromHell extends JFrame implements ActionListener, MouseListener{ //Personal imformation private JLabel jlName; private JLabel jlAge; private JTextField jtfName; private JTextField jtfAge; //Array of names for each letter of the alphabet private String[] names; //Solor sliders and button and something else private JLabel jlRed; private JLabel jlGreen; private JLabel jlBlue; private JSlider jsRed; private JSlider jsGreen; private JSlider jsBlue; private JButton jbSetColor; //Slider values private int red; private int blue; private int green; //Rating buttins private JLabel jlRate; private JRadioButton jrbOne; private JRadioButton jrbTwo; private JRadioButton jrbThree; private JRadioButton jrbFour; private JRadioButton jrbFive; private JRadioButton jrbHidden; //File menu options private JMenuItem jmiExit; private JMenuItem jmiClear; private JMenuItem jmiAbout; //holds last value for age - makes sure age dosn't repeat add if user presses enter private String lastAge; //Exit counter - counts number of times exit has been pressed (reset to 0 with clear) private int exitCount; //Removed "FINE DON'T PUSH IT" after button was pushed private boolean buttonPushed; /* * Starts the GUI after asking several anoying questions */ public static void main(String [] args){ //ask lots of annoying questions if(true){//Set to false when working on the code to speed things up try{//Try catch needed for sleep method JOptionPane.showMessageDialog(null, "Welcome to GUI from Hell"); JOptionPane.showMessageDialog(null, "Made by Timothy Endersby"); JOptionPane.showMessageDialog(null, "Are you ready to begin?"); Thread.sleep(2500);//wait 2.5 seconds - prevents user from just hitting enter over and over JOptionPane.showMessageDialog(null, "Are you sure?"); Thread.sleep(1000); JOptionPane.showMessageDialog(null, "You may start..."); Thread.sleep(1000); JOptionPane.showMessageDialog(null, "right..."); Thread.sleep(1000); JOptionPane.showMessageDialog(null, "now..."); }catch(InterruptedException e){} } new GUIFromHell(); } /* * Creates the 4 sections of the GUI * Menu Bar * Personal Info * Color Sliders * Rating */ public GUIFromHell(){ //Set defaults addMouseListener(this); lastAge = ""; red = 128; green = 128; blue = 128; getContentPane().setBackground(Color.YELLOW); exitCount = 0; buttonPushed = false; //List of names and gender of those names are random names = new String[]{"Anthony", "Brian", "Cara", "David", "Emma", "Freddy", "Grace", "Hannah", "Isaac", "Jessica", "Kyle", "Lauren", "Matthew ", "Natalie", "Oliver", "Paige", "Quinn", "Ryan", "Samuel", "Thomas", "Urias", "Victoria", "Willian", "Xavier", "Yazmin", "Zachary"}; //Make top section with menu bar and personal info JPanel jpTop = new JPanel(new BorderLayout()); jpTop.setOpaque(false);//So background color can come through //Make Menu Bar JMenuBar menuBar = new JMenuBar(); JMenu jmFile = new JMenu("File"); jmiClear = new JMenuItem("Clear"); jmFile.add(jmiClear); jmiExit = new JMenuItem("Exit"); jmFile.add(jmiExit); menuBar.add(jmFile); JMenu jmHelp = new JMenu("Help"); jmiAbout = new JMenuItem("About"); jmHelp.add(jmiAbout); menuBar.add(jmHelp); jmiClear.addActionListener(this); jmiExit.addActionListener(this); jmiAbout.addActionListener(this); jpTop.add(menuBar, BorderLayout.NORTH); //Make personal information section JPanel jpInfo = new JPanel(new GridLayout(0, 2)); jpInfo.setOpaque(false); jlName = new JLabel("Name:"); jlName.setHorizontalAlignment(JLabel.RIGHT); jpInfo.add(jlName); jtfName = new JTextField(10); jpInfo.add(jtfName); jlAge = new JLabel("Age:"); jlAge.setHorizontalAlignment(JLabel.RIGHT); jpInfo.add(jlAge); jtfAge = new JTextField(10); jpInfo.add(jtfAge); jpTop.add(jpInfo); add(jpTop, BorderLayout.NORTH); //add Key Listener to name text field KeyListener klName = new KeyListener() { public void keyPressed(KeyEvent keyEvent) {} public void keyTyped(KeyEvent keyEvent) { } /* * Replaces name with name from array matching first letter * if not a letter, it will be cleared * turns off listener once name has been set */ public void keyReleased(KeyEvent keyEvent) { try{ String name = names[(int)Character.toLowerCase(keyEvent.getKeyChar()) - 97]; jtfName.setText(name); jtfName.enable(false); }catch(ArrayIndexOutOfBoundsException e){ jtfName.setText(""); System.out.println("Text Error - tried to acess: " + ((int)keyEvent.getKeyChar() - 97) + " / " + keyEvent.getKeyChar()); } } }; jtfName.addKeyListener(klName); //add Age key listener KeyListener klAge = new KeyListener(){ public void keyPressed(KeyEvent keyEvent) {} public void keyTyped(KeyEvent keyEvent) {} /* * Pop up window, tells user what number they typed * Adds one to the number after user closes the window */ public void keyReleased(KeyEvent keyEvent) { if(!jtfAge.getText().equals(lastAge)){//to ensure no duplicates due to user pressing enter or spacebar try{ int age = Integer.parseInt(jtfAge.getText()); JOptionPane.showMessageDialog(null, "You typed a " + keyEvent.getKeyChar()); jtfAge.setText((age+1) + ""); lastAge = jtfAge.getText(); }catch(NumberFormatException e){ jtfAge.setText(""); } } } }; jtfAge.addKeyListener(klAge); //Make section two - Color Sliders JPanel jpSliders = new JPanel(new GridLayout(7,0)); //jpSliders.addMouseListener(this); jpSliders.setOpaque(false); //Make Label jlRed = new JLabel("Red"); jlRed.setHorizontalAlignment(JLabel.CENTER); jpSliders.add(jlRed); //Make red slider changes jsRed = new JSlider(JSlider.HORIZONTAL, 0, 255, 128); jsRed.addMouseListener(this); jsRed.setMinorTickSpacing(16); jsRed.setMajorTickSpacing(32); jsRed.setPaintTicks(true); jsRed.setPaintLabels(true); jsRed.setOpaque(false); jpSliders.add(jsRed); //Ad change listener to change color when slider is moved jsRed.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ce) { red = ((JSlider) ce.getSource()).getValue(); getContentPane().setBackground(new Color(red, 0, 0)); } }); //Green slider jlGreen = new JLabel("Green"); jlGreen.setHorizontalAlignment(JLabel.CENTER); jpSliders.add(jlGreen); jsGreen = new JSlider(JSlider.HORIZONTAL, 0, 255, 128); jsGreen.addMouseListener(this); jsGreen.setMinorTickSpacing(16); jsGreen.setMajorTickSpacing(32); jsGreen.setPaintTicks(true); jsGreen.setPaintLabels(true); jsGreen.setOpaque(false); jpSliders.add(jsGreen); jsGreen.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ce) { green = ((JSlider) ce.getSource()).getValue(); getContentPane().setBackground(new Color(0, green, 0)); } }); //Blue slider jlBlue = new JLabel("Blue"); jlBlue.setHorizontalAlignment(JLabel.CENTER); jpSliders.add(jlBlue); jsBlue = new JSlider(JSlider.HORIZONTAL, 0, 255, 128); jsBlue.addMouseListener(this); jsBlue.setMinorTickSpacing(16); jsBlue.setMajorTickSpacing(32); jsBlue.setPaintTicks(true); jsBlue.setPaintLabels(true); jsBlue.setOpaque(false); jpSliders.add(jsBlue); jsBlue.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ce) { blue = ((JSlider) ce.getSource()).getValue(); getContentPane().setBackground(new Color(0, 0, blue)); } }); //"Set color" button jbSetColor = new JButton("Set Color"); jbSetColor.setToolTipText("This button is pretty self explanatory"); jpSliders.add(jbSetColor); jbSetColor.addActionListener(this); jbSetColor.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseExited(MouseEvent e) { jbSetColor.setBackground(new Color(red, blue, green)); if(!buttonPushed){ JOptionPane.showMessageDialog(null, "FINE, DON'T PUSH IT"); }else{ buttonPushed = false; } } public void mouseEntered(MouseEvent e) { jbSetColor.setBackground(new Color(red, blue, green).brighter()); JOptionPane.showMessageDialog(null, "You going to press the button or not?"); } }); add(jpSliders, BorderLayout.CENTER); //Make app 5 star rating section JPanel jpRating = new JPanel(new GridLayout(2, 0)); jlRate = new JLabel("Please Rate this app from 1 to 5 stars"); jpRating.add(jlRate); jpRating.setOpaque(false); jlRate.setOpaque(false); JPanel jpStars = new JPanel(new GridLayout(0, 5)); jpStars.setOpaque(false); //Make the 6 (one invisible) radio buttons jrbOne = new JRadioButton("1"); jrbOne.setOpaque(false); jrbTwo = new JRadioButton("2"); jrbTwo.setOpaque(false); jrbThree = new JRadioButton("3"); jrbThree.setOpaque(false); jrbFour = new JRadioButton("4"); jrbFour.setOpaque(false); jrbFive = new JRadioButton("5"); jrbFive.setOpaque(false); jrbHidden = new JRadioButton("hidden");//this one is not visible, selected to deselect all others //Add 6 Radio buttons to the group ButtonGroup bgStars = new ButtonGroup(); bgStars.add(jrbOne); bgStars.add(jrbTwo); bgStars.add(jrbThree); bgStars.add(jrbFour); bgStars.add(jrbFive); bgStars.add(jrbHidden); //Add 5 to the panel jpStars.add(jrbOne); jpStars.add(jrbTwo); jpStars.add(jrbThree); jpStars.add(jrbFour); jpStars.add(jrbFive); //Add action listeners to the 5 buttons ActionListener ratingListener = new ActionListener() { public void actionPerformed(ActionEvent ae){ Object choice = ae.getSource(); if(choice == jrbOne){ JOptionPane.showMessageDialog(null, "ONLY ONE STAR?!?!?!?!?! WHO ARE YOU?"); jrbHidden.setSelected(true); } else if(choice == jrbTwo){ JOptionPane.showMessageDialog(null, "I put a lot of time into this, and you only gave me two stars?\nYou're a terrible human."); jrbHidden.setSelected(true); } else if(choice == jrbThree){ JOptionPane.showMessageDialog(null, "Really? Three Star? This must be a mistake."); jrbHidden.setSelected(true); } else if(choice == jrbFour){ JOptionPane.showMessageDialog(null, "Seriously? Why only 4?"); jrbHidden.setSelected(true); } else if(choice == jrbFive){ JOptionPane.showMessageDialog(null, "Thank you\nSince you're so nice, we're going to let you select that again."); jrbHidden.setSelected(true); } } }; jrbOne.addActionListener(ratingListener); jrbTwo.addActionListener(ratingListener); jrbThree.addActionListener(ratingListener); jrbFour.addActionListener(ratingListener); jrbFive.addActionListener(ratingListener); jpRating.add(jpStars); add(jpRating, BorderLayout.SOUTH); pack(); setLocationRelativeTo(null); setTitle("Tim Endersby - GUI from Hell"); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } /* * Controls responses for rating buttons, set color, and menu options */ public void actionPerformed(ActionEvent ae){ Object choice = ae.getSource(); //Set color button if(choice == jbSetColor){ randomTextColors(); getContentPane().setBackground(new Color(red, green, blue)); JOptionPane.showMessageDialog(null, "Color set to " + red + ", " + blue + ", " + green); buttonPushed = true; try{ Thread.sleep(1500); }catch(InterruptedException e){} getContentPane().setBackground(Color.YELLOW); JOptionPane.showMessageDialog(null, "Nevermind, that color was UGLY!" + "\n I like yellow better"); //Menu items }else if(choice == jmiClear){ clear(); }else if(choice == jmiAbout){ JOptionPane.showMessageDialog(null, "GUI from hell" + "\nMade by Timothy Endersby" + "\n\nWhen you first open the game" + "\n A series of JOptionPanes will pop up, welcoming you to the game" + "\n Between some of them there is 1 or 2 second delay, stopping the user from just pushing enter over and over" + "\n\nControls for GUI from hell" + "\n Menu" + "\n File" + "\n Clear - Fills personal info with random name and age (0-100), sets background to random color and sliders to match that color, sets a 5 star rating, sets text to random colors" + "\n Exit - First time you click, JOptionPane pops up, program does not exit, Second time you click, JOptionPane pops up, program closes (counter for this resets with clear)" + "\n About" + "\n Help - Shows help window with information about the program (This one)" + "\n\n Personal info" + "\n Name - When user enters a letter, it fills the field with a name that stars with that letter, and locks it (if something other than a letter is entered, it is deleted)" + "\n Age - When user enters a number, a JOptionPane pops up, telling the user what number it enterned, and then adds one to the age ((if something other than a number is entered, it is deleted)" + "\n\n Color" + "\n Sliders - When selected, background shows color of that slider only (with other colors set to zero) - when mouse released, color is set back to yellow" + "\n Set Color - Changes to color of sliders when moused over, JOptionPane pops up when moused over, when mouse leaves button, another JOptionPane apears" + "\n When button is clicked, background is set to color of sliders, and JOptionPane pops up to show color values, after 1.5 seconds, color is set back to yellow as a JOptionPane pops up" + "\n Also sets all text to random colors" + "\n\n Rating" + "\n 1-4 stars - JOptionPane pops up, asks why they scored it so low, and then deselects their choice" + "\n 5 stars - JOptionPane pops up, thanks them for picking 5, deselects 5 and tells them to do it again"); }else if(choice == jmiExit){ exitCount++; if(exitCount == 1){ JOptionPane.showMessageDialog(null, "Why do you want to leave so soon?\nI'm sure if you spend more time you'll like it"); }else if(exitCount == 2){ JOptionPane.showMessageDialog(null, "FINE! LEAVE! WE DON'T NEED YOU"); JOptionPane.showMessageDialog(null, "Closing..."); System.exit(0); }else{ System.out.println("exit count error"); System.exit(0); } } else{ System.out.println("How did you get here with " + choice); } } /* * Executed when clear is pressed in menu * Sets name, age, color, and sliders to random values * Sets rating to 5 stars * Resets exit counter */ private void clear(){ Random ran = new Random(); try{ randomTextColors(); //Random personal info jtfName.setText(names[ran.nextInt(26)]); jtfName.enable(false); jtfAge.setText(ran.nextInt(100) + ""); //Random color, and slider to match that color red = ran.nextInt(256); green = ran.nextInt(256); blue = ran.nextInt(256); jsRed.setValue(red); jsGreen.setValue(green); jsBlue.setValue(blue); getContentPane().setBackground(new Color(red, green, blue)); //Select 5 stars jrbFive.setSelected(true); //reser ecit counter exitCount = 0; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Random number error"); } } /* * Sets all the text in the GUI to random colors */ public void randomTextColors(){ Random ran = new Random(); jlName.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jlAge.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbOne.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbTwo.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbThree.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbFour.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbFive.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jlRed.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jlGreen.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jlBlue.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jsRed.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jsGreen.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jsBlue.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jbSetColor.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); } /* * Sets background color to yellow after slider is released */ public void mouseReleased(MouseEvent e) { getContentPane().setBackground(Color.YELLOW); } public void mousePressed(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} }
GUIFromHell.java
import javax.swing.*; import java.awt.*; import java.awt.Color.*; import java.awt.event.*; import javax.swing.event.*; import java.util.Random; /* * Timothy Endersby * ISTE 121 * Homework 2 - "GUI from Hell" */ public class GUIFromHell extends JFrame implements ActionListener, MouseListener{ //Personal imformation private JLabel jlName; private JLabel jlAge; private JTextField jtfName; private JTextField jtfAge; //Array of names for each letter of the alphabet private String[] names; //Solor sliders and button and something else private JLabel jlRed; private JLabel jlGreen; private JLabel jlBlue; private JSlider jsRed; private JSlider jsGreen; private JSlider jsBlue; private JButton jbSetColor; //Slider values private int red; private int blue; private int green; //Rating buttins private JLabel jlRate; private JRadioButton jrbOne; private JRadioButton jrbTwo; private JRadioButton jrbThree; private JRadioButton jrbFour; private JRadioButton jrbFive; private JRadioButton jrbHidden; //File menu options private JMenuItem jmiExit; private JMenuItem jmiClear; private JMenuItem jmiAbout; //holds last value for age - makes sure age dosn't repeat add if user presses enter private String lastAge; //Exit counter - counts number of times exit has been pressed (reset to 0 with clear) private int exitCount; //Removed "FINE DON'T PUSH IT" after button was pushed private boolean buttonPushed; /* * Starts the GUI after asking several anoying questions */ public static void main(String [] args){ //ask lots of annoying questions if(true){//Set to false when working on the code to speed things up try{//Try catch needed for sleep method JOptionPane.showMessageDialog(null, "Welcome to GUI from Hell"); JOptionPane.showMessageDialog(null, "Made by Timothy Endersby"); JOptionPane.showMessageDialog(null, "Are you ready to begin?"); Thread.sleep(2500);//wait 2.5 seconds - prevents user from just hitting enter over and over JOptionPane.showMessageDialog(null, "Are you sure?"); Thread.sleep(1000); JOptionPane.showMessageDialog(null, "You may start..."); Thread.sleep(1000); JOptionPane.showMessageDialog(null, "right..."); Thread.sleep(1000); JOptionPane.showMessageDialog(null, "now..."); }catch(InterruptedException e){} } new GUIFromHell(); } /* * Creates the 4 sections of the GUI * Menu Bar * Personal Info * Color Sliders * Rating */ public GUIFromHell(){ //Set defaults addMouseListener(this); lastAge = ""; red = 128; green = 128; blue = 128; getContentPane().setBackground(Color.YELLOW); exitCount = 0; buttonPushed = false; //List of names and gender of those names are random names = new String[]{"Anthony", "Brian", "Cara", "David", "Emma", "Freddy", "Grace", "Hannah", "Isaac", "Jessica", "Kyle", "Lauren", "Matthew ", "Natalie", "Oliver", "Paige", "Quinn", "Ryan", "Samuel", "Thomas", "Urias", "Victoria", "Willian", "Xavier", "Yazmin", "Zachary"}; //Make top section with menu bar and personal info JPanel jpTop = new JPanel(new BorderLayout()); jpTop.setOpaque(false);//So background color can come through //Make Menu Bar JMenuBar menuBar = new JMenuBar(); JMenu jmFile = new JMenu("File"); jmiClear = new JMenuItem("Clear"); jmFile.add(jmiClear); jmiExit = new JMenuItem("Exit"); jmFile.add(jmiExit); menuBar.add(jmFile); JMenu jmHelp = new JMenu("Help"); jmiAbout = new JMenuItem("About"); jmHelp.add(jmiAbout); menuBar.add(jmHelp); jmiClear.addActionListener(this); jmiExit.addActionListener(this); jmiAbout.addActionListener(this); jpTop.add(menuBar, BorderLayout.NORTH); //Make personal information section JPanel jpInfo = new JPanel(new GridLayout(0, 2)); jpInfo.setOpaque(false); jlName = new JLabel("Name:"); jlName.setHorizontalAlignment(JLabel.RIGHT); jpInfo.add(jlName); jtfName = new JTextField(10); jpInfo.add(jtfName); jlAge = new JLabel("Age:"); jlAge.setHorizontalAlignment(JLabel.RIGHT); jpInfo.add(jlAge); jtfAge = new JTextField(10); jpInfo.add(jtfAge); jpTop.add(jpInfo); add(jpTop, BorderLayout.NORTH); //add Key Listener to name text field KeyListener klName = new KeyListener() { public void keyPressed(KeyEvent keyEvent) {} public void keyTyped(KeyEvent keyEvent) { } /* * Replaces name with name from array matching first letter * if not a letter, it will be cleared * turns off listener once name has been set */ public void keyReleased(KeyEvent keyEvent) { try{ String name = names[(int)Character.toLowerCase(keyEvent.getKeyChar()) - 97]; jtfName.setText(name); jtfName.enable(false); }catch(ArrayIndexOutOfBoundsException e){ jtfName.setText(""); System.out.println("Text Error - tried to acess: " + ((int)keyEvent.getKeyChar() - 97) + " / " + keyEvent.getKeyChar()); } } }; jtfName.addKeyListener(klName); //add Age key listener KeyListener klAge = new KeyListener(){ public void keyPressed(KeyEvent keyEvent) {} public void keyTyped(KeyEvent keyEvent) {} /* * Pop up window, tells user what number they typed * Adds one to the number after user closes the window */ public void keyReleased(KeyEvent keyEvent) { if(!jtfAge.getText().equals(lastAge)){//to ensure no duplicates due to user pressing enter or spacebar try{ int age = Integer.parseInt(jtfAge.getText()); JOptionPane.showMessageDialog(null, "You typed a " + keyEvent.getKeyChar()); jtfAge.setText((age+1) + ""); lastAge = jtfAge.getText(); }catch(NumberFormatException e){ jtfAge.setText(""); } } } }; jtfAge.addKeyListener(klAge); //Make section two - Color Sliders JPanel jpSliders = new JPanel(new GridLayout(7,0)); //jpSliders.addMouseListener(this); jpSliders.setOpaque(false); //Make Label jlRed = new JLabel("Red"); jlRed.setHorizontalAlignment(JLabel.CENTER); jpSliders.add(jlRed); //Make red slider jsRed = new JSlider(JSlider.HORIZONTAL, 0, 255, 128); jsRed.addMouseListener(this); jsRed.setMinorTickSpacing(16); jsRed.setMajorTickSpacing(32); jsRed.setPaintTicks(true); jsRed.setPaintLabels(true); jsRed.setOpaque(false); jpSliders.add(jsRed); //Ad change listener to change color when slider is moved jsRed.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ce) { red = ((JSlider) ce.getSource()).getValue(); getContentPane().setBackground(new Color(red, 0, 0)); } }); //Green slider jlGreen = new JLabel("Green"); jlGreen.setHorizontalAlignment(JLabel.CENTER); jpSliders.add(jlGreen); jsGreen = new JSlider(JSlider.HORIZONTAL, 0, 255, 128); jsGreen.addMouseListener(this); jsGreen.setMinorTickSpacing(16); jsGreen.setMajorTickSpacing(32); jsGreen.setPaintTicks(true); jsGreen.setPaintLabels(true); jsGreen.setOpaque(false); jpSliders.add(jsGreen); jsGreen.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ce) { green = ((JSlider) ce.getSource()).getValue(); getContentPane().setBackground(new Color(0, green, 0)); } }); //Blue slider jlBlue = new JLabel("Blue"); jlBlue.setHorizontalAlignment(JLabel.CENTER); jpSliders.add(jlBlue); jsBlue = new JSlider(JSlider.HORIZONTAL, 0, 255, 128); jsBlue.addMouseListener(this); jsBlue.setMinorTickSpacing(16); jsBlue.setMajorTickSpacing(32); jsBlue.setPaintTicks(true); jsBlue.setPaintLabels(true); jsBlue.setOpaque(false); jpSliders.add(jsBlue); jsBlue.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ce) { blue = ((JSlider) ce.getSource()).getValue(); getContentPane().setBackground(new Color(0, 0, blue)); } }); //"Set color" button jbSetColor = new JButton("Set Color"); jbSetColor.setToolTipText("This button is pretty self explanatory"); jpSliders.add(jbSetColor); jbSetColor.addActionListener(this); jbSetColor.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseExited(MouseEvent e) { jbSetColor.setBackground(new Color(red, blue, green)); if(!buttonPushed){ JOptionPane.showMessageDialog(null, "FINE, DON'T PUSH IT"); }else{ buttonPushed = false; } } public void mouseEntered(MouseEvent e) { jbSetColor.setBackground(new Color(red, blue, green).brighter()); JOptionPane.showMessageDialog(null, "You going to press the button or not?"); } }); add(jpSliders, BorderLayout.CENTER); //Make app 5 star rating section JPanel jpRating = new JPanel(new GridLayout(2, 0)); jlRate = new JLabel("Please Rate this app from 1 to 5 stars"); jpRating.add(jlRate); jpRating.setOpaque(false); jlRate.setOpaque(false); JPanel jpStars = new JPanel(new GridLayout(0, 5)); jpStars.setOpaque(false); //Make the 6 (one invisible) radio buttons jrbOne = new JRadioButton("1"); jrbOne.setOpaque(false); jrbTwo = new JRadioButton("2"); jrbTwo.setOpaque(false); jrbThree = new JRadioButton("3"); jrbThree.setOpaque(false); jrbFour = new JRadioButton("4"); jrbFour.setOpaque(false); jrbFive = new JRadioButton("5"); jrbFive.setOpaque(false); jrbHidden = new JRadioButton("hidden");//this one is not visible, selected to deselect all others //Add 6 Radio buttons to the group ButtonGroup bgStars = new ButtonGroup(); bgStars.add(jrbOne); bgStars.add(jrbTwo); bgStars.add(jrbThree); bgStars.add(jrbFour); bgStars.add(jrbFive); bgStars.add(jrbHidden); //Add 5 to the panel jpStars.add(jrbOne); jpStars.add(jrbTwo); jpStars.add(jrbThree); jpStars.add(jrbFour); jpStars.add(jrbFive); //Add action listeners to the 5 buttons ActionListener ratingListener = new ActionListener() { public void actionPerformed(ActionEvent ae){ Object choice = ae.getSource(); if(choice == jrbOne){ JOptionPane.showMessageDialog(null, "ONLY ONE STAR?!?!?!?!?! WHO ARE YOU?"); jrbHidden.setSelected(true); } else if(choice == jrbTwo){ JOptionPane.showMessageDialog(null, "I put a lot of time into this, and you only gave me two stars?\nYou're a terrible human."); jrbHidden.setSelected(true); } else if(choice == jrbThree){ JOptionPane.showMessageDialog(null, "Really? Three Star? This must be a mistake."); jrbHidden.setSelected(true); } else if(choice == jrbFour){ JOptionPane.showMessageDialog(null, "Seriously? Why only 4?"); jrbHidden.setSelected(true); } else if(choice == jrbFive){ JOptionPane.showMessageDialog(null, "Thank you\nSince you're so nice, we're going to let you select that again."); jrbHidden.setSelected(true); } } }; jrbOne.addActionListener(ratingListener); jrbTwo.addActionListener(ratingListener); jrbThree.addActionListener(ratingListener); jrbFour.addActionListener(ratingListener); jrbFive.addActionListener(ratingListener); jpRating.add(jpStars); add(jpRating, BorderLayout.SOUTH); pack(); setLocationRelativeTo(null); setTitle("Tim Endersby - GUI from Hell"); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } /* * Controls responses for rating buttons, set color, and menu options */ public void actionPerformed(ActionEvent ae){ Object choice = ae.getSource(); //Set color button if(choice == jbSetColor){ randomTextColors(); getContentPane().setBackground(new Color(red, green, blue)); JOptionPane.showMessageDialog(null, "Color set to " + red + ", " + blue + ", " + green); buttonPushed = true; try{ Thread.sleep(1500); }catch(InterruptedException e){} getContentPane().setBackground(Color.YELLOW); JOptionPane.showMessageDialog(null, "Nevermind, that color was UGLY!" + "\n I like yellow better"); //Menu items }else if(choice == jmiClear){ clear(); }else if(choice == jmiAbout){ JOptionPane.showMessageDialog(null, "GUI from hell" + "\nMade by Timothy Endersby" + "\n\nWhen you first open the game" + "\n A series of JOptionPanes will pop up, welcoming you to the game" + "\n Between some of them there is 1 or 2 second delay, stopping the user from just pushing enter over and over" + "\n\nControls for GUI from hell" + "\n Menu" + "\n File" + "\n Clear - Fills personal info with random name and age (0-100), sets background to random color and sliders to match that color, sets a 5 star rating, sets text to random colors" + "\n Exit - First time you click, JOptionPane pops up, program does not exit, Second time you click, JOptionPane pops up, program closes (counter for this resets with clear)" + "\n About" + "\n Help - Shows help window with information about the program (This one)" + "\n\n Personal info" + "\n Name - When user enters a letter, it fills the field with a name that stars with that letter, and locks it (if something other than a letter is entered, it is deleted)" + "\n Age - When user enters a number, a JOptionPane pops up, telling the user what number it enterned, and then adds one to the age ((if something other than a number is entered, it is deleted)" + "\n\n Color" + "\n Sliders - When selected, background shows color of that slider only (with other colors set to zero) - when mouse released, color is set back to yellow" + "\n Set Color - Changes to color of sliders when moused over, JOptionPane pops up when moused over, when mouse leaves button, another JOptionPane apears" + "\n When button is clicked, background is set to color of sliders, and JOptionPane pops up to show color values, after 1.5 seconds, color is set back to yellow as a JOptionPane pops up" + "\n Also sets all text to random colors" + "\n\n Rating" + "\n 1-4 stars - JOptionPane pops up, asks why they scored it so low, and then deselects their choice" + "\n 5 stars - JOptionPane pops up, thanks them for picking 5, deselects 5 and tells them to do it again"); }else if(choice == jmiExit){ exitCount++; if(exitCount == 1){ JOptionPane.showMessageDialog(null, "Why do you want to leave so soon?\nI'm sure if you spend more time you'll like it"); }else if(exitCount == 2){ JOptionPane.showMessageDialog(null, "FINE! LEAVE! WE DON'T NEED YOU"); JOptionPane.showMessageDialog(null, "Closing..."); System.exit(0); }else{ System.out.println("exit count error"); System.exit(0); } } else{ System.out.println("How did you get here with " + choice); } } /* * Executed when clear is pressed in menu * Sets name, age, color, and sliders to random values * Sets rating to 5 stars * Resets exit counter */ private void clear(){ Random ran = new Random(); try{ randomTextColors(); //Random personal info jtfName.setText(names[ran.nextInt(26)]); jtfName.enable(false); jtfAge.setText(ran.nextInt(100) + ""); //Random color, and slider to match that color red = ran.nextInt(256); green = ran.nextInt(256); blue = ran.nextInt(256); jsRed.setValue(red); jsGreen.setValue(green); jsBlue.setValue(blue); getContentPane().setBackground(new Color(red, green, blue)); //Select 5 stars jrbFive.setSelected(true); //reser ecit counter exitCount = 0; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Random number error"); } } /* * Sets all the text in the GUI to random colors */ public void randomTextColors(){ Random ran = new Random(); jlName.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jlAge.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbOne.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbTwo.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbThree.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbFour.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jrbFive.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jlRed.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jlGreen.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jlBlue.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jsRed.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jsGreen.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jsBlue.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); jbSetColor.setForeground(new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256))); } /* * Sets background color to yellow after slider is released */ public void mouseReleased(MouseEvent e) { getContentPane().setBackground(Color.YELLOW); } public void mousePressed(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} }
Changed comment
GUIFromHell.java
Changed comment
Java
agpl-3.0
ab345dc4c356c399d5009a9badcc89fd34582395
0
akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow
/* * Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package org.waterforpeople.mapping.app.gwt.server.surveyinstance; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.QuestionAnswerStoreDto; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceService; import org.waterforpeople.mapping.app.util.DtoMarshaller; import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.SurveyAttributeMapping; import org.waterforpeople.mapping.domain.SurveyInstance; import org.waterforpeople.mapping.helper.SurveyEventHelper; import com.gallatinsystems.framework.analytics.summarization.DataSummarizationRequest; import com.gallatinsystems.framework.domain.DataChangeRecord; import com.gallatinsystems.framework.gwt.dto.client.ResponseDto; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.surveyal.app.web.SurveyalRestRequest; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class SurveyInstanceServiceImpl extends RemoteServiceServlet implements SurveyInstanceService { private static final long serialVersionUID = -9175237700587455358L; private static final Logger log = Logger .getLogger(SurveyInstanceServiceImpl.class); @Override public ResponseDto<ArrayList<SurveyInstanceDto>> listSurveyInstance( Date beginDate, Date toDate, boolean unapprovedOnlyFlag, Long surveyId, String source, String cursorString) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); HashMap<Long, String> surveyMap = new HashMap<Long, String>(); for (Survey s : surveyList) { surveyMap.put(s.getKey().getId(), s.getPath() + "/" + s.getCode()); } List<SurveyInstance> siList = null; if (beginDate == null && toDate == null) { Calendar c = Calendar.getInstance(); c.add(Calendar.YEAR, -90); beginDate = c.getTime(); } siList = dao.listByDateRange(beginDate, toDate, unapprovedOnlyFlag, surveyId, source, cursorString); String newCursor = SurveyInstanceDAO.getCursor(siList); ArrayList<SurveyInstanceDto> siDtoList = new ArrayList<SurveyInstanceDto>(); for (SurveyInstance siItem : siList) { String code = surveyMap.get(siItem.getSurveyId()); SurveyInstanceDto siDto = marshalToDto(siItem); if (code != null) siDto.setSurveyCode(code); siDtoList.add(siDto); } ResponseDto<ArrayList<SurveyInstanceDto>> response = new ResponseDto<ArrayList<SurveyInstanceDto>>(); response.setCursorString(newCursor); response.setPayload(siDtoList); return response; } public List<QuestionAnswerStoreDto> listQuestionsByInstance(Long instanceId) { List<QuestionAnswerStoreDto> questionDtos = new ArrayList<QuestionAnswerStoreDto>(); SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> questions = dao.listQuestionAnswerStore( instanceId, null); QuestionDao qDao = new QuestionDao(); if (questions != null && questions.size() > 0) { List<Question> qList = qDao.listQuestionInOrder(questions.get(0) .getSurveyId()); Map<Integer, QuestionAnswerStoreDto> orderedResults = new TreeMap<Integer, QuestionAnswerStoreDto>(); int notFoundCount = 0; if (qList != null) { for (QuestionAnswerStore qas : questions) { QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(qas, qasDto); int idx = -1 - notFoundCount; for (int i = 0; i < qList.size(); i++) { if (Long.parseLong(qas.getQuestionID()) == qList.get(i) .getKey().getId()) { qasDto.setQuestionText(qList.get(i).getText()); idx = i; break; } } if (idx < 0) { // do this to prevent collisions on the -1 key if there // is more than one questionAnswerStore item that isn't // in the question list notFoundCount++; } orderedResults.put(idx, qasDto); } } questionDtos = new ArrayList<QuestionAnswerStoreDto>( orderedResults.values()); } return questionDtos; } private SurveyInstanceDto marshalToDto(SurveyInstance si) { SurveyInstanceDto siDto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(si, siDto); siDto.setQuestionAnswersStore(null); if (si.getQuestionAnswersStore() != null) { for (QuestionAnswerStore qas : si.getQuestionAnswersStore()) { siDto.addQuestionAnswerStore(marshalToDto(qas)); } } return siDto; } private QuestionAnswerStoreDto marshalToDto(QuestionAnswerStore qas) { QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(qas, qasDto); return qasDto; } /** * updates the list of QAS dto objects passed in and fires summarization * messages to the async queues */ @Override public List<QuestionAnswerStoreDto> updateQuestions( List<QuestionAnswerStoreDto> dtoList, boolean isApproved) { return updateQuestions(dtoList, isApproved, true); } public List<QuestionAnswerStoreDto> updateQuestions( List<QuestionAnswerStoreDto> dtoList, boolean isApproved, boolean processSummaries) { List<QuestionAnswerStore> domainList = new ArrayList<QuestionAnswerStore>(); for (QuestionAnswerStoreDto dto : dtoList) { QuestionAnswerStore answer = new QuestionAnswerStore(); DtoMarshaller.copyToCanonical(answer, dto); if (answer.getValue() != null) { answer.setValue(answer.getValue().replaceAll("\t", "")); } domainList.add(answer); } SurveyInstanceDAO dao = new SurveyInstanceDAO(); dao.save(domainList); // this is not active - questionAnswerSummary objects are updated in bulk // after the import in RawDataSpreadsheetImporter if (isApproved && processSummaries) { SurveyAttributeMappingDao mappingDao = new SurveyAttributeMappingDao(); // now send a change message for each item Queue queue = QueueFactory.getQueue("dataUpdate"); for (QuestionAnswerStoreDto item : dtoList) { DataChangeRecord value = new DataChangeRecord( QuestionAnswerStore.class.getName(), item.getQuestionID(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "QuestionDataChange") .param(DataSummarizationRequest.VALUE_KEY, value.packString())); // see if the question is mapped. And if it is, send an Access // Point // change message SurveyAttributeMapping mapping = mappingDao .findMappingForQuestion(item.getQuestionID()); if (mapping != null) { DataChangeRecord apValue = new DataChangeRecord( "AcessPointUpdate", mapping.getSurveyId() + "|" + mapping.getSurveyQuestionId() + "|" + item.getSurveyInstanceId() + "|" + mapping.getKey().getId(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "AccessPointChange") .param(DataSummarizationRequest.VALUE_KEY, apValue.packString())); } } } return dtoList; } /** * lists all responses for a single question */ @Override public ResponseDto<ArrayList<QuestionAnswerStoreDto>> listResponsesByQuestion( Long questionId, String cursorString) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> qasList = dao .listQuestionAnswerStoreForQuestion(questionId.toString(), cursorString); String newCursor = SurveyInstanceDAO.getCursor(qasList); ArrayList<QuestionAnswerStoreDto> qasDtoList = new ArrayList<QuestionAnswerStoreDto>(); for (QuestionAnswerStore item : qasList) { qasDtoList.add(marshalToDto(item)); } ResponseDto<ArrayList<QuestionAnswerStoreDto>> response = new ResponseDto<ArrayList<QuestionAnswerStoreDto>>(); response.setCursorString(newCursor); response.setPayload(qasDtoList); return response; } /** * deletes a survey instance. This will only back out Question summaries. To * back out the access point, the AP needs to be deleted manually since it * may have come from multiple instances. */ @Override public void deleteSurveyInstance(Long instanceId) { if (instanceId != null) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> answers = dao.listQuestionAnswerStore( instanceId, null); if (answers != null) { // back out summaries Queue queue = QueueFactory.getQueue("dataUpdate"); for (QuestionAnswerStore ans : answers) { DataChangeRecord value = new DataChangeRecord( QuestionAnswerStore.class.getName(), ans.getQuestionID(), ans.getValue(), ""); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, ans.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "QuestionDataChange") .param(DataSummarizationRequest.VALUE_KEY, value.packString())); } dao.delete(answers); } SurveyInstance instance = dao.getByKey(instanceId); if (instance != null) { dao.delete(instance); log.log(Level.INFO, "Deleted: " + instanceId); } } } /** * saves a new survey instance and triggers processing * * @param instance * @return */ public SurveyInstanceDto submitSurveyInstance(SurveyInstanceDto instance) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyInstance domain = new SurveyInstance(); DtoMarshaller.copyToCanonical(domain, instance); if (domain.getCollectionDate() == null) { domain.setCollectionDate(new Date()); } domain = dao.save(domain); instance.setKeyId(domain.getKey().getId()); if (instance.getQuestionAnswersStore() != null) { List<QuestionAnswerStore> answerList = new ArrayList<QuestionAnswerStore>(); for (QuestionAnswerStoreDto ans : instance .getQuestionAnswersStore()) { QuestionAnswerStore store = new QuestionAnswerStore(); if (ans.getCollectionDate() == null) { ans.setCollectionDate(domain.getCollectionDate()); } if (ans.getValue() != null) { ans.setValue(ans.getValue().replaceAll("\t", "")); if (ans.getValue().length() > 500) { ans.setValue(ans.getValue().substring(0, 499)); } } DtoMarshaller.copyToCanonical(store, ans); store.setSurveyInstanceId(domain.getKey().getId()); answerList.add(store); } dao.save(answerList); if (instance.getApprovedFlag() == null || !"False".equalsIgnoreCase(instance.getApprovedFlag())) { sendProcessingMessages(domain); } } SurveyEventHelper.fireEvent(SurveyEventHelper.SUBMISSION_EVENT, instance.getSurveyId(), instance.getKeyId()); return instance; } /** * marks the survey instance as approved, updating any changed answers as it * does so and then sends a processing message to the task queue so the * instance can be summarized. */ public void approveSurveyInstance(Long surveyInstanceId, List<QuestionAnswerStoreDto> changedAnswers) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyInstance instance = dao.getByKey(surveyInstanceId); if (changedAnswers != null && changedAnswers.size() > 0) { updateQuestions(changedAnswers, false); } if (instance != null) { if (instance.getApprovedFlag() == null || !"True".equalsIgnoreCase(instance.getApprovedFlag())) { instance.setApprovedFlag("True"); sendProcessingMessages(instance); // fire a survey event SurveyEventHelper.fireEvent(SurveyEventHelper.APPROVAL_EVENT, instance.getSurveyId(), instance.getKey().getId()); } } } /** * lists all surveyInstances associated with the surveyedLocaleId passed in. * * @param localeId * @return */ public ResponseDto<ArrayList<SurveyInstanceDto>> listInstancesByLocale( Long localeId, Date dateFrom, Date dateTo, String cursor) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); ResponseDto<ArrayList<SurveyInstanceDto>> response = new ResponseDto<ArrayList<SurveyInstanceDto>>(); ArrayList<SurveyInstanceDto> dtoList = new ArrayList<SurveyInstanceDto>(); List<SurveyInstance> instances = dao.listInstancesByLocale(localeId, dateFrom, dateTo, cursor); if (instances != null) { for (SurveyInstance inst : instances) { SurveyInstanceDto dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(inst, dto); dtoList.add(dto); } response.setPayload(dtoList); if (dtoList.size() == SurveyInstanceDAO.DEFAULT_RESULT_COUNT) { response.setCursorString(SurveyInstanceDAO.getCursor(instances)); } } return response; } public void sendProcessingMessages(SurveyInstance domain) { // send async request to populate the AccessPoint using the mapping QueueFactory.getDefaultQueue().add( TaskOptions.Builder.withUrl("/app_worker/task") .param("action", "addAccessPoint") .param("surveyId", domain.getKey().getId() + "")); // send asyn crequest to summarize the instance QueueFactory.getQueue("dataSummarization").add( TaskOptions.Builder.withUrl("/app_worker/datasummarization") .param("objectKey", domain.getKey().getId() + "") .param("type", "SurveyInstance")); QueueFactory.getDefaultQueue().add( TaskOptions.Builder .withUrl("/app_worker/surveyalservlet") .param(SurveyalRestRequest.ACTION_PARAM, SurveyalRestRequest.INGEST_INSTANCE_ACTION) .param(SurveyalRestRequest.SURVEY_INSTANCE_PARAM, domain.getKey().getId() + "")); } }
GAE/src/org/waterforpeople/mapping/app/gwt/server/surveyinstance/SurveyInstanceServiceImpl.java
/* * Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package org.waterforpeople.mapping.app.gwt.server.surveyinstance; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.QuestionAnswerStoreDto; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceService; import org.waterforpeople.mapping.app.util.DtoMarshaller; import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.SurveyAttributeMapping; import org.waterforpeople.mapping.domain.SurveyInstance; import org.waterforpeople.mapping.helper.SurveyEventHelper; import com.gallatinsystems.framework.analytics.summarization.DataSummarizationRequest; import com.gallatinsystems.framework.domain.DataChangeRecord; import com.gallatinsystems.framework.gwt.dto.client.ResponseDto; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.surveyal.app.web.SurveyalRestRequest; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class SurveyInstanceServiceImpl extends RemoteServiceServlet implements SurveyInstanceService { private static final long serialVersionUID = -9175237700587455358L; private static final Logger log = Logger .getLogger(SurveyInstanceServiceImpl.class); @Override public ResponseDto<ArrayList<SurveyInstanceDto>> listSurveyInstance( Date beginDate, Date toDate, boolean unapprovedOnlyFlag, Long surveyId, String source, String cursorString) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); HashMap<Long, String> surveyMap = new HashMap<Long, String>(); for (Survey s : surveyList) { surveyMap.put(s.getKey().getId(), s.getPath() + "/" + s.getCode()); } List<SurveyInstance> siList = null; if (beginDate == null && toDate == null) { Calendar c = Calendar.getInstance(); c.add(Calendar.YEAR, -90); beginDate = c.getTime(); } siList = dao.listByDateRange(beginDate, toDate, unapprovedOnlyFlag, surveyId, source, cursorString); String newCursor = SurveyInstanceDAO.getCursor(siList); ArrayList<SurveyInstanceDto> siDtoList = new ArrayList<SurveyInstanceDto>(); for (SurveyInstance siItem : siList) { String code = surveyMap.get(siItem.getSurveyId()); SurveyInstanceDto siDto = marshalToDto(siItem); if (code != null) siDto.setSurveyCode(code); siDtoList.add(siDto); } ResponseDto<ArrayList<SurveyInstanceDto>> response = new ResponseDto<ArrayList<SurveyInstanceDto>>(); response.setCursorString(newCursor); response.setPayload(siDtoList); return response; } public List<QuestionAnswerStoreDto> listQuestionsByInstance(Long instanceId) { List<QuestionAnswerStoreDto> questionDtos = new ArrayList<QuestionAnswerStoreDto>(); SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> questions = dao.listQuestionAnswerStore( instanceId, null); QuestionDao qDao = new QuestionDao(); if (questions != null && questions.size() > 0) { List<Question> qList = qDao.listQuestionInOrder(questions.get(0) .getSurveyId()); Map<Integer, QuestionAnswerStoreDto> orderedResults = new TreeMap<Integer, QuestionAnswerStoreDto>(); int notFoundCount = 0; if (qList != null) { for (QuestionAnswerStore qas : questions) { QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(qas, qasDto); int idx = -1 - notFoundCount; for (int i = 0; i < qList.size(); i++) { if (Long.parseLong(qas.getQuestionID()) == qList.get(i) .getKey().getId()) { qasDto.setQuestionText(qList.get(i).getText()); idx = i; break; } } if (idx < 0) { // do this to prevent collisions on the -1 key if there // is more than one questionAnswerStore item that isn't // in the question list notFoundCount++; } orderedResults.put(idx, qasDto); } } questionDtos = new ArrayList<QuestionAnswerStoreDto>( orderedResults.values()); } return questionDtos; } private SurveyInstanceDto marshalToDto(SurveyInstance si) { SurveyInstanceDto siDto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(si, siDto); siDto.setQuestionAnswersStore(null); if (si.getQuestionAnswersStore() != null) { for (QuestionAnswerStore qas : si.getQuestionAnswersStore()) { siDto.addQuestionAnswerStore(marshalToDto(qas)); } } return siDto; } private QuestionAnswerStoreDto marshalToDto(QuestionAnswerStore qas) { QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(qas, qasDto); return qasDto; } /** * updates the list of QAS dto objects passed in and fires summarization * messages to the async queues */ @Override public List<QuestionAnswerStoreDto> updateQuestions( List<QuestionAnswerStoreDto> dtoList, boolean isApproved) { return updateQuestions(dtoList, isApproved, true); } public List<QuestionAnswerStoreDto> updateQuestions( List<QuestionAnswerStoreDto> dtoList, boolean isApproved, boolean processSummaries) { List<QuestionAnswerStore> domainList = new ArrayList<QuestionAnswerStore>(); for (QuestionAnswerStoreDto dto : dtoList) { QuestionAnswerStore answer = new QuestionAnswerStore(); DtoMarshaller.copyToCanonical(answer, dto); if (answer.getValue() != null) { answer.setValue(answer.getValue().replaceAll("\t", "")); } domainList.add(answer); } SurveyInstanceDAO dao = new SurveyInstanceDAO(); dao.save(domainList); if (isApproved && processSummaries) { SurveyAttributeMappingDao mappingDao = new SurveyAttributeMappingDao(); // now send a change message for each item Queue queue = QueueFactory.getQueue("dataUpdate"); for (QuestionAnswerStoreDto item : dtoList) { DataChangeRecord value = new DataChangeRecord( QuestionAnswerStore.class.getName(), item.getQuestionID(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "QuestionDataChange") .param(DataSummarizationRequest.VALUE_KEY, value.packString())); // see if the question is mapped. And if it is, send an Access // Point // change message SurveyAttributeMapping mapping = mappingDao .findMappingForQuestion(item.getQuestionID()); if (mapping != null) { DataChangeRecord apValue = new DataChangeRecord( "AcessPointUpdate", mapping.getSurveyId() + "|" + mapping.getSurveyQuestionId() + "|" + item.getSurveyInstanceId() + "|" + mapping.getKey().getId(), item.getOldValue(), item.getValue()); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, item.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "AccessPointChange") .param(DataSummarizationRequest.VALUE_KEY, apValue.packString())); } } } return dtoList; } /** * lists all responses for a single question */ @Override public ResponseDto<ArrayList<QuestionAnswerStoreDto>> listResponsesByQuestion( Long questionId, String cursorString) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> qasList = dao .listQuestionAnswerStoreForQuestion(questionId.toString(), cursorString); String newCursor = SurveyInstanceDAO.getCursor(qasList); ArrayList<QuestionAnswerStoreDto> qasDtoList = new ArrayList<QuestionAnswerStoreDto>(); for (QuestionAnswerStore item : qasList) { qasDtoList.add(marshalToDto(item)); } ResponseDto<ArrayList<QuestionAnswerStoreDto>> response = new ResponseDto<ArrayList<QuestionAnswerStoreDto>>(); response.setCursorString(newCursor); response.setPayload(qasDtoList); return response; } /** * deletes a survey instance. This will only back out Question summaries. To * back out the access point, the AP needs to be deleted manually since it * may have come from multiple instances. */ @Override public void deleteSurveyInstance(Long instanceId) { if (instanceId != null) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<QuestionAnswerStore> answers = dao.listQuestionAnswerStore( instanceId, null); if (answers != null) { // back out summaries Queue queue = QueueFactory.getQueue("dataUpdate"); for (QuestionAnswerStore ans : answers) { DataChangeRecord value = new DataChangeRecord( QuestionAnswerStore.class.getName(), ans.getQuestionID(), ans.getValue(), ""); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, ans.getQuestionID()) .param(DataSummarizationRequest.OBJECT_TYPE, "QuestionDataChange") .param(DataSummarizationRequest.VALUE_KEY, value.packString())); } dao.delete(answers); } SurveyInstance instance = dao.getByKey(instanceId); if (instance != null) { dao.delete(instance); log.log(Level.INFO, "Deleted: " + instanceId); } } } /** * saves a new survey instance and triggers processing * * @param instance * @return */ public SurveyInstanceDto submitSurveyInstance(SurveyInstanceDto instance) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyInstance domain = new SurveyInstance(); DtoMarshaller.copyToCanonical(domain, instance); if (domain.getCollectionDate() == null) { domain.setCollectionDate(new Date()); } domain = dao.save(domain); instance.setKeyId(domain.getKey().getId()); if (instance.getQuestionAnswersStore() != null) { List<QuestionAnswerStore> answerList = new ArrayList<QuestionAnswerStore>(); for (QuestionAnswerStoreDto ans : instance .getQuestionAnswersStore()) { QuestionAnswerStore store = new QuestionAnswerStore(); if (ans.getCollectionDate() == null) { ans.setCollectionDate(domain.getCollectionDate()); } if (ans.getValue() != null) { ans.setValue(ans.getValue().replaceAll("\t", "")); if (ans.getValue().length() > 500) { ans.setValue(ans.getValue().substring(0, 499)); } } DtoMarshaller.copyToCanonical(store, ans); store.setSurveyInstanceId(domain.getKey().getId()); answerList.add(store); } dao.save(answerList); if (instance.getApprovedFlag() == null || !"False".equalsIgnoreCase(instance.getApprovedFlag())) { sendProcessingMessages(domain); } } SurveyEventHelper.fireEvent(SurveyEventHelper.SUBMISSION_EVENT, instance.getSurveyId(), instance.getKeyId()); return instance; } /** * marks the survey instance as approved, updating any changed answers as it * does so and then sends a processing message to the task queue so the * instance can be summarized. */ public void approveSurveyInstance(Long surveyInstanceId, List<QuestionAnswerStoreDto> changedAnswers) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); SurveyInstance instance = dao.getByKey(surveyInstanceId); if (changedAnswers != null && changedAnswers.size() > 0) { updateQuestions(changedAnswers, false); } if (instance != null) { if (instance.getApprovedFlag() == null || !"True".equalsIgnoreCase(instance.getApprovedFlag())) { instance.setApprovedFlag("True"); sendProcessingMessages(instance); // fire a survey event SurveyEventHelper.fireEvent(SurveyEventHelper.APPROVAL_EVENT, instance.getSurveyId(), instance.getKey().getId()); } } } /** * lists all surveyInstances associated with the surveyedLocaleId passed in. * * @param localeId * @return */ public ResponseDto<ArrayList<SurveyInstanceDto>> listInstancesByLocale( Long localeId, Date dateFrom, Date dateTo, String cursor) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); ResponseDto<ArrayList<SurveyInstanceDto>> response = new ResponseDto<ArrayList<SurveyInstanceDto>>(); ArrayList<SurveyInstanceDto> dtoList = new ArrayList<SurveyInstanceDto>(); List<SurveyInstance> instances = dao.listInstancesByLocale(localeId, dateFrom, dateTo, cursor); if (instances != null) { for (SurveyInstance inst : instances) { SurveyInstanceDto dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(inst, dto); dtoList.add(dto); } response.setPayload(dtoList); if (dtoList.size() == SurveyInstanceDAO.DEFAULT_RESULT_COUNT) { response.setCursorString(SurveyInstanceDAO.getCursor(instances)); } } return response; } public void sendProcessingMessages(SurveyInstance domain) { // send async request to populate the AccessPoint using the mapping QueueFactory.getDefaultQueue().add( TaskOptions.Builder.withUrl("/app_worker/task") .param("action", "addAccessPoint") .param("surveyId", domain.getKey().getId() + "")); // send asyn crequest to summarize the instance QueueFactory.getQueue("dataSummarization").add( TaskOptions.Builder.withUrl("/app_worker/datasummarization") .param("objectKey", domain.getKey().getId() + "") .param("type", "SurveyInstance")); QueueFactory.getDefaultQueue().add( TaskOptions.Builder .withUrl("/app_worker/surveyalservlet") .param(SurveyalRestRequest.ACTION_PARAM, SurveyalRestRequest.INGEST_INSTANCE_ACTION) .param(SurveyalRestRequest.SURVEY_INSTANCE_PARAM, domain.getKey().getId() + "")); } }
Issue #185 - add comment to surveyInstanceServiceImpl
GAE/src/org/waterforpeople/mapping/app/gwt/server/surveyinstance/SurveyInstanceServiceImpl.java
Issue #185 - add comment to surveyInstanceServiceImpl
Java
agpl-3.0
c213f896895667c542d86e2cda54153e529ff167
0
EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,dfsilva/actor-platform,EaglesoftZJ/actor-platform,dfsilva/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform,actorapp/actor-platform,ufosky-server/actor-platform,actorapp/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,dfsilva/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform,actorapp/actor-platform
package im.actor.core.modules.internal; import java.util.HashMap; import im.actor.core.api.ApiOutPeer; import im.actor.core.api.ApiPeerType; import im.actor.core.api.rpc.RequestCallInProgress; import im.actor.core.api.rpc.RequestDoCall; import im.actor.core.api.rpc.RequestEndCall; import im.actor.core.api.rpc.RequestSendCallSignal; import im.actor.core.api.rpc.RequestSubscribeToCalls; import im.actor.core.api.rpc.ResponseDoCall; import im.actor.core.entity.User; import im.actor.core.entity.signals.AbsSignal; import im.actor.core.modules.AbsModule; import im.actor.core.modules.ModuleContext; import im.actor.core.modules.events.IncomingCall; import im.actor.core.modules.internal.calls.CallActor; import im.actor.core.network.RpcCallback; import im.actor.core.network.RpcException; import im.actor.core.viewmodel.Command; import im.actor.core.viewmodel.CommandCallback; import im.actor.runtime.Log; import im.actor.runtime.actors.ActorCreator; import im.actor.runtime.actors.ActorRef; import im.actor.runtime.actors.ActorSystem; import im.actor.runtime.actors.Props; public class CallsModule extends AbsModule { public static final int MAX_CALLS_COUNT = 1; private static final String TAG = "CALLS"; public CallsModule(ModuleContext context) { super(context); } public static final int CALL_TIMEOUT = 10; public static boolean CALLS_ENABLED = false; public static boolean MULTIPLE_CALLS_ENABLED = false; HashMap<Long, ActorRef> calls = new HashMap<Long, ActorRef>(); public void run() { if (CALLS_ENABLED) { request(new RequestSubscribeToCalls()); } } public Command<ResponseDoCall> makeCall(final int uid, final CallCallback callCallback) { return new Command<ResponseDoCall>() { @Override public void start(final CommandCallback<ResponseDoCall> callback) { User u = users().getValue(uid); request(new RequestDoCall(new ApiOutPeer(ApiPeerType.PRIVATE, u.getUid(), u.getAccessHash()), CALL_TIMEOUT), new RpcCallback<ResponseDoCall>() { @Override public void onResult(final ResponseDoCall response) { callback.onResult(response); Log.d(TAG, "make call " + response.getCallId()); calls.put(response.getCallId(), ActorSystem.system().actorOf(Props.create(CallActor.class, new ActorCreator<CallActor>() { @Override public CallActor create() { return new CallActor(response.getCallId(), callCallback, context()); } }), "actor/call_" + response.getCallId())); } @Override public void onError(RpcException e) { callback.onError(e); } }); } }; } public void callInProgress(long callId) { request(new RequestCallInProgress(callId, CALL_TIMEOUT)); } public void handleCall(final long callId, final CallCallback callback) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.HandleCall(callback)); } else { //can't find call - close fragment callback.onCallEnd(); } } //do end call public void endCall(long callId) { Log.d(TAG, "do end call" + callId); request(new RequestEndCall(callId)); ActorRef call = calls.get(callId); if (call != null) { Log.d(TAG, "call exist - end it"); call.send(new CallActor.EndCall()); } else { Log.d(TAG, "call not exist - remove it"); onCallEnded(callId); } } public void onIncomingCall(final long callId, int uid) { Log.d(TAG, "incoming call " + callId); if (!calls.keySet().contains(callId)) { calls.put(callId, ActorSystem.system().actorOf(Props.create(CallActor.class, new ActorCreator<CallActor>() { @Override public CallActor create() { return new CallActor(callId, context()); } }), "actor/call_" + callId)); if (!MULTIPLE_CALLS_ENABLED & calls.keySet().size() > MAX_CALLS_COUNT) { calls.get(callId).send(new CallActor.EndCall()); } else { context().getEvents().post(new IncomingCall(callId, uid)); } } } //on end call update public void onEndCall(long callId) { Log.d(TAG, "end call update: " + callId); ActorRef call = calls.get(callId); if (call != null) { Log.d(TAG, "call exist - end it"); call.send(new CallActor.EndCall()); } else { Log.d(TAG, "call not exist - remove it"); calls.remove(callId); } } //after end call update processed by CallActor public void onCallEnded(long callId) { Log.d(TAG, "on callActor ended call: " + callId); calls.remove(callId); } public void onCallInProgress(long callId, int timeout) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.CallInProgress(timeout)); } } public void sendSignal(long callId, AbsSignal signal) { request(new RequestSendCallSignal(callId, signal.toByteArray())); } public void onSignal(long callId, byte[] data) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.Signal(data)); } } public interface CallCallback { void onCallEnd(); void onSignal(byte[] data); } }
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/internal/CallsModule.java
package im.actor.core.modules.internal; import java.util.HashMap; import im.actor.core.api.ApiOutPeer; import im.actor.core.api.ApiPeerType; import im.actor.core.api.rpc.RequestCallInProgress; import im.actor.core.api.rpc.RequestDoCall; import im.actor.core.api.rpc.RequestEndCall; import im.actor.core.api.rpc.RequestSendCallSignal; import im.actor.core.api.rpc.RequestSubscribeToCalls; import im.actor.core.api.rpc.ResponseDoCall; import im.actor.core.entity.User; import im.actor.core.entity.signals.AbsSignal; import im.actor.core.modules.AbsModule; import im.actor.core.modules.ModuleContext; import im.actor.core.modules.events.IncomingCall; import im.actor.core.modules.internal.calls.CallActor; import im.actor.core.network.RpcCallback; import im.actor.core.network.RpcException; import im.actor.core.viewmodel.Command; import im.actor.core.viewmodel.CommandCallback; import im.actor.runtime.Log; import im.actor.runtime.actors.ActorCreator; import im.actor.runtime.actors.ActorRef; import im.actor.runtime.actors.ActorSystem; import im.actor.runtime.actors.Props; public class CallsModule extends AbsModule { public static final int MAX_CALLS_COUNT = 1; private static final String TAG = "CALLS"; public CallsModule(ModuleContext context) { super(context); } public static final int CALL_TIMEOUT = 10; public static boolean CALLS_ENABLED = false; public static boolean MULTIPLE_CALLS_ENABLED = false; HashMap<Long, ActorRef> calls = new HashMap<Long, ActorRef>(); public void run() { if (CALLS_ENABLED) { request(new RequestSubscribeToCalls()); } } public Command<ResponseDoCall> makeCall(final int uid, final CallCallback callCallback) { return new Command<ResponseDoCall>() { @Override public void start(final CommandCallback<ResponseDoCall> callback) { User u = users().getValue(uid); request(new RequestDoCall(new ApiOutPeer(ApiPeerType.PRIVATE, u.getUid(), u.getAccessHash()), CALL_TIMEOUT), new RpcCallback<ResponseDoCall>() { @Override public void onResult(final ResponseDoCall response) { callback.onResult(response); Log.d(TAG, "make call " + response.getCallId()); calls.put(response.getCallId(), ActorSystem.system().actorOf(Props.create(CallActor.class, new ActorCreator<CallActor>() { @Override public CallActor create() { return new CallActor(response.getCallId(), callCallback, context()); } }), "actor/call")); } @Override public void onError(RpcException e) { callback.onError(e); } }); } }; } public void callInProgress(long callId) { request(new RequestCallInProgress(callId, CALL_TIMEOUT)); } public void handleCall(final long callId, final CallCallback callback) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.HandleCall(callback)); } else { //can't find call - close fragment callback.onCallEnd(); } } //do end call public void endCall(long callId) { Log.d(TAG, "do end call" + callId); request(new RequestEndCall(callId)); ActorRef call = calls.get(callId); if (call != null) { Log.d(TAG, "call exist - end it"); call.send(new CallActor.EndCall()); } else { Log.d(TAG, "call not exist - remove it"); onCallEnded(callId); } } public void onIncomingCall(final long callId, int uid) { Log.d(TAG, "incoming call " + callId); if (!calls.keySet().contains(callId)) { calls.put(callId, ActorSystem.system().actorOf(Props.create(CallActor.class, new ActorCreator<CallActor>() { @Override public CallActor create() { return new CallActor(callId, context()); } }), "actor/call")); if (!MULTIPLE_CALLS_ENABLED & calls.keySet().size() > MAX_CALLS_COUNT) { calls.get(callId).send(new CallActor.EndCall()); } else { context().getEvents().post(new IncomingCall(callId, uid)); } } } //on end call update public void onEndCall(long callId) { Log.d(TAG, "end call update: " + callId); ActorRef call = calls.get(callId); if (call != null) { Log.d(TAG, "call exist - end it"); call.send(new CallActor.EndCall()); } else { Log.d(TAG, "call not exist - remove it"); calls.remove(callId); } } //after end call update processed by CallActor public void onCallEnded(long callId) { Log.d(TAG, "on callActor ended call: " + callId); calls.remove(callId); } public void onCallInProgress(long callId, int timeout) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.CallInProgress(timeout)); } } public void sendSignal(long callId, AbsSignal signal) { request(new RequestSendCallSignal(callId, signal.toByteArray())); } public void onSignal(long callId, byte[] data) { ActorRef call = calls.get(callId); if (call != null) { call.send(new CallActor.Signal(data)); } } public interface CallCallback { void onCallEnd(); void onSignal(byte[] data); } }
fix(core): CallActor path with callId
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/internal/CallsModule.java
fix(core): CallActor path with callId
Java
lgpl-2.1
dde12fa2a2efc705ed336c75e77e0506a804cecc
0
lolodo/algorithm,lolodo/algorithm,lolodo/algorithm,lolodo/algorithm,lolodo/algorithm,lolodo/algorithm
import java.util.Arrays; public class HeapSort { public static void buildHeap(int[] array, int last) { int i; int max; for(i = (last - 1) / 2; i >= 0; i--) { int k = 2 * i + 1;//left int biggerest = k; if (k < last) { if(array[k] < array[k + 1]) { biggerest++; } } if(array[biggerest] > array[i]) { max = array[biggerest]; array[biggerest] = array[i]; array[i] = max; } } } public static void heapSort(int[] array) { int i; for (i = 0; i < array.length; i++) { buildHeap(array, array.length - 1); } } public static void main(String[] args) { int[] a = ShellSort.array; if(a.length <= 1) { return; } heapSort(a); System.out.println(Arrays.toString(a)); // ShellSort.printArray(a); } }
java/SortFunc/HeapSort.java
import java.util.Arrays; public class HeapSort { public static void buildHeap(int[] array, int last) { int i; int max; for(i = (last - 1) / 2; i >= 0; i--) { int k = 2 * i + 1;//left int biggerest = k; if (k < last) { if(array[k] < array[k + 1]) { biggerest++; } } if(array[biggerest] > array[i]) { max = array[biggerest]; array[biggerest] = array[i]; array[i] = max; } } } public static void heapSort(int[] array) { int i; for (i = 0; i < array.length; i++) { buildHeap(array, array.length - 1) } } public static void main(String[] args) { int[] a = ShellSort.array; if(a.length <= 1) { return; } heapSort(a); System.out.println(Arrays.toString(a)); // ShellSort.printArray(a); } }
nothing
java/SortFunc/HeapSort.java
nothing
Java
apache-2.0
ae64b4cd971b3ab131362aed08a9f7bac43f43b6
0
thomasliasn/aerogear-otp-java,dufabricio/aerogear-otp-java,aerogear/aerogear-otp-java
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aerogear.security.otp; import org.jboss.aerogear.security.otp.api.Base32; import org.jboss.aerogear.security.otp.api.Clock; import org.jboss.aerogear.security.otp.api.Digits; import org.jboss.aerogear.security.otp.api.Hash; import org.jboss.aerogear.security.otp.api.Hmac; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; public class Totp { private final String secret; private final Clock clock; private static final int DELAY_WINDOW = 1; public Totp(String secret) { this.secret = secret; clock = new Clock(); } public Totp(String secret, Clock clock) { this.secret = secret; this.clock = clock; } public String uri(String name) { try { return String.format("otpauth://totp/%s?secret=%s", URLEncoder.encode(name, "UTF-8"), secret); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage(), e); } } public String now() { return Integer.toString(hash(secret, clock.getCurrentInterval())); } public int generate(String secret, long interval) { return hash(secret, interval); } private int hash(String secret, long interval) { byte[] hash = new byte[0]; try { //Base32 encoding is just a requirement for google authenticator. We can remove it on the next releases. hash = new Hmac(Hash.SHA1, Base32.decode(secret), interval).digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (Base32.DecodingException e) { e.printStackTrace(); } return bytesToInt(hash); } private int bytesToInt(byte[] hash) { // put selected bytes into result int int offset = hash[hash.length - 1] & 0xf; int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); return binary % Digits.SIX.getValue(); } /** * Taken from Google Authenticator with small modifications from * {@see <a href="http://code.google.com/p/google-authenticator/source/browse/src/com/google/android/apps/authenticator/PasscodeGenerator.java?repo=android#212">PasscodeGenerator.java</a>} * * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param otp Timeout code * @return True if the timeout code is valid * * @author [email protected] (Steve Weis) */ public boolean verify(String otp) { long code = Long.parseLong(otp); long currentInterval = clock.getCurrentInterval(); int pastResponse = Math.max(DELAY_WINDOW, 0); for (int i = pastResponse; i >= 0; --i) { int candidate = generate(this.secret, currentInterval - i); if (candidate == code) { return true; } } return false; } }
src/main/java/org/jboss/aerogear/security/otp/Totp.java
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aerogear.security.otp; import org.jboss.aerogear.security.otp.api.Base32; import org.jboss.aerogear.security.otp.api.Clock; import org.jboss.aerogear.security.otp.api.Digits; import org.jboss.aerogear.security.otp.api.Hash; import org.jboss.aerogear.security.otp.api.Hmac; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; public class Totp { private final String secret; private final Clock clock; private static final int DELAY_WINDOW = 1; public Totp(String secret) { this.secret = secret; clock = new Clock(); } public Totp(String secret, Clock clock) { this.secret = secret; this.clock = clock; } public String uri(String name) { try { return String.format("otpauth://totp/%s?secret=%s", URLEncoder.encode(name, "UTF-8"), secret); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage(), e); } } public String now() { return Integer.toString(hash(secret, clock.getCurrentInterval())); } public int generate(String secret, long interval) { return hash(secret, interval); } private int hash(String secret, long interval) { byte[] hash = new byte[0]; try { hash = new Hmac(Hash.SHA1, Base32.decode(secret), interval).digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (Base32.DecodingException e) { e.printStackTrace(); } return bytesToInt(hash); } private int bytesToInt(byte[] hash) { // put selected bytes into result int int offset = hash[hash.length - 1] & 0xf; int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); return binary % Digits.SIX.getValue(); } /** * Taken from Google Authenticator with small modifications from * {@see <a href="http://code.google.com/p/google-authenticator/source/browse/src/com/google/android/apps/authenticator/PasscodeGenerator.java?repo=android#212">PasscodeGenerator.java</a>} * * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param otp Timeout code * @return True if the timeout code is valid * * @author [email protected] (Steve Weis) */ public boolean verify(String otp) { long code = Long.parseLong(otp); long currentInterval = clock.getCurrentInterval(); int pastResponse = Math.max(DELAY_WINDOW, 0); for (int i = pastResponse; i >= 0; --i) { int candidate = generate(this.secret, currentInterval - i); if (candidate == code) { return true; } } return false; } }
Just a note on Base32 encoding
src/main/java/org/jboss/aerogear/security/otp/Totp.java
Just a note on Base32 encoding
Java
apache-2.0
a3214bd9c4f8b3866ec99df2fe088ebe0cf67517
0
kamranzafar/jtar
/** * Copyright 2012 Kamran Zafar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.kamranzafar.jtar; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; /** * @author Kamran Zafar * */ public class TarOutputStream extends OutputStream { private final OutputStream out; private long bytesWritten; private long currentFileSize; private TarEntry currentEntry; public TarOutputStream(OutputStream out) { this.out = out; bytesWritten = 0; currentFileSize = 0; } public TarOutputStream(final File fout) throws FileNotFoundException { this.out = new BufferedOutputStream(new FileOutputStream(fout)); bytesWritten = 0; currentFileSize = 0; } /** * Opens a file for writing. */ public TarOutputStream(final File fout, final boolean append) throws IOException { @SuppressWarnings("resource") RandomAccessFile raf = new RandomAccessFile(fout, "rw"); final long fileSize = fout.length(); if (append && fileSize > TarConstants.EOF_BLOCK) { raf.seek(fileSize - TarConstants.EOF_BLOCK); } out = new BufferedOutputStream(new FileOutputStream(raf.getFD())); } /** * Appends the EOF record and closes the stream * * @see java.io.FilterOutputStream#close() */ @Override public void close() throws IOException { closeCurrentEntry(); write( new byte[TarConstants.EOF_BLOCK] ); out.close(); } /** * Writes a byte to the stream and updates byte counters * * @see java.io.FilterOutputStream#write(int) */ @Override public void write(int b) throws IOException { out.write( b ); bytesWritten += 1; if (currentEntry != null) { currentFileSize += 1; } } /** * Checks if the bytes being written exceed the current entry size. * * @see java.io.FilterOutputStream#write(byte[], int, int) */ @Override public void write(byte[] b, int off, int len) throws IOException { if (currentEntry != null && !currentEntry.isDirectory()) { if (currentEntry.getSize() < currentFileSize + len) { throw new IOException( "The current entry[" + currentEntry.getName() + "] size[" + currentEntry.getSize() + "] is smaller than the bytes[" + ( currentFileSize + len ) + "] being written." ); } } out.write( b, off, len ); bytesWritten += len; if (currentEntry != null) { currentFileSize += len; } } /** * Writes the next tar entry header on the stream * * @param entry * @throws IOException */ public void putNextEntry(TarEntry entry) throws IOException { closeCurrentEntry(); byte[] header = new byte[TarConstants.HEADER_BLOCK]; entry.writeEntryHeader( header ); write( header ); currentEntry = entry; } /** * Closes the current tar entry * * @throws IOException */ protected void closeCurrentEntry() throws IOException { if (currentEntry != null) { if (currentEntry.getSize() > currentFileSize) { throw new IOException( "The current entry[" + currentEntry.getName() + "] of size[" + currentEntry.getSize() + "] has not been fully written." ); } currentEntry = null; currentFileSize = 0; pad(); } } /** * Pads the last content block * * @throws IOException */ protected void pad() throws IOException { if (bytesWritten > 0) { int extra = (int) ( bytesWritten % TarConstants.DATA_BLOCK ); if (extra > 0) { write( new byte[TarConstants.DATA_BLOCK - extra] ); } } } }
src/main/java/org/kamranzafar/jtar/TarOutputStream.java
/** * Copyright 2012 Kamran Zafar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.kamranzafar.jtar; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; /** * @author Kamran Zafar * */ public class TarOutputStream extends OutputStream { private final OutputStream out; private long bytesWritten; private long currentFileSize; private TarEntry currentEntry; public TarOutputStream(OutputStream out) { this.out = out; bytesWritten = 0; currentFileSize = 0; } public TarOutputStream(final File fout) throws FileNotFoundException { // TODO: Wrap bufferedoutputstream this.out = new FileOutputStream(fout); bytesWritten = 0; currentFileSize = 0; } /** * Opens a file for writing. */ public TarOutputStream(final File fout, final boolean append) throws IOException { @SuppressWarnings("resource") RandomAccessFile raf = new RandomAccessFile(fout, "rw"); final long fileSize = fout.length(); if (append && fileSize > TarConstants.EOF_BLOCK) { raf.seek(fileSize - TarConstants.EOF_BLOCK); } // TODO: Wrap bufferedoutputstream out = new FileOutputStream(raf.getFD()); } /** * Appends the EOF record and closes the stream * * @see java.io.FilterOutputStream#close() */ @Override public void close() throws IOException { closeCurrentEntry(); write( new byte[TarConstants.EOF_BLOCK] ); out.close(); } /** * Writes a byte to the stream and updates byte counters * * @see java.io.FilterOutputStream#write(int) */ @Override public void write(int b) throws IOException { out.write( b ); bytesWritten += 1; if (currentEntry != null) { currentFileSize += 1; } } /** * Checks if the bytes being written exceed the current entry size. * * @see java.io.FilterOutputStream#write(byte[], int, int) */ @Override public void write(byte[] b, int off, int len) throws IOException { if (currentEntry != null && !currentEntry.isDirectory()) { if (currentEntry.getSize() < currentFileSize + len) { throw new IOException( "The current entry[" + currentEntry.getName() + "] size[" + currentEntry.getSize() + "] is smaller than the bytes[" + ( currentFileSize + len ) + "] being written." ); } } out.write( b, off, len ); bytesWritten += len; if (currentEntry != null) { currentFileSize += len; } } /** * Writes the next tar entry header on the stream * * @param entry * @throws IOException */ public void putNextEntry(TarEntry entry) throws IOException { closeCurrentEntry(); byte[] header = new byte[TarConstants.HEADER_BLOCK]; entry.writeEntryHeader( header ); write( header ); currentEntry = entry; } /** * Closes the current tar entry * * @throws IOException */ protected void closeCurrentEntry() throws IOException { if (currentEntry != null) { if (currentEntry.getSize() > currentFileSize) { throw new IOException( "The current entry[" + currentEntry.getName() + "] of size[" + currentEntry.getSize() + "] has not been fully written." ); } currentEntry = null; currentFileSize = 0; pad(); } } /** * Pads the last content block * * @throws IOException */ protected void pad() throws IOException { if (bytesWritten > 0) { int extra = (int) ( bytesWritten % TarConstants.DATA_BLOCK ); if (extra > 0) { write( new byte[TarConstants.DATA_BLOCK - extra] ); } } } }
Wrap the FileOutputStream in a BufferedOutputStream.
src/main/java/org/kamranzafar/jtar/TarOutputStream.java
Wrap the FileOutputStream in a BufferedOutputStream.
Java
apache-2.0
2652d00f77b5fd3d5c21eb205c3a25b10c8e71b0
0
protyposis/Spectaculum,protyposis/Spectaculum
/* * Copyright (c) 2014 Mario Guggenberger <[email protected]> * * This file is part of MediaPlayer-Extended. * * MediaPlayer-Extended is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MediaPlayer-Extended is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MediaPlayer-Extended. If not, see <http://www.gnu.org/licenses/>. */ package net.protyposis.android.spectaculum; import android.content.Context; import android.graphics.Bitmap; import android.graphics.SurfaceTexture; import android.opengl.*; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.SurfaceHolder; import net.protyposis.android.spectaculum.effects.Effect; import net.protyposis.android.spectaculum.effects.EffectException; import net.protyposis.android.spectaculum.effects.Parameter; import net.protyposis.android.spectaculum.effects.ParameterHandler; import net.protyposis.android.spectaculum.gles.*; /** * Created by Mario on 14.06.2014. */ public class SpectaculumView extends GLSurfaceView implements SurfaceTexture.OnFrameAvailableListener, Effect.Listener, GLRenderer.EffectEventListener, GLRenderer.OnFrameCapturedCallback { private static final String TAG = SpectaculumView.class.getSimpleName(); public interface EffectEventListener extends GLRenderer.EffectEventListener {} public interface OnFrameCapturedCallback extends GLRenderer.OnFrameCapturedCallback {} private GLRenderer mRenderer; private InputSurfaceHolder mInputSurfaceHolder; private Handler mRunOnUiThreadHandler = new Handler(); private ScaleGestureDetector mScaleGestureDetector; private GestureDetector mGestureDetector; private EffectEventListener mEffectEventListener; private OnFrameCapturedCallback mOnFrameCapturedCallback; private PipelineResolution mPipelineResolution = PipelineResolution.SOURCE; private float mZoomLevel = 1.0f; private float mZoomSnappingRange = 0.02f; private float mPanX; private float mPanY; private float mPanSnappingRange = 0.02f; private boolean mTouchEnabled = false; protected int mImageWidth; protected int mImageHeight; public SpectaculumView(Context context) { super(context); init(context); } public SpectaculumView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { if(isInEditMode()) { // do not start renderer in layout editor return; } if(!net.protyposis.android.spectaculum.gles.GLUtils.isGlEs2Supported(context)) { Log.e(TAG, "GLES 2.0 is not supported"); return; } LibraryHelper.setContext(context); mRenderer = new GLRenderer(); mRenderer.setOnExternalSurfaceTextureCreatedListener(mExternalSurfaceTextureCreatedListener); mRenderer.setEffectEventListener(mRendererEffectEventListener); mInputSurfaceHolder = new InputSurfaceHolder(); setEGLContextClientVersion(2); setRenderer(mRenderer); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); mScaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { mZoomLevel *= detector.getScaleFactor(); if(LibraryHelper.isBetween(mZoomLevel, 1-mZoomSnappingRange, 1+mZoomSnappingRange)) { mZoomLevel = 1.0f; } // limit zooming to magnification zooms (zoom-ins) if(mZoomLevel < 1.0f) { mZoomLevel = 1.0f; } setZoom(mZoomLevel); return true; } }); mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // divide by zoom level to adjust panning speed to zoomed picture size // multiply by fixed scaling factor to compensate for panning lag mPanX += distanceX / getWidth() / mZoomLevel * 1.2f; mPanY += distanceY / getHeight() / mZoomLevel * 1.2f; float panSnappingRange = mPanSnappingRange / mZoomLevel; if(LibraryHelper.isBetween(mPanX, -panSnappingRange, +panSnappingRange)) { mPanX = 0; } if(LibraryHelper.isBetween(mPanY, -panSnappingRange, +panSnappingRange)) { mPanY = 0; } // limit panning to the texture bounds so it always covers the complete view float maxPanX = Math.abs((1.0f / mZoomLevel) - 1.0f); float maxPanY = Math.abs((1.0f / mZoomLevel) - 1.0f); mPanX = LibraryHelper.clamp(mPanX, -maxPanX, maxPanX); mPanY = LibraryHelper.clamp(mPanY, -maxPanY, maxPanY); setPan(mPanX, mPanY); return true; } @Override public boolean onDoubleTap(MotionEvent e) { mZoomLevel = 1; mPanX = 0; mPanY = 0; setZoom(mZoomLevel); setPan(mPanX, mPanY); return true; } }); } /** * Sets the zoom factor of the texture in the view. 1.0 means no zoom, 2.0 2x zoom, etc. */ public void setZoom(float zoomFactor) { mZoomLevel = zoomFactor; mRenderer.setZoomLevel(mZoomLevel); requestRender(GLRenderer.RenderRequest.GEOMETRY); } /** * Gets the zoom level. * @see #setZ(float) for an explanation if the value * @return */ public float getZoomLevel() { return mZoomLevel; } /** * Sets the panning of the texture in the view. (0.0, 0.0) centers the texture and means no * panning, (-1.0, -1.0) moves the texture to the lower right quarter. */ public void setPan(float x, float y) { mPanX = x; mPanY = y; mRenderer.setPan(-mPanX, mPanY); requestRender(GLRenderer.RenderRequest.GEOMETRY); } /** * Gets the horizontal panning. Zero means centered, positive is to the left. */ public float getPanX() { return mPanX; } /** * Gets the vertical panning. Zero means centered, positive is to the bottom. */ public float getPanY() { return mPanY; } /** * Enables or disables touch zoom/pan gestures. When disabled, a parent container (e.g. an activity) * can still pass touch events to this view's {@link #onTouchEvent(MotionEvent)} to process * zoom/pan gestures. * @see #isTouchEnabled() */ public void setTouchEnabled(boolean enabled) { mTouchEnabled = enabled; } /** * Checks if touch gestures are enabled. Touch gestures are disabled by default. * @see #setTouchEnabled(boolean) */ public boolean isTouchEnabled() { return mTouchEnabled; } /** * Resizes the video view according to the video size to keep aspect ratio. * Code copied from {@link android.widget.VideoView#onMeasure(int, int)}. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.i("@@@@", "onMeasure(" + MeasureSpec.toString(widthMeasureSpec) + ", " + MeasureSpec.toString(heightMeasureSpec) + ")"); int width = getDefaultSize(mImageWidth, widthMeasureSpec); int height = getDefaultSize(mImageHeight, heightMeasureSpec); if (mImageWidth > 0 && mImageHeight > 0) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.EXACTLY && heightSpecMode == MeasureSpec.EXACTLY) { // the size is fixed width = widthSpecSize; height = heightSpecSize; // for compatibility, we adjust size based on aspect ratio if ( mImageWidth * height < width * mImageHeight) { //Log.i("@@@", "image too wide, correcting"); width = height * mImageWidth / mImageHeight; } else if ( mImageWidth * height > width * mImageHeight) { //Log.i("@@@", "image too tall, correcting"); height = width * mImageHeight / mImageWidth; } } else if (widthSpecMode == MeasureSpec.EXACTLY) { // only the width is fixed, adjust the height to match aspect ratio if possible width = widthSpecSize; height = width * mImageHeight / mImageWidth; if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) { // couldn't match aspect ratio within the constraints height = heightSpecSize; } } else if (heightSpecMode == MeasureSpec.EXACTLY) { // only the height is fixed, adjust the width to match aspect ratio if possible height = heightSpecSize; width = height * mImageWidth / mImageHeight; if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) { // couldn't match aspect ratio within the constraints width = widthSpecSize; } } else { // neither the width nor the height are fixed, try to use actual video size width = mImageWidth; height = mImageHeight; if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) { // too tall, decrease both width and height height = heightSpecSize; width = height * mImageWidth / mImageHeight; } if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) { // too wide, decrease both width and height width = widthSpecSize; height = width * mImageHeight / mImageWidth; } } } else { // no size yet, just adopt the given spec sizes } setMeasuredDimension(width, height); } @Override public boolean onTouchEvent(MotionEvent event) { /* * NOTE: These calls should not be simplified to a logical chain, because the evaluation * would stop at the first true value and not execute the following functions. */ boolean event1 = mScaleGestureDetector.onTouchEvent(event); boolean event2 = mGestureDetector.onTouchEvent(event); return event1 || event2; } @Override public boolean dispatchTouchEvent(MotionEvent event) { if(!mTouchEnabled) { // Touch events are disabled and we return false to route all events to the parent return false; } return super.dispatchTouchEvent(event); } /** * Implement this method to receive the input surface holder when it is ready to be used. * The input surface holder holds the surface and surface texture to which input data, i.e. image * data from some source that should be processed and displayed, should be written to display * it in the view. * * External callers should add a callback to the holder through {@link InputSurfaceHolder#addCallback(InputSurfaceHolder.Callback)} * to be notified about this event in {@link InputSurfaceHolder.Callback#surfaceCreated(InputSurfaceHolder)}. * * @param inputSurfaceHolder the input surface holder which holds the surface where image data should be written to */ public void onInputSurfaceCreated(InputSurfaceHolder inputSurfaceHolder) { // nothing to do here } /** * Gets the input surface holder that holds the surface where image data should be written to * for processing and display. The holder is always available but only holds an actual surface * after {@link #onInputSurfaceCreated(InputSurfaceHolder)} respectively * {@link InputSurfaceHolder.Callback#surfaceCreated(InputSurfaceHolder)} have been called. * * The input surface holder holds the input surface (texture) that is used to write image data * into the processing pipeline, opposed to the surface holder from {@link #getHolder()} that holds * the surface to which the final result of the processing pipeline will be written to for display. * * @return the input surface holder or null if it is not available yet */ public InputSurfaceHolder getInputHolder() { return mInputSurfaceHolder; } @Override public void surfaceDestroyed(SurfaceHolder holder) { // Delete the external texture, else it stays in RAM if(getInputHolder().getExternalSurfaceTexture() != null) { getInputHolder().getExternalSurfaceTexture().delete(); } super.surfaceDestroyed(holder); } /** * Adds one or more effects to the view. Added effects can then be activated/selected by calling * {@link #selectEffect(int)}. The effect indices start at zero and are in the order that they * are added to the view. * @param effects effects to add */ public void addEffect(final Effect... effects) { for(Effect effect : effects) { effect.setListener(this); effect.setParameterHandler(new ParameterHandler(this)); } queueEvent(new Runnable() { @Override public void run() { mRenderer.addEffect(effects); } }); } /** * Selects/activates the effect with the given index as it has been added through {@link #addEffect(Effect...)}. * @param index the index of the effect to activate */ public void selectEffect(final int index) { queueEvent(new Runnable() { @Override public void run() { mRenderer.selectEffect(index); requestRender(GLRenderer.RenderRequest.EFFECT); } }); } /** * Gets called when an effect has been initialized after being selected for the first time * with {@link #selectEffect(int)}. Effect initialization happens asynchronously and can take * some time when a lot of data (framebuffers, textures, ...) is loaded. * Can be overwritten in subclasses but must be called through. External callers should use * {@link #setEffectEventListener(EffectEventListener)}. * @param index the index of the initialized effect * @param effect the initialized effect */ @Override public void onEffectInitialized(int index, Effect effect) { if(mEffectEventListener != null) { mEffectEventListener.onEffectInitialized(index, effect); } requestRender(GLRenderer.RenderRequest.EFFECT); } /** * Gets called when an effect has been successfully selected with {@link #selectEffect(int)}. * Can be overwritten in subclasses but must be called through. External callers should use * {@link #setEffectEventListener(EffectEventListener)}. * @param index the index of the selected effect * @param effect the selected effect */ @Override public void onEffectSelected(int index, Effect effect) { if(mEffectEventListener != null) { mEffectEventListener.onEffectSelected(index, effect); } } /** * Gets called when an effect selection with {@link #selectEffect(int)} fails. * Can be overwritten in subclasses but must be called through. External callers should use * {@link #setEffectEventListener(EffectEventListener)}. * @param index the index of the failed effect * @param effect the failed effect */ @Override public void onEffectError(int index, Effect effect, EffectException e) { Log.e(TAG, "effect error", e); if(mEffectEventListener != null) { mEffectEventListener.onEffectError(index, effect, e); } } /** * Sets an event listener that gets called when effect-related event happens. * @param listener the event listener to be called on an event */ public void setEffectEventListener(EffectEventListener listener) { mEffectEventListener = listener; } /** * Gets called when a parameter of an effect has changed. This method then triggers a fresh * rendering of the effect. Can be overridden in subclasses but must be called through. * @param effect the effect of which a parameter value has changed * @see net.protyposis.android.spectaculum.effects.Effect.Listener */ @Override public void onEffectChanged(Effect effect) { requestRender(GLRenderer.RenderRequest.EFFECT); } /** * Gets called when a parameter is added to an effect. * Can be overridden in subclasses but must be called through. * @param effect the effect to which a parameter was added * @param parameter the added parameter * @see net.protyposis.android.spectaculum.effects.Effect.Listener */ @Override public void onParameterAdded(Effect effect, Parameter parameter) { // nothing to do here } /** * Gets called when a parameter is removed from an effect. * Can be overridden in subclasses but must be called through. * @param effect the effect from which a parameter was removed * @param parameter the removed parameter * @see net.protyposis.android.spectaculum.effects.Effect.Listener */ @Override public void onParameterRemoved(Effect effect, Parameter parameter) { // nothing to do here } /** * Gets called when a new image frame has been written to the surface texture and requests a * fresh rendering of the view. The texture can be obtained through {@link #onInputSurfaceCreated(InputSurfaceHolder)} * or {@link #getInputHolder()}. * Can be overridden in subclasses but must be called through. * @param surfaceTexture the updated surface texture */ @Override public void onFrameAvailable(SurfaceTexture surfaceTexture) { requestRender(GLRenderer.RenderRequest.ALL); } /** * Requests a render pass of the specified render pipeline section. * @param renderRequest specifies the pipeline section to be rendered */ protected void requestRender(final GLRenderer.RenderRequest renderRequest) { queueEvent(new Runnable() { @Override public void run() { mRenderer.setRenderRequest(renderRequest); requestRender(); } }); } /** * Requests a capture of the current frame on the view. The frame is asynchronously requested * from the renderer and will be passed back on the UI thread to {@link #onFrameCaptured(Bitmap)} * and the event listener that can be set with {@link #setOnFrameCapturedCallback(OnFrameCapturedCallback)}. */ public void captureFrame() { queueEvent(new Runnable() { @Override public void run() { mRenderer.saveCurrentFrame(new GLRenderer.OnFrameCapturedCallback() { @Override public void onFrameCaptured(final Bitmap bitmap) { mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { SpectaculumView.this.onFrameCaptured(bitmap); } }); } }); } }); } /** * Receives a captured frame from the renderer. Can be overwritten in subclasses but must be * called through. External callers should use {@link #setOnFrameCapturedCallback(OnFrameCapturedCallback)}. */ @Override public void onFrameCaptured(Bitmap bitmap) { if(mOnFrameCapturedCallback != null) { mOnFrameCapturedCallback.onFrameCaptured(bitmap); } } /** * Sets a callback event handler that receives a bitmap of the captured frame. */ public void setOnFrameCapturedCallback(OnFrameCapturedCallback callback) { mOnFrameCapturedCallback = callback; } /** * Sets the resolution mode of the processing pipeline. * @see PipelineResolution */ public void setPipelineResolution(PipelineResolution resolution) { mPipelineResolution = resolution; } /** * Gets the configured resolution mode of the processing pipeline. */ public PipelineResolution getPipelineResolution() { return mPipelineResolution; } /** * Sets the resolution of the source data and recomputes the layout. This implicitly also sets * the resolution of the view output surface if pipeline resolution mode {@link PipelineResolution#SOURCE} * is set. In SOURCE mode, output will therefore be computed in the input resolution and then * at the very end scaled (most often downscaled) to fit the view in the layout. * * TODO decouple input, processing and output resolution * * @param width the width of the input image data * @param height the height of the input image data */ public void updateResolution(int width, int height) { if(width == mImageWidth && height == mImageHeight) { // Don't do anything if resolution has stayed the same return; } mImageWidth = width; mImageHeight = height; // If desired, set output resolution to source resolution if (width != 0 && height != 0 && mPipelineResolution == PipelineResolution.SOURCE) { getHolder().setFixedSize(width, height); } // Resize view according to the new size to fit the layout requestLayout(); } private GLRenderer.OnExternalSurfaceTextureCreatedListener mExternalSurfaceTextureCreatedListener = new GLRenderer.OnExternalSurfaceTextureCreatedListener() { @Override public void onExternalSurfaceTextureCreated(final ExternalSurfaceTexture surfaceTexture) { // dispatch event to UI thread mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { // Create an input surface holder and call the event handler mInputSurfaceHolder.update(surfaceTexture); onInputSurfaceCreated(mInputSurfaceHolder); } }); surfaceTexture.setOnFrameAvailableListener(SpectaculumView.this); } }; /** * Effect event listener that transfers the events to the UI thread. */ private EffectEventListener mRendererEffectEventListener = new EffectEventListener() { @Override public void onEffectInitialized(final int index, final Effect effect) { mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { SpectaculumView.this.onEffectInitialized(index, effect); } }); } @Override public void onEffectSelected(final int index, final Effect effect) { mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { SpectaculumView.this.onEffectSelected(index, effect); } }); } @Override public void onEffectError(final int index, final Effect effect, final EffectException e) { mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { SpectaculumView.this.onEffectError(index, effect, e); } }); } }; }
Spectaculum-Core/src/main/java/net/protyposis/android/spectaculum/SpectaculumView.java
/* * Copyright (c) 2014 Mario Guggenberger <[email protected]> * * This file is part of MediaPlayer-Extended. * * MediaPlayer-Extended is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MediaPlayer-Extended is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MediaPlayer-Extended. If not, see <http://www.gnu.org/licenses/>. */ package net.protyposis.android.spectaculum; import android.content.Context; import android.graphics.Bitmap; import android.graphics.SurfaceTexture; import android.opengl.*; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.SurfaceHolder; import net.protyposis.android.spectaculum.effects.Effect; import net.protyposis.android.spectaculum.effects.EffectException; import net.protyposis.android.spectaculum.effects.Parameter; import net.protyposis.android.spectaculum.effects.ParameterHandler; import net.protyposis.android.spectaculum.gles.*; /** * Created by Mario on 14.06.2014. */ public class SpectaculumView extends GLSurfaceView implements SurfaceTexture.OnFrameAvailableListener, Effect.Listener, GLRenderer.EffectEventListener, GLRenderer.OnFrameCapturedCallback { private static final String TAG = SpectaculumView.class.getSimpleName(); public interface EffectEventListener extends GLRenderer.EffectEventListener {} public interface OnFrameCapturedCallback extends GLRenderer.OnFrameCapturedCallback {} private GLRenderer mRenderer; private InputSurfaceHolder mInputSurfaceHolder; private Handler mRunOnUiThreadHandler = new Handler(); private ScaleGestureDetector mScaleGestureDetector; private GestureDetector mGestureDetector; private EffectEventListener mEffectEventListener; private OnFrameCapturedCallback mOnFrameCapturedCallback; private PipelineResolution mPipelineResolution = PipelineResolution.SOURCE; private float mZoomLevel = 1.0f; private float mZoomSnappingRange = 0.02f; private float mPanX; private float mPanY; private float mPanSnappingRange = 0.02f; private boolean mTouchEnabled = false; protected int mImageWidth; protected int mImageHeight; public SpectaculumView(Context context) { super(context); init(context); } public SpectaculumView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { if(isInEditMode()) { // do not start renderer in layout editor return; } if(!net.protyposis.android.spectaculum.gles.GLUtils.isGlEs2Supported(context)) { Log.e(TAG, "GLES 2.0 is not supported"); return; } LibraryHelper.setContext(context); mRenderer = new GLRenderer(); mRenderer.setOnExternalSurfaceTextureCreatedListener(mExternalSurfaceTextureCreatedListener); mRenderer.setEffectEventListener(mRendererEffectEventListener); mInputSurfaceHolder = new InputSurfaceHolder(); setEGLContextClientVersion(2); setRenderer(mRenderer); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); mScaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { mZoomLevel *= detector.getScaleFactor(); if(LibraryHelper.isBetween(mZoomLevel, 1-mZoomSnappingRange, 1+mZoomSnappingRange)) { mZoomLevel = 1.0f; } // limit zooming to magnification zooms (zoom-ins) if(mZoomLevel < 1.0f) { mZoomLevel = 1.0f; } setZoom(mZoomLevel); return true; } }); mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // divide by zoom level to adjust panning speed to zoomed picture size // multiply by fixed scaling factor to compensate for panning lag mPanX += distanceX / getWidth() / mZoomLevel * 1.2f; mPanY += distanceY / getHeight() / mZoomLevel * 1.2f; float panSnappingRange = mPanSnappingRange / mZoomLevel; if(LibraryHelper.isBetween(mPanX, -panSnappingRange, +panSnappingRange)) { mPanX = 0; } if(LibraryHelper.isBetween(mPanY, -panSnappingRange, +panSnappingRange)) { mPanY = 0; } // limit panning to the texture bounds so it always covers the complete view float maxPanX = Math.abs((1.0f / mZoomLevel) - 1.0f); float maxPanY = Math.abs((1.0f / mZoomLevel) - 1.0f); mPanX = LibraryHelper.clamp(mPanX, -maxPanX, maxPanX); mPanY = LibraryHelper.clamp(mPanY, -maxPanY, maxPanY); setPan(mPanX, mPanY); return true; } @Override public boolean onDoubleTap(MotionEvent e) { mZoomLevel = 1; mPanX = 0; mPanY = 0; setZoom(mZoomLevel); setPan(mPanX, mPanY); return true; } }); } /** * Sets the zoom factor of the texture in the view. 1.0 means no zoom, 2.0 2x zoom, etc. */ public void setZoom(float zoomFactor) { mZoomLevel = zoomFactor; mRenderer.setZoomLevel(mZoomLevel); requestRender(GLRenderer.RenderRequest.GEOMETRY); } /** * Gets the zoom level. * @see #setZ(float) for an explanation if the value * @return */ public float getZoomLevel() { return mZoomLevel; } /** * Sets the panning of the texture in the view. (0.0, 0.0) centers the texture and means no * panning, (-1.0, -1.0) moves the texture to the lower right quarter. */ public void setPan(float x, float y) { mPanX = x; mPanY = y; mRenderer.setPan(-mPanX, mPanY); requestRender(GLRenderer.RenderRequest.GEOMETRY); } /** * Gets the horizontal panning. Zero means centered, positive is to the left. */ public float getPanX() { return mPanX; } /** * Gets the vertical panning. Zero means centered, positive is to the bottom. */ public float getPanY() { return mPanY; } /** * Enables or disables touch zoom/pan gestures. When disabled, a parent container (e.g. an activity) * can still pass touch events to this view's {@link #onTouchEvent(MotionEvent)} to process * zoom/pan gestures. * @see #isTouchEnabled() */ public void setTouchEnabled(boolean enabled) { mTouchEnabled = enabled; } /** * Checks if touch gestures are enabled. Touch gestures are disabled by default. * @see #setTouchEnabled(boolean) */ public boolean isTouchEnabled() { return mTouchEnabled; } /** * Resizes the video view according to the video size to keep aspect ratio. * Code copied from {@link android.widget.VideoView#onMeasure(int, int)}. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.i("@@@@", "onMeasure(" + MeasureSpec.toString(widthMeasureSpec) + ", " + MeasureSpec.toString(heightMeasureSpec) + ")"); int width = getDefaultSize(mImageWidth, widthMeasureSpec); int height = getDefaultSize(mImageHeight, heightMeasureSpec); if (mImageWidth > 0 && mImageHeight > 0) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.EXACTLY && heightSpecMode == MeasureSpec.EXACTLY) { // the size is fixed width = widthSpecSize; height = heightSpecSize; // for compatibility, we adjust size based on aspect ratio if ( mImageWidth * height < width * mImageHeight) { //Log.i("@@@", "image too wide, correcting"); width = height * mImageWidth / mImageHeight; } else if ( mImageWidth * height > width * mImageHeight) { //Log.i("@@@", "image too tall, correcting"); height = width * mImageHeight / mImageWidth; } } else if (widthSpecMode == MeasureSpec.EXACTLY) { // only the width is fixed, adjust the height to match aspect ratio if possible width = widthSpecSize; height = width * mImageHeight / mImageWidth; if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) { // couldn't match aspect ratio within the constraints height = heightSpecSize; } } else if (heightSpecMode == MeasureSpec.EXACTLY) { // only the height is fixed, adjust the width to match aspect ratio if possible height = heightSpecSize; width = height * mImageWidth / mImageHeight; if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) { // couldn't match aspect ratio within the constraints width = widthSpecSize; } } else { // neither the width nor the height are fixed, try to use actual video size width = mImageWidth; height = mImageHeight; if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) { // too tall, decrease both width and height height = heightSpecSize; width = height * mImageWidth / mImageHeight; } if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) { // too wide, decrease both width and height width = widthSpecSize; height = width * mImageHeight / mImageWidth; } } } else { // no size yet, just adopt the given spec sizes } setMeasuredDimension(width, height); } @Override public boolean onTouchEvent(MotionEvent event) { /* * NOTE: These calls should not be simplified to a logical chain, because the evaluation * would stop at the first true value and not execute the following functions. */ boolean event1 = mScaleGestureDetector.onTouchEvent(event); boolean event2 = mGestureDetector.onTouchEvent(event); return event1 || event2; } @Override public boolean dispatchTouchEvent(MotionEvent event) { if(!mTouchEnabled) { // Touch events are disabled and we return false to route all events to the parent return false; } return super.dispatchTouchEvent(event); } /** * Implement this method to receive the input surface holder when it is ready to be used. * The input surface holder holds the surface and surface texture to which input data, i.e. image * data from some source that should be processed and displayed, should be written to display * it in the view. * * External callers should add a callback to the holder through {@link InputSurfaceHolder#addCallback(InputSurfaceHolder.Callback)} * to be notified about this event in {@link InputSurfaceHolder.Callback#surfaceCreated(InputSurfaceHolder)}. * * @param inputSurfaceHolder the input surface holder which holds the surface where image data should be written to */ public void onInputSurfaceCreated(InputSurfaceHolder inputSurfaceHolder) { // nothing to do here } /** * Gets the input surface holder that holds the surface where image data should be written to * for processing and display. The holder is always available but only holds an actual surface * after {@link #onInputSurfaceCreated(InputSurfaceHolder)} respectively * {@link InputSurfaceHolder.Callback#surfaceCreated(InputSurfaceHolder)} have been called. * * The input surface holder holds the input surface (texture) that is used to write image data * into the processing pipeline, opposed to the surface holder from {@link #getHolder()} that holds * the surface to which the final result of the processing pipeline will be written to for display. * * @return the input surface holder or null if it is not available yet */ public InputSurfaceHolder getInputHolder() { return mInputSurfaceHolder; } @Override public void surfaceDestroyed(SurfaceHolder holder) { // Delete the external texture, else it stays in RAM if(getInputHolder().getExternalSurfaceTexture() != null) { getInputHolder().getExternalSurfaceTexture().delete(); } super.surfaceDestroyed(holder); } /** * Adds one or more effects to the view. Added effects can then be activated/selected by calling * {@link #selectEffect(int)}. The effect indices start at zero and are in the order that they * are added to the view. * @param effects effects to add */ public void addEffect(final Effect... effects) { for(Effect effect : effects) { effect.setListener(this); effect.setParameterHandler(new ParameterHandler(this)); } queueEvent(new Runnable() { @Override public void run() { mRenderer.addEffect(effects); } }); } /** * Selects/activates the effect with the given index as it has been added through {@link #addEffect(Effect...)}. * @param index the index of the effect to activate */ public void selectEffect(final int index) { queueEvent(new Runnable() { @Override public void run() { mRenderer.selectEffect(index); requestRender(GLRenderer.RenderRequest.EFFECT); } }); } /** * Gets called when an effect has been initialized after being selected for the first time * with {@link #selectEffect(int)}. Effect initialization happens asynchronously and can take * some time when a lot of data (framebuffers, textures, ...) is loaded. * Can be overwritten in subclasses but must be called through. External callers should use * {@link #setEffectEventListener(EffectEventListener)}. * @param index the index of the initialized effect * @param effect the initialized effect */ @Override public void onEffectInitialized(int index, Effect effect) { if(mEffectEventListener != null) { mEffectEventListener.onEffectInitialized(index, effect); } requestRender(GLRenderer.RenderRequest.EFFECT); } /** * Gets called when an effect has been successfully selected with {@link #selectEffect(int)}. * Can be overwritten in subclasses but must be called through. External callers should use * {@link #setEffectEventListener(EffectEventListener)}. * @param index the index of the selected effect * @param effect the selected effect */ @Override public void onEffectSelected(int index, Effect effect) { if(mEffectEventListener != null) { mEffectEventListener.onEffectSelected(index, effect); } } /** * Gets called when an effect selection with {@link #selectEffect(int)} fails. * Can be overwritten in subclasses but must be called through. External callers should use * {@link #setEffectEventListener(EffectEventListener)}. * @param index the index of the failed effect * @param effect the failed effect */ @Override public void onEffectError(int index, Effect effect, EffectException e) { Log.e(TAG, "effect error", e); if(mEffectEventListener != null) { mEffectEventListener.onEffectError(index, effect, e); } } /** * Sets an event listener that gets called when effect-related event happens. * @param listener the event listener to be called on an event */ public void setEffectEventListener(EffectEventListener listener) { mEffectEventListener = listener; } /** * Gets called when a parameter of an effect has changed. This method then triggers a fresh * rendering of the effect. Can be overridden in subclasses but must be called through. * @param effect the effect of which a parameter value has changed * @see net.protyposis.android.spectaculum.effects.Effect.Listener */ @Override public void onEffectChanged(Effect effect) { requestRender(GLRenderer.RenderRequest.EFFECT); } /** * Gets called when a parameter is added to an effect. * Can be overridden in subclasses but must be called through. * @param effect the effect to which a parameter was added * @param parameter the added parameter * @see net.protyposis.android.spectaculum.effects.Effect.Listener */ @Override public void onParameterAdded(Effect effect, Parameter parameter) { // nothing to do here } /** * Gets called when a parameter is removed from an effect. * Can be overridden in subclasses but must be called through. * @param effect the effect from which a parameter was removed * @param parameter the removed parameter * @see net.protyposis.android.spectaculum.effects.Effect.Listener */ @Override public void onParameterRemoved(Effect effect, Parameter parameter) { // nothing to do here } /** * Gets called when a new image frame has been written to the surface texture and requests a * fresh rendering of the view. The texture can be obtained through {@link #onInputSurfaceCreated(InputSurfaceHolder)} * or {@link #getInputHolder()}. * Can be overridden in subclasses but must be called through. * @param surfaceTexture the updated surface texture */ @Override public void onFrameAvailable(SurfaceTexture surfaceTexture) { requestRender(GLRenderer.RenderRequest.ALL); } /** * Requests a render pass of the specified render pipeline section. * @param renderRequest specifies the pipeline section to be rendered */ protected void requestRender(final GLRenderer.RenderRequest renderRequest) { queueEvent(new Runnable() { @Override public void run() { mRenderer.setRenderRequest(renderRequest); requestRender(); } }); } /** * Requests a capture of the current frame on the view. The frame is asynchronously requested * from the renderer and will be passed back on the UI thread to {@link #onFrameCaptured(Bitmap)} * and the event listener that can be set with {@link #setOnFrameCapturedCallback(OnFrameCapturedCallback)}. */ public void captureFrame() { queueEvent(new Runnable() { @Override public void run() { mRenderer.saveCurrentFrame(new GLRenderer.OnFrameCapturedCallback() { @Override public void onFrameCaptured(final Bitmap bitmap) { mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { SpectaculumView.this.onFrameCaptured(bitmap); } }); } }); } }); } /** * Receives a captured frame from the renderer. Can be overwritten in subclasses but must be * called through. External callers should use {@link #setOnFrameCapturedCallback(OnFrameCapturedCallback)}. */ @Override public void onFrameCaptured(Bitmap bitmap) { if(mOnFrameCapturedCallback != null) { mOnFrameCapturedCallback.onFrameCaptured(bitmap); } } /** * Sets a callback event handler that receives a bitmap of the captured frame. */ public void setOnFrameCapturedCallback(OnFrameCapturedCallback callback) { mOnFrameCapturedCallback = callback; } /** * Sets the resolution mode of the processing pipeline. * @see PipelineResolution */ public void setPipelineResolution(PipelineResolution resolution) { mPipelineResolution = resolution; } /** * Gets the configured resolution mode of the processing pipeline. */ public PipelineResolution getPipelineResolution() { return mPipelineResolution; } /** * Sets the resolution of the source data and recomputes the layout. This implicitly also sets * the resolution of the view output surface if pipeline resolution mode {@link PipelineResolution#SOURCE} * is set. In SOURCE mode, output will therefore be computed in the input resolution and then * at the very end scaled (most often downscaled) to fit the view in the layout. * * TODO decouple input, processing and output resolution * * @param width the width of the input image data * @param height the height of the input image data */ public void updateResolution(int width, int height) { mImageWidth = width; mImageHeight = height; // If desired, set output resolution to source resolution if (width != 0 && height != 0 && mPipelineResolution == PipelineResolution.SOURCE) { getHolder().setFixedSize(width, height); } // Resize view according to the new size to fit the layout requestLayout(); } private GLRenderer.OnExternalSurfaceTextureCreatedListener mExternalSurfaceTextureCreatedListener = new GLRenderer.OnExternalSurfaceTextureCreatedListener() { @Override public void onExternalSurfaceTextureCreated(final ExternalSurfaceTexture surfaceTexture) { // dispatch event to UI thread mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { // Create an input surface holder and call the event handler mInputSurfaceHolder.update(surfaceTexture); onInputSurfaceCreated(mInputSurfaceHolder); } }); surfaceTexture.setOnFrameAvailableListener(SpectaculumView.this); } }; /** * Effect event listener that transfers the events to the UI thread. */ private EffectEventListener mRendererEffectEventListener = new EffectEventListener() { @Override public void onEffectInitialized(final int index, final Effect effect) { mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { SpectaculumView.this.onEffectInitialized(index, effect); } }); } @Override public void onEffectSelected(final int index, final Effect effect) { mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { SpectaculumView.this.onEffectSelected(index, effect); } }); } @Override public void onEffectError(final int index, final Effect effect, final EffectException e) { mRunOnUiThreadHandler.post(new Runnable() { @Override public void run() { SpectaculumView.this.onEffectError(index, effect, e); } }); } }; }
Skip unnecessary layout processing
Spectaculum-Core/src/main/java/net/protyposis/android/spectaculum/SpectaculumView.java
Skip unnecessary layout processing
Java
apache-2.0
d64020eb20373cc454eefc39f6a07f1d63ae3b02
0
e-Spirit/FSDevTools,e-Spirit/FSDevTools,e-Spirit/FSDevTools,e-Spirit/FSDevTools,e-Spirit/FSDevTools,e-Spirit/FSDevTools
/* * * ********************************************************************* * fsdevtools * %% * Copyright (C) 2016 e-Spirit AG * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************* * */ package com.espirit.moddev.cli.commands.export; import com.espirit.moddev.cli.api.annotations.Description; import com.espirit.moddev.cli.api.parsing.identifier.Identifier; import com.espirit.moddev.cli.api.parsing.identifier.RootNodeIdentifier; import com.espirit.moddev.cli.api.parsing.parser.UidIdentifierParser; import com.espirit.moddev.cli.results.ExportResult; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.help.Examples; import de.espirit.firstspirit.agency.OperationAgent; import de.espirit.firstspirit.agency.StoreAgent; import de.espirit.firstspirit.store.access.nexport.operations.ExportOperation; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; /** * This command can be used to export elements from all stores at the same time. * It makes use of its command arguments to retrieve elements for the export. * * @author e-Spirit AG */ @Command(name = "all", groupNames = {"export"}) @Examples(examples = { "export all -- pagetemplate:default page:homepage", "export all -- root:templatestore page:homepage", "export all -- page:homepage entities:news" }, descriptions = { "Exports a pagetemplate and a page", "Exports the templatestore and a page", "Exports a page and news entities according to the configured filter" }) public class ExportCommand extends AbstractExportCommand { @Override public ExportResult call() { List<Identifier> uids = getIdentifiers(); final ExportOperation exportOperation = this.getContext().requireSpecialist(OperationAgent.TYPE).getOperation(ExportOperation.TYPE); exportOperation.setDeleteObsoleteFiles(isDeleteObsoleteFiles()); exportOperation.setExportChildElements(isExportChildElements()); exportOperation.setExportParentElements(isExportParentElements()); exportOperation.setExportRelease(isExportReleaseState()); addExportElements(this.getContext().requireSpecialist(StoreAgent.TYPE), uids, exportOperation); final ExportOperation.Result result; try { result = exportOperation.perform(getSynchronizationDirectory()); } catch (IOException e) { return new ExportResult(e); } return new ExportResult(result); } @Description public static String getDescription() { return "Exports elements from all stores. If no arguments given, the store roots are exported. \n" + "Known prefixes for export: " + UidIdentifierParser.getAllKnownPrefixStrings() .stream() .collect(Collectors.joining(", ")) + "\n" + "Export entities with identifiers like 'entities:news'\n" + "Known root node identifiers: " + RootNodeIdentifier.getAllStorePostfixes().keySet().stream().collect(Collectors.joining(", ")) + "\n\n"; } }
fsdevtools-cli/src/main/java/com/espirit/moddev/cli/commands/export/ExportCommand.java
/* * * ********************************************************************* * fsdevtools * %% * Copyright (C) 2016 e-Spirit AG * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************* * */ package com.espirit.moddev.cli.commands.export; import com.espirit.moddev.cli.api.annotations.Description; import com.espirit.moddev.cli.api.parsing.identifier.Identifier; import com.espirit.moddev.cli.api.parsing.identifier.RootNodeIdentifier; import com.espirit.moddev.cli.api.parsing.parser.UidIdentifierParser; import com.espirit.moddev.cli.results.ExportResult; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.help.Examples; import de.espirit.firstspirit.agency.OperationAgent; import de.espirit.firstspirit.agency.StoreAgent; import de.espirit.firstspirit.store.access.nexport.operations.ExportOperation; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; /** * This command can be used to export elements from all stores at the same time. * It makes use of its command arguments to retrieve elements for the export. * * @author e-Spirit AG */ @Command(name = "all", groupNames = {"export"}) @Examples(examples = { "export all -- pagetemplate:default page:homepage", "export all -- root:templatestore page:homepage", "export all -- page:homepage entities:news" }, descriptions = { "Exports a pagetemplate and a page", "Exports the templatestore and a page", "Exports a page and news entities according to the configured filter" }) public class ExportCommand extends AbstractExportCommand { @Override public ExportResult call() { List<Identifier> uids = getIdentifiers(); final ExportOperation exportOperation = this.getContext().requireSpecialist(OperationAgent.TYPE).getOperation(ExportOperation.TYPE); exportOperation.setDeleteObsoleteFiles(isDeleteObsoleteFiles()); exportOperation.setExportChildElements(isExportChildElements()); exportOperation.setExportParentElements(isExportParentElements()); exportOperation.setExportRelease(isExportReleaseState()); addExportElements(this.getContext().requireSpecialist(StoreAgent.TYPE), uids, exportOperation); final ExportOperation.Result result; try { result = exportOperation.perform(getSynchronizationDirectory()); } catch (IOException e) { return new ExportResult(e); } return new ExportResult(result); } @Description public static String getDescription() { return "Exports elements from all stores. If no arguments given, the store roots are exported. \n" + "Known prefixes for export: " + UidIdentifierParser.getAllKnownPrefixStrings() .stream() .filter(prefix -> !UidIdentifierParser.getAllKnownPrefixStrings().contains(prefix)) .collect(Collectors.joining(", ")) + "\n" + "Export entities with identifiers like 'entities:news'\n" + "Known root node identifiers: " + RootNodeIdentifier.getAllStorePostfixes().keySet().stream().collect(Collectors.joining(", ")) + "\n\n"; } }
DEVEX-65 fixed knownPrefixes description
fsdevtools-cli/src/main/java/com/espirit/moddev/cli/commands/export/ExportCommand.java
DEVEX-65 fixed knownPrefixes description
Java
apache-2.0
c9b0f39857408c78780ad8e05451ae811c3dffbc
0
jpaw/persistence-java,jpaw/persistence-java
package de.jpaw.bonaparte.jpa; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.converters.Converter; import org.eclipse.persistence.sessions.Session; import de.jpaw.bonaparte.core.BonaPortable; import de.jpaw.bonaparte.core.ByteArrayComposer; import de.jpaw.bonaparte.core.ByteArrayParser; import de.jpaw.bonaparte.core.MessageParserException; public class BonaPortableConverter implements Converter { private static final long serialVersionUID = 1L; @Override public Object convertDataValueToObjectValue(Object dataValue, Session session) { if (dataValue == null) { return null; } ByteArrayParser parser = new ByteArrayParser((byte[]) dataValue, 0, -1); try { return parser.readObject("(JPA)", BonaPortable.class, true, true); } catch (MessageParserException e) { throw new RuntimeException(e); } } @Override public Object convertObjectValueToDataValue(Object objectValue, Session session) { if (objectValue == null) { return null; } else { ByteArrayComposer composer = new ByteArrayComposer(); composer.addField((BonaPortable) objectValue); return composer.getBytes(); } } @Override public void initialize(DatabaseMapping mapping, Session session) { } @Override public boolean isMutable() { return false; } }
persistence-eclipselink/src/main/java/de/jpaw/bonaparte/jpa/BonaPortableConverter.java
package de.jpaw.bonaparte.jpa; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.converters.Converter; import org.eclipse.persistence.sessions.Session; import de.jpaw.bonaparte.core.BonaPortable; import de.jpaw.bonaparte.core.ByteArrayComposer; import de.jpaw.bonaparte.core.ByteArrayParser; import de.jpaw.bonaparte.core.MessageParserException; public class BonaPortableConverter implements Converter { private static final long serialVersionUID = 1L; @Override public Object convertDataValueToObjectValue(Object dataValue, Session session) { if (dataValue == null) { return null; } ByteArrayParser parser = new ByteArrayParser((byte[]) dataValue, 0, -1); try { return parser.readObject(BonaPortable.class, true, true); } catch (MessageParserException e) { throw new RuntimeException(e); } } @Override public Object convertObjectValueToDataValue(Object objectValue, Session session) { if (objectValue == null) { return null; } else { ByteArrayComposer composer = new ByteArrayComposer(); composer.addField((BonaPortable) objectValue); return composer.getBytes(); } } @Override public void initialize(DatabaseMapping mapping, Session session) { } @Override public boolean isMutable() { return false; } }
adjust
persistence-eclipselink/src/main/java/de/jpaw/bonaparte/jpa/BonaPortableConverter.java
adjust
Java
apache-2.0
01df56c6bc8ddcb78524b0829a3fca494a48c272
0
jeluard/stone,jeluard/stone
/* * Copyright 2013 julien. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jeluard.stone.api; import com.github.jeluard.guayaba.annotation.Idempotent; import com.github.jeluard.guayaba.lang.Cancelable; import com.github.jeluard.guayaba.util.concurrent.Scheduler; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.joda.time.Duration; /** * Base implementation tracking a metric for a collection of resources <T> periodically. */ public abstract class BasePoller<T> implements Cancelable { private final Database database; private final Duration period; private final Iterable<T> ts; private final Collection<Archive> archives; private final Map<T, TimeSeries> timeseriess; private final Scheduler scheduler; public BasePoller(final Database database, final Iterable<T> ts, final Duration period, final Collection<Archive> archives, final ExecutorService schedulerExecutorService) throws IOException { this.database = Preconditions.checkNotNull(database, "null database"); this.period = Preconditions.checkNotNull(period, "null period"); this.ts = Preconditions.checkNotNull(ts, "null ts"); this.archives = Preconditions.checkNotNull(archives, "null archives"); this.timeseriess = createTimeSeries(ts); this.scheduler = new Scheduler(period.getMillis(), TimeUnit.MILLISECONDS, schedulerExecutorService, Loggers.BASE_LOGGER); } public BasePoller(final Database database, final Iterable<T> ts, final Duration period, final Collection<Archive> archives) throws IOException { this(database, ts, period, archives, Scheduler.defaultExecutorService(1, Loggers.BASE_LOGGER)); } private Map<T, TimeSeries> createTimeSeries(final Iterable<T> ts) throws IOException { final Map<T, TimeSeries> map = new HashMap<T, TimeSeries>(); for (final T t : ts) { final String id = id(t); final Collection<ConsolidationListener> consolidationListeners = createConsolidationListeners(t, id).or(Collections.<ConsolidationListener>emptyList()); map.put(t, this.database.createOrOpen(id, this.period, this.archives, consolidationListeners)); } return map; } protected Optional<Collection<ConsolidationListener>> createConsolidationListeners(final T t, final String id) { return Optional.absent(); } /** * Start the polling process. */ @Idempotent public final void start() { //TODO Make sure this idempotent this.scheduler.schedule(new Runnable() { @Override public void run() { for (final T t : BasePoller.this.ts) { final long timestamp = System.currentTimeMillis(); try { final int metric = metric(t); try { BasePoller.this.timeseriess.get(t).publish(timestamp, metric); } catch (InterruptedIOException e) { //If metric extraction is too long process will be interrupted if (Loggers.BASE_LOGGER.isLoggable(Level.FINEST)) { Loggers.BASE_LOGGER.log(Level.FINEST, "Interrupted while publishing for <"+t+">", e); } } catch (IOException e) { if (Loggers.BASE_LOGGER.isLoggable(Level.WARNING)) { Loggers.BASE_LOGGER.log(Level.WARNING, "Got exception while publishing for <"+t+">", e); } } } catch (InterruptedException e) { //If metric extraction is too long process will be interrupted if (Loggers.BASE_LOGGER.isLoggable(Level.FINEST)) { Loggers.BASE_LOGGER.log(Level.FINEST, "Interrupted while publishing for <"+t+">", e); } } catch (Exception e) { if (Loggers.BASE_LOGGER.isLoggable(Level.WARNING)) { Loggers.BASE_LOGGER.log(Level.WARNING, "Got exception while accessing metric for <"+t+">", e); } } } } @Override public String toString() { return "Poller"; } }); } /** * @param t * @return a unique id for this {@link TimeSeries} */ protected String id(T t) { return t.toString(); } /** * @param t * @return the extracted metric for {@link TimeSeries} * @throws Exception */ protected abstract int metric(T t) throws Exception; public final Map<String, Map<Window, Reader>> getReaders() { return null;//TODO } @Override public final void cancel() { this.scheduler.cancel(); try { this.database.close(); } catch (IOException e) { if (Loggers.BASE_LOGGER.isLoggable(Level.WARNING)) { Loggers.BASE_LOGGER.log(Level.WARNING, "Got exception while publishing for <"+ts+">", e); } } } }
core/src/main/java/com/github/jeluard/stone/api/BasePoller.java
/* * Copyright 2013 julien. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jeluard.stone.api; import com.github.jeluard.guayaba.annotation.Idempotent; import com.github.jeluard.guayaba.lang.Cancelable; import com.github.jeluard.guayaba.util.concurrent.Scheduler; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.joda.time.Duration; /** * Base implementation tracking a metric for a collection of resources <T> periodically. */ public abstract class BasePoller<T> implements Cancelable { private final Database database; private final Duration period; private final Iterable<T> ts; private final Collection<Archive> archives; private final Map<T, TimeSeries> timeseriess; private final Scheduler scheduler; public BasePoller(final Database database, final Iterable<T> ts, final Duration period, final Collection<Archive> archives, final ExecutorService schedulerExecutorService) throws IOException { this.database = Preconditions.checkNotNull(database, "null database"); this.period = Preconditions.checkNotNull(period, "null period"); this.ts = Preconditions.checkNotNull(ts, "null ts"); this.archives = Preconditions.checkNotNull(archives, "null archives"); this.timeseriess = createTimeSeries(ts); this.scheduler = new Scheduler(period.getMillis(), TimeUnit.MILLISECONDS, schedulerExecutorService, Loggers.BASE_LOGGER); } public BasePoller(final Database database, final Iterable<T> ts, final Duration period, final Collection<Archive> archives) throws IOException { this(database, ts, period, archives, Scheduler.defaultExecutorService(1, Loggers.BASE_LOGGER)); } private Map<T, TimeSeries> createTimeSeries(final Iterable<T> ts) throws IOException { final Map<T, TimeSeries> map = new HashMap<T, TimeSeries>(); for (final T t : ts) { final String id = id(t); final Collection<ConsolidationListener> consolidationListeners = createConsolidationListeners(t, id).or(Collections.<ConsolidationListener>emptyList()); map.put(t, this.database.createOrOpen(id, this.period, this.archives, consolidationListeners)); } return map; } protected Optional<Collection<ConsolidationListener>> createConsolidationListeners(final T t, final String id) { return Optional.absent(); } /** * Start the polling process. */ @Idempotent public final void start() { //TODO Make sure this idempotent this.scheduler.schedule(new Runnable() { @Override public void run() { for (final T t : BasePoller.this.ts) { final long timestamp = System.currentTimeMillis(); try { final int metric = metric(t); try { BasePoller.this.timeseriess.get(t).publish(timestamp, metric); } catch (IOException e) { //If metric extraction is too long process will be interrupted if (e instanceof InterruptedIOException) { if (Loggers.BASE_LOGGER.isLoggable(Level.FINEST)) { Loggers.BASE_LOGGER.log(Level.FINEST, "Interrupted while publishing for <"+t+">", e); } return; } if (Loggers.BASE_LOGGER.isLoggable(Level.WARNING)) { Loggers.BASE_LOGGER.log(Level.WARNING, "Got exception while publishing for <"+t+">", e); } } } catch (Exception e) { //If metric extraction is too long process will be interrupted if (e instanceof InterruptedException) { if (Loggers.BASE_LOGGER.isLoggable(Level.FINEST)) { Loggers.BASE_LOGGER.log(Level.FINEST, "Interrupted while publishing for <"+t+">", e); } return; } if (Loggers.BASE_LOGGER.isLoggable(Level.WARNING)) { Loggers.BASE_LOGGER.log(Level.WARNING, "Got exception while accessing metric for <"+t+">", e); } } } } @Override public String toString() { return "Poller"; } }); } /** * @param t * @return a unique id for this {@link TimeSeries} */ protected String id(T t) { return t.toString(); } /** * @param t * @return the extracted metric for {@link TimeSeries} * @throws Exception */ protected abstract int metric(T t) throws Exception; public final Map<String, Map<Window, Reader>> getReaders() { return null;//TODO } @Override public final void cancel() { this.scheduler.cancel(); try { this.database.close(); } catch (IOException e) { if (Loggers.BASE_LOGGER.isLoggable(Level.WARNING)) { Loggers.BASE_LOGGER.log(Level.WARNING, "Got exception while publishing for <"+ts+">", e); } } } }
Simplified error handling.
core/src/main/java/com/github/jeluard/stone/api/BasePoller.java
Simplified error handling.
Java
apache-2.0
ea22b5780279fb672f85cb49db5c2acf7870d6b0
0
phax/ph-oton,phax/ph-oton,phax/ph-oton
/** * Copyright (C) 2014-2015 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.photon.security.login; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import org.joda.time.Period; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.annotation.ReturnsMutableObject; import com.helger.commons.annotation.UsedViaReflection; import com.helger.commons.callback.CallbackList; import com.helger.commons.collection.CollectionHelper; import com.helger.commons.scope.IScope; import com.helger.commons.scope.ISessionScope; import com.helger.commons.scope.mgr.ScopeManager; import com.helger.commons.scope.singleton.AbstractGlobalSingleton; import com.helger.commons.state.EChange; import com.helger.commons.string.StringHelper; import com.helger.commons.string.ToStringGenerator; import com.helger.photon.basic.audit.AuditHelper; import com.helger.photon.basic.auth.ICurrentUserIDProvider; import com.helger.photon.security.lock.ObjectLockManager; import com.helger.photon.security.mgr.PhotonSecurityManager; import com.helger.photon.security.password.GlobalPasswordSettings; import com.helger.photon.security.user.IUser; import com.helger.photon.security.user.UserManager; import com.helger.photon.security.util.SecurityHelper; import com.helger.web.scope.ISessionWebScope; import com.helger.web.scope.session.ISessionWebScopeActivationHandler; import com.helger.web.scope.singleton.AbstractSessionWebSingleton; /** * This class manages all logged-in users. * * @author Philip Helger */ @ThreadSafe public final class LoggedInUserManager extends AbstractGlobalSingleton implements ICurrentUserIDProvider { /** * This class manages the user ID of the current session. This is an internal * class and should not be used from the outside! * * @author Philip Helger */ public static final class InternalSessionUserHolder extends AbstractSessionWebSingleton implements ISessionWebScopeActivationHandler { private static final long serialVersionUID = 2322897734799334L; private transient IUser m_aUser; private String m_sUserID; private transient LoggedInUserManager m_aOwningMgr; @Deprecated @UsedViaReflection public InternalSessionUserHolder () {} /** * @return The instance of the current session. If none exists, an instance * is created. Never <code>null</code>. */ @Nonnull static InternalSessionUserHolder getInstance () { return getSessionSingleton (InternalSessionUserHolder.class); } /** * @return The instance of the current session. If none exists, * <code>null</code> is returned. */ @Nullable static InternalSessionUserHolder getInstanceIfInstantiated () { return getSessionSingletonIfInstantiated (InternalSessionUserHolder.class); } @Nullable static InternalSessionUserHolder getInstanceIfInstantiatedInScope (@Nullable final ISessionScope aScope) { return getSingletonIfInstantiated (aScope, InternalSessionUserHolder.class); } private void readObject (@Nonnull final ObjectInputStream aOIS) throws IOException, ClassNotFoundException { aOIS.defaultReadObject (); // Resolve user ID if (m_sUserID != null) { m_aUser = PhotonSecurityManager.getUserMgr ().getUserOfID (m_sUserID); if (m_aUser == null) throw new IllegalStateException ("Failed to resolve user with ID '" + m_sUserID + "'"); } // Resolve manager m_aOwningMgr = LoggedInUserManager.getInstance (); } public void onSessionDidActivate (@Nonnull final ISessionWebScope aSessionScope) { // Finally remember that the user is logged in m_aOwningMgr.internalSessionActivateUser (m_aUser, aSessionScope); } boolean hasUser () { return m_aUser != null; } @Nullable String getUserID () { return m_sUserID; } void setUser (@Nonnull final LoggedInUserManager aOwningMgr, @Nonnull final IUser aUser) { ValueEnforcer.notNull (aOwningMgr, "OwningMgr"); ValueEnforcer.notNull (aUser, "User"); if (m_aUser != null) throw new IllegalStateException ("Session already has a user!"); m_aOwningMgr = aOwningMgr; m_aUser = aUser; m_sUserID = aUser.getID (); } void _reset () { // Reset to avoid access while or after logout m_aUser = null; m_sUserID = null; m_aOwningMgr = null; } @Override protected void onDestroy (@Nonnull final IScope aScopeInDestruction) { // Called when the session is destroyed // -> Ensure the user is logged out! // Remember stuff final LoggedInUserManager aOwningMgr = m_aOwningMgr; final String sUserID = m_sUserID; _reset (); // Finally logout the user if (aOwningMgr != null) aOwningMgr.logoutUser (sUserID); } @Override public String toString () { return ToStringGenerator.getDerived (super.toString ()).append ("userID", m_sUserID).toString (); } } /** * Special logout callback that is executed every time a user logs out. It * removes all objects from the {@link ObjectLockManager}. * * @author Philip Helger */ final class UserLogoutCallbackUnlockAllObjects extends DefaultUserLogoutCallback { @Override public void onUserLogout (@Nonnull final LoginInfo aInfo) { final ObjectLockManager aOLMgr = ObjectLockManager.getInstanceIfInstantiated (); if (aOLMgr != null) aOLMgr.getDefaultLockMgr ().unlockAllObjectsOfUser (aInfo.getUserID ()); } } public static final boolean DEFAULT_LOGOUT_ALREADY_LOGGED_IN_USER = false; private static final Logger s_aLogger = LoggerFactory.getLogger (LoggedInUserManager.class); // Set of logged in user IDs @GuardedBy ("m_aRWLock") private final Map <String, LoginInfo> m_aLoggedInUsers = new HashMap <String, LoginInfo> (); private final CallbackList <IUserLoginCallback> m_aUserLoginCallbacks = new CallbackList <IUserLoginCallback> (); private final CallbackList <IUserLogoutCallback> m_aUserLogoutCallbacks = new CallbackList <IUserLogoutCallback> (); private boolean m_bLogoutAlreadyLoggedInUser = DEFAULT_LOGOUT_ALREADY_LOGGED_IN_USER; @Deprecated @UsedViaReflection public LoggedInUserManager () { // Ensure that all objects of a user are unlocked upon logout m_aUserLogoutCallbacks.addCallback (new UserLogoutCallbackUnlockAllObjects ()); } /** * @return The global instance of this class. Never <code>null</code>. */ @Nonnull public static LoggedInUserManager getInstance () { return getGlobalSingleton (LoggedInUserManager.class); } /** * @return The user login callback list. Never <code>null</code>. */ @Nonnull @ReturnsMutableObject ("design") public CallbackList <IUserLoginCallback> getUserLoginCallbacks () { return m_aUserLoginCallbacks; } /** * @return The user logout callback list. Never <code>null</code>. */ @Nonnull @ReturnsMutableObject ("design") public CallbackList <IUserLogoutCallback> getUserLogoutCallbacks () { return m_aUserLogoutCallbacks; } /** * @return <code>true</code> if a new login of a user, destroys any previously * present session, <code>false</code> if a login should fail, if that * user is already logged in. */ public boolean isLogoutAlreadyLoggedInUser () { m_aRWLock.readLock ().lock (); try { return m_bLogoutAlreadyLoggedInUser; } finally { m_aRWLock.readLock ().unlock (); } } public void setLogoutAlreadyLoggedInUser (final boolean bLogoutAlreadyLoggedInUser) { m_aRWLock.writeLock ().lock (); try { m_bLogoutAlreadyLoggedInUser = bLogoutAlreadyLoggedInUser; } finally { m_aRWLock.writeLock ().unlock (); } } /** * Login the passed user without much ado. * * @param sLoginName * Login name of the user to log-in. May be <code>null</code>. * @param sPlainTextPassword * Plain text password to use. May be <code>null</code>. * @return Never <code>null</code> login status. */ @Nonnull public ELoginResult loginUser (@Nullable final String sLoginName, @Nullable final String sPlainTextPassword) { return loginUser (sLoginName, sPlainTextPassword, (Collection <String>) null); } /** * Login the passed user and require a set of certain roles, the used needs to * have to login here. * * @param sLoginName * Login name of the user to log-in. May be <code>null</code>. * @param sPlainTextPassword * Plain text password to use. May be <code>null</code>. * @param aRequiredRoleIDs * A set of required role IDs, the user needs to have. May be * <code>null</code>. * @return Never <code>null</code> login status. */ @Nonnull public ELoginResult loginUser (@Nullable final String sLoginName, @Nullable final String sPlainTextPassword, @Nullable final Collection <String> aRequiredRoleIDs) { // Try to resolve the user final IUser aUser = PhotonSecurityManager.getUserMgr ().getUserOfLoginName (sLoginName); if (aUser == null) { AuditHelper.onAuditExecuteFailure ("login", sLoginName, "no-such-loginname"); return ELoginResult.USER_NOT_EXISTING; } return loginUser (aUser, sPlainTextPassword, aRequiredRoleIDs); } @Nonnull private ELoginResult _onLoginError (@Nonnull @Nonempty final String sUserID, @Nonnull final ELoginResult eLoginResult) { for (final IUserLoginCallback aUserLoginCallback : m_aUserLoginCallbacks.getAllCallbacks ()) try { aUserLoginCallback.onUserLoginError (sUserID, eLoginResult); } catch (final Throwable t) { s_aLogger.error ("Failed to invoke onUserLoginError callback on " + aUserLoginCallback + "(" + sUserID + "," + eLoginResult.toString () + ")", t); } return eLoginResult; } void internalSessionActivateUser (@Nonnull final IUser aUser, @Nonnull final ISessionScope aSessionScope) { ValueEnforcer.notNull (aUser, "User"); ValueEnforcer.notNull (aSessionScope, "SessionScope"); m_aRWLock.writeLock ().lock (); try { final LoginInfo aInfo = new LoginInfo (aUser, aSessionScope); m_aLoggedInUsers.put (aUser.getID (), aInfo); } finally { m_aRWLock.writeLock ().unlock (); } } /** * Login the passed user and require a set of certain roles, the used needs to * have to login here. * * @param aUser * The user to log-in. May be <code>null</code>. When the user is * <code>null</code> the login must fail. * @param sPlainTextPassword * Plain text password to use. May be <code>null</code>. * @param aRequiredRoleIDs * A set of required role IDs, the user needs to have. May be * <code>null</code>. * @return Never <code>null</code> login status. */ @Nonnull public ELoginResult loginUser (@Nullable final IUser aUser, @Nullable final String sPlainTextPassword, @Nullable final Collection <String> aRequiredRoleIDs) { if (aUser == null) return ELoginResult.USER_NOT_EXISTING; final String sUserID = aUser.getID (); // Deleted user? if (aUser.isDeleted ()) { AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-deleted"); return _onLoginError (sUserID, ELoginResult.USER_IS_DELETED); } // Disabled user? if (aUser.isDisabled ()) { AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-disabled"); return _onLoginError (sUserID, ELoginResult.USER_IS_DISABLED); } // Are all roles present? if (!SecurityHelper.hasUserAllRoles (sUserID, aRequiredRoleIDs)) { AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-missing-required-roles", StringHelper.getToString (aRequiredRoleIDs)); return _onLoginError (sUserID, ELoginResult.USER_IS_MISSING_ROLE); } // Check the password final UserManager aUserMgr = PhotonSecurityManager.getUserMgr (); if (!aUserMgr.areUserIDAndPasswordValid (sUserID, sPlainTextPassword)) { AuditHelper.onAuditExecuteFailure ("login", sUserID, "invalid-password"); return _onLoginError (sUserID, ELoginResult.INVALID_PASSWORD); } // Check if the password hash needs to be updated final String sExistingPasswordHashAlgorithmName = aUser.getPasswordHash ().getAlgorithmName (); final String sDefaultPasswordHashAlgorithmName = GlobalPasswordSettings.getPasswordHashCreatorManager () .getDefaultPasswordHashCreatorAlgorithmName (); if (!sExistingPasswordHashAlgorithmName.equals (sDefaultPasswordHashAlgorithmName)) { // This implicitly implies using the default hash creator algorithm // This automatically saves the file aUserMgr.setUserPassword (sUserID, sPlainTextPassword); s_aLogger.info ("Updated password hash of user '" + sUserID + "' from algorithm '" + sExistingPasswordHashAlgorithmName + "' to '" + sDefaultPasswordHashAlgorithmName + "'"); } boolean bLoggedOutUser = false; LoginInfo aInfo; m_aRWLock.writeLock ().lock (); try { if (m_aLoggedInUsers.containsKey (sUserID)) { // The user is already logged in if (isLogoutAlreadyLoggedInUser ()) { // Explicitly log out logoutUser (sUserID); // Just a short check if (m_aLoggedInUsers.containsKey (sUserID)) throw new IllegalStateException ("Failed to logout '" + sUserID + "'"); AuditHelper.onAuditExecuteSuccess ("logout-in-login", sUserID); bLoggedOutUser = true; } else { AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-already-logged-in"); return _onLoginError (sUserID, ELoginResult.USER_ALREADY_LOGGED_IN); } } final InternalSessionUserHolder aSUH = InternalSessionUserHolder.getInstance (); if (aSUH.hasUser ()) { // This session already has a user s_aLogger.warn ("The session user holder already has the user ID '" + aSUH.getUserID () + "' so the new ID '" + sUserID + "' will not be set!"); AuditHelper.onAuditExecuteFailure ("login", sUserID, "session-already-has-user"); return _onLoginError (sUserID, ELoginResult.SESSION_ALREADY_HAS_USER); } aInfo = new LoginInfo (aUser, ScopeManager.getSessionScope ()); m_aLoggedInUsers.put (sUserID, aInfo); aSUH.setUser (this, aUser); } finally { m_aRWLock.writeLock ().unlock (); } s_aLogger.info ("Logged in user '" + sUserID + "' with login name '" + aUser.getLoginName () + "'"); AuditHelper.onAuditExecuteSuccess ("login-user", sUserID, aUser.getLoginName ()); // Execute callback as the very last action for (final IUserLoginCallback aUserLoginCallback : m_aUserLoginCallbacks.getAllCallbacks ()) try { aUserLoginCallback.onUserLogin (aInfo); } catch (final Throwable t) { s_aLogger.error ("Failed to invoke onUserLogin callback on " + aUserLoginCallback.toString () + "(" + aInfo.toString () + ")", t); } return bLoggedOutUser ? ELoginResult.SUCCESS_WITH_LOGOUT : ELoginResult.SUCCESS; } /** * Manually log out the specified user * * @param sUserID * The user ID to log out * @return {@link EChange} if something changed */ @Nonnull public EChange logoutUser (@Nullable final String sUserID) { m_aRWLock.writeLock ().lock (); LoginInfo aInfo; try { aInfo = m_aLoggedInUsers.remove (sUserID); if (aInfo == null) { AuditHelper.onAuditExecuteSuccess ("logout", sUserID, "user-not-logged-in"); return EChange.UNCHANGED; } // Ensure that the SessionUser is empty. This is only relevant if user is // manually logged out without destructing the underlying session final InternalSessionUserHolder aSUH = InternalSessionUserHolder.getInstanceIfInstantiatedInScope (aInfo.getSessionScope ()); if (aSUH != null) aSUH._reset (); // Set logout time - in case somebody has a strong reference to the // LoginInfo object aInfo.setLogoutDTNow (); } finally { m_aRWLock.writeLock ().unlock (); } s_aLogger.info ("Logged out user '" + sUserID + "' after " + new Period (aInfo.getLoginDT (), aInfo.getLogoutDT ()).toString ()); AuditHelper.onAuditExecuteSuccess ("logout", sUserID); // Execute callback as the very last action for (final IUserLogoutCallback aUserLogoutCallback : m_aUserLogoutCallbacks.getAllCallbacks ()) try { aUserLogoutCallback.onUserLogout (aInfo); } catch (final Throwable t) { s_aLogger.error ("Failed to invoke onUserLogout callback on " + aUserLogoutCallback.toString () + "(" + aInfo.toString () + ")", t); } return EChange.CHANGED; } /** * Manually log out the current user * * @return {@link EChange} if something changed */ @Nonnull public EChange logoutCurrentUser () { return logoutUser (getCurrentUserID ()); } /** * Check if the specified user is logged in or not * * @param sUserID * The user ID to check. May be <code>null</code>. * @return <code>true</code> if the user is logged in, <code>false</code> * otherwise. */ public boolean isUserLoggedIn (@Nullable final String sUserID) { m_aRWLock.readLock ().lock (); try { return m_aLoggedInUsers.containsKey (sUserID); } finally { m_aRWLock.readLock ().unlock (); } } /** * @return A non-<code>null</code> but maybe empty set with all currently * logged in user IDs. */ @Nonnull @ReturnsMutableCopy public Set <String> getAllLoggedInUserIDs () { m_aRWLock.readLock ().lock (); try { return CollectionHelper.newSet (m_aLoggedInUsers.keySet ()); } finally { m_aRWLock.readLock ().unlock (); } } /** * Get the login details of the specified user. * * @param sUserID * The user ID to check. May be <code>null</code>. * @return <code>null</code> if the passed user is not logged in. */ @Nullable public LoginInfo getLoginInfo (@Nullable final String sUserID) { m_aRWLock.readLock ().lock (); try { return m_aLoggedInUsers.get (sUserID); } finally { m_aRWLock.readLock ().unlock (); } } /** * @return A non-<code>null</code> but maybe empty collection with the details * of all currently logged in users. */ @Nonnull @ReturnsMutableCopy public Collection <LoginInfo> getAllLoginInfos () { m_aRWLock.readLock ().lock (); try { return CollectionHelper.newList (m_aLoggedInUsers.values ()); } finally { m_aRWLock.readLock ().unlock (); } } /** * @return The number of currently logged in users. Always &ge; 0. */ @Nonnegative public int getLoggedInUserCount () { m_aRWLock.readLock ().lock (); try { return m_aLoggedInUsers.size (); } finally { m_aRWLock.readLock ().unlock (); } } /** * @return The ID of the user logged in this session or <code>null</code> if * no user is logged in. */ @Nullable public String getCurrentUserID () { final InternalSessionUserHolder aSUH = InternalSessionUserHolder.getInstanceIfInstantiated (); return aSUH == null ? null : aSUH.m_sUserID; } /** * @return <code>true</code> if a user is currently logged into this session, * <code>false</code> otherwise. This is the inverse of * {@link #isNoUserLoggedInInCurrentSession()}. */ public boolean isUserLoggedInInCurrentSession () { return getCurrentUserID () != null; } /** * @return <code>true</code> if not user is currently logged into this * session, <code>false</code> if it is. This is the inverse of * {@link #isUserLoggedInInCurrentSession()}. */ public boolean isNoUserLoggedInInCurrentSession () { return getCurrentUserID () == null; } /** * @return The user currently logged in this session or <code>null</code> if * no user is logged in. */ @Nullable public IUser getCurrentUser () { final InternalSessionUserHolder aSUH = InternalSessionUserHolder.getInstanceIfInstantiated (); return aSUH == null ? null : aSUH.m_aUser; } /** * @return <code>true</code> if a user is logged in and is administrator */ public boolean isCurrentUserAdministrator () { final IUser aUser = getCurrentUser (); return aUser != null && aUser.isAdministrator (); } @Override public String toString () { return ToStringGenerator.getDerived (super.toString ()) .append ("loggedInUsers", m_aLoggedInUsers) .append ("userLoginCallbacks", m_aUserLoginCallbacks) .append ("userLogoutCallbacks", m_aUserLogoutCallbacks) .append ("logoutAlreadyLoggedInUser", m_bLogoutAlreadyLoggedInUser) .toString (); } }
ph-oton-security/src/main/java/com/helger/photon/security/login/LoggedInUserManager.java
/** * Copyright (C) 2014-2015 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.photon.security.login; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import org.joda.time.Period; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.annotation.ReturnsMutableObject; import com.helger.commons.annotation.UsedViaReflection; import com.helger.commons.callback.CallbackList; import com.helger.commons.collection.CollectionHelper; import com.helger.commons.scope.IScope; import com.helger.commons.scope.ISessionScope; import com.helger.commons.scope.mgr.ScopeManager; import com.helger.commons.scope.singleton.AbstractGlobalSingleton; import com.helger.commons.state.EChange; import com.helger.commons.string.StringHelper; import com.helger.commons.string.ToStringGenerator; import com.helger.photon.basic.audit.AuditHelper; import com.helger.photon.basic.auth.ICurrentUserIDProvider; import com.helger.photon.security.lock.ObjectLockManager; import com.helger.photon.security.mgr.PhotonSecurityManager; import com.helger.photon.security.password.GlobalPasswordSettings; import com.helger.photon.security.user.IUser; import com.helger.photon.security.user.UserManager; import com.helger.photon.security.util.SecurityHelper; import com.helger.web.scope.ISessionWebScope; import com.helger.web.scope.session.ISessionWebScopeActivationHandler; import com.helger.web.scope.singleton.AbstractSessionWebSingleton; /** * This class manages all logged-in users. * * @author Philip Helger */ @ThreadSafe public final class LoggedInUserManager extends AbstractGlobalSingleton implements ICurrentUserIDProvider { /** * This class manages the user ID of the current session. This is an internal * class and should not be used from the outside! * * @author Philip Helger */ public static final class SessionUserHolder extends AbstractSessionWebSingleton implements ISessionWebScopeActivationHandler { private static final long serialVersionUID = 2322897734799334L; private transient IUser m_aUser; private String m_sUserID; private transient LoggedInUserManager m_aOwningMgr; @Deprecated @UsedViaReflection public SessionUserHolder () {} /** * @return The instance of the current session. If none exists, an instance * is created. Never <code>null</code>. */ @Nonnull static SessionUserHolder getInstance () { return getSessionSingleton (SessionUserHolder.class); } /** * @return The instance of the current session. If none exists, * <code>null</code> is returned. */ @Nullable static SessionUserHolder getInstanceIfInstantiated () { return getSessionSingletonIfInstantiated (SessionUserHolder.class); } @Nullable static SessionUserHolder getInstanceIfInstantiatedInScope (@Nullable final ISessionScope aScope) { return getSingletonIfInstantiated (aScope, SessionUserHolder.class); } private void readObject (@Nonnull final ObjectInputStream aOIS) throws IOException, ClassNotFoundException { aOIS.defaultReadObject (); // Resolve user ID if (m_sUserID != null) { m_aUser = PhotonSecurityManager.getUserMgr ().getUserOfID (m_sUserID); if (m_aUser == null) throw new IllegalStateException ("Failed to resolve user with ID '" + m_sUserID + "'"); } // Resolve manager m_aOwningMgr = LoggedInUserManager.getInstance (); } public void onSessionDidActivate (@Nonnull final ISessionWebScope aSessionScope) { // Finally remember that the user is logged in m_aOwningMgr.internalSessionActivateUser (m_aUser, aSessionScope); } boolean hasUser () { return m_aUser != null; } @Nullable String getUserID () { return m_sUserID; } void setUser (@Nonnull final LoggedInUserManager aOwningMgr, @Nonnull final IUser aUser) { ValueEnforcer.notNull (aOwningMgr, "OwningMgr"); ValueEnforcer.notNull (aUser, "User"); if (m_aUser != null) throw new IllegalStateException ("Session already has a user!"); m_aOwningMgr = aOwningMgr; m_aUser = aUser; m_sUserID = aUser.getID (); } void _reset () { // Reset to avoid access while or after logout m_aUser = null; m_sUserID = null; m_aOwningMgr = null; } @Override protected void onDestroy (@Nonnull final IScope aScopeInDestruction) { // Called when the session is destroyed // -> Ensure the user is logged out! // Remember stuff final LoggedInUserManager aOwningMgr = m_aOwningMgr; final String sUserID = m_sUserID; _reset (); // Finally logout the user if (aOwningMgr != null) aOwningMgr.logoutUser (sUserID); } @Override public String toString () { return ToStringGenerator.getDerived (super.toString ()).append ("userID", m_sUserID).toString (); } } /** * Special logout callback that is executed every time a user logs out. It * removes all objects from the {@link ObjectLockManager}. * * @author Philip Helger */ final class UserLogoutCallbackUnlockAllObjects extends DefaultUserLogoutCallback { @Override public void onUserLogout (@Nonnull final LoginInfo aInfo) { final ObjectLockManager aOLMgr = ObjectLockManager.getInstanceIfInstantiated (); if (aOLMgr != null) aOLMgr.getDefaultLockMgr ().unlockAllObjectsOfUser (aInfo.getUserID ()); } } public static final boolean DEFAULT_LOGOUT_ALREADY_LOGGED_IN_USER = false; private static final Logger s_aLogger = LoggerFactory.getLogger (LoggedInUserManager.class); // Set of logged in user IDs @GuardedBy ("m_aRWLock") private final Map <String, LoginInfo> m_aLoggedInUsers = new HashMap <String, LoginInfo> (); private final CallbackList <IUserLoginCallback> m_aUserLoginCallbacks = new CallbackList <IUserLoginCallback> (); private final CallbackList <IUserLogoutCallback> m_aUserLogoutCallbacks = new CallbackList <IUserLogoutCallback> (); private boolean m_bLogoutAlreadyLoggedInUser = DEFAULT_LOGOUT_ALREADY_LOGGED_IN_USER; @Deprecated @UsedViaReflection public LoggedInUserManager () { // Ensure that all objects of a user are unlocked upon logout m_aUserLogoutCallbacks.addCallback (new UserLogoutCallbackUnlockAllObjects ()); } /** * @return The global instance of this class. Never <code>null</code>. */ @Nonnull public static LoggedInUserManager getInstance () { return getGlobalSingleton (LoggedInUserManager.class); } /** * @return The user login callback list. Never <code>null</code>. */ @Nonnull @ReturnsMutableObject ("design") public CallbackList <IUserLoginCallback> getUserLoginCallbacks () { return m_aUserLoginCallbacks; } /** * @return The user logout callback list. Never <code>null</code>. */ @Nonnull @ReturnsMutableObject ("design") public CallbackList <IUserLogoutCallback> getUserLogoutCallbacks () { return m_aUserLogoutCallbacks; } /** * @return <code>true</code> if a new login of a user, destroys any previously * present session, <code>false</code> if a login should fail, if that * user is already logged in. */ public boolean isLogoutAlreadyLoggedInUser () { m_aRWLock.readLock ().lock (); try { return m_bLogoutAlreadyLoggedInUser; } finally { m_aRWLock.readLock ().unlock (); } } public void setLogoutAlreadyLoggedInUser (final boolean bLogoutAlreadyLoggedInUser) { m_aRWLock.writeLock ().lock (); try { m_bLogoutAlreadyLoggedInUser = bLogoutAlreadyLoggedInUser; } finally { m_aRWLock.writeLock ().unlock (); } } /** * Login the passed user without much ado. * * @param sLoginName * Login name of the user to log-in. May be <code>null</code>. * @param sPlainTextPassword * Plain text password to use. May be <code>null</code>. * @return Never <code>null</code> login status. */ @Nonnull public ELoginResult loginUser (@Nullable final String sLoginName, @Nullable final String sPlainTextPassword) { return loginUser (sLoginName, sPlainTextPassword, (Collection <String>) null); } /** * Login the passed user and require a set of certain roles, the used needs to * have to login here. * * @param sLoginName * Login name of the user to log-in. May be <code>null</code>. * @param sPlainTextPassword * Plain text password to use. May be <code>null</code>. * @param aRequiredRoleIDs * A set of required role IDs, the user needs to have. May be * <code>null</code>. * @return Never <code>null</code> login status. */ @Nonnull public ELoginResult loginUser (@Nullable final String sLoginName, @Nullable final String sPlainTextPassword, @Nullable final Collection <String> aRequiredRoleIDs) { // Try to resolve the user final IUser aUser = PhotonSecurityManager.getUserMgr ().getUserOfLoginName (sLoginName); if (aUser == null) { AuditHelper.onAuditExecuteFailure ("login", sLoginName, "no-such-loginname"); return ELoginResult.USER_NOT_EXISTING; } return loginUser (aUser, sPlainTextPassword, aRequiredRoleIDs); } @Nonnull private ELoginResult _onLoginError (@Nonnull @Nonempty final String sUserID, @Nonnull final ELoginResult eLoginResult) { for (final IUserLoginCallback aUserLoginCallback : m_aUserLoginCallbacks.getAllCallbacks ()) try { aUserLoginCallback.onUserLoginError (sUserID, eLoginResult); } catch (final Throwable t) { s_aLogger.error ("Failed to invoke onUserLoginError callback on " + aUserLoginCallback + "(" + sUserID + "," + eLoginResult.toString () + ")", t); } return eLoginResult; } void internalSessionActivateUser (@Nonnull final IUser aUser, @Nonnull final ISessionScope aSessionScope) { ValueEnforcer.notNull (aUser, "User"); ValueEnforcer.notNull (aSessionScope, "SessionScope"); m_aRWLock.writeLock ().lock (); try { final LoginInfo aInfo = new LoginInfo (aUser, aSessionScope); m_aLoggedInUsers.put (aUser.getID (), aInfo); } finally { m_aRWLock.writeLock ().unlock (); } } /** * Login the passed user and require a set of certain roles, the used needs to * have to login here. * * @param aUser * The user to log-in. May be <code>null</code>. When the user is * <code>null</code> the login must fail. * @param sPlainTextPassword * Plain text password to use. May be <code>null</code>. * @param aRequiredRoleIDs * A set of required role IDs, the user needs to have. May be * <code>null</code>. * @return Never <code>null</code> login status. */ @Nonnull public ELoginResult loginUser (@Nullable final IUser aUser, @Nullable final String sPlainTextPassword, @Nullable final Collection <String> aRequiredRoleIDs) { if (aUser == null) return ELoginResult.USER_NOT_EXISTING; final String sUserID = aUser.getID (); // Deleted user? if (aUser.isDeleted ()) { AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-deleted"); return _onLoginError (sUserID, ELoginResult.USER_IS_DELETED); } // Disabled user? if (aUser.isDisabled ()) { AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-disabled"); return _onLoginError (sUserID, ELoginResult.USER_IS_DISABLED); } // Are all roles present? if (!SecurityHelper.hasUserAllRoles (sUserID, aRequiredRoleIDs)) { AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-missing-required-roles", StringHelper.getToString (aRequiredRoleIDs)); return _onLoginError (sUserID, ELoginResult.USER_IS_MISSING_ROLE); } // Check the password final UserManager aUserMgr = PhotonSecurityManager.getUserMgr (); if (!aUserMgr.areUserIDAndPasswordValid (sUserID, sPlainTextPassword)) { AuditHelper.onAuditExecuteFailure ("login", sUserID, "invalid-password"); return _onLoginError (sUserID, ELoginResult.INVALID_PASSWORD); } // Check if the password hash needs to be updated final String sExistingPasswordHashAlgorithmName = aUser.getPasswordHash ().getAlgorithmName (); final String sDefaultPasswordHashAlgorithmName = GlobalPasswordSettings.getPasswordHashCreatorManager () .getDefaultPasswordHashCreatorAlgorithmName (); if (!sExistingPasswordHashAlgorithmName.equals (sDefaultPasswordHashAlgorithmName)) { // This implicitly implies using the default hash creator algorithm // This automatically saves the file aUserMgr.setUserPassword (sUserID, sPlainTextPassword); s_aLogger.info ("Updated password hash of user '" + sUserID + "' from algorithm '" + sExistingPasswordHashAlgorithmName + "' to '" + sDefaultPasswordHashAlgorithmName + "'"); } boolean bLoggedOutUser = false; LoginInfo aInfo; m_aRWLock.writeLock ().lock (); try { if (m_aLoggedInUsers.containsKey (sUserID)) { // The user is already logged in if (isLogoutAlreadyLoggedInUser ()) { // Explicitly log out logoutUser (sUserID); // Just a short check if (m_aLoggedInUsers.containsKey (sUserID)) throw new IllegalStateException ("Failed to logout '" + sUserID + "'"); AuditHelper.onAuditExecuteSuccess ("logout-in-login", sUserID); bLoggedOutUser = true; } else { AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-already-logged-in"); return _onLoginError (sUserID, ELoginResult.USER_ALREADY_LOGGED_IN); } } final SessionUserHolder aSUH = SessionUserHolder.getInstance (); if (aSUH.hasUser ()) { // This session already has a user s_aLogger.warn ("The session user holder already has the user ID '" + aSUH.getUserID () + "' so the new ID '" + sUserID + "' will not be set!"); AuditHelper.onAuditExecuteFailure ("login", sUserID, "session-already-has-user"); return _onLoginError (sUserID, ELoginResult.SESSION_ALREADY_HAS_USER); } aInfo = new LoginInfo (aUser, ScopeManager.getSessionScope ()); m_aLoggedInUsers.put (sUserID, aInfo); aSUH.setUser (this, aUser); } finally { m_aRWLock.writeLock ().unlock (); } s_aLogger.info ("Logged in user '" + sUserID + "' with login name '" + aUser.getLoginName () + "'"); AuditHelper.onAuditExecuteSuccess ("login-user", sUserID, aUser.getLoginName ()); // Execute callback as the very last action for (final IUserLoginCallback aUserLoginCallback : m_aUserLoginCallbacks.getAllCallbacks ()) try { aUserLoginCallback.onUserLogin (aInfo); } catch (final Throwable t) { s_aLogger.error ("Failed to invoke onUserLogin callback on " + aUserLoginCallback.toString () + "(" + aInfo.toString () + ")", t); } return bLoggedOutUser ? ELoginResult.SUCCESS_WITH_LOGOUT : ELoginResult.SUCCESS; } /** * Manually log out the specified user * * @param sUserID * The user ID to log out * @return {@link EChange} if something changed */ @Nonnull public EChange logoutUser (@Nullable final String sUserID) { m_aRWLock.writeLock ().lock (); LoginInfo aInfo; try { aInfo = m_aLoggedInUsers.remove (sUserID); if (aInfo == null) { AuditHelper.onAuditExecuteSuccess ("logout", sUserID, "user-not-logged-in"); return EChange.UNCHANGED; } // Ensure that the SessionUser is empty. This is only relevant if user is // manually logged out without destructing the underlying session final SessionUserHolder aSUH = SessionUserHolder.getInstanceIfInstantiatedInScope (aInfo.getSessionScope ()); if (aSUH != null) aSUH._reset (); // Set logout time - in case somebody has a strong reference to the // LoginInfo object aInfo.setLogoutDTNow (); } finally { m_aRWLock.writeLock ().unlock (); } s_aLogger.info ("Logged out user '" + sUserID + "' after " + new Period (aInfo.getLoginDT (), aInfo.getLogoutDT ()).toString ()); AuditHelper.onAuditExecuteSuccess ("logout", sUserID); // Execute callback as the very last action for (final IUserLogoutCallback aUserLogoutCallback : m_aUserLogoutCallbacks.getAllCallbacks ()) try { aUserLogoutCallback.onUserLogout (aInfo); } catch (final Throwable t) { s_aLogger.error ("Failed to invoke onUserLogout callback on " + aUserLogoutCallback.toString () + "(" + aInfo.toString () + ")", t); } return EChange.CHANGED; } /** * Manually log out the current user * * @return {@link EChange} if something changed */ @Nonnull public EChange logoutCurrentUser () { return logoutUser (getCurrentUserID ()); } /** * Check if the specified user is logged in or not * * @param sUserID * The user ID to check. May be <code>null</code>. * @return <code>true</code> if the user is logged in, <code>false</code> * otherwise. */ public boolean isUserLoggedIn (@Nullable final String sUserID) { m_aRWLock.readLock ().lock (); try { return m_aLoggedInUsers.containsKey (sUserID); } finally { m_aRWLock.readLock ().unlock (); } } /** * @return A non-<code>null</code> but maybe empty set with all currently * logged in user IDs. */ @Nonnull @ReturnsMutableCopy public Set <String> getAllLoggedInUserIDs () { m_aRWLock.readLock ().lock (); try { return CollectionHelper.newSet (m_aLoggedInUsers.keySet ()); } finally { m_aRWLock.readLock ().unlock (); } } /** * Get the login details of the specified user. * * @param sUserID * The user ID to check. May be <code>null</code>. * @return <code>null</code> if the passed user is not logged in. */ @Nullable public LoginInfo getLoginInfo (@Nullable final String sUserID) { m_aRWLock.readLock ().lock (); try { return m_aLoggedInUsers.get (sUserID); } finally { m_aRWLock.readLock ().unlock (); } } /** * @return A non-<code>null</code> but maybe empty collection with the details * of all currently logged in users. */ @Nonnull @ReturnsMutableCopy public Collection <LoginInfo> getAllLoginInfos () { m_aRWLock.readLock ().lock (); try { return CollectionHelper.newList (m_aLoggedInUsers.values ()); } finally { m_aRWLock.readLock ().unlock (); } } /** * @return The number of currently logged in users. Always &ge; 0. */ @Nonnegative public int getLoggedInUserCount () { m_aRWLock.readLock ().lock (); try { return m_aLoggedInUsers.size (); } finally { m_aRWLock.readLock ().unlock (); } } /** * @return The ID of the user logged in this session or <code>null</code> if * no user is logged in. */ @Nullable public String getCurrentUserID () { final SessionUserHolder aSUH = SessionUserHolder.getInstanceIfInstantiated (); return aSUH == null ? null : aSUH.m_sUserID; } /** * @return <code>true</code> if a user is currently logged into this session, * <code>false</code> otherwise. This is the inverse of * {@link #isNoUserLoggedInInCurrentSession()}. */ public boolean isUserLoggedInInCurrentSession () { return getCurrentUserID () != null; } /** * @return <code>true</code> if not user is currently logged into this * session, <code>false</code> if it is. This is the inverse of * {@link #isUserLoggedInInCurrentSession()}. */ public boolean isNoUserLoggedInInCurrentSession () { return getCurrentUserID () == null; } /** * @return The user currently logged in this session or <code>null</code> if * no user is logged in. */ @Nullable public IUser getCurrentUser () { final SessionUserHolder aSUH = SessionUserHolder.getInstanceIfInstantiated (); return aSUH == null ? null : aSUH.m_aUser; } /** * @return <code>true</code> if a user is logged in and is administrator */ public boolean isCurrentUserAdministrator () { final IUser aUser = getCurrentUser (); return aUser != null && aUser.isAdministrator (); } @Override public String toString () { return ToStringGenerator.getDerived (super.toString ()) .append ("loggedInUsers", m_aLoggedInUsers) .append ("userLoginCallbacks", m_aUserLoginCallbacks) .append ("userLogoutCallbacks", m_aUserLogoutCallbacks) .append ("logoutAlreadyLoggedInUser", m_bLogoutAlreadyLoggedInUser) .toString (); } }
Renamed internal class
ph-oton-security/src/main/java/com/helger/photon/security/login/LoggedInUserManager.java
Renamed internal class
Java
apache-2.0
3e607cd9a677b44b3cc89b72b19fb08d134dc272
0
akjava/gwt-three.js-test,sebasbaumh/gwt-three.js,akjava/gwt-three.js-test,akjava/gwt-three.js-test,sebasbaumh/gwt-three.js,sebasbaumh/gwt-three.js
package com.akjava.gwt.three.client.core; import com.google.gwt.core.client.JavaScriptObject; public class Matrix4 extends JavaScriptObject { protected Matrix4(){} public native final void setRotationFromEuler(Vector3 vec,String order)/*-{ this.setRotationFromEuler(vec,order); }-*/; public native final void setPosition(Vector3 vec)/*-{ this.setPosition(vec); }-*/; public final native Matrix4 clone()/*-{ return this.clone(); }-*/; //value is shared usually got a problem //return THREE.Matrix4.__v1.set( this.n14, this.n24, this.n34 ); public native final Vector3 getPosition()/*-{ return this.getPosition().clone(); }-*/; public native final Vector3 getColumnX()/*-{ return this.getColumnX().clone(); }-*/; public native final Vector3 getColumnY()/*-{ return this.getColumnY().clone(); }-*/; public native final Vector3 getColumnZ()/*-{ return this.getColumnZ().clone(); }-*/; public native final Matrix4 makeRotationX(double v)/*-{ return this.makeRotationX(v); }-*/; public native final Matrix4 makeRotationY(double v)/*-{ return this.makeRotationY(v); }-*/; public native final Matrix4 makeRotationZ(double v)/*-{ return this.makeRotationZ(v); }-*/; public native final Matrix4 multiply(Matrix4 a,Matrix4 b)/*-{ return this.multiply(a,b); }-*/; public native final Matrix4 multiplySelf(Matrix4 b)/*-{ return this.multiply(this,b); }-*/; public native final Matrix4 setRotationFromQuaternion(Quaternion q)/*-{ return this.setRotationFromQuaternion(q); }-*/; public native final Matrix4 getInverse(Matrix4 b)/*-{ return this.getInverse(b); }-*/; public native final Vector3 multiplyVector3(Vector3 vec)/*-{ return this.multiplyVector3(vec); }-*/; /** * @deprecated * @param x * @param y * @param z */ public native final void setRotationX(double thera)/*-{ this.makeRotationX(thera); }-*/; /** * @deprecated * @param x * @param y * @param z */ public native final void setRotationY(double thera)/*-{ this.makeRotationY(thera); }-*/; /** * @deprecated * @param x * @param y * @param z */ public native final void setRotationZ(double thera)/*-{ this.makeRotationZ(thera); }-*/; /** * @deprecated * @param x * @param y * @param z */ public native final void setTranslation(double x,double y,double z)/*-{ this.makeTranslation(x,y,z); }-*/; public native final void makeTranslation(double x,double y,double z)/*-{ this.makeTranslation(x,y,z); }-*/; public native final Matrix4 lookAt(Vector3 eye,Vector3 center,Vector3 up)/*-{ return this.lookAt(eye,center,up); }-*/; }
src/com/akjava/gwt/three/client/core/Matrix4.java
package com.akjava.gwt.three.client.core; import com.google.gwt.core.client.JavaScriptObject; public class Matrix4 extends JavaScriptObject { protected Matrix4(){} public native final void setRotationFromEuler(Vector3 vec,String order)/*-{ this.setRotationFromEuler(vec,order); }-*/; public native final void setPosition(Vector3 vec)/*-{ this.setPosition(vec); }-*/; public final native Matrix4 clone()/*-{ return this.clone(); }-*/; //value is shared usually got a problem //return THREE.Matrix4.__v1.set( this.n14, this.n24, this.n34 ); public native final Vector3 getPosition()/*-{ return this.getPosition().clone(); }-*/; public native final Vector3 getColumnX()/*-{ return this.getColumnX().clone(); }-*/; public native final Vector3 getColumnY()/*-{ return this.getColumnY().clone(); }-*/; public native final Vector3 getColumnZ()/*-{ return this.getColumnZ().clone(); }-*/; public native final Matrix4 makeRotationX(double v)/*-{ return this.makeRotationX(v); }-*/; public native final Matrix4 makeRotationY(double v)/*-{ return this.makeRotationY(v); }-*/; public native final Matrix4 makeRotationZ(double v)/*-{ return this.makeRotationZ(v); }-*/; public native final Matrix4 multiply(Matrix4 a,Matrix4 b)/*-{ return this.multiply(a,b); }-*/; public native final Matrix4 multiplySelf(Matrix4 b)/*-{ return this.multiply(this,b); }-*/; public native final Matrix4 setRotationFromQuaternion(Quaternion q)/*-{ return this.setRotationFromQuaternion(q); }-*/; public native final Matrix4 getInverse(Matrix4 b)/*-{ return this.getInverse(b); }-*/; public native final Vector3 multiplyVector3(Vector3 vec)/*-{ return this.multiplyVector3(vec); }-*/; public native final void setRotationX(double thera)/*-{ this.setRotationX(thera); }-*/; public native final void setRotationY(double thera)/*-{ this.setRotationY(thera); }-*/; public native final void setRotationZ(double thera)/*-{ this.setRotationZ(thera); }-*/; public native final void setTranslation(double x,double y,double z)/*-{ this.setTranslation(x,y,z); }-*/; public native final Matrix4 lookAt(Vector3 eye,Vector3 center,Vector3 up)/*-{ return this.lookAt(eye,center,up); }-*/; }
fixed #12
src/com/akjava/gwt/three/client/core/Matrix4.java
fixed #12
Java
apache-2.0
2180016ff01de9c0a056f743387b90c2de11b2d4
0
mjuhasz/BDSup2Sub,mjuhasz/BDSup2Sub
/* * Copyright 2012 Miklos Juhasz (mjuhasz), JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package bdsup2sub.gui.support; import javax.swing.*; import javax.swing.plaf.synth.Region; import javax.swing.plaf.synth.SynthLookAndFeel; import javax.swing.plaf.synth.SynthStyle; import javax.swing.plaf.synth.SynthStyleFactory; import java.awt.*; import java.lang.reflect.Field; import java.lang.reflect.Method; public final class GuiUtils { public static final Color GTK_AMBIANCE_TEXT_COLOR = new Color(223, 219, 210); public static final Color GTK_AMBIANCE_BACKGROUND_COLOR = new Color(67, 66, 63); private GuiUtils() { } public static boolean isUnderGTKLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("GTK"); } public static String getGtkThemeName() { final LookAndFeel laf = UIManager.getLookAndFeel(); if (laf != null && "GTKLookAndFeel".equals(laf.getClass().getSimpleName())) { try { final Method method = laf.getClass().getDeclaredMethod("getGtkThemeName"); method.setAccessible(true); final Object theme = method.invoke(laf); if (theme != null) { return theme.toString(); } } catch (Exception ignored) { } } return null; } public static void applyGtkThemeWorkarounds() { fixGtkPopupStyle(); fixGtkPopupWeight(); } private static void fixGtkPopupStyle() { if (!isUnderGTKLookAndFeel()) { return; } final SynthStyleFactory original = SynthLookAndFeel.getStyleFactory(); SynthLookAndFeel.setStyleFactory(new SynthStyleFactory() { @Override public SynthStyle getStyle(final JComponent c, final Region id) { final SynthStyle style = original.getStyle(c, id); if (id == Region.POPUP_MENU) { fixPopupMenuStyle(style); } else if (id == Region.POPUP_MENU_SEPARATOR) { fixPopupMenuSeparatorStyle(style); } return style; } private void fixPopupMenuStyle(SynthStyle style) { try { Field f = getAccessibleFieldFromStyle(style, "xThickness"); final Object x = f.get(style); if (x instanceof Integer && (Integer)x == 0) { f.set(style, 1); f = getAccessibleFieldFromStyle(style, "yThickness"); f.set(style, 3); } } catch (Exception ignore) { // ignore } } private void fixPopupMenuSeparatorStyle(SynthStyle style) { try { Field f = getAccessibleFieldFromStyle(style, "yThickness"); final Object y = f.get(style); if (y instanceof Integer && (Integer)y == 0) { f.set(style, 2); } } catch (Exception ignore) { // ignore } } private Field getAccessibleFieldFromStyle(SynthStyle style, String fieldName) throws IllegalAccessException, NoSuchFieldException { Field f = style.getClass().getDeclaredField(fieldName); f.setAccessible(true); return f; } }); new JPopupMenu(); // invokes updateUI() -> updateStyle() new JPopupMenu.Separator(); // invokes updateUI() -> updateStyle() SynthLookAndFeel.setStyleFactory(original); } private static void fixGtkPopupWeight() { if (!isUnderGTKLookAndFeel()) { return; } PopupFactory factory = PopupFactory.getSharedInstance(); if (!(factory instanceof MyPopupFactory)) { factory = new MyPopupFactory(factory); PopupFactory.setSharedInstance(factory); } } private static class MyPopupFactory extends PopupFactory { private static final int WEIGHT_HEAVY = 2; // package-private in PopupFactory private final PopupFactory myDelegate; public MyPopupFactory(final PopupFactory delegate) { myDelegate = delegate; } public Popup getPopup(final Component owner, final Component contents, final int x, final int y) throws IllegalArgumentException { final int popupType = GuiUtils.isUnderGTKLookAndFeel() ? WEIGHT_HEAVY : PopupUtil.getPopupType(this); if (popupType >= 0) { PopupUtil.setPopupType(myDelegate, popupType); } return myDelegate.getPopup(owner, contents, x, y); } } public static void centerRelativeToOwner(Window window) { Window owner = window.getOwner(); Point p = owner.getLocation(); window.setLocation(p.x + owner.getWidth() / 2 - window.getWidth() / 2, p.y + owner.getHeight() / 2 - window.getHeight() / 2); } }
src/main/java/bdsup2sub/gui/support/GuiUtils.java
/* * Copyright 2012 Miklos Juhasz (mjuhasz), JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package bdsup2sub.gui.support; import javax.swing.*; import javax.swing.plaf.synth.Region; import javax.swing.plaf.synth.SynthLookAndFeel; import javax.swing.plaf.synth.SynthStyle; import javax.swing.plaf.synth.SynthStyleFactory; import java.awt.*; import java.lang.reflect.Field; import java.lang.reflect.Method; public final class GuiUtils { public static final Color GTK_AMBIANCE_TEXT_COLOR = new Color(223, 219, 210); public static final Color GTK_AMBIANCE_BACKGROUND_COLOR = new Color(67, 66, 63); private GuiUtils() { } public static boolean isUnderGTKLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("GTK"); } public static String getGtkThemeName() { final LookAndFeel laf = UIManager.getLookAndFeel(); if (laf != null && "GTKLookAndFeel".equals(laf.getClass().getSimpleName())) { try { final Method method = laf.getClass().getDeclaredMethod("getGtkThemeName"); method.setAccessible(true); final Object theme = method.invoke(laf); if (theme != null) { return theme.toString(); } } catch (Exception ignored) { } } return null; } public static void applyGtkThemeWorkarounds() { fixGtkPopupStyle(); fixGtkPopupWeight(); } private static void fixGtkPopupStyle() { if (!isUnderGTKLookAndFeel()) { return; } final SynthStyleFactory original = SynthLookAndFeel.getStyleFactory(); SynthLookAndFeel.setStyleFactory(new SynthStyleFactory() { @Override public SynthStyle getStyle(final JComponent c, final Region id) { final SynthStyle style = original.getStyle(c, id); if (id == Region.POPUP_MENU) { try { Field f = style.getClass().getDeclaredField("xThickness"); f.setAccessible(true); final Object x = f.get(style); if (x instanceof Integer && (Integer)x == 0) { f.set(style, 1); f = style.getClass().getDeclaredField("yThickness"); f.setAccessible(true); f.set(style, 3); } } catch (Exception ignore) { // ignore } } return style; } }); new JPopupMenu(); // invokes updateUI() -> updateStyle() SynthLookAndFeel.setStyleFactory(original); } private static void fixGtkPopupWeight() { if (!isUnderGTKLookAndFeel()) { return; } PopupFactory factory = PopupFactory.getSharedInstance(); if (!(factory instanceof MyPopupFactory)) { factory = new MyPopupFactory(factory); PopupFactory.setSharedInstance(factory); } } private static class MyPopupFactory extends PopupFactory { private static final int WEIGHT_HEAVY = 2; // package-private in PopupFactory private final PopupFactory myDelegate; public MyPopupFactory(final PopupFactory delegate) { myDelegate = delegate; } public Popup getPopup(final Component owner, final Component contents, final int x, final int y) throws IllegalArgumentException { final int popupType = GuiUtils.isUnderGTKLookAndFeel() ? WEIGHT_HEAVY : PopupUtil.getPopupType(this); if (popupType >= 0) { PopupUtil.setPopupType(myDelegate, popupType); } return myDelegate.getPopup(owner, contents, x, y); } } public static void centerRelativeToOwner(Window window) { Window owner = window.getOwner(); Point p = owner.getLocation(); window.setLocation(p.x + owner.getWidth() / 2 - window.getWidth() / 2, p.y + owner.getHeight() / 2 - window.getHeight() / 2); } }
Fix missing popupmenu separator under gtk theme.
src/main/java/bdsup2sub/gui/support/GuiUtils.java
Fix missing popupmenu separator under gtk theme.
Java
apache-2.0
77e5972005f7ce7d6888e4ec379db9a75b5f4f5c
0
brettwooldridge/HikariCP,nitincchauhan/HikariCP,polpot78/HikariCP,ams2990/HikariCP,udayshnk/HikariCP,brettwooldridge/HikariCP
/* * Copyright (C) 2013, 2014 Brett Wooldridge * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zaxxer.hikari; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import com.zaxxer.hikari.metrics.MetricsTrackerFactory; import com.zaxxer.hikari.util.PropertyElf; import static com.zaxxer.hikari.util.UtilityElf.getNullIfEmpty; public class HikariConfig implements HikariConfigMXBean { private static final Logger LOGGER = LoggerFactory.getLogger(HikariConfig.class); private static final long CONNECTION_TIMEOUT = TimeUnit.SECONDS.toMillis(30); private static final long VALIDATION_TIMEOUT = TimeUnit.SECONDS.toMillis(5); private static final long IDLE_TIMEOUT = TimeUnit.MINUTES.toMillis(10); private static final long MAX_LIFETIME = TimeUnit.MINUTES.toMillis(30); private static final AtomicInteger POOL_NUMBER; private static boolean unitTest; // Properties changeable at runtime through the MBean // private volatile long connectionTimeout; private volatile long validationTimeout; private volatile long idleTimeout; private volatile long leakDetectionThreshold; private volatile long maxLifetime; private volatile int maxPoolSize; private volatile int minIdle; // Properties NOT changeable at runtime // private String catalog; private String connectionInitSql; private String connectionTestQuery; private String dataSourceClassName; private String dataSourceJndiName; private String driverClassName; private String jdbcUrl; private String password; private String poolName; private String transactionIsolationName; private String username; private boolean isAutoCommit; private boolean isReadOnly; private boolean isInitializationFailFast; private boolean isIsolateInternalQueries; private boolean isRegisterMbeans; private boolean isAllowPoolSuspension; private DataSource dataSource; private Properties dataSourceProperties; private ThreadFactory threadFactory; private ScheduledThreadPoolExecutor scheduledExecutor; private MetricsTrackerFactory metricsTrackerFactory; private Object metricRegistry; private Object healthCheckRegistry; private Properties healthCheckProperties; static { // POOL_NUMBER is global to the VM to avoid overlapping pool numbers in classloader scoped environments final Properties sysProps = System.getProperties(); AtomicInteger poolNumber = (AtomicInteger) sysProps.get("com.zaxxer.hikari.pool_number"); if (poolNumber == null) { POOL_NUMBER = new AtomicInteger(); sysProps.put("com.zaxxer.hikari.pool_number", POOL_NUMBER); } else { POOL_NUMBER = poolNumber; } } /** * Default constructor */ public HikariConfig() { dataSourceProperties = new Properties(); healthCheckProperties = new Properties(); connectionTimeout = CONNECTION_TIMEOUT; validationTimeout = VALIDATION_TIMEOUT; idleTimeout = IDLE_TIMEOUT; isAutoCommit = true; isInitializationFailFast = true; minIdle = -1; maxPoolSize = 10; maxLifetime = MAX_LIFETIME; String systemProp = System.getProperty("hikaricp.configurationFile"); if ( systemProp != null) { loadProperties(systemProp); } } /** * Construct a HikariConfig from the specified properties object. * * @param properties the name of the property file */ public HikariConfig(Properties properties) { this(); PropertyElf.setTargetFromProperties(this, properties); } /** * Construct a HikariConfig from the specified property file name. <code>propertyFileName</code> * will first be treated as a path in the file-system, and if that fails the * Class.getResourceAsStream(propertyFileName) will be tried. * * @param propertyFileName the name of the property file */ public HikariConfig(String propertyFileName) { this(); loadProperties(propertyFileName); } /** * Get the default catalog name to be set on connections. * * @return the default catalog name */ public String getCatalog() { return catalog; } /** * Set the default catalog name to be set on connections. * * @param catalog the catalog name, or null */ public void setCatalog(String catalog) { this.catalog = catalog; } /** * Get the SQL query to be executed to test the validity of connections. * * @return the SQL query string, or null */ public String getConnectionTestQuery() { return connectionTestQuery; } /** * Set the SQL query to be executed to test the validity of connections. Using * the JDBC4 <code>Connection.isValid()</code> method to test connection validity can * be more efficient on some databases and is recommended. See * {@link HikariConfig#setJdbc4ConnectionTest(boolean)}. * * @param connectionTestQuery a SQL query string */ public void setConnectionTestQuery(String connectionTestQuery) { this.connectionTestQuery = connectionTestQuery; } /** * Get the SQL string that will be executed on all new connections when they are * created, before they are added to the pool. * * @return the SQL to execute on new connections, or null */ public String getConnectionInitSql() { return connectionInitSql; } /** * Set the SQL string that will be executed on all new connections when they are * created, before they are added to the pool. If this query fails, it will be * treated as a failed connection attempt. * * @param connectionInitSql the SQL to execute on new connections */ public void setConnectionInitSql(String connectionInitSql) { this.connectionInitSql = connectionInitSql; } /** {@inheritDoc} */ @Override public long getConnectionTimeout() { return connectionTimeout; } /** {@inheritDoc} */ @Override public void setConnectionTimeout(long connectionTimeoutMs) { if (connectionTimeoutMs == 0) { this.connectionTimeout = Integer.MAX_VALUE; } else if (connectionTimeoutMs < 1000) { throw new IllegalArgumentException("connectionTimeout cannot be less than 1000ms"); } else { this.connectionTimeout = connectionTimeoutMs; } if (validationTimeout > connectionTimeoutMs) { this.validationTimeout = connectionTimeoutMs; } } /** {@inheritDoc} */ @Override public long getValidationTimeout() { return validationTimeout; } /** {@inheritDoc} */ @Override public void setValidationTimeout(long validationTimeoutMs) { if (validationTimeoutMs < 1000) { throw new IllegalArgumentException("validationTimeout cannot be less than 1000ms"); } else { this.validationTimeout = validationTimeoutMs; } if (validationTimeout > connectionTimeout) { this.validationTimeout = connectionTimeout; } } /** * Get the {@link DataSource} that has been explicitly specified to be wrapped by the * pool. * * @return the {@link DataSource} instance, or null */ public DataSource getDataSource() { return dataSource; } /** * Set a {@link DataSource} for the pool to explicitly wrap. This setter is not * available through property file based initialization. * * @param dataSource a specific {@link DataSource} to be wrapped by the pool */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public String getDataSourceClassName() { return dataSourceClassName; } public void setDataSourceClassName(String className) { this.dataSourceClassName = className; } public void addDataSourceProperty(String propertyName, Object value) { dataSourceProperties.put(propertyName, value); } public String getDataSourceJNDI() { return this.dataSourceJndiName; } public void setDataSourceJNDI(String jndiDataSource) { this.dataSourceJndiName = jndiDataSource; } public Properties getDataSourceProperties() { return dataSourceProperties; } public void setDataSourceProperties(Properties dsProperties) { dataSourceProperties.putAll(dsProperties); } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { try { Class<?> driverClass = this.getClass().getClassLoader().loadClass(driverClassName); driverClass.newInstance(); this.driverClassName = driverClassName; } catch (Exception e) { throw new RuntimeException("Could not load class of driverClassName " + driverClassName, e); } } /** {@inheritDoc} */ @Override public long getIdleTimeout() { return idleTimeout; } /** {@inheritDoc} */ @Override public void setIdleTimeout(long idleTimeoutMs) { if (idleTimeoutMs < 0) { throw new IllegalArgumentException("idleTimeout cannot be negative"); } this.idleTimeout = idleTimeoutMs; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } /** * Get the default auto-commit behavior of connections in the pool. * * @return the default auto-commit behavior of connections */ public boolean isAutoCommit() { return isAutoCommit; } /** * Set the default auto-commit behavior of connections in the pool. * * @param isAutoCommit the desired auto-commit default for connections */ public void setAutoCommit(boolean isAutoCommit) { this.isAutoCommit = isAutoCommit; } /** * Get the pool suspension behavior (allowed or disallowed). * * @return the pool suspension behavior */ public boolean isAllowPoolSuspension() { return isAllowPoolSuspension; } /** * Set whether or not pool suspension is allowed. There is a performance * impact when pool suspension is enabled. Unless you need it (for a * redundancy system for example) do not enable it. * * @param isAllowPoolSuspension the desired pool suspension allowance */ public void setAllowPoolSuspension(boolean isAllowPoolSuspension) { this.isAllowPoolSuspension = isAllowPoolSuspension; } /** * Get whether or not the construction of the pool should throw an exception * if the minimum number of connections cannot be created. * * @return whether or not initialization should fail on error immediately */ public boolean isInitializationFailFast() { return isInitializationFailFast; } /** * Set whether or not the construction of the pool should throw an exception * if the minimum number of connections cannot be created. * * @param failFast true if the pool should fail if the minimum connections cannot be created */ public void setInitializationFailFast(boolean failFast) { isInitializationFailFast = failFast; } public boolean isIsolateInternalQueries() { return isIsolateInternalQueries; } public void setIsolateInternalQueries(boolean isolate) { this.isIsolateInternalQueries = isolate; } @Deprecated public boolean isJdbc4ConnectionTest() { return false; } @Deprecated public void setJdbc4ConnectionTest(boolean useIsValid) { LOGGER.warn("The jdbcConnectionTest property is now deprecated, see the documentation for connectionTestQuery"); } public MetricsTrackerFactory getMetricsTrackerFactory() { return metricsTrackerFactory; } public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory) { if (metricRegistry != null) { throw new IllegalStateException("cannot use setMetricsTrackerFactory() and setMetricRegistry() together"); } this.metricsTrackerFactory = metricsTrackerFactory; } /** * Get the Codahale MetricRegistry, could be null. * * @return the codahale MetricRegistry instance */ public Object getMetricRegistry() { return metricRegistry; } /** * Set a Codahale MetricRegistry to use for HikariCP. * * @param metricRegistry the Codahale MetricRegistry to set */ public void setMetricRegistry(Object metricRegistry) { if (metricsTrackerFactory != null) { throw new IllegalStateException("cannot use setMetricRegistry() and setMetricsTrackerFactory() together"); } if (metricRegistry != null) { if (metricRegistry instanceof String) { try { InitialContext initCtx = new InitialContext(); metricRegistry = (MetricRegistry) initCtx.lookup((String) metricRegistry); } catch (NamingException e) { throw new IllegalArgumentException(e); } } if (!(metricRegistry instanceof MetricRegistry)) { throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.MetricRegistry"); } } this.metricRegistry = metricRegistry; } /** * Get the Codahale HealthCheckRegistry, could be null. * * @return the Codahale HealthCheckRegistry instance */ public Object getHealthCheckRegistry() { return healthCheckRegistry; } /** * Set a Codahale HealthCheckRegistry to use for HikariCP. * * @param healthCheckRegistry the Codahale HealthCheckRegistry to set */ public void setHealthCheckRegistry(Object healthCheckRegistry) { if (healthCheckRegistry != null) { if (healthCheckRegistry instanceof String) { try { InitialContext initCtx = new InitialContext(); healthCheckRegistry = (HealthCheckRegistry) initCtx.lookup((String) healthCheckRegistry); } catch (NamingException e) { throw new IllegalArgumentException(e); } } if (!(healthCheckRegistry instanceof HealthCheckRegistry)) { throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.health.HealthCheckRegistry"); } } this.healthCheckRegistry = healthCheckRegistry; } public Properties getHealthCheckProperties() { return healthCheckProperties; } public void setHealthCheckProperties(Properties healthCheckProperties) { this.healthCheckProperties.putAll(healthCheckProperties); } public void addHealthCheckProperty(String key, String value) { healthCheckProperties.setProperty(key, value); } public boolean isReadOnly() { return isReadOnly; } public void setReadOnly(boolean readOnly) { this.isReadOnly = readOnly; } public boolean isRegisterMbeans() { return isRegisterMbeans; } public void setRegisterMbeans(boolean register) { this.isRegisterMbeans = register; } /** {@inheritDoc} */ @Override public long getLeakDetectionThreshold() { return leakDetectionThreshold; } /** {@inheritDoc} */ @Override public void setLeakDetectionThreshold(long leakDetectionThresholdMs) { this.leakDetectionThreshold = leakDetectionThresholdMs; } /** {@inheritDoc} */ @Override public long getMaxLifetime() { return maxLifetime; } /** {@inheritDoc} */ @Override public void setMaxLifetime(long maxLifetimeMs) { this.maxLifetime = maxLifetimeMs; } /** {@inheritDoc} */ @Override public int getMaximumPoolSize() { return maxPoolSize; } /** {@inheritDoc} */ @Override public void setMaximumPoolSize(int maxPoolSize) { if (maxPoolSize < 1) { throw new IllegalArgumentException("maxPoolSize cannot be less than 1"); } this.maxPoolSize = maxPoolSize; } /** {@inheritDoc} */ @Override public int getMinimumIdle() { return minIdle; } /** {@inheritDoc} */ @Override public void setMinimumIdle(int minIdle) { if (minIdle < 0) { throw new IllegalArgumentException("minimumIdle cannot be negative"); } this.minIdle = minIdle; } /** * Get the default password to use for DataSource.getConnection(username, password) calls. * @return the password */ public String getPassword() { return password; } /** * Set the default password to use for DataSource.getConnection(username, password) calls. * @param password the password */ public void setPassword(String password) { this.password = password; } /** {@inheritDoc} */ @Override public String getPoolName() { return poolName; } /** * Set the name of the connection pool. This is primarily used for the MBean * to uniquely identify the pool configuration. * * @param poolName the name of the connection pool to use */ public void setPoolName(String poolName) { this.poolName = poolName; } /** * Get the ScheduledExecutorService used for housekeeping. * * @return the executor */ public ScheduledThreadPoolExecutor getScheduledExecutorService() { return scheduledExecutor; } /** * Set the ScheduledExecutorService used for housekeeping. * * @param executor the ScheduledExecutorService */ public void setScheduledExecutorService(ScheduledThreadPoolExecutor executor) { this.scheduledExecutor = executor; } public String getTransactionIsolation() { return transactionIsolationName; } /** * Set the default transaction isolation level. The specified value is the * constant name from the <code>Connection</code> class, eg. * <code>TRANSACTION_REPEATABLE_READ</code>. * * @param isolationLevel the name of the isolation level */ public void setTransactionIsolation(String isolationLevel) { this.transactionIsolationName = isolationLevel; } /** * Get the default username used for DataSource.getConnection(username, password) calls. * * @return the username */ public String getUsername() { return username; } /** * Set the default username used for DataSource.getConnection(username, password) calls. * * @param username the username */ public void setUsername(String username) { this.username = username; } /** * Get the thread factory used to create threads. * * @return the thread factory (may be null, in which case the default thread factory is used) */ public ThreadFactory getThreadFactory() { return threadFactory; } /** * Set the thread factory to be used to create threads. * * @param threadFactory the thread factory (setting to null causes the default thread factory to be used) */ public void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; } public void validate() { validateNumerics(); // treat empty property as null catalog = getNullIfEmpty(catalog); connectionInitSql = getNullIfEmpty(connectionInitSql); connectionTestQuery = getNullIfEmpty(connectionTestQuery); transactionIsolationName = getNullIfEmpty(transactionIsolationName); dataSourceClassName = getNullIfEmpty(dataSourceClassName); dataSourceJndiName = getNullIfEmpty(dataSourceJndiName); driverClassName = getNullIfEmpty(driverClassName); jdbcUrl = getNullIfEmpty(jdbcUrl); if (poolName == null) { poolName = "HikariPool-" + POOL_NUMBER.getAndIncrement(); } if (poolName.contains(":") && isRegisterMbeans) { throw new IllegalArgumentException("poolName cannot contain ':' when used with JMX"); } // Check Data Source Options if (dataSource != null) { if (dataSourceClassName != null) { LOGGER.warn("using dataSource and ignoring dataSourceClassName"); } } else if (dataSourceClassName != null) { if (driverClassName != null) { LOGGER.error("cannot use driverClassName and dataSourceClassName together"); throw new IllegalArgumentException("cannot use driverClassName and dataSourceClassName together"); } else if (jdbcUrl != null) { LOGGER.warn("using dataSourceClassName and ignoring jdbcUrl"); } } else if (jdbcUrl != null) { } else if (driverClassName != null) { LOGGER.error("jdbcUrl is required with driverClassName"); throw new IllegalArgumentException("jdbcUrl is required with driverClassName"); } else { LOGGER.error("{} - dataSource or dataSourceClassName or jdbcUrl is required.", poolName); throw new IllegalArgumentException("dataSource or dataSourceClassName or jdbcUrl is required."); } if (isIsolateInternalQueries) { // set it false if not required isIsolateInternalQueries = connectionInitSql != null || connectionTestQuery != null; } if (LOGGER.isDebugEnabled() || unitTest) { logConfiguration(); } } private void validateNumerics() { if (maxLifetime < 0) { LOGGER.error("maxLifetime cannot be negative."); throw new IllegalArgumentException("maxLifetime cannot be negative."); } else if (maxLifetime > 0 && maxLifetime < TimeUnit.SECONDS.toMillis(30)) { LOGGER.warn("maxLifetime is less than 30000ms, setting to default {}ms.", MAX_LIFETIME); maxLifetime = MAX_LIFETIME; } if (idleTimeout != 0 && idleTimeout < TimeUnit.SECONDS.toMillis(10)) { LOGGER.warn("idleTimeout is less than 10000ms, setting to default {}ms.", IDLE_TIMEOUT); idleTimeout = IDLE_TIMEOUT; } if (idleTimeout + TimeUnit.SECONDS.toMillis(1) > maxLifetime && maxLifetime > 0) { LOGGER.warn("idleTimeout is close to or greater than maxLifetime, disabling it."); maxLifetime = idleTimeout; idleTimeout = 0; } if (maxLifetime == 0 && idleTimeout == 0) { LOGGER.warn("setting idleTimeout to {}ms.", IDLE_TIMEOUT); idleTimeout = IDLE_TIMEOUT; } if (leakDetectionThreshold != 0 && leakDetectionThreshold < TimeUnit.SECONDS.toMillis(2) && !unitTest) { LOGGER.warn("leakDetectionThreshold is less than 2000ms, setting to minimum 2000ms."); leakDetectionThreshold = 2000L; } if (connectionTimeout != Integer.MAX_VALUE) { if (validationTimeout > connectionTimeout) { LOGGER.warn("validationTimeout should be less than connectionTimeout, setting validationTimeout to connectionTimeout"); validationTimeout = connectionTimeout; } if (maxLifetime > 0 && connectionTimeout > maxLifetime) { LOGGER.warn("connectionTimeout should be less than maxLifetime, setting maxLifetime to connectionTimeout"); maxLifetime = connectionTimeout; } } if (minIdle < 0) { minIdle = maxPoolSize; } else if (minIdle > maxPoolSize) { LOGGER.warn("minIdle should be less than maxPoolSize, setting maxPoolSize to minIdle"); maxPoolSize = minIdle; } } private void logConfiguration() { LOGGER.debug("{} - configuration:", poolName); final Set<String> propertyNames = new TreeSet<>(PropertyElf.getPropertyNames(HikariConfig.class)); for (String prop : propertyNames) { try { Object value = PropertyElf.getProperty(prop, this); if ("dataSourceProperties".equals(prop)) { Properties dsProps = PropertyElf.copyProperties(dataSourceProperties); dsProps.setProperty("password", "<masked>"); value = dsProps; } if (prop.contains("password")) { value = "<masked>"; } else if (value instanceof String) { value = "\"" + value + "\""; // quote to see lead/trailing spaces is any } LOGGER.debug((prop + "................................................").substring(0, 32) + value); } catch (Exception e) { continue; } } } protected void loadProperties(String propertyFileName) { final File propFile = new File(propertyFileName); try (final InputStream is = propFile.isFile() ? new FileInputStream(propFile) : this.getClass().getResourceAsStream(propertyFileName)) { if (is != null) { Properties props = new Properties(); props.load(is); PropertyElf.setTargetFromProperties(this, props); } else { throw new IllegalArgumentException("Property file " + propertyFileName + " was not found."); } } catch (IOException io) { throw new RuntimeException("Error loading properties file", io); } } public void copyState(HikariConfig other) { for (Field field : HikariConfig.class.getDeclaredFields()) { if (!Modifier.isFinal(field.getModifiers())) { field.setAccessible(true); try { field.set(other, field.get(this)); } catch (Exception e) { throw new RuntimeException("Exception copying HikariConfig state: " + e.getMessage(), e); } } } } }
src/main/java/com/zaxxer/hikari/HikariConfig.java
/* * Copyright (C) 2013, 2014 Brett Wooldridge * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zaxxer.hikari; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import com.zaxxer.hikari.metrics.MetricsTrackerFactory; import com.zaxxer.hikari.util.PropertyElf; import static com.zaxxer.hikari.util.UtilityElf.getNullIfEmpty; public class HikariConfig implements HikariConfigMXBean { private static final Logger LOGGER = LoggerFactory.getLogger(HikariConfig.class); private static final long CONNECTION_TIMEOUT = TimeUnit.SECONDS.toMillis(30); private static final long VALIDATION_TIMEOUT = TimeUnit.SECONDS.toMillis(5); private static final long IDLE_TIMEOUT = TimeUnit.MINUTES.toMillis(10); private static final long MAX_LIFETIME = TimeUnit.MINUTES.toMillis(30); private static final AtomicInteger POOL_NUMBER; private static boolean unitTest; // Properties changeable at runtime through the MBean // private volatile long connectionTimeout; private volatile long validationTimeout; private volatile long idleTimeout; private volatile long leakDetectionThreshold; private volatile long maxLifetime; private volatile int maxPoolSize; private volatile int minIdle; // Properties NOT changeable at runtime // private String catalog; private String connectionInitSql; private String connectionTestQuery; private String dataSourceClassName; private String dataSourceJndiName; private String driverClassName; private String jdbcUrl; private String password; private String poolName; private String transactionIsolationName; private String username; private boolean isAutoCommit; private boolean isReadOnly; private boolean isInitializationFailFast; private boolean isIsolateInternalQueries; private boolean isRegisterMbeans; private boolean isAllowPoolSuspension; private DataSource dataSource; private Properties dataSourceProperties; private ThreadFactory threadFactory; private ScheduledThreadPoolExecutor scheduledExecutor; private MetricsTrackerFactory metricsTrackerFactory; private Object metricRegistry; private Object healthCheckRegistry; private Properties healthCheckProperties; static { // POOL_NUMBER is global to the VM to avoid overlapping pool numbers in classloader scoped environments final Properties sysProps = System.getProperties(); sysProps.putIfAbsent("com.zaxxer.hikari.pool_number", new AtomicInteger()); POOL_NUMBER = (AtomicInteger) sysProps.get("com.zaxxer.hikari.pool_number"); } /** * Default constructor */ public HikariConfig() { dataSourceProperties = new Properties(); healthCheckProperties = new Properties(); connectionTimeout = CONNECTION_TIMEOUT; validationTimeout = VALIDATION_TIMEOUT; idleTimeout = IDLE_TIMEOUT; isAutoCommit = true; isInitializationFailFast = true; minIdle = -1; maxPoolSize = 10; maxLifetime = MAX_LIFETIME; String systemProp = System.getProperty("hikaricp.configurationFile"); if ( systemProp != null) { loadProperties(systemProp); } } /** * Construct a HikariConfig from the specified properties object. * * @param properties the name of the property file */ public HikariConfig(Properties properties) { this(); PropertyElf.setTargetFromProperties(this, properties); } /** * Construct a HikariConfig from the specified property file name. <code>propertyFileName</code> * will first be treated as a path in the file-system, and if that fails the * Class.getResourceAsStream(propertyFileName) will be tried. * * @param propertyFileName the name of the property file */ public HikariConfig(String propertyFileName) { this(); loadProperties(propertyFileName); } /** * Get the default catalog name to be set on connections. * * @return the default catalog name */ public String getCatalog() { return catalog; } /** * Set the default catalog name to be set on connections. * * @param catalog the catalog name, or null */ public void setCatalog(String catalog) { this.catalog = catalog; } /** * Get the SQL query to be executed to test the validity of connections. * * @return the SQL query string, or null */ public String getConnectionTestQuery() { return connectionTestQuery; } /** * Set the SQL query to be executed to test the validity of connections. Using * the JDBC4 <code>Connection.isValid()</code> method to test connection validity can * be more efficient on some databases and is recommended. See * {@link HikariConfig#setJdbc4ConnectionTest(boolean)}. * * @param connectionTestQuery a SQL query string */ public void setConnectionTestQuery(String connectionTestQuery) { this.connectionTestQuery = connectionTestQuery; } /** * Get the SQL string that will be executed on all new connections when they are * created, before they are added to the pool. * * @return the SQL to execute on new connections, or null */ public String getConnectionInitSql() { return connectionInitSql; } /** * Set the SQL string that will be executed on all new connections when they are * created, before they are added to the pool. If this query fails, it will be * treated as a failed connection attempt. * * @param connectionInitSql the SQL to execute on new connections */ public void setConnectionInitSql(String connectionInitSql) { this.connectionInitSql = connectionInitSql; } /** {@inheritDoc} */ @Override public long getConnectionTimeout() { return connectionTimeout; } /** {@inheritDoc} */ @Override public void setConnectionTimeout(long connectionTimeoutMs) { if (connectionTimeoutMs == 0) { this.connectionTimeout = Integer.MAX_VALUE; } else if (connectionTimeoutMs < 1000) { throw new IllegalArgumentException("connectionTimeout cannot be less than 1000ms"); } else { this.connectionTimeout = connectionTimeoutMs; } if (validationTimeout > connectionTimeoutMs) { this.validationTimeout = connectionTimeoutMs; } } /** {@inheritDoc} */ @Override public long getValidationTimeout() { return validationTimeout; } /** {@inheritDoc} */ @Override public void setValidationTimeout(long validationTimeoutMs) { if (validationTimeoutMs < 1000) { throw new IllegalArgumentException("validationTimeout cannot be less than 1000ms"); } else { this.validationTimeout = validationTimeoutMs; } if (validationTimeout > connectionTimeout) { this.validationTimeout = connectionTimeout; } } /** * Get the {@link DataSource} that has been explicitly specified to be wrapped by the * pool. * * @return the {@link DataSource} instance, or null */ public DataSource getDataSource() { return dataSource; } /** * Set a {@link DataSource} for the pool to explicitly wrap. This setter is not * available through property file based initialization. * * @param dataSource a specific {@link DataSource} to be wrapped by the pool */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public String getDataSourceClassName() { return dataSourceClassName; } public void setDataSourceClassName(String className) { this.dataSourceClassName = className; } public void addDataSourceProperty(String propertyName, Object value) { dataSourceProperties.put(propertyName, value); } public String getDataSourceJNDI() { return this.dataSourceJndiName; } public void setDataSourceJNDI(String jndiDataSource) { this.dataSourceJndiName = jndiDataSource; } public Properties getDataSourceProperties() { return dataSourceProperties; } public void setDataSourceProperties(Properties dsProperties) { dataSourceProperties.putAll(dsProperties); } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { try { Class<?> driverClass = this.getClass().getClassLoader().loadClass(driverClassName); driverClass.newInstance(); this.driverClassName = driverClassName; } catch (Exception e) { throw new RuntimeException("Could not load class of driverClassName " + driverClassName, e); } } /** {@inheritDoc} */ @Override public long getIdleTimeout() { return idleTimeout; } /** {@inheritDoc} */ @Override public void setIdleTimeout(long idleTimeoutMs) { if (idleTimeoutMs < 0) { throw new IllegalArgumentException("idleTimeout cannot be negative"); } this.idleTimeout = idleTimeoutMs; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } /** * Get the default auto-commit behavior of connections in the pool. * * @return the default auto-commit behavior of connections */ public boolean isAutoCommit() { return isAutoCommit; } /** * Set the default auto-commit behavior of connections in the pool. * * @param isAutoCommit the desired auto-commit default for connections */ public void setAutoCommit(boolean isAutoCommit) { this.isAutoCommit = isAutoCommit; } /** * Get the pool suspension behavior (allowed or disallowed). * * @return the pool suspension behavior */ public boolean isAllowPoolSuspension() { return isAllowPoolSuspension; } /** * Set whether or not pool suspension is allowed. There is a performance * impact when pool suspension is enabled. Unless you need it (for a * redundancy system for example) do not enable it. * * @param isAllowPoolSuspension the desired pool suspension allowance */ public void setAllowPoolSuspension(boolean isAllowPoolSuspension) { this.isAllowPoolSuspension = isAllowPoolSuspension; } /** * Get whether or not the construction of the pool should throw an exception * if the minimum number of connections cannot be created. * * @return whether or not initialization should fail on error immediately */ public boolean isInitializationFailFast() { return isInitializationFailFast; } /** * Set whether or not the construction of the pool should throw an exception * if the minimum number of connections cannot be created. * * @param failFast true if the pool should fail if the minimum connections cannot be created */ public void setInitializationFailFast(boolean failFast) { isInitializationFailFast = failFast; } public boolean isIsolateInternalQueries() { return isIsolateInternalQueries; } public void setIsolateInternalQueries(boolean isolate) { this.isIsolateInternalQueries = isolate; } @Deprecated public boolean isJdbc4ConnectionTest() { return false; } @Deprecated public void setJdbc4ConnectionTest(boolean useIsValid) { LOGGER.warn("The jdbcConnectionTest property is now deprecated, see the documentation for connectionTestQuery"); } public MetricsTrackerFactory getMetricsTrackerFactory() { return metricsTrackerFactory; } public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory) { if (metricRegistry != null) { throw new IllegalStateException("cannot use setMetricsTrackerFactory() and setMetricRegistry() together"); } this.metricsTrackerFactory = metricsTrackerFactory; } /** * Get the Codahale MetricRegistry, could be null. * * @return the codahale MetricRegistry instance */ public Object getMetricRegistry() { return metricRegistry; } /** * Set a Codahale MetricRegistry to use for HikariCP. * * @param metricRegistry the Codahale MetricRegistry to set */ public void setMetricRegistry(Object metricRegistry) { if (metricsTrackerFactory != null) { throw new IllegalStateException("cannot use setMetricRegistry() and setMetricsTrackerFactory() together"); } if (metricRegistry != null) { if (metricRegistry instanceof String) { try { InitialContext initCtx = new InitialContext(); metricRegistry = (MetricRegistry) initCtx.lookup((String) metricRegistry); } catch (NamingException e) { throw new IllegalArgumentException(e); } } if (!(metricRegistry instanceof MetricRegistry)) { throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.MetricRegistry"); } } this.metricRegistry = metricRegistry; } /** * Get the Codahale HealthCheckRegistry, could be null. * * @return the Codahale HealthCheckRegistry instance */ public Object getHealthCheckRegistry() { return healthCheckRegistry; } /** * Set a Codahale HealthCheckRegistry to use for HikariCP. * * @param healthCheckRegistry the Codahale HealthCheckRegistry to set */ public void setHealthCheckRegistry(Object healthCheckRegistry) { if (healthCheckRegistry != null) { if (healthCheckRegistry instanceof String) { try { InitialContext initCtx = new InitialContext(); healthCheckRegistry = (HealthCheckRegistry) initCtx.lookup((String) healthCheckRegistry); } catch (NamingException e) { throw new IllegalArgumentException(e); } } if (!(healthCheckRegistry instanceof HealthCheckRegistry)) { throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.health.HealthCheckRegistry"); } } this.healthCheckRegistry = healthCheckRegistry; } public Properties getHealthCheckProperties() { return healthCheckProperties; } public void setHealthCheckProperties(Properties healthCheckProperties) { this.healthCheckProperties.putAll(healthCheckProperties); } public void addHealthCheckProperty(String key, String value) { healthCheckProperties.setProperty(key, value); } public boolean isReadOnly() { return isReadOnly; } public void setReadOnly(boolean readOnly) { this.isReadOnly = readOnly; } public boolean isRegisterMbeans() { return isRegisterMbeans; } public void setRegisterMbeans(boolean register) { this.isRegisterMbeans = register; } /** {@inheritDoc} */ @Override public long getLeakDetectionThreshold() { return leakDetectionThreshold; } /** {@inheritDoc} */ @Override public void setLeakDetectionThreshold(long leakDetectionThresholdMs) { this.leakDetectionThreshold = leakDetectionThresholdMs; } /** {@inheritDoc} */ @Override public long getMaxLifetime() { return maxLifetime; } /** {@inheritDoc} */ @Override public void setMaxLifetime(long maxLifetimeMs) { this.maxLifetime = maxLifetimeMs; } /** {@inheritDoc} */ @Override public int getMaximumPoolSize() { return maxPoolSize; } /** {@inheritDoc} */ @Override public void setMaximumPoolSize(int maxPoolSize) { if (maxPoolSize < 1) { throw new IllegalArgumentException("maxPoolSize cannot be less than 1"); } this.maxPoolSize = maxPoolSize; } /** {@inheritDoc} */ @Override public int getMinimumIdle() { return minIdle; } /** {@inheritDoc} */ @Override public void setMinimumIdle(int minIdle) { if (minIdle < 0) { throw new IllegalArgumentException("minimumIdle cannot be negative"); } this.minIdle = minIdle; } /** * Get the default password to use for DataSource.getConnection(username, password) calls. * @return the password */ public String getPassword() { return password; } /** * Set the default password to use for DataSource.getConnection(username, password) calls. * @param password the password */ public void setPassword(String password) { this.password = password; } /** {@inheritDoc} */ @Override public String getPoolName() { return poolName; } /** * Set the name of the connection pool. This is primarily used for the MBean * to uniquely identify the pool configuration. * * @param poolName the name of the connection pool to use */ public void setPoolName(String poolName) { this.poolName = poolName; } /** * Get the ScheduledExecutorService used for housekeeping. * * @return the executor */ public ScheduledThreadPoolExecutor getScheduledExecutorService() { return scheduledExecutor; } /** * Set the ScheduledExecutorService used for housekeeping. * * @param executor the ScheduledExecutorService */ public void setScheduledExecutorService(ScheduledThreadPoolExecutor executor) { this.scheduledExecutor = executor; } public String getTransactionIsolation() { return transactionIsolationName; } /** * Set the default transaction isolation level. The specified value is the * constant name from the <code>Connection</code> class, eg. * <code>TRANSACTION_REPEATABLE_READ</code>. * * @param isolationLevel the name of the isolation level */ public void setTransactionIsolation(String isolationLevel) { this.transactionIsolationName = isolationLevel; } /** * Get the default username used for DataSource.getConnection(username, password) calls. * * @return the username */ public String getUsername() { return username; } /** * Set the default username used for DataSource.getConnection(username, password) calls. * * @param username the username */ public void setUsername(String username) { this.username = username; } /** * Get the thread factory used to create threads. * * @return the thread factory (may be null, in which case the default thread factory is used) */ public ThreadFactory getThreadFactory() { return threadFactory; } /** * Set the thread factory to be used to create threads. * * @param threadFactory the thread factory (setting to null causes the default thread factory to be used) */ public void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; } public void validate() { validateNumerics(); // treat empty property as null catalog = getNullIfEmpty(catalog); connectionInitSql = getNullIfEmpty(connectionInitSql); connectionTestQuery = getNullIfEmpty(connectionTestQuery); transactionIsolationName = getNullIfEmpty(transactionIsolationName); dataSourceClassName = getNullIfEmpty(dataSourceClassName); dataSourceJndiName = getNullIfEmpty(dataSourceJndiName); driverClassName = getNullIfEmpty(driverClassName); jdbcUrl = getNullIfEmpty(jdbcUrl); if (poolName == null) { poolName = "HikariPool-" + POOL_NUMBER.getAndIncrement(); } if (poolName.contains(":") && isRegisterMbeans) { throw new IllegalArgumentException("poolName cannot contain ':' when used with JMX"); } // Check Data Source Options if (dataSource != null) { if (dataSourceClassName != null) { LOGGER.warn("using dataSource and ignoring dataSourceClassName"); } } else if (dataSourceClassName != null) { if (driverClassName != null) { LOGGER.error("cannot use driverClassName and dataSourceClassName together"); throw new IllegalArgumentException("cannot use driverClassName and dataSourceClassName together"); } else if (jdbcUrl != null) { LOGGER.warn("using dataSourceClassName and ignoring jdbcUrl"); } } else if (jdbcUrl != null) { } else if (driverClassName != null) { LOGGER.error("jdbcUrl is required with driverClassName"); throw new IllegalArgumentException("jdbcUrl is required with driverClassName"); } else { LOGGER.error("{} - dataSource or dataSourceClassName or jdbcUrl is required.", poolName); throw new IllegalArgumentException("dataSource or dataSourceClassName or jdbcUrl is required."); } if (isIsolateInternalQueries) { // set it false if not required isIsolateInternalQueries = connectionInitSql != null || connectionTestQuery != null; } if (LOGGER.isDebugEnabled() || unitTest) { logConfiguration(); } } private void validateNumerics() { if (maxLifetime < 0) { LOGGER.error("maxLifetime cannot be negative."); throw new IllegalArgumentException("maxLifetime cannot be negative."); } else if (maxLifetime > 0 && maxLifetime < TimeUnit.SECONDS.toMillis(30)) { LOGGER.warn("maxLifetime is less than 30000ms, setting to default {}ms.", MAX_LIFETIME); maxLifetime = MAX_LIFETIME; } if (idleTimeout != 0 && idleTimeout < TimeUnit.SECONDS.toMillis(10)) { LOGGER.warn("idleTimeout is less than 10000ms, setting to default {}ms.", IDLE_TIMEOUT); idleTimeout = IDLE_TIMEOUT; } if (idleTimeout + TimeUnit.SECONDS.toMillis(1) > maxLifetime && maxLifetime > 0) { LOGGER.warn("idleTimeout is close to or greater than maxLifetime, disabling it."); maxLifetime = idleTimeout; idleTimeout = 0; } if (maxLifetime == 0 && idleTimeout == 0) { LOGGER.warn("setting idleTimeout to {}ms.", IDLE_TIMEOUT); idleTimeout = IDLE_TIMEOUT; } if (leakDetectionThreshold != 0 && leakDetectionThreshold < TimeUnit.SECONDS.toMillis(2) && !unitTest) { LOGGER.warn("leakDetectionThreshold is less than 2000ms, setting to minimum 2000ms."); leakDetectionThreshold = 2000L; } if (connectionTimeout != Integer.MAX_VALUE) { if (validationTimeout > connectionTimeout) { LOGGER.warn("validationTimeout should be less than connectionTimeout, setting validationTimeout to connectionTimeout"); validationTimeout = connectionTimeout; } if (maxLifetime > 0 && connectionTimeout > maxLifetime) { LOGGER.warn("connectionTimeout should be less than maxLifetime, setting maxLifetime to connectionTimeout"); maxLifetime = connectionTimeout; } } if (minIdle < 0) { minIdle = maxPoolSize; } else if (minIdle > maxPoolSize) { LOGGER.warn("minIdle should be less than maxPoolSize, setting maxPoolSize to minIdle"); maxPoolSize = minIdle; } } private void logConfiguration() { LOGGER.debug("{} - configuration:", poolName); final Set<String> propertyNames = new TreeSet<>(PropertyElf.getPropertyNames(HikariConfig.class)); for (String prop : propertyNames) { try { Object value = PropertyElf.getProperty(prop, this); if ("dataSourceProperties".equals(prop)) { Properties dsProps = PropertyElf.copyProperties(dataSourceProperties); dsProps.setProperty("password", "<masked>"); value = dsProps; } if (prop.contains("password")) { value = "<masked>"; } else if (value instanceof String) { value = "\"" + value + "\""; // quote to see lead/trailing spaces is any } LOGGER.debug((prop + "................................................").substring(0, 32) + value); } catch (Exception e) { continue; } } } protected void loadProperties(String propertyFileName) { final File propFile = new File(propertyFileName); try (final InputStream is = propFile.isFile() ? new FileInputStream(propFile) : this.getClass().getResourceAsStream(propertyFileName)) { if (is != null) { Properties props = new Properties(); props.load(is); PropertyElf.setTargetFromProperties(this, props); } else { throw new IllegalArgumentException("Property file " + propertyFileName + " was not found."); } } catch (IOException io) { throw new RuntimeException("Error loading properties file", io); } } public void copyState(HikariConfig other) { for (Field field : HikariConfig.class.getDeclaredFields()) { if (!Modifier.isFinal(field.getModifiers())) { field.setAccessible(true); try { field.set(other, field.get(this)); } catch (Exception e) { throw new RuntimeException("Exception copying HikariConfig state: " + e.getMessage(), e); } } } } }
Fix for Java 7.
src/main/java/com/zaxxer/hikari/HikariConfig.java
Fix for Java 7.
Java
apache-2.0
fead20c3d8502f6d9cf0f88b9901932d2ec69be4
0
DataSketches/sketches-core
/* * Copyright 2018, Yahoo! Inc. Licensed under the terms of the * Apache License 2.0. See LICENSE file at the project root for terms. */ package com.yahoo.sketches; /** * Common static methods for quantiles sketches */ public class QuantilesHelper { /** * Convert the weights into totals of the weights preceding each item * @param array of weights * @return total weight */ public static long convertToPrecedingCummulative(final long[] array) { long subtotal = 0; for (int i = 0; i < array.length; i++) { final long newSubtotal = subtotal + array[i]; array[i] = subtotal; subtotal = newSubtotal; } return subtotal; } /** * Returns the zero-based index (position) of a value in the hypothetical sorted stream of * values of size n. * @param phi the fractional position where: 0 &le; &#966; &le; 1.0. * @param n the size of the stream * @return the index, a value between 0 and n-1. */ public static long posOfPhi(final double phi, final long n) { final long pos = (long) Math.floor(phi * n); return (pos == n) ? n - 1 : pos; } /** * This is written in terms of a plain array to facilitate testing. * @param arr the chunk containing the position * @param pos the position * @return the index of the chunk containing the position */ public static int chunkContainingPos(final long[] arr, final long pos) { final int nominalLength = arr.length - 1; /* remember, arr contains an "extra" position */ assert nominalLength > 0; final long n = arr[nominalLength]; assert 0 <= pos; assert pos < n; final int l = 0; final int r = nominalLength; // the following three asserts should probably be retained since they ensure // that the necessary invariants hold at the beginning of the search assert l < r; assert arr[l] <= pos; assert pos < arr[r]; return searchForChunkContainingPos(arr, pos, l, r); } // Let m_i denote the minimum position of the length=n "full" sorted sequence // that is represented in slot i of the length = n "chunked" sorted sequence. // // Note that m_i is the same thing as auxCumWtsArr_[i] // // Then the answer to a positional query 0 <= q < n is l, where 0 <= l < len, // A) m_l <= q // B) q < m_r // C) l+1 = r // // A) and B) provide the invariants for our binary search. // Observe that they are satisfied by the initial conditions: l = 0 and r = len. private static int searchForChunkContainingPos(final long[] arr, final long pos, final int l, final int r) { // the following three asserts can probably go away eventually, since it is fairly clear // that if these invariants hold at the beginning of the search, they will be maintained assert l < r; assert arr[l] <= pos; assert pos < arr[r]; if (l + 1 == r) { return l; } final int m = l + (r - l) / 2; if (arr[m] <= pos) { return searchForChunkContainingPos(arr, pos, m, r); } return searchForChunkContainingPos(arr, pos, l, m); } /** * Compute an array of evenly spaced normalized ranks from 0 to 1 inclusive. * A value of 1 will result in [0], 2 will result in [0, 1], * 3 will result in [0, .5, 1] and so on. * @param n number of ranks needed (must be greater than 0) * @return array of ranks */ public static double[] getEvenlySpacedRanks(final int n) { if (n <= 0) { throw new SketchesArgumentException("n must be > 0"); } final double[] fractions = new double[n]; fractions[0] = 0.0; for (int i = 1; i < n; i++) { fractions[i] = (double) i / (n - 1); } if (n > 1) { fractions[n - 1] = 1.0; } return fractions; } }
src/main/java/com/yahoo/sketches/QuantilesHelper.java
package com.yahoo.sketches; /** * Common static methods for quantiles sketches */ public class QuantilesHelper { /** * Convert the weights into totals of the weights preceding each item * @param array of weights * @return total weight */ public static long convertToPrecedingCummulative(final long[] array) { long subtotal = 0; for (int i = 0; i < array.length; i++) { final long newSubtotal = subtotal + array[i]; array[i] = subtotal; subtotal = newSubtotal; } return subtotal; } /** * Returns the zero-based index (position) of a value in the hypothetical sorted stream of * values of size n. * @param phi the fractional position where: 0 &le; &#966; &le; 1.0. * @param n the size of the stream * @return the index, a value between 0 and n-1. */ public static long posOfPhi(final double phi, final long n) { final long pos = (long) Math.floor(phi * n); return (pos == n) ? n - 1 : pos; } /** * This is written in terms of a plain array to facilitate testing. * @param arr the chunk containing the position * @param pos the position * @return the index of the chunk containing the position */ public static int chunkContainingPos(final long[] arr, final long pos) { final int nominalLength = arr.length - 1; /* remember, arr contains an "extra" position */ assert nominalLength > 0; final long n = arr[nominalLength]; assert 0 <= pos; assert pos < n; final int l = 0; final int r = nominalLength; // the following three asserts should probably be retained since they ensure // that the necessary invariants hold at the beginning of the search assert l < r; assert arr[l] <= pos; assert pos < arr[r]; return searchForChunkContainingPos(arr, pos, l, r); } // Let m_i denote the minimum position of the length=n "full" sorted sequence // that is represented in slot i of the length = n "chunked" sorted sequence. // // Note that m_i is the same thing as auxCumWtsArr_[i] // // Then the answer to a positional query 0 <= q < n is l, where 0 <= l < len, // A) m_l <= q // B) q < m_r // C) l+1 = r // // A) and B) provide the invariants for our binary search. // Observe that they are satisfied by the initial conditions: l = 0 and r = len. private static int searchForChunkContainingPos(final long[] arr, final long pos, final int l, final int r) { // the following three asserts can probably go away eventually, since it is fairly clear // that if these invariants hold at the beginning of the search, they will be maintained assert l < r; assert arr[l] <= pos; assert pos < arr[r]; if (l + 1 == r) { return l; } final int m = l + (r - l) / 2; if (arr[m] <= pos) { return searchForChunkContainingPos(arr, pos, m, r); } return searchForChunkContainingPos(arr, pos, l, m); } /** * Compute an array of evenly spaced normalized ranks from 0 to 1 inclusive. * A value of 1 will result in [0], 2 will result in [0, 1], * 3 will result in [0, .5, 1] and so on. * @param n number of ranks needed (must be greater than 0) * @return array of ranks */ public static double[] getEvenlySpacedRanks(final int n) { if (n <= 0) { throw new SketchesArgumentException("n must be > 0"); } final double[] fractions = new double[n]; fractions[0] = 0.0; for (int i = 1; i < n; i++) { fractions[i] = (double) i / (n - 1); } if (n > 1) { fractions[n - 1] = 1.0; } return fractions; } }
added missing license
src/main/java/com/yahoo/sketches/QuantilesHelper.java
added missing license
Java
apache-2.0
11101e2d8d8feda53735f096f42dbd8841d8a542
0
ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf
/* * $Log: XComSender.java,v $ * Revision 1.16 2011-12-08 09:12:09 europe\m168309 * fixed javadoc * * Revision 1.15 2011/11/30 13:52:04 Peter Leeuwenburgh <[email protected]> * adjusted/reversed "Upgraded from WebSphere v5.1 to WebSphere v6.1" * * Revision 1.1 2011/10/19 14:49:54 Peter Leeuwenburgh <[email protected]> * Upgraded from WebSphere v5.1 to WebSphere v6.1 * * Revision 1.13 2010/03/10 14:30:05 Peter Leeuwenburgh <[email protected]> * rolled back testtool adjustments (IbisDebuggerDummy) * * Revision 1.11 2005/12/19 17:18:55 Gerrit van Brakel <[email protected]> * corrected typos in javadoc * * Revision 1.10 2005/12/19 17:14:42 Gerrit van Brakel <[email protected]> * updated javadoc * * Revision 1.9 2005/12/19 16:59:39 Gerrit van Brakel <[email protected]> * corrected typo: had only single r in carriageflag * * Revision 1.8 2005/12/19 16:40:15 Gerrit van Brakel <[email protected]> * added authentication using authentication-alias * * Revision 1.7 2005/10/31 14:42:40 Gerrit van Brakel <[email protected]> * updated javadoc * * Revision 1.6 2005/10/28 12:31:05 John Dekker <[email protected]> * Corrected bug with password added twice to command * * Revision 1.5 2005/10/27 13:29:26 John Dekker <[email protected]> * Add optional configFile property * * Revision 1.4 2005/10/27 07:58:57 John Dekker <[email protected]> * Host is not longer a required property, since it could be set in a config file * * Revision 1.3 2005/10/24 09:59:24 John Dekker <[email protected]> * Add support for pattern parameters, and include them into several listeners, * senders and pipes that are file related * * Revision 1.2 2005/10/11 13:04:50 John Dekker <[email protected]> * *** empty log message *** * * Revision 1.1 2005/10/11 13:04:24 John Dekker <[email protected]> * Support for sending files via the XComSender * */ package nl.nn.adapterframework.xcom; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ParameterException; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.core.SenderWithParametersBase; import nl.nn.adapterframework.core.TimeOutException; import nl.nn.adapterframework.parameters.ParameterResolutionContext; import nl.nn.adapterframework.util.CredentialFactory; import nl.nn.adapterframework.util.FileUtils; import org.apache.commons.lang.StringUtils; /** * XCom client voor het versturen van files via XCom. * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>classname</td><td>nl.nn.ibis4fundation.XComSender</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the sender</td><td>&nbsp;</td></tr> * <tr><td>{@link #setWorkingDirName(String) workingDirName}</td><td>directory in which to run the xcomtcp command</td><td>&nbsp;</td></tr> * <tr><td>{@link #setXcomtcp(String) xcomtcp}</td><td>Path to xcomtcp command</td><td>&nbsp;</td></tr> * <tr><td>{@link #setFileOption(String) fileOption}</td><td>One of CREATE, APPEND or REPLACE</td><td>&nbsp;</td></tr> * <tr><td>{@link #setQueue(Boolean) queue}</td><td>Set queue off or on</td><td>&nbsp;</td></tr> * <tr><td>{@link #setTruncation(Boolean) truncation}</td><td>Set truncation off or on</td><td>&nbsp;</td></tr> * <tr><td>{@link #setTracelevel(Integer) tracelevel}</td><td>Set between 0 (no trace) and 10</td><td>&nbsp;</td></tr> * <tr><td>{@link #setCodeflag(String) codeflag}</td><td>Characterset conversion, one of ASCII or EBCDIC</td><td>&nbsp;</td></tr> * <tr><td>{@link #setCarriageflag(String) carriageflag}</td><td>One of YES, NO, VRL, VRL2, MPACK or XPACK</td><td>&nbsp;</td></tr> * <tr><td>{@link #setCompress(String) compress}</td><td>One of YES, NO, RLE, COMPACT, LZLARGE, LZMEDIUM or LZSMALL</td><td>&nbsp;</td></tr> * <tr><td>{@link #setLogfile(String) logfile}</td><td>Name of logfile for xcomtcp to be used</td><td>&nbsp;</td></tr> * <tr><td>{@link #setRemoteSystem(String) remoteSystem}</td><td>Hostname or tcpip adres of remote host</td><td>&nbsp;</td></tr> * <tr><td>{@link #setPort(String) port}</td><td>Port of remote host</td><td>&nbsp;</td></tr> * <tr><td>{@link #setRemoteDirectory(String) remoteDirectory}</td><td>Remote directory is prefixed witht the remote file</td><td>&nbsp;</td></tr> * <tr><td>{@link #setRemoteFilePattern(String) remoteFilePattern}</td><td>Remote file to create. If empty, the name is equal to the local file</td><td>&nbsp;</td></tr> * <tr><td>{@link #setAuthAlias(String) authAlias}</td><td>name of the alias to obtain credentials to authenticatie on remote server</td><td>&nbsp;</td></tr> * <tr><td>{@link #setUserid(String) userid}</td><td>Loginname of user on remote system</td><td>&nbsp;</td></tr> * <tr><td>{@link #setPassword(String) password}</td><td>Password of user on remote system</td><td>&nbsp;</td></tr> * </table> * </p> * * @author John Dekker */ public class XComSender extends SenderWithParametersBase { public static final String version = "$RCSfile: XComSender.java,v $ $Revision: 1.16 $ $Date: 2011-12-08 09:12:09 $"; private File workingDir; private String name; private String fileOption = null; private Boolean queue = null; private Boolean truncation = null; private Integer tracelevel = null; private String logfile = null; private String codeflag = null; private String carriageflag = null; private String port = null; private String authAlias = null; private String userid = null; private String password = null; private String compress = null; private String remoteSystem = null; private String remoteDirectory = null; private String remoteFilePattern = null; private String configFile = null; private String workingDirName = "."; private String xcomtcp = "xcomtcp"; /* (non-Javadoc) * @see nl.nn.adapterframework.core.ISender#configure() */ public void configure() throws ConfigurationException { if (StringUtils.isNotEmpty(fileOption) && ! "CREATE".equals(fileOption) && ! "APPEND".equals(fileOption) && ! "REPLACE".equals(fileOption) ) { throw new ConfigurationException("Attribute [fileOption] has incorrect value " + fileOption + ", should be one of CREATE | APPEND or REPLACE"); } if (! StringUtils.isEmpty(compress) && ! "YES".equals(compress) && ! "COMPACT".equals(compress) && ! "LZLARGE".equals(compress) && ! "LZMEDIUM".equals(compress) && ! "LZSMALL".equals(compress) && ! "RLE".equals(compress) && ! "NO".equals(compress) ) { throw new ConfigurationException("Attribute [compress] has incorrect value " + compress + ", should be one of YES | NO | RLE | COMPACT | LZLARGE | LZMEDIUM | LZSMALL"); } if (! StringUtils.isEmpty(codeflag) && ! "EBCDIC".equals(codeflag) && ! "ASCII".equals(codeflag) ) { throw new ConfigurationException("Attribute [codeflag] has incorrect value " + fileOption + ", should be ASCII or EBCDIC"); } if (! StringUtils.isEmpty(carriageflag) && ! "YES".equals(carriageflag) && ! "VLR".equals(carriageflag) && ! "VLR2".equals(carriageflag) && ! "MPACK".equals(carriageflag) && ! "XPACK".equals(carriageflag) && ! "NO".equals(carriageflag) ) { throw new ConfigurationException("Attribute [cariageflag] has incorrect value " + compress + ", should be one of YES | NO | VRL | VRL2 | MPACK | XPACK"); } if (! StringUtils.isEmpty(port)) { try { Integer.parseInt(port); } catch(NumberFormatException e) { throw new ConfigurationException("Attribute [port] is not a number"); } } if (tracelevel != null && (tracelevel.intValue() < 0 || tracelevel.intValue() > 10)) { throw new ConfigurationException("Attribute [tracelevel] should be between 0 (no trace) and 10, not " + tracelevel.intValue()); } if (StringUtils.isEmpty(workingDirName)) { throw new ConfigurationException("Attribute [workingDirName] is not set"); } else { workingDir = new File(workingDirName); if (! workingDir.isDirectory()) { throw new ConfigurationException("Working directory [workingDirName=" + workingDirName + "] is not a directory"); } } } /* (non-Javadoc) * @see nl.nn.adapterframework.core.ISender#isSynchronous() */ public boolean isSynchronous() { return true; } /* (non-Javadoc) * @see nl.nn.adapterframework.core.ISender#sendMessage(java.lang.String, java.lang.String) */ public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException { for (Iterator filenameIt = getFileList(message).iterator(); filenameIt.hasNext(); ) { String filename = (String)filenameIt.next(); log.debug("Start sending " + filename); // get file to send File localFile = new File(filename); // execute command in a new operating process try { String cmd = getCommand(prc.getSession(), localFile, true); Process p = Runtime.getRuntime().exec(cmd, null, workingDir); // read the output of the process BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuffer output = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { output.append(line); } // wait until the process is completely finished try { p.waitFor(); } catch(InterruptedException e) { } log.debug("output for " + localFile.getName() + " = " + output.toString()); log.debug(localFile.getName() + " exits with " + p.exitValue()); // throw an exception if the command returns an error exit value if (p.exitValue() != 0) { throw new SenderException("XComSender failed for file " + localFile.getAbsolutePath() + "\r\n" + output.toString()); } } catch(IOException e) { throw new SenderException("Error while executing command " + getCommand(prc.getSession(), localFile, false), e); } } return message; } private String getCommand(PipeLineSession session, File localFile, boolean inclPasswd) throws SenderException { try { StringBuffer sb = new StringBuffer(); sb.append(xcomtcp). append(" -c1"); if (StringUtils.isNotEmpty(configFile)) { sb.append(" -f ").append(configFile); } if (StringUtils.isNotEmpty(remoteSystem)) { sb.append(" REMOTE_SYSTEM=").append(remoteSystem); } if (localFile != null) { sb.append(" LOCAL_FILE=").append(localFile.getAbsolutePath()); sb.append(" REMOTE_FILE="); if (! StringUtils.isEmpty(remoteDirectory)) sb.append(remoteDirectory); if (StringUtils.isEmpty(remoteFilePattern)) sb.append(localFile.getName()); else sb.append(FileUtils.getFilename(paramList, session, localFile, remoteFilePattern)); } CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserid(), password); // optional parameters if (StringUtils.isNotEmpty(fileOption)) sb.append(" FILE_OPTION=").append(fileOption); if (queue != null) sb.append(" QUEUE=").append(queue.booleanValue() ? "YES" : "NO"); if (tracelevel != null) sb.append(" TRACE=").append(tracelevel.intValue()); if (truncation != null) sb.append(" TRUNCATION=").append(truncation.booleanValue() ? "YES" : "NO"); if (! StringUtils.isEmpty(port)) sb.append(" PORT=" + port); if (! StringUtils.isEmpty(logfile)) sb.append(" XLOGFILE=" + logfile); if (! StringUtils.isEmpty(compress)) sb.append(" COMPRESS=").append(compress); if (! StringUtils.isEmpty(codeflag)) sb.append(" CODE_FLAG=").append(codeflag); if (! StringUtils.isEmpty(carriageflag)) sb.append(" CARRIAGE_FLAG=").append(carriageflag); if (! StringUtils.isEmpty(cf.getUsername())) sb.append(" USERID=").append(cf.getUsername()); if (inclPasswd && ! StringUtils.isEmpty(cf.getPassword())) sb.append(" PASSWORD=").append(cf.getPassword()); return sb.toString(); } catch(ParameterException e) { throw new SenderException(e); } } public String getXcomtcp() { return xcomtcp; } private List getFileList(String message) { StringTokenizer st = new StringTokenizer(message, ";"); LinkedList list = new LinkedList(); while (st.hasMoreTokens()) { list.add(st.nextToken()); } return list; } /* (non-Javadoc) * @see nl.nn.adapterframework.core.INamedObject#getName() */ public String getName() { return name; } /* (non-Javadoc) * @see nl.nn.adapterframework.core.INamedObject#setName(java.lang.String) */ public void setName(String name) { this.name = name; } public String getFileOption() { return fileOption; } public void setFileOption(String newVal) { fileOption = newVal; } public String getRemoteDirectory() { return remoteDirectory; } public void setRemoteDirectory(String string) { remoteDirectory = string; } public String getCariageflag() { return carriageflag; } public String getCodeflag() { return codeflag; } public String getCompress() { return compress; } public String getLogfile() { return logfile; } public String getPort() { return port; } public Boolean isQueue() { return queue; } public String getRemoteSystem() { return remoteSystem; } public Integer getTracelevel() { return tracelevel; } public Boolean isTruncation() { return truncation; } public String getUserid() { return userid; } public void setCarriageflag(String string) { carriageflag = string; } public void setCodeflag(String string) { codeflag = string; } public void setCompress(String string) { compress = string; } public void setLogfile(String string) { logfile = string; } public void setPassword(String string) { password = string; } public void setPort(String string) { port = string; } public void setQueue(Boolean b) { queue = b; } public void setRemoteSystem(String string) { remoteSystem = string; } public void setTracelevel(Integer i) { tracelevel = i; } public void setTruncation(Boolean b) { truncation = b; } public void setUserid(String string) { userid = string; } public String getRemoteFilePattern() { return remoteFilePattern; } public void setRemoteFilePattern(String string) { remoteFilePattern = string; } public String getWorkingDirName() { return workingDirName; } public void setWorkingDirName(String string) { workingDirName = string; } public void setXcomtcp(String string) { xcomtcp = string; } public String getConfigFile() { return configFile; } public void setConfigFile(String string) { configFile = string; } public void setAuthAlias(String string) { authAlias = string; } public String getAuthAlias() { return authAlias; } }
JavaSource/nl/nn/adapterframework/xcom/XComSender.java
/* * $Log: XComSender.java,v $ * Revision 1.15 2011-11-30 13:52:04 europe\m168309 * adjusted/reversed "Upgraded from WebSphere v5.1 to WebSphere v6.1" * * Revision 1.1 2011/10/19 14:49:54 Peter Leeuwenburgh <[email protected]> * Upgraded from WebSphere v5.1 to WebSphere v6.1 * * Revision 1.13 2010/03/10 14:30:05 Peter Leeuwenburgh <[email protected]> * rolled back testtool adjustments (IbisDebuggerDummy) * * Revision 1.11 2005/12/19 17:18:55 Gerrit van Brakel <[email protected]> * corrected typos in javadoc * * Revision 1.10 2005/12/19 17:14:42 Gerrit van Brakel <[email protected]> * updated javadoc * * Revision 1.9 2005/12/19 16:59:39 Gerrit van Brakel <[email protected]> * corrected typo: had only single r in carriageflag * * Revision 1.8 2005/12/19 16:40:15 Gerrit van Brakel <[email protected]> * added authentication using authentication-alias * * Revision 1.7 2005/10/31 14:42:40 Gerrit van Brakel <[email protected]> * updated javadoc * * Revision 1.6 2005/10/28 12:31:05 John Dekker <[email protected]> * Corrected bug with password added twice to command * * Revision 1.5 2005/10/27 13:29:26 John Dekker <[email protected]> * Add optional configFile property * * Revision 1.4 2005/10/27 07:58:57 John Dekker <[email protected]> * Host is not longer a required property, since it could be set in a config file * * Revision 1.3 2005/10/24 09:59:24 John Dekker <[email protected]> * Add support for pattern parameters, and include them into several listeners, * senders and pipes that are file related * * Revision 1.2 2005/10/11 13:04:50 John Dekker <[email protected]> * *** empty log message *** * * Revision 1.1 2005/10/11 13:04:24 John Dekker <[email protected]> * Support for sending files via the XComSender * */ package nl.nn.adapterframework.xcom; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.ParameterException; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.core.SenderWithParametersBase; import nl.nn.adapterframework.core.TimeOutException; import nl.nn.adapterframework.parameters.ParameterResolutionContext; import nl.nn.adapterframework.util.CredentialFactory; import nl.nn.adapterframework.util.FileUtils; import org.apache.commons.lang.StringUtils; /** * XCom client voor het versturen van files via XCom. * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>classname</td><td>nl.nn.ibis4fundation.XComSender</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the sender</td><td>&nbsp;</td></tr> * <tr><td>{@link #setWorkingDirName(String) workingDirName}</td><td>directory in which to run the xcomtcp command</td><td>&nbsp;</td></tr> * <tr><td>{@link #setXcomtcp(String) xcomtcp}</td><td>Path to xcomtcp command</td><td>&nbsp;</td></tr> * <tr><td>{@link #setFileOption(String) fileOption}</td><td>One of CREATE, APPEND or REPLACE</td><td>&nbsp;</td></tr> * <tr><td>{@link #setQueue(Boolean) queue}</td><td>Set queue off or on</td><td>&nbsp;</td></tr> * <tr><td>{@link #setTruncation(Boolean) truncation}</td><td>Set truncation off or on</td><td>&nbsp;</td></tr> * <tr><td>{@link #setTracelevel(Integer) tracelevel}</td><td>Set between 0 (no trace) and 10</td><td>&nbsp;</td></tr> * <tr><td>{@link #setCodeflag(String) codeflag}</td><td>Characterset conversion, one of ASCII or EBCDIC</td><td>&nbsp;</td></tr> * <tr><td>{@link #setCarriageflag(String) carriageflag}</td><td>One of YES, NO, VRL, VRL2, MPACK or XPACK</td><td>&nbsp;</td></tr> * <tr><td>{@link #setCompress(String) compress}</td><td>One of YES, NO, RLE, COMPACT, LZLARGE, LZMEDIUM or LZSMALL</td><td>&nbsp;</td></tr> * <tr><td>{@link #setLogfile(String) logfile}</td><td>Name of logfile for xcomtcp to be used</td><td>&nbsp;</td></tr> * <tr><td>{@link #setRemoteSystem(String) remoteSystem}</td><td>Hostname or tcpip adres of remote host</td><td>&nbsp;</td></tr> * <tr><td>{@link #setPort(String) port}</td><td>Port of remote host</td><td>&nbsp;</td></tr> * <tr><td>{@link #setRemoteDirectory(String) remoteDirectory}</td><td>Remote directory is prefixed witht the remote file</td><td>&nbsp;</td></tr> * <tr><td>{@link #setRemoteFilePattern(String) remoteFilePattern}</td><td>Remote file to create. If empty, the name is equal to the local file</td><td>&nbsp;</td></tr> * <tr><td>{@link #setAuthAlias(String) authAlias}</td><td>name of the alias to obtain credentials to authenticatie on remote server</td><td>&nbsp;</td></tr> * <tr><td>{@link #setUserid(String) userid}</td><td>Loginname of user on remote system</td><td>&nbsp;</td></tr> * <tr><td>{@link #setPassword(String) password}</td><td>Password of user on remote system</td><td>&nbsp;</td></tr> * </table> * </p> * * @author: John Dekker */ public class XComSender extends SenderWithParametersBase { public static final String version = "$RCSfile: XComSender.java,v $ $Revision: 1.15 $ $Date: 2011-11-30 13:52:04 $"; private File workingDir; private String name; private String fileOption = null; private Boolean queue = null; private Boolean truncation = null; private Integer tracelevel = null; private String logfile = null; private String codeflag = null; private String carriageflag = null; private String port = null; private String authAlias = null; private String userid = null; private String password = null; private String compress = null; private String remoteSystem = null; private String remoteDirectory = null; private String remoteFilePattern = null; private String configFile = null; private String workingDirName = "."; private String xcomtcp = "xcomtcp"; /* (non-Javadoc) * @see nl.nn.adapterframework.core.ISender#configure() */ public void configure() throws ConfigurationException { if (StringUtils.isNotEmpty(fileOption) && ! "CREATE".equals(fileOption) && ! "APPEND".equals(fileOption) && ! "REPLACE".equals(fileOption) ) { throw new ConfigurationException("Attribute [fileOption] has incorrect value " + fileOption + ", should be one of CREATE | APPEND or REPLACE"); } if (! StringUtils.isEmpty(compress) && ! "YES".equals(compress) && ! "COMPACT".equals(compress) && ! "LZLARGE".equals(compress) && ! "LZMEDIUM".equals(compress) && ! "LZSMALL".equals(compress) && ! "RLE".equals(compress) && ! "NO".equals(compress) ) { throw new ConfigurationException("Attribute [compress] has incorrect value " + compress + ", should be one of YES | NO | RLE | COMPACT | LZLARGE | LZMEDIUM | LZSMALL"); } if (! StringUtils.isEmpty(codeflag) && ! "EBCDIC".equals(codeflag) && ! "ASCII".equals(codeflag) ) { throw new ConfigurationException("Attribute [codeflag] has incorrect value " + fileOption + ", should be ASCII or EBCDIC"); } if (! StringUtils.isEmpty(carriageflag) && ! "YES".equals(carriageflag) && ! "VLR".equals(carriageflag) && ! "VLR2".equals(carriageflag) && ! "MPACK".equals(carriageflag) && ! "XPACK".equals(carriageflag) && ! "NO".equals(carriageflag) ) { throw new ConfigurationException("Attribute [cariageflag] has incorrect value " + compress + ", should be one of YES | NO | VRL | VRL2 | MPACK | XPACK"); } if (! StringUtils.isEmpty(port)) { try { Integer.parseInt(port); } catch(NumberFormatException e) { throw new ConfigurationException("Attribute [port] is not a number"); } } if (tracelevel != null && (tracelevel.intValue() < 0 || tracelevel.intValue() > 10)) { throw new ConfigurationException("Attribute [tracelevel] should be between 0 (no trace) and 10, not " + tracelevel.intValue()); } if (StringUtils.isEmpty(workingDirName)) { throw new ConfigurationException("Attribute [workingDirName] is not set"); } else { workingDir = new File(workingDirName); if (! workingDir.isDirectory()) { throw new ConfigurationException("Working directory [workingDirName=" + workingDirName + "] is not a directory"); } } } /* (non-Javadoc) * @see nl.nn.adapterframework.core.ISender#isSynchronous() */ public boolean isSynchronous() { return true; } /* (non-Javadoc) * @see nl.nn.adapterframework.core.ISender#sendMessage(java.lang.String, java.lang.String) */ public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException { for (Iterator filenameIt = getFileList(message).iterator(); filenameIt.hasNext(); ) { String filename = (String)filenameIt.next(); log.debug("Start sending " + filename); // get file to send File localFile = new File(filename); // execute command in a new operating process try { String cmd = getCommand(prc.getSession(), localFile, true); Process p = Runtime.getRuntime().exec(cmd, null, workingDir); // read the output of the process BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuffer output = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { output.append(line); } // wait until the process is completely finished try { p.waitFor(); } catch(InterruptedException e) { } log.debug("output for " + localFile.getName() + " = " + output.toString()); log.debug(localFile.getName() + " exits with " + p.exitValue()); // throw an exception if the command returns an error exit value if (p.exitValue() != 0) { throw new SenderException("XComSender failed for file " + localFile.getAbsolutePath() + "\r\n" + output.toString()); } } catch(IOException e) { throw new SenderException("Error while executing command " + getCommand(prc.getSession(), localFile, false), e); } } return message; } private String getCommand(PipeLineSession session, File localFile, boolean inclPasswd) throws SenderException { try { StringBuffer sb = new StringBuffer(); sb.append(xcomtcp). append(" -c1"); if (StringUtils.isNotEmpty(configFile)) { sb.append(" -f ").append(configFile); } if (StringUtils.isNotEmpty(remoteSystem)) { sb.append(" REMOTE_SYSTEM=").append(remoteSystem); } if (localFile != null) { sb.append(" LOCAL_FILE=").append(localFile.getAbsolutePath()); sb.append(" REMOTE_FILE="); if (! StringUtils.isEmpty(remoteDirectory)) sb.append(remoteDirectory); if (StringUtils.isEmpty(remoteFilePattern)) sb.append(localFile.getName()); else sb.append(FileUtils.getFilename(paramList, session, localFile, remoteFilePattern)); } CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserid(), password); // optional parameters if (StringUtils.isNotEmpty(fileOption)) sb.append(" FILE_OPTION=").append(fileOption); if (queue != null) sb.append(" QUEUE=").append(queue.booleanValue() ? "YES" : "NO"); if (tracelevel != null) sb.append(" TRACE=").append(tracelevel.intValue()); if (truncation != null) sb.append(" TRUNCATION=").append(truncation.booleanValue() ? "YES" : "NO"); if (! StringUtils.isEmpty(port)) sb.append(" PORT=" + port); if (! StringUtils.isEmpty(logfile)) sb.append(" XLOGFILE=" + logfile); if (! StringUtils.isEmpty(compress)) sb.append(" COMPRESS=").append(compress); if (! StringUtils.isEmpty(codeflag)) sb.append(" CODE_FLAG=").append(codeflag); if (! StringUtils.isEmpty(carriageflag)) sb.append(" CARRIAGE_FLAG=").append(carriageflag); if (! StringUtils.isEmpty(cf.getUsername())) sb.append(" USERID=").append(cf.getUsername()); if (inclPasswd && ! StringUtils.isEmpty(cf.getPassword())) sb.append(" PASSWORD=").append(cf.getPassword()); return sb.toString(); } catch(ParameterException e) { throw new SenderException(e); } } public String getXcomtcp() { return xcomtcp; } private List getFileList(String message) { StringTokenizer st = new StringTokenizer(message, ";"); LinkedList list = new LinkedList(); while (st.hasMoreTokens()) { list.add(st.nextToken()); } return list; } /* (non-Javadoc) * @see nl.nn.adapterframework.core.INamedObject#getName() */ public String getName() { return name; } /* (non-Javadoc) * @see nl.nn.adapterframework.core.INamedObject#setName(java.lang.String) */ public void setName(String name) { this.name = name; } public String getFileOption() { return fileOption; } public void setFileOption(String newVal) { fileOption = newVal; } public String getRemoteDirectory() { return remoteDirectory; } public void setRemoteDirectory(String string) { remoteDirectory = string; } public String getCariageflag() { return carriageflag; } public String getCodeflag() { return codeflag; } public String getCompress() { return compress; } public String getLogfile() { return logfile; } public String getPort() { return port; } public Boolean isQueue() { return queue; } public String getRemoteSystem() { return remoteSystem; } public Integer getTracelevel() { return tracelevel; } public Boolean isTruncation() { return truncation; } public String getUserid() { return userid; } public void setCarriageflag(String string) { carriageflag = string; } public void setCodeflag(String string) { codeflag = string; } public void setCompress(String string) { compress = string; } public void setLogfile(String string) { logfile = string; } public void setPassword(String string) { password = string; } public void setPort(String string) { port = string; } public void setQueue(Boolean b) { queue = b; } public void setRemoteSystem(String string) { remoteSystem = string; } public void setTracelevel(Integer i) { tracelevel = i; } public void setTruncation(Boolean b) { truncation = b; } public void setUserid(String string) { userid = string; } public String getRemoteFilePattern() { return remoteFilePattern; } public void setRemoteFilePattern(String string) { remoteFilePattern = string; } public String getWorkingDirName() { return workingDirName; } public void setWorkingDirName(String string) { workingDirName = string; } public void setXcomtcp(String string) { xcomtcp = string; } public String getConfigFile() { return configFile; } public void setConfigFile(String string) { configFile = string; } public void setAuthAlias(String string) { authAlias = string; } public String getAuthAlias() { return authAlias; } }
fixed javadoc
JavaSource/nl/nn/adapterframework/xcom/XComSender.java
fixed javadoc
Java
apache-2.0
8b8768e8f8254f803dae635bcf859c04f95b4c3c
0
jonmcewen/camel,apache/camel,sverkera/camel,jamesnetherton/camel,isavin/camel,CodeSmell/camel,Thopap/camel,adessaigne/camel,objectiser/camel,sverkera/camel,salikjan/camel,onders86/camel,DariusX/camel,tdiesler/camel,sverkera/camel,isavin/camel,pax95/camel,anton-k11/camel,gautric/camel,jamesnetherton/camel,apache/camel,pkletsko/camel,mgyongyosi/camel,yuruki/camel,Fabryprog/camel,gautric/camel,tadayosi/camel,kevinearls/camel,gnodet/camel,snurmine/camel,nikhilvibhav/camel,dmvolod/camel,davidkarlsen/camel,zregvart/camel,Thopap/camel,jonmcewen/camel,curso007/camel,mgyongyosi/camel,apache/camel,Fabryprog/camel,drsquidop/camel,alvinkwekel/camel,rmarting/camel,ullgren/camel,tadayosi/camel,adessaigne/camel,nikhilvibhav/camel,punkhorn/camel-upstream,tadayosi/camel,drsquidop/camel,yuruki/camel,akhettar/camel,akhettar/camel,gautric/camel,pkletsko/camel,dmvolod/camel,apache/camel,mcollovati/camel,CodeSmell/camel,adessaigne/camel,pmoerenhout/camel,snurmine/camel,pax95/camel,curso007/camel,jonmcewen/camel,cunningt/camel,drsquidop/camel,objectiser/camel,mgyongyosi/camel,pax95/camel,pkletsko/camel,nikhilvibhav/camel,rmarting/camel,anton-k11/camel,anoordover/camel,snurmine/camel,christophd/camel,jonmcewen/camel,pax95/camel,rmarting/camel,kevinearls/camel,dmvolod/camel,tadayosi/camel,pmoerenhout/camel,mcollovati/camel,Thopap/camel,jamesnetherton/camel,sverkera/camel,gautric/camel,gautric/camel,Thopap/camel,alvinkwekel/camel,drsquidop/camel,tadayosi/camel,pmoerenhout/camel,ullgren/camel,mgyongyosi/camel,anton-k11/camel,anoordover/camel,anton-k11/camel,nicolaferraro/camel,anton-k11/camel,CodeSmell/camel,pkletsko/camel,rmarting/camel,jamesnetherton/camel,nikhilvibhav/camel,davidkarlsen/camel,kevinearls/camel,onders86/camel,tdiesler/camel,curso007/camel,Fabryprog/camel,tdiesler/camel,tlehoux/camel,punkhorn/camel-upstream,zregvart/camel,drsquidop/camel,ullgren/camel,mcollovati/camel,alvinkwekel/camel,zregvart/camel,onders86/camel,pmoerenhout/camel,dmvolod/camel,anoordover/camel,pax95/camel,gnodet/camel,sverkera/camel,snurmine/camel,christophd/camel,dmvolod/camel,gnodet/camel,pmoerenhout/camel,gnodet/camel,tlehoux/camel,DariusX/camel,kevinearls/camel,adessaigne/camel,tdiesler/camel,curso007/camel,tlehoux/camel,DariusX/camel,anoordover/camel,yuruki/camel,davidkarlsen/camel,nicolaferraro/camel,Fabryprog/camel,akhettar/camel,onders86/camel,cunningt/camel,kevinearls/camel,tlehoux/camel,cunningt/camel,mcollovati/camel,rmarting/camel,tdiesler/camel,tlehoux/camel,nicolaferraro/camel,pax95/camel,christophd/camel,salikjan/camel,apache/camel,yuruki/camel,snurmine/camel,yuruki/camel,pkletsko/camel,tadayosi/camel,gautric/camel,christophd/camel,akhettar/camel,alvinkwekel/camel,jamesnetherton/camel,mgyongyosi/camel,yuruki/camel,davidkarlsen/camel,akhettar/camel,onders86/camel,jamesnetherton/camel,onders86/camel,objectiser/camel,Thopap/camel,kevinearls/camel,anton-k11/camel,punkhorn/camel-upstream,sverkera/camel,CodeSmell/camel,mgyongyosi/camel,jonmcewen/camel,anoordover/camel,cunningt/camel,cunningt/camel,christophd/camel,cunningt/camel,snurmine/camel,curso007/camel,isavin/camel,nicolaferraro/camel,dmvolod/camel,pmoerenhout/camel,tlehoux/camel,Thopap/camel,ullgren/camel,punkhorn/camel-upstream,isavin/camel,isavin/camel,adessaigne/camel,isavin/camel,apache/camel,anoordover/camel,curso007/camel,DariusX/camel,jonmcewen/camel,rmarting/camel,akhettar/camel,gnodet/camel,adessaigne/camel,drsquidop/camel,objectiser/camel,pkletsko/camel,christophd/camel,zregvart/camel,tdiesler/camel
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.kafka; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; import org.apache.camel.Exchange; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.StateRepository; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; import org.apache.camel.spi.UriPath; import org.apache.camel.util.jsse.CipherSuitesParameters; import org.apache.camel.util.jsse.KeyManagersParameters; import org.apache.camel.util.jsse.KeyStoreParameters; import org.apache.camel.util.jsse.SSLContextParameters; import org.apache.camel.util.jsse.SecureSocketProtocolsParameters; import org.apache.camel.util.jsse.TrustManagersParameters; import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.config.SaslConfigs; import org.apache.kafka.common.config.SslConfigs; @UriParams public class KafkaConfiguration implements Cloneable { //Common configuration properties @UriPath(label = "common") @Metadata(required = "true") private String topic; @UriParam(label = "common") private String brokers; @UriParam(label = "common") private String clientId; @UriParam(label = "consumer") private String groupId; @UriParam(label = "consumer", defaultValue = "10") private int consumerStreams = 10; @UriParam(label = "consumer", defaultValue = "1") private int consumersCount = 1; //interceptor.classes @UriParam(label = "common,monitoring") private String interceptorClasses; //key.deserializer @UriParam(label = "consumer", defaultValue = KafkaConstants.KAFKA_DEFAULT_DESERIALIZER) private String keyDeserializer = KafkaConstants.KAFKA_DEFAULT_DESERIALIZER; //value.deserializer @UriParam(label = "consumer", defaultValue = KafkaConstants.KAFKA_DEFAULT_DESERIALIZER) private String valueDeserializer = KafkaConstants.KAFKA_DEFAULT_DESERIALIZER; //fetch.min.bytes @UriParam(label = "consumer", defaultValue = "1") private Integer fetchMinBytes = 1; //fetch.min.bytes @UriParam(label = "consumer", defaultValue = "52428800") private Integer fetchMaxBytes = 50 * 1024 * 1024; //heartbeat.interval.ms @UriParam(label = "consumer", defaultValue = "3000") private Integer heartbeatIntervalMs = 3000; //max.partition.fetch.bytes @UriParam(label = "consumer", defaultValue = "1048576") private Integer maxPartitionFetchBytes = 1048576; //session.timeout.ms @UriParam(label = "consumer", defaultValue = "10000") private Integer sessionTimeoutMs = 10000; @UriParam(label = "consumer", defaultValue = "500") private Integer maxPollRecords; @UriParam(label = "consumer", defaultValue = "5000") private Long pollTimeoutMs = 5000L; //auto.offset.reset1 @UriParam(label = "consumer", defaultValue = "latest", enums = "latest,earliest,none") private String autoOffsetReset = "latest"; //partition.assignment.strategy @UriParam(label = "consumer", defaultValue = KafkaConstants.PARTITIONER_RANGE_ASSIGNOR) private String partitionAssignor = KafkaConstants.PARTITIONER_RANGE_ASSIGNOR; //request.timeout.ms @UriParam(label = "consumer", defaultValue = "40000") private Integer consumerRequestTimeoutMs = 40000; //auto.commit.interval.ms @UriParam(label = "consumer", defaultValue = "5000") private Integer autoCommitIntervalMs = 5000; //check.crcs @UriParam(label = "consumer", defaultValue = "true") private Boolean checkCrcs = true; //fetch.max.wait.ms @UriParam(label = "consumer", defaultValue = "500") private Integer fetchWaitMaxMs = 500; @UriParam(label = "consumer", enums = "beginning,end") private String seekTo; //Consumer configuration properties @UriParam(label = "consumer", defaultValue = "true") private Boolean autoCommitEnable = true; @UriParam(label = "consumer", defaultValue = "sync", enums = "sync,async,none") private String autoCommitOnStop = "sync"; @UriParam(label = "consumer") private boolean breakOnFirstError; @UriParam(label = "consumer") private StateRepository<String, String> offsetRepository; //Producer Camel specific configuration properties @UriParam(label = "producer") private boolean bridgeEndpoint; @UriParam(label = "producer", defaultValue = "true") private boolean circularTopicDetection = true; //Producer configuration properties @UriParam(label = "producer", defaultValue = KafkaConstants.KAFKA_DEFAULT_PARTITIONER) private String partitioner = KafkaConstants.KAFKA_DEFAULT_PARTITIONER; @UriParam(label = "producer", defaultValue = "100") private Integer retryBackoffMs = 100; @UriParam(label = "producer") private ExecutorService workerPool; @UriParam(label = "producer", defaultValue = "10") private Integer workerPoolCoreSize = 10; @UriParam(label = "producer", defaultValue = "20") private Integer workerPoolMaxSize = 20; //Async producer config @UriParam(label = "producer", defaultValue = "10000") private Integer queueBufferingMaxMessages = 10000; @UriParam(label = "producer", defaultValue = KafkaConstants.KAFKA_DEFAULT_SERIALIZER) private String serializerClass = KafkaConstants.KAFKA_DEFAULT_SERIALIZER; @UriParam(label = "producer", defaultValue = KafkaConstants.KAFKA_DEFAULT_SERIALIZER) private String keySerializerClass = KafkaConstants.KAFKA_DEFAULT_SERIALIZER; @UriParam(label = "producer") private String key; @UriParam(label = "producer") private Integer partitionKey; @UriParam(label = "producer", enums = "-1,0,1,all", defaultValue = "1") private String requestRequiredAcks = "1"; //buffer.memory @UriParam(label = "producer", defaultValue = "33554432") private Integer bufferMemorySize = 33554432; //compression.type @UriParam(label = "producer", defaultValue = "none", enums = "none,gzip,snappy,lz4") private String compressionCodec = "none"; //retries @UriParam(label = "producer", defaultValue = "0") private Integer retries = 0; //batch.size @UriParam(label = "producer", defaultValue = "16384") private Integer producerBatchSize = 16384; //connections.max.idle.ms @UriParam(label = "producer", defaultValue = "540000") private Integer connectionMaxIdleMs = 540000; //linger.ms @UriParam(label = "producer", defaultValue = "0") private Integer lingerMs = 0; //linger.ms @UriParam(label = "producer", defaultValue = "60000") private Integer maxBlockMs = 60000; //max.request.size @UriParam(label = "producer", defaultValue = "1048576") private Integer maxRequestSize = 1048576; //receive.buffer.bytes @UriParam(label = "producer", defaultValue = "65536") private Integer receiveBufferBytes = 65536; //request.timeout.ms @UriParam(label = "producer", defaultValue = "305000") private Integer requestTimeoutMs = 305000; //send.buffer.bytes @UriParam(label = "producer", defaultValue = "131072") private Integer sendBufferBytes = 131072; @UriParam(label = "producer", defaultValue = "true") private boolean recordMetadata = true; //max.in.flight.requests.per.connection @UriParam(label = "producer", defaultValue = "5") private Integer maxInFlightRequest = 5; //metadata.max.age.ms @UriParam(label = "producer", defaultValue = "300000") private Integer metadataMaxAgeMs = 300000; //metric.reporters @UriParam(label = "producer") private String metricReporters; //metrics.num.samples @UriParam(label = "producer", defaultValue = "2") private Integer noOfMetricsSample = 2; //metrics.sample.window.ms @UriParam(label = "producer", defaultValue = "30000") private Integer metricsSampleWindowMs = 30000; //reconnect.backoff.ms @UriParam(label = "producer", defaultValue = "50") private Integer reconnectBackoffMs = 50; // SSL @UriParam(label = "common,security") private SSLContextParameters sslContextParameters; // SSL // ssl.key.password @UriParam(label = "producer,security", secret = true) private String sslKeyPassword; // ssl.keystore.location @UriParam(label = "producer,security") private String sslKeystoreLocation; // ssl.keystore.password @UriParam(label = "producer,security", secret = true) private String sslKeystorePassword; //ssl.truststore.location @UriParam(label = "producer,security") private String sslTruststoreLocation; //ssl.truststore.password @UriParam(label = "producer,security", secret = true) private String sslTruststorePassword; //SSL //ssl.enabled.protocols @UriParam(label = "common,security", defaultValue = SslConfigs.DEFAULT_SSL_ENABLED_PROTOCOLS) private String sslEnabledProtocols = SslConfigs.DEFAULT_SSL_ENABLED_PROTOCOLS; //ssl.keystore.type @UriParam(label = "common,security", defaultValue = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE) private String sslKeystoreType = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE; //ssl.protocol @UriParam(label = "common,security", defaultValue = SslConfigs.DEFAULT_SSL_PROTOCOL) private String sslProtocol = SslConfigs.DEFAULT_SSL_PROTOCOL; //ssl.provider @UriParam(label = "common,security") private String sslProvider; //ssl.truststore.type @UriParam(label = "common,security", defaultValue = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE) private String sslTruststoreType = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE; //SSL //ssl.cipher.suites @UriParam(label = "common,security") private String sslCipherSuites; //ssl.endpoint.identification.algorithm @UriParam(label = "common,security") private String sslEndpointAlgorithm; //ssl.keymanager.algorithm @UriParam(label = "common,security", defaultValue = "SunX509") private String sslKeymanagerAlgorithm = "SunX509"; //ssl.trustmanager.algorithm @UriParam(label = "common,security", defaultValue = "PKIX") private String sslTrustmanagerAlgorithm = "PKIX"; // SASL & sucurity Protocol //sasl.kerberos.service.name @UriParam(label = "common,security") private String saslKerberosServiceName; //security.protocol @UriParam(label = "common,security", defaultValue = CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL) private String securityProtocol = CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL; //SASL //sasl.kerberos.kinit.cmd @UriParam(label = "common,security", defaultValue = SaslConfigs.DEFAULT_SASL_MECHANISM) private String saslMechanism = SaslConfigs.DEFAULT_SASL_MECHANISM; //sasl.kerberos.kinit.cmd @UriParam(label = "common,security", defaultValue = SaslConfigs.DEFAULT_KERBEROS_KINIT_CMD) private String kerberosInitCmd = SaslConfigs.DEFAULT_KERBEROS_KINIT_CMD; //sasl.kerberos.min.time.before.relogin @UriParam(label = "common,security", defaultValue = "60000") private Integer kerberosBeforeReloginMinTime = 60000; //sasl.kerberos.ticket.renew.jitter @UriParam(label = "common,security", defaultValue = "0.05") private Double kerberosRenewJitter = SaslConfigs.DEFAULT_KERBEROS_TICKET_RENEW_JITTER; //sasl.kerberos.ticket.renew.window.factor @UriParam(label = "common,security", defaultValue = "0.8") private Double kerberosRenewWindowFactor = SaslConfigs.DEFAULT_KERBEROS_TICKET_RENEW_WINDOW_FACTOR; @UriParam(label = "common,security", defaultValue = "DEFAULT") //sasl.kerberos.principal.to.local.rules private String kerberosPrincipalToLocalRules; public KafkaConfiguration() { } /** * Returns a copy of this configuration */ public KafkaConfiguration copy() { try { KafkaConfiguration copy = (KafkaConfiguration) clone(); return copy; } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public Properties createProducerProperties() { Properties props = new Properties(); addPropertyIfNotNull(props, ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, getKeySerializerClass()); addPropertyIfNotNull(props, ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, getSerializerClass()); addPropertyIfNotNull(props, ProducerConfig.ACKS_CONFIG, getRequestRequiredAcks()); addPropertyIfNotNull(props, ProducerConfig.BUFFER_MEMORY_CONFIG, getBufferMemorySize()); addPropertyIfNotNull(props, ProducerConfig.COMPRESSION_TYPE_CONFIG, getCompressionCodec()); addPropertyIfNotNull(props, ProducerConfig.RETRIES_CONFIG, getRetries()); addPropertyIfNotNull(props, ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, getInterceptorClasses()); // SSL applySslConfiguration(props, getSslContextParameters()); addPropertyIfNotNull(props, SslConfigs.SSL_KEY_PASSWORD_CONFIG, getSslKeyPassword()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, getSslKeystoreLocation()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, getSslKeystorePassword()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, getSslTruststoreLocation()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, getSslTruststorePassword()); addPropertyIfNotNull(props, ProducerConfig.SEND_BUFFER_CONFIG, getRetries()); addPropertyIfNotNull(props, ProducerConfig.BATCH_SIZE_CONFIG, getProducerBatchSize()); addPropertyIfNotNull(props, ProducerConfig.CLIENT_ID_CONFIG, getClientId()); addPropertyIfNotNull(props, ProducerConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG, getConnectionMaxIdleMs()); addPropertyIfNotNull(props, ProducerConfig.LINGER_MS_CONFIG, getLingerMs()); addPropertyIfNotNull(props, ProducerConfig.MAX_BLOCK_MS_CONFIG, getMaxBlockMs()); addPropertyIfNotNull(props, ProducerConfig.MAX_REQUEST_SIZE_CONFIG, getMaxRequestSize()); addPropertyIfNotNull(props, ProducerConfig.PARTITIONER_CLASS_CONFIG, getPartitioner()); addPropertyIfNotNull(props, ProducerConfig.RECEIVE_BUFFER_CONFIG, getReceiveBufferBytes()); addPropertyIfNotNull(props, ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, getRequestTimeoutMs()); // Security protocol addPropertyIfNotNull(props, CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, getSecurityProtocol()); addPropertyIfNotNull(props, ProducerConfig.SEND_BUFFER_CONFIG, getSendBufferBytes()); //SSL addPropertyIfNotNull(props, SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, getSslEnabledProtocols()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, getSslKeystoreType()); addPropertyIfNotNull(props, SslConfigs.SSL_PROTOCOL_CONFIG, getSslProtocol()); addPropertyIfNotNull(props, SslConfigs.SSL_PROVIDER_CONFIG, getSslProvider()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, getSslTruststoreType()); addPropertyIfNotNull(props, ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, getMaxInFlightRequest()); addPropertyIfNotNull(props, ProducerConfig.METADATA_MAX_AGE_CONFIG, getMetadataMaxAgeMs()); addPropertyIfNotNull(props, ProducerConfig.METRIC_REPORTER_CLASSES_CONFIG, getMetricReporters()); addPropertyIfNotNull(props, ProducerConfig.METRICS_NUM_SAMPLES_CONFIG, getNoOfMetricsSample()); addPropertyIfNotNull(props, ProducerConfig.METRICS_SAMPLE_WINDOW_MS_CONFIG, getMetricsSampleWindowMs()); addPropertyIfNotNull(props, ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG, getReconnectBackoffMs()); addPropertyIfNotNull(props, ProducerConfig.RETRY_BACKOFF_MS_CONFIG, getRetryBackoffMs()); //SASL addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_SERVICE_NAME, getSaslKerberosServiceName()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_KINIT_CMD, getKerberosInitCmd()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN, getKerberosBeforeReloginMinTime()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_JITTER, getKerberosRenewJitter()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR, getKerberosRenewWindowFactor()); addListPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_PRINCIPAL_TO_LOCAL_RULES, getKerberosPrincipalToLocalRules()); addPropertyIfNotNull(props, SaslConfigs.SASL_MECHANISM, getSaslMechanism()); //SSL addPropertyIfNotNull(props, SslConfigs.SSL_CIPHER_SUITES_CONFIG, getSslCipherSuites()); addPropertyIfNotNull(props, SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, getSslEndpointAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, getSslKeymanagerAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, getSslTrustmanagerAlgorithm()); return props; } public Properties createConsumerProperties() { Properties props = new Properties(); addPropertyIfNotNull(props, ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, getKeyDeserializer()); addPropertyIfNotNull(props, ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, getValueDeserializer()); addPropertyIfNotNull(props, ConsumerConfig.FETCH_MIN_BYTES_CONFIG, getFetchMinBytes()); addPropertyIfNotNull(props, ConsumerConfig.FETCH_MAX_BYTES_CONFIG, getFetchMaxBytes()); addPropertyIfNotNull(props, ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, getHeartbeatIntervalMs()); addPropertyIfNotNull(props, ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, getMaxPartitionFetchBytes()); addPropertyIfNotNull(props, ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, getSessionTimeoutMs()); addPropertyIfNotNull(props, ConsumerConfig.MAX_POLL_RECORDS_CONFIG, getMaxPollRecords()); addPropertyIfNotNull(props, ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, getInterceptorClasses()); // SSL applySslConfiguration(props, getSslContextParameters()); addPropertyIfNotNull(props, SslConfigs.SSL_KEY_PASSWORD_CONFIG, getSslKeyPassword()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, getSslKeystoreLocation()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, getSslKeystorePassword()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, getSslTruststoreLocation()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, getSslTruststorePassword()); addPropertyIfNotNull(props, ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, getAutoOffsetReset()); addPropertyIfNotNull(props, ConsumerConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG, getConnectionMaxIdleMs()); addPropertyIfNotNull(props, ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, isAutoCommitEnable()); addPropertyIfNotNull(props, ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, getPartitionAssignor()); addPropertyIfNotNull(props, ConsumerConfig.RECEIVE_BUFFER_CONFIG, getReceiveBufferBytes()); addPropertyIfNotNull(props, ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, getConsumerRequestTimeoutMs()); // Security protocol addPropertyIfNotNull(props, CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, getSecurityProtocol()); addPropertyIfNotNull(props, ProducerConfig.SEND_BUFFER_CONFIG, getSendBufferBytes()); //SSL addPropertyIfNotNull(props, SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, getSslEnabledProtocols()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, getSslKeystoreType()); addPropertyIfNotNull(props, SslConfigs.SSL_PROTOCOL_CONFIG, getSslProtocol()); addPropertyIfNotNull(props, SslConfigs.SSL_PROVIDER_CONFIG, getSslProvider()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, getSslTruststoreType()); addPropertyIfNotNull(props, ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, getAutoCommitIntervalMs()); addPropertyIfNotNull(props, ConsumerConfig.CHECK_CRCS_CONFIG, getCheckCrcs()); addPropertyIfNotNull(props, ConsumerConfig.CLIENT_ID_CONFIG, getClientId()); addPropertyIfNotNull(props, ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, getFetchWaitMaxMs()); addPropertyIfNotNull(props, ConsumerConfig.METADATA_MAX_AGE_CONFIG, getMetadataMaxAgeMs()); addPropertyIfNotNull(props, ConsumerConfig.METRIC_REPORTER_CLASSES_CONFIG, getMetricReporters()); addPropertyIfNotNull(props, ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, getNoOfMetricsSample()); addPropertyIfNotNull(props, ConsumerConfig.METRICS_SAMPLE_WINDOW_MS_CONFIG, getMetricsSampleWindowMs()); addPropertyIfNotNull(props, ConsumerConfig.RECONNECT_BACKOFF_MS_CONFIG, getReconnectBackoffMs()); addPropertyIfNotNull(props, ConsumerConfig.RETRY_BACKOFF_MS_CONFIG, getRetryBackoffMs()); //SASL addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_SERVICE_NAME, getSaslKerberosServiceName()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_KINIT_CMD, getKerberosInitCmd()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN, getKerberosBeforeReloginMinTime()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_JITTER, getKerberosRenewJitter()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR, getKerberosRenewWindowFactor()); addListPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_PRINCIPAL_TO_LOCAL_RULES, getKerberosPrincipalToLocalRules()); addPropertyIfNotNull(props, SaslConfigs.SASL_MECHANISM, getSaslMechanism()); //SSL addPropertyIfNotNull(props, SslConfigs.SSL_CIPHER_SUITES_CONFIG, getSslCipherSuites()); addPropertyIfNotNull(props, SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, getSslEndpointAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, getSslKeymanagerAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, getSslTrustmanagerAlgorithm()); return props; } /** * Uses the standard camel {@link SSLContextParameters} object to fill the Kafka SSL properties * * @param props Kafka properties * @param sslContextParameters SSL configuration */ private void applySslConfiguration(Properties props, SSLContextParameters sslContextParameters) { if (sslContextParameters != null) { addPropertyIfNotNull(props, SslConfigs.SSL_PROTOCOL_CONFIG, sslContextParameters.getSecureSocketProtocol()); addPropertyIfNotNull(props, SslConfigs.SSL_PROVIDER_CONFIG, sslContextParameters.getProvider()); CipherSuitesParameters cipherSuites = sslContextParameters.getCipherSuites(); if (cipherSuites != null) { addCommaSeparatedList(props, SslConfigs.SSL_CIPHER_SUITES_CONFIG, cipherSuites.getCipherSuite()); } SecureSocketProtocolsParameters secureSocketProtocols = sslContextParameters.getSecureSocketProtocols(); if (secureSocketProtocols != null) { addCommaSeparatedList(props, SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, secureSocketProtocols.getSecureSocketProtocol()); } KeyManagersParameters keyManagers = sslContextParameters.getKeyManagers(); if (keyManagers != null) { addPropertyIfNotNull(props, SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, keyManagers.getAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_KEY_PASSWORD_CONFIG, keyManagers.getKeyPassword()); KeyStoreParameters keyStore = keyManagers.getKeyStore(); if (keyStore != null) { addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, keyStore.getType()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, keyStore.getResource()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, keyStore.getPassword()); } } TrustManagersParameters trustManagers = sslContextParameters.getTrustManagers(); if (trustManagers != null) { addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, trustManagers.getAlgorithm()); KeyStoreParameters keyStore = trustManagers.getKeyStore(); if (keyStore != null) { addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, keyStore.getType()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, keyStore.getResource()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, keyStore.getPassword()); } } } } private static <T> void addPropertyIfNotNull(Properties props, String key, T value) { if (value != null) { // Kafka expects all properties as String props.put(key, value.toString()); } } private static <T> void addListPropertyIfNotNull(Properties props, String key, T value) { if (value != null) { // Kafka expects all properties as String String[] values = value.toString().split(","); List<String> list = Arrays.asList(values); props.put(key, list); } } private static void addCommaSeparatedList(Properties props, String key, List<String> values) { if (values != null && !values.isEmpty()) { props.put(key, values.stream().collect(Collectors.joining(","))); } } public String getGroupId() { return groupId; } /** * A string that uniquely identifies the group of consumer processes to which this consumer belongs. * By setting the same group id multiple processes indicate that they are all part of the same consumer group. * * This option is required for consumers. */ public void setGroupId(String groupId) { this.groupId = groupId; } public boolean isBridgeEndpoint() { return bridgeEndpoint; } /** * If the option is true, then KafkaProducer will ignore the KafkaConstants.TOPIC header setting of the inbound message. */ public void setBridgeEndpoint(boolean bridgeEndpoint) { this.bridgeEndpoint = bridgeEndpoint; } public boolean isCircularTopicDetection() { return circularTopicDetection; } /** * If the option is true, then KafkaProducer will detect if the message is attempted to be sent back to the same topic * it may come from, if the message was original from a kafka consumer. If the KafkaConstants.TOPIC header is the * same as the original kafka consumer topic, then the header setting is ignored, and the topic of the producer * endpoint is used. In other words this avoids sending the same message back to where it came from. * This option is not in use if the option bridgeEndpoint is set to true. */ public void setCircularTopicDetection(boolean circularTopicDetection) { this.circularTopicDetection = circularTopicDetection; } public String getPartitioner() { return partitioner; } /** * The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. */ public void setPartitioner(String partitioner) { this.partitioner = partitioner; } public String getTopic() { return topic; } /** * Name of the topic to use. * * On the consumer you can use comma to separate multiple topics. * A producer can only send a message to a single topic. */ public void setTopic(String topic) { this.topic = topic; } public int getConsumerStreams() { return consumerStreams; } /** * Number of concurrent consumers on the consumer */ public void setConsumerStreams(int consumerStreams) { this.consumerStreams = consumerStreams; } public int getConsumersCount() { return consumersCount; } /** * The number of consumers that connect to kafka server */ public void setConsumersCount(int consumersCount) { this.consumersCount = consumersCount; } public String getClientId() { return clientId; } /** * The client id is a user-specified string sent in each request to help trace calls. * It should logically identify the application making the request. */ public void setClientId(String clientId) { this.clientId = clientId; } public Boolean isAutoCommitEnable() { return offsetRepository == null ? autoCommitEnable : false; } /** * If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. * This committed offset will be used when the process fails as the position from which the new consumer will begin. */ public void setAutoCommitEnable(Boolean autoCommitEnable) { this.autoCommitEnable = autoCommitEnable; } public StateRepository<String, String> getOffsetRepository() { return offsetRepository; } /** * The offset repository to use in order to locally store the offset of each partition of the topic. * Defining one will disable the autocommit. */ public void setOffsetRepository(StateRepository<String, String> offsetRepository) { this.offsetRepository = offsetRepository; } public Integer getAutoCommitIntervalMs() { return autoCommitIntervalMs; } /** * The frequency in ms that the consumer offsets are committed to zookeeper. */ public void setAutoCommitIntervalMs(Integer autoCommitIntervalMs) { this.autoCommitIntervalMs = autoCommitIntervalMs; } public Integer getFetchMinBytes() { return fetchMinBytes; } /** * The minimum amount of data the server should return for a fetch request. * If insufficient data is available the request will wait for that much data to accumulate before answering the request. */ public void setFetchMinBytes(Integer fetchMinBytes) { this.fetchMinBytes = fetchMinBytes; } /** * The maximum amount of data the server should return for a fetch request * This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than * this value, the message will still be returned to ensure that the consumer can make progress. * The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or * max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. */ public Integer getFetchMaxBytes() { return fetchMaxBytes; } public void setFetchMaxBytes(Integer fetchMaxBytes) { this.fetchMaxBytes = fetchMaxBytes; } public Integer getFetchWaitMaxMs() { return fetchWaitMaxMs; } /** * The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes */ public void setFetchWaitMaxMs(Integer fetchWaitMaxMs) { this.fetchWaitMaxMs = fetchWaitMaxMs; } public String getAutoOffsetReset() { return autoOffsetReset; } /** * What to do when there is no initial offset in ZooKeeper or if an offset is out of range: * smallest : automatically reset the offset to the smallest offset * largest : automatically reset the offset to the largest offset * fail: throw exception to the consumer */ public void setAutoOffsetReset(String autoOffsetReset) { this.autoOffsetReset = autoOffsetReset; } public String getAutoCommitOnStop() { return autoCommitOnStop; } /** * Whether to perform an explicit auto commit when the consumer stops to ensure the broker * has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. * The possible values are: sync, async, or none. And sync is the default value. */ public void setAutoCommitOnStop(String autoCommitOnStop) { this.autoCommitOnStop = autoCommitOnStop; } public boolean isBreakOnFirstError() { return breakOnFirstError; } /** * This options controls what happens when a consumer is processing an exchange and it fails. * If the option is <tt>false</tt> then the consumer continues to the next message and processes it. * If the option is <tt>true</tt> then the consumer breaks out, and will seek back to offset of the * message that caused a failure, and then re-attempt to process this message. However this can lead * to endless processing of the same message if its bound to fail every time, eg a poison message. * Therefore its recommended to deal with that for example by using Camel's error handler. */ public void setBreakOnFirstError(boolean breakOnFirstError) { this.breakOnFirstError = breakOnFirstError; } public String getBrokers() { return brokers; } /** * URL of the Kafka brokers to use. * The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. * <p/> * This option is known as <tt>bootstrap.servers</tt> in the Kafka documentation. */ public void setBrokers(String brokers) { this.brokers = brokers; } public String getCompressionCodec() { return compressionCodec; } /** * This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are "none", "gzip" and "snappy". */ public void setCompressionCodec(String compressionCodec) { this.compressionCodec = compressionCodec; } public Integer getRetryBackoffMs() { return retryBackoffMs; } /** * Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. * Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. */ public void setRetryBackoffMs(Integer retryBackoffMs) { this.retryBackoffMs = retryBackoffMs; } public Integer getSendBufferBytes() { return sendBufferBytes; } /** * Socket write buffer size */ public void setSendBufferBytes(Integer sendBufferBytes) { this.sendBufferBytes = sendBufferBytes; } public Integer getRequestTimeoutMs() { return requestTimeoutMs; } /** * The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. */ public void setRequestTimeoutMs(Integer requestTimeoutMs) { this.requestTimeoutMs = requestTimeoutMs; } public Integer getQueueBufferingMaxMessages() { return queueBufferingMaxMessages; } /** * The maximum number of unsent messages that can be queued up the producer when using async * mode before either the producer must be blocked or data must be dropped. */ public void setQueueBufferingMaxMessages(Integer queueBufferingMaxMessages) { this.queueBufferingMaxMessages = queueBufferingMaxMessages; } public String getSerializerClass() { return serializerClass; } /** * The serializer class for messages. */ public void setSerializerClass(String serializerClass) { this.serializerClass = serializerClass; } public String getKeySerializerClass() { return keySerializerClass; } /** * The serializer class for keys (defaults to the same as for messages if nothing is given). */ public void setKeySerializerClass(String keySerializerClass) { this.keySerializerClass = keySerializerClass; } public String getKerberosInitCmd() { return kerberosInitCmd; } /** * Kerberos kinit command path. Default is /usr/bin/kinit */ public void setKerberosInitCmd(String kerberosInitCmd) { this.kerberosInitCmd = kerberosInitCmd; } public Integer getKerberosBeforeReloginMinTime() { return kerberosBeforeReloginMinTime; } /** * Login thread sleep time between refresh attempts. */ public void setKerberosBeforeReloginMinTime(Integer kerberosBeforeReloginMinTime) { this.kerberosBeforeReloginMinTime = kerberosBeforeReloginMinTime; } public Double getKerberosRenewJitter() { return kerberosRenewJitter; } /** * Percentage of random jitter added to the renewal time. */ public void setKerberosRenewJitter(Double kerberosRenewJitter) { this.kerberosRenewJitter = kerberosRenewJitter; } public Double getKerberosRenewWindowFactor() { return kerberosRenewWindowFactor; } /** * Login thread will sleep until the specified window factor of time from last * refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. */ public void setKerberosRenewWindowFactor(Double kerberosRenewWindowFactor) { this.kerberosRenewWindowFactor = kerberosRenewWindowFactor; } public String getKerberosPrincipalToLocalRules() { return kerberosPrincipalToLocalRules; } /** * A list of rules for mapping from principal names to short names (typically operating system usernames). * The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. * By default, principal names of the form {username}/{hostname}@{REALM} are mapped to {username}. * For more details on the format please see <a href=\"#security_authz\"> security authorization and acls</a>. * <p/> * Multiple values can be separated by comma */ public void setKerberosPrincipalToLocalRules(String kerberosPrincipalToLocalRules) { this.kerberosPrincipalToLocalRules = kerberosPrincipalToLocalRules; } public String getSslCipherSuites() { return sslCipherSuites; } /** * A list of cipher suites. This is a named combination of authentication, encryption, * MAC and key exchange algorithm used to negotiate the security settings for a network connection * using TLS or SSL network protocol.By default all the available cipher suites are supported. */ public void setSslCipherSuites(String sslCipherSuites) { this.sslCipherSuites = sslCipherSuites; } public String getSslEndpointAlgorithm() { return sslEndpointAlgorithm; } /** * The endpoint identification algorithm to validate server hostname using server certificate. */ public void setSslEndpointAlgorithm(String sslEndpointAlgorithm) { this.sslEndpointAlgorithm = sslEndpointAlgorithm; } public String getSslKeymanagerAlgorithm() { return sslKeymanagerAlgorithm; } /** * The algorithm used by key manager factory for SSL connections. Default value is the key * manager factory algorithm configured for the Java Virtual Machine. */ public void setSslKeymanagerAlgorithm(String sslKeymanagerAlgorithm) { this.sslKeymanagerAlgorithm = sslKeymanagerAlgorithm; } public String getSslTrustmanagerAlgorithm() { return sslTrustmanagerAlgorithm; } /** * The algorithm used by trust manager factory for SSL connections. Default value is the * trust manager factory algorithm configured for the Java Virtual Machine. */ public void setSslTrustmanagerAlgorithm(String sslTrustmanagerAlgorithm) { this.sslTrustmanagerAlgorithm = sslTrustmanagerAlgorithm; } public String getSslEnabledProtocols() { return sslEnabledProtocols; } /** * The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. */ public void setSslEnabledProtocols(String sslEnabledProtocols) { this.sslEnabledProtocols = sslEnabledProtocols; } public String getSslKeystoreType() { return sslKeystoreType; } /** * The file format of the key store file. This is optional for client. Default value is JKS */ public void setSslKeystoreType(String sslKeystoreType) { this.sslKeystoreType = sslKeystoreType; } public String getSslProtocol() { return sslProtocol; } /** * The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. * Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, * but their usage is discouraged due to known security vulnerabilities. */ public void setSslProtocol(String sslProtocol) { this.sslProtocol = sslProtocol; } public String getSslProvider() { return sslProvider; } /** * The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. */ public void setSslProvider(String sslProvider) { this.sslProvider = sslProvider; } public String getSslTruststoreType() { return sslTruststoreType; } /** * The file format of the trust store file. Default value is JKS. */ public void setSslTruststoreType(String sslTruststoreType) { this.sslTruststoreType = sslTruststoreType; } public String getSaslKerberosServiceName() { return saslKerberosServiceName; } /** * The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS * config or in Kafka's config. */ public void setSaslKerberosServiceName(String saslKerberosServiceName) { this.saslKerberosServiceName = saslKerberosServiceName; } public String getSaslMechanism() { return saslMechanism; } /** * The Simple Authentication and Security Layer (SASL) Mechanism used. * For the valid values see <a href="http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml">http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml</a> */ public void setSaslMechanism(String saslMechanism) { this.saslMechanism = saslMechanism; } public String getSecurityProtocol() { return securityProtocol; } /** * Protocol used to communicate with brokers. Currently only PLAINTEXT and SSL are supported. */ public void setSecurityProtocol(String securityProtocol) { this.securityProtocol = securityProtocol; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * SSL configuration using a Camel {@link SSLContextParameters} object. If configured it's applied before the other SSL endpoint parameters. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public String getSslKeyPassword() { return sslKeyPassword; } /** * The password of the private key in the key store file. This is optional for client. */ public void setSslKeyPassword(String sslKeyPassword) { this.sslKeyPassword = sslKeyPassword; } public String getSslKeystoreLocation() { return sslKeystoreLocation; } /** * The location of the key store file. This is optional for client and can be used for two-way * authentication for client. */ public void setSslKeystoreLocation(String sslKeystoreLocation) { this.sslKeystoreLocation = sslKeystoreLocation; } public String getSslKeystorePassword() { return sslKeystorePassword; } /** * The store password for the key store file.This is optional for client and only needed * if ssl.keystore.location is configured. */ public void setSslKeystorePassword(String sslKeystorePassword) { this.sslKeystorePassword = sslKeystorePassword; } public String getSslTruststoreLocation() { return sslTruststoreLocation; } /** * The location of the trust store file. */ public void setSslTruststoreLocation(String sslTruststoreLocation) { this.sslTruststoreLocation = sslTruststoreLocation; } public String getSslTruststorePassword() { return sslTruststorePassword; } /** * The password for the trust store file. */ public void setSslTruststorePassword(String sslTruststorePassword) { this.sslTruststorePassword = sslTruststorePassword; } public Integer getBufferMemorySize() { return bufferMemorySize; } /** * The total bytes of memory the producer can use to buffer records waiting to be sent to the server. * If records are sent faster than they can be delivered to the server the producer will either block * or throw an exception based on the preference specified by block.on.buffer.full.This setting should * correspond roughly to the total memory the producer will use, but is not a hard bound since not all * memory the producer uses is used for buffering. Some additional memory will be used for compression * (if compression is enabled) as well as for maintaining in-flight requests. */ public void setBufferMemorySize(Integer bufferMemorySize) { this.bufferMemorySize = bufferMemorySize; } public String getKey() { return key; } /** * The record key (or null if no key is specified). * If this option has been configured then it take precedence over header {@link KafkaConstants#KEY} */ public void setKey(String key) { this.key = key; } public Integer getPartitionKey() { return partitionKey; } /** * The partition to which the record will be sent (or null if no partition was specified). * If this option has been configured then it take precedence over header {@link KafkaConstants#PARTITION_KEY} */ public void setPartitionKey(Integer partitionKey) { this.partitionKey = partitionKey; } public String getRequestRequiredAcks() { return requestRequiredAcks; } /** * The number of acknowledgments the producer requires the leader to have received before considering a request complete. * This controls the durability of records that are sent. The following settings are common: * acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. * The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server * has received the record in this case, and the retries configuration will not take effect (as the client won't generally * know of any failures). The offset given back for each record will always be set to -1. * acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement * from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have * replicated it then the record will be lost. * acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the * record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. */ public void setRequestRequiredAcks(String requestRequiredAcks) { this.requestRequiredAcks = requestRequiredAcks; } public Integer getRetries() { return retries; } /** * Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. * Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially * change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second * succeeds, then the second record may appear first. */ public void setRetries(Integer retries) { this.retries = retries; } public Integer getProducerBatchSize() { return producerBatchSize; } /** * The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. * This helps performance on both the client and the server. This configuration controls the default batch size in bytes. * No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each * partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero * will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the * specified batch size in anticipation of additional records. */ public void setProducerBatchSize(Integer producerBatchSize) { this.producerBatchSize = producerBatchSize; } public Integer getConnectionMaxIdleMs() { return connectionMaxIdleMs; } /** * Close idle connections after the number of milliseconds specified by this config. */ public void setConnectionMaxIdleMs(Integer connectionMaxIdleMs) { this.connectionMaxIdleMs = connectionMaxIdleMs; } public Integer getLingerMs() { return lingerMs; } /** * The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this * occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce * the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delay—that is, * rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that * the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on * the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, * however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more * records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the * number of requests sent but would add up to 5ms of latency to records sent in the absense of load. */ public void setLingerMs(Integer lingerMs) { this.lingerMs = lingerMs; } public Integer getMaxBlockMs() { return maxBlockMs; } /** * The configuration controls how long sending to kafka will block. These methods can be * blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent * in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of * partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata */ public void setMaxBlockMs(Integer maxBlockMs) { this.maxBlockMs = maxBlockMs; } public Integer getMaxRequestSize() { return maxRequestSize; } /** * The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size * which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid * sending huge requests. */ public void setMaxRequestSize(Integer maxRequestSize) { this.maxRequestSize = maxRequestSize; } public Integer getReceiveBufferBytes() { return receiveBufferBytes; } /** * The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. */ public void setReceiveBufferBytes(Integer receiveBufferBytes) { this.receiveBufferBytes = receiveBufferBytes; } public Integer getMaxInFlightRequest() { return maxInFlightRequest; } /** * The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting * is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). */ public void setMaxInFlightRequest(Integer maxInFlightRequest) { this.maxInFlightRequest = maxInFlightRequest; } public Integer getMetadataMaxAgeMs() { return metadataMaxAgeMs; } /** * The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership * changes to proactively discover any new brokers or partitions. */ public void setMetadataMaxAgeMs(Integer metadataMaxAgeMs) { this.metadataMaxAgeMs = metadataMaxAgeMs; } public String getMetricReporters() { return metricReporters; } /** * A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be * notified of new metric creation. The JmxReporter is always included to register JMX statistics. */ public void setMetricReporters(String metricReporters) { this.metricReporters = metricReporters; } public Integer getNoOfMetricsSample() { return noOfMetricsSample; } /** * The number of samples maintained to compute metrics. */ public void setNoOfMetricsSample(Integer noOfMetricsSample) { this.noOfMetricsSample = noOfMetricsSample; } public Integer getMetricsSampleWindowMs() { return metricsSampleWindowMs; } /** * The number of samples maintained to compute metrics. */ public void setMetricsSampleWindowMs(Integer metricsSampleWindowMs) { this.metricsSampleWindowMs = metricsSampleWindowMs; } public Integer getReconnectBackoffMs() { return reconnectBackoffMs; } /** * The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host * in a tight loop. This backoff applies to all requests sent by the consumer to the broker. */ public void setReconnectBackoffMs(Integer reconnectBackoffMs) { this.reconnectBackoffMs = reconnectBackoffMs; } public Integer getHeartbeatIntervalMs() { return heartbeatIntervalMs; } /** * The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. * Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new * consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set * no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. */ public void setHeartbeatIntervalMs(Integer heartbeatIntervalMs) { this.heartbeatIntervalMs = heartbeatIntervalMs; } public Integer getMaxPartitionFetchBytes() { return maxPartitionFetchBytes; } /** * The maximum amount of data per-partition the server will return. The maximum total memory used for * a request will be #partitions * max.partition.fetch.bytes. This size must be at least as large as the * maximum message size the server allows or else it is possible for the producer to send messages larger * than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message * on a certain partition. */ public void setMaxPartitionFetchBytes(Integer maxPartitionFetchBytes) { this.maxPartitionFetchBytes = maxPartitionFetchBytes; } public Integer getSessionTimeoutMs() { return sessionTimeoutMs; } /** * The timeout used to detect failures when using Kafka's group management facilities. */ public void setSessionTimeoutMs(Integer sessionTimeoutMs) { this.sessionTimeoutMs = sessionTimeoutMs; } public Integer getMaxPollRecords() { return maxPollRecords; } /** * The maximum number of records returned in a single call to poll() */ public void setMaxPollRecords(Integer maxPollRecords) { this.maxPollRecords = maxPollRecords; } public Long getPollTimeoutMs() { return pollTimeoutMs; } /** * The timeout used when polling the KafkaConsumer. */ public void setPollTimeoutMs(Long pollTimeoutMs) { this.pollTimeoutMs = pollTimeoutMs; } public String getPartitionAssignor() { return partitionAssignor; } /** * The class name of the partition assignment strategy that the client will use to distribute * partition ownership amongst consumer instances when group management is used */ public void setPartitionAssignor(String partitionAssignor) { this.partitionAssignor = partitionAssignor; } public Integer getConsumerRequestTimeoutMs() { return consumerRequestTimeoutMs; } /** * The configuration controls the maximum amount of time the client will wait for the response * of a request. If the response is not received before the timeout elapses the client will resend * the request if necessary or fail the request if retries are exhausted. */ public void setConsumerRequestTimeoutMs(Integer consumerRequestTimeoutMs) { this.consumerRequestTimeoutMs = consumerRequestTimeoutMs; } public Boolean getCheckCrcs() { return checkCrcs; } /** * Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk * corruption to the messages occurred. This check adds some overhead, so it may be disabled in * cases seeking extreme performance. */ public void setCheckCrcs(Boolean checkCrcs) { this.checkCrcs = checkCrcs; } public String getKeyDeserializer() { return keyDeserializer; } /** * Deserializer class for key that implements the Deserializer interface. */ public void setKeyDeserializer(String keyDeserializer) { this.keyDeserializer = keyDeserializer; } public String getValueDeserializer() { return valueDeserializer; } /** * Deserializer class for value that implements the Deserializer interface. */ public void setValueDeserializer(String valueDeserializer) { this.valueDeserializer = valueDeserializer; } public String getSeekTo() { return seekTo; } /** * Set if KafkaConsumer will read from beginning or end on startup: * beginning : read from beginning * end : read from end * * This is replacing the earlier property seekToBeginning */ public void setSeekTo(String seekTo) { this.seekTo = seekTo; } public ExecutorService getWorkerPool() { return workerPool; } /** * To use a custom worker pool for continue routing {@link Exchange} after kafka server has acknowledge * the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. */ public void setWorkerPool(ExecutorService workerPool) { this.workerPool = workerPool; } public Integer getWorkerPoolCoreSize() { return workerPoolCoreSize; } /** * Number of core threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge * the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. */ public void setWorkerPoolCoreSize(Integer workerPoolCoreSize) { this.workerPoolCoreSize = workerPoolCoreSize; } public Integer getWorkerPoolMaxSize() { return workerPoolMaxSize; } /** * Maximum number of threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge * the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. */ public void setWorkerPoolMaxSize(Integer workerPoolMaxSize) { this.workerPoolMaxSize = workerPoolMaxSize; } public boolean isRecordMetadata() { return recordMetadata; } /** * Whether the producer should store the {@link RecordMetadata} results from sending to Kafka. * * The results are stored in a {@link List} containing the {@link RecordMetadata} metadata's. * The list is stored on a header with the key {@link KafkaConstants#KAFKA_RECORDMETA} */ public void setRecordMetadata(boolean recordMetadata) { this.recordMetadata = recordMetadata; } public String getInterceptorClasses() { return interceptorClasses; } /** * Sets interceptors for producer or consumers. * Producer interceptors have to be classes implementing {@link org.apache.kafka.clients.producer.ProducerInterceptor} * Consumer interceptors have to be classes implementing {@link org.apache.kafka.clients.consumer.ConsumerInterceptor} * Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime */ public void setInterceptorClasses(String interceptorClasses) { this.interceptorClasses = interceptorClasses; } }
components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConfiguration.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.kafka; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; import org.apache.camel.Exchange; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.StateRepository; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; import org.apache.camel.spi.UriPath; import org.apache.camel.util.jsse.CipherSuitesParameters; import org.apache.camel.util.jsse.KeyManagersParameters; import org.apache.camel.util.jsse.KeyStoreParameters; import org.apache.camel.util.jsse.SSLContextParameters; import org.apache.camel.util.jsse.SecureSocketProtocolsParameters; import org.apache.camel.util.jsse.TrustManagersParameters; import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.config.SaslConfigs; import org.apache.kafka.common.config.SslConfigs; @UriParams public class KafkaConfiguration implements Cloneable { //Common configuration properties @UriPath(label = "common") @Metadata(required = "true") private String topic; @UriParam(label = "common") private String brokers; @UriParam(label = "common") private String clientId; @UriParam(label = "consumer") private String groupId; @UriParam(label = "consumer", defaultValue = "10") private int consumerStreams = 10; @UriParam(label = "consumer", defaultValue = "1") private int consumersCount = 1; //interceptor.classes @UriParam(label = "common,monitoring") private String interceptorClasses; //key.deserializer @UriParam(label = "consumer", defaultValue = KafkaConstants.KAFKA_DEFAULT_DESERIALIZER) private String keyDeserializer = KafkaConstants.KAFKA_DEFAULT_DESERIALIZER; //value.deserializer @UriParam(label = "consumer", defaultValue = KafkaConstants.KAFKA_DEFAULT_DESERIALIZER) private String valueDeserializer = KafkaConstants.KAFKA_DEFAULT_DESERIALIZER; //fetch.min.bytes @UriParam(label = "consumer", defaultValue = "1") private Integer fetchMinBytes = 1; //fetch.min.bytes @UriParam(label = "consumer", defaultValue = "52428800") private Integer fetchMaxBytes = 50 * 1024 * 1024; //heartbeat.interval.ms @UriParam(label = "consumer", defaultValue = "3000") private Integer heartbeatIntervalMs = 3000; //max.partition.fetch.bytes @UriParam(label = "consumer", defaultValue = "1048576") private Integer maxPartitionFetchBytes = 1048576; //session.timeout.ms @UriParam(label = "consumer", defaultValue = "10000") private Integer sessionTimeoutMs = 10000; @UriParam(label = "consumer", defaultValue = "500") private Integer maxPollRecords; @UriParam(label = "consumer", defaultValue = "5000") private Long pollTimeoutMs = 5000L; //auto.offset.reset1 @UriParam(label = "consumer", defaultValue = "latest", enums = "latest,earliest,none") private String autoOffsetReset = "latest"; //partition.assignment.strategy @UriParam(label = "consumer", defaultValue = KafkaConstants.PARTITIONER_RANGE_ASSIGNOR) private String partitionAssignor = KafkaConstants.PARTITIONER_RANGE_ASSIGNOR; //request.timeout.ms @UriParam(label = "consumer", defaultValue = "40000") private Integer consumerRequestTimeoutMs = 40000; //auto.commit.interval.ms @UriParam(label = "consumer", defaultValue = "5000") private Integer autoCommitIntervalMs = 5000; //check.crcs @UriParam(label = "consumer", defaultValue = "true") private Boolean checkCrcs = true; //fetch.max.wait.ms @UriParam(label = "consumer", defaultValue = "500") private Integer fetchWaitMaxMs = 500; @UriParam(label = "consumer", enums = "beginning,end") private String seekTo; //Consumer configuration properties @UriParam(label = "consumer", defaultValue = "true") private Boolean autoCommitEnable = true; @UriParam(label = "consumer", defaultValue = "sync", enums = "sync,async,none") private String autoCommitOnStop = "sync"; @UriParam(label = "consumer", defaultValue = "true") private boolean breakOnFirstError = true; @UriParam(label = "consumer") private StateRepository<String, String> offsetRepository; //Producer Camel specific configuration properties @UriParam(label = "producer") private boolean bridgeEndpoint; @UriParam(label = "producer", defaultValue = "true") private boolean circularTopicDetection = true; //Producer configuration properties @UriParam(label = "producer", defaultValue = KafkaConstants.KAFKA_DEFAULT_PARTITIONER) private String partitioner = KafkaConstants.KAFKA_DEFAULT_PARTITIONER; @UriParam(label = "producer", defaultValue = "100") private Integer retryBackoffMs = 100; @UriParam(label = "producer") private ExecutorService workerPool; @UriParam(label = "producer", defaultValue = "10") private Integer workerPoolCoreSize = 10; @UriParam(label = "producer", defaultValue = "20") private Integer workerPoolMaxSize = 20; //Async producer config @UriParam(label = "producer", defaultValue = "10000") private Integer queueBufferingMaxMessages = 10000; @UriParam(label = "producer", defaultValue = KafkaConstants.KAFKA_DEFAULT_SERIALIZER) private String serializerClass = KafkaConstants.KAFKA_DEFAULT_SERIALIZER; @UriParam(label = "producer", defaultValue = KafkaConstants.KAFKA_DEFAULT_SERIALIZER) private String keySerializerClass = KafkaConstants.KAFKA_DEFAULT_SERIALIZER; @UriParam(label = "producer") private String key; @UriParam(label = "producer") private Integer partitionKey; @UriParam(label = "producer", enums = "-1,0,1,all", defaultValue = "1") private String requestRequiredAcks = "1"; //buffer.memory @UriParam(label = "producer", defaultValue = "33554432") private Integer bufferMemorySize = 33554432; //compression.type @UriParam(label = "producer", defaultValue = "none", enums = "none,gzip,snappy,lz4") private String compressionCodec = "none"; //retries @UriParam(label = "producer", defaultValue = "0") private Integer retries = 0; //batch.size @UriParam(label = "producer", defaultValue = "16384") private Integer producerBatchSize = 16384; //connections.max.idle.ms @UriParam(label = "producer", defaultValue = "540000") private Integer connectionMaxIdleMs = 540000; //linger.ms @UriParam(label = "producer", defaultValue = "0") private Integer lingerMs = 0; //linger.ms @UriParam(label = "producer", defaultValue = "60000") private Integer maxBlockMs = 60000; //max.request.size @UriParam(label = "producer", defaultValue = "1048576") private Integer maxRequestSize = 1048576; //receive.buffer.bytes @UriParam(label = "producer", defaultValue = "65536") private Integer receiveBufferBytes = 65536; //request.timeout.ms @UriParam(label = "producer", defaultValue = "305000") private Integer requestTimeoutMs = 305000; //send.buffer.bytes @UriParam(label = "producer", defaultValue = "131072") private Integer sendBufferBytes = 131072; @UriParam(label = "producer", defaultValue = "true") private boolean recordMetadata = true; //max.in.flight.requests.per.connection @UriParam(label = "producer", defaultValue = "5") private Integer maxInFlightRequest = 5; //metadata.max.age.ms @UriParam(label = "producer", defaultValue = "300000") private Integer metadataMaxAgeMs = 300000; //metric.reporters @UriParam(label = "producer") private String metricReporters; //metrics.num.samples @UriParam(label = "producer", defaultValue = "2") private Integer noOfMetricsSample = 2; //metrics.sample.window.ms @UriParam(label = "producer", defaultValue = "30000") private Integer metricsSampleWindowMs = 30000; //reconnect.backoff.ms @UriParam(label = "producer", defaultValue = "50") private Integer reconnectBackoffMs = 50; // SSL @UriParam(label = "common,security") private SSLContextParameters sslContextParameters; // SSL // ssl.key.password @UriParam(label = "producer,security", secret = true) private String sslKeyPassword; // ssl.keystore.location @UriParam(label = "producer,security") private String sslKeystoreLocation; // ssl.keystore.password @UriParam(label = "producer,security", secret = true) private String sslKeystorePassword; //ssl.truststore.location @UriParam(label = "producer,security") private String sslTruststoreLocation; //ssl.truststore.password @UriParam(label = "producer,security", secret = true) private String sslTruststorePassword; //SSL //ssl.enabled.protocols @UriParam(label = "common,security", defaultValue = SslConfigs.DEFAULT_SSL_ENABLED_PROTOCOLS) private String sslEnabledProtocols = SslConfigs.DEFAULT_SSL_ENABLED_PROTOCOLS; //ssl.keystore.type @UriParam(label = "common,security", defaultValue = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE) private String sslKeystoreType = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE; //ssl.protocol @UriParam(label = "common,security", defaultValue = SslConfigs.DEFAULT_SSL_PROTOCOL) private String sslProtocol = SslConfigs.DEFAULT_SSL_PROTOCOL; //ssl.provider @UriParam(label = "common,security") private String sslProvider; //ssl.truststore.type @UriParam(label = "common,security", defaultValue = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE) private String sslTruststoreType = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE; //SSL //ssl.cipher.suites @UriParam(label = "common,security") private String sslCipherSuites; //ssl.endpoint.identification.algorithm @UriParam(label = "common,security") private String sslEndpointAlgorithm; //ssl.keymanager.algorithm @UriParam(label = "common,security", defaultValue = "SunX509") private String sslKeymanagerAlgorithm = "SunX509"; //ssl.trustmanager.algorithm @UriParam(label = "common,security", defaultValue = "PKIX") private String sslTrustmanagerAlgorithm = "PKIX"; // SASL & sucurity Protocol //sasl.kerberos.service.name @UriParam(label = "common,security") private String saslKerberosServiceName; //security.protocol @UriParam(label = "common,security", defaultValue = CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL) private String securityProtocol = CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL; //SASL //sasl.kerberos.kinit.cmd @UriParam(label = "common,security", defaultValue = SaslConfigs.DEFAULT_SASL_MECHANISM) private String saslMechanism = SaslConfigs.DEFAULT_SASL_MECHANISM; //sasl.kerberos.kinit.cmd @UriParam(label = "common,security", defaultValue = SaslConfigs.DEFAULT_KERBEROS_KINIT_CMD) private String kerberosInitCmd = SaslConfigs.DEFAULT_KERBEROS_KINIT_CMD; //sasl.kerberos.min.time.before.relogin @UriParam(label = "common,security", defaultValue = "60000") private Integer kerberosBeforeReloginMinTime = 60000; //sasl.kerberos.ticket.renew.jitter @UriParam(label = "common,security", defaultValue = "0.05") private Double kerberosRenewJitter = SaslConfigs.DEFAULT_KERBEROS_TICKET_RENEW_JITTER; //sasl.kerberos.ticket.renew.window.factor @UriParam(label = "common,security", defaultValue = "0.8") private Double kerberosRenewWindowFactor = SaslConfigs.DEFAULT_KERBEROS_TICKET_RENEW_WINDOW_FACTOR; @UriParam(label = "common,security", defaultValue = "DEFAULT") //sasl.kerberos.principal.to.local.rules private String kerberosPrincipalToLocalRules; public KafkaConfiguration() { } /** * Returns a copy of this configuration */ public KafkaConfiguration copy() { try { KafkaConfiguration copy = (KafkaConfiguration) clone(); return copy; } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public Properties createProducerProperties() { Properties props = new Properties(); addPropertyIfNotNull(props, ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, getKeySerializerClass()); addPropertyIfNotNull(props, ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, getSerializerClass()); addPropertyIfNotNull(props, ProducerConfig.ACKS_CONFIG, getRequestRequiredAcks()); addPropertyIfNotNull(props, ProducerConfig.BUFFER_MEMORY_CONFIG, getBufferMemorySize()); addPropertyIfNotNull(props, ProducerConfig.COMPRESSION_TYPE_CONFIG, getCompressionCodec()); addPropertyIfNotNull(props, ProducerConfig.RETRIES_CONFIG, getRetries()); addPropertyIfNotNull(props, ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, getInterceptorClasses()); // SSL applySslConfiguration(props, getSslContextParameters()); addPropertyIfNotNull(props, SslConfigs.SSL_KEY_PASSWORD_CONFIG, getSslKeyPassword()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, getSslKeystoreLocation()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, getSslKeystorePassword()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, getSslTruststoreLocation()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, getSslTruststorePassword()); addPropertyIfNotNull(props, ProducerConfig.SEND_BUFFER_CONFIG, getRetries()); addPropertyIfNotNull(props, ProducerConfig.BATCH_SIZE_CONFIG, getProducerBatchSize()); addPropertyIfNotNull(props, ProducerConfig.CLIENT_ID_CONFIG, getClientId()); addPropertyIfNotNull(props, ProducerConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG, getConnectionMaxIdleMs()); addPropertyIfNotNull(props, ProducerConfig.LINGER_MS_CONFIG, getLingerMs()); addPropertyIfNotNull(props, ProducerConfig.MAX_BLOCK_MS_CONFIG, getMaxBlockMs()); addPropertyIfNotNull(props, ProducerConfig.MAX_REQUEST_SIZE_CONFIG, getMaxRequestSize()); addPropertyIfNotNull(props, ProducerConfig.PARTITIONER_CLASS_CONFIG, getPartitioner()); addPropertyIfNotNull(props, ProducerConfig.RECEIVE_BUFFER_CONFIG, getReceiveBufferBytes()); addPropertyIfNotNull(props, ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, getRequestTimeoutMs()); // Security protocol addPropertyIfNotNull(props, CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, getSecurityProtocol()); addPropertyIfNotNull(props, ProducerConfig.SEND_BUFFER_CONFIG, getSendBufferBytes()); //SSL addPropertyIfNotNull(props, SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, getSslEnabledProtocols()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, getSslKeystoreType()); addPropertyIfNotNull(props, SslConfigs.SSL_PROTOCOL_CONFIG, getSslProtocol()); addPropertyIfNotNull(props, SslConfigs.SSL_PROVIDER_CONFIG, getSslProvider()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, getSslTruststoreType()); addPropertyIfNotNull(props, ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, getMaxInFlightRequest()); addPropertyIfNotNull(props, ProducerConfig.METADATA_MAX_AGE_CONFIG, getMetadataMaxAgeMs()); addPropertyIfNotNull(props, ProducerConfig.METRIC_REPORTER_CLASSES_CONFIG, getMetricReporters()); addPropertyIfNotNull(props, ProducerConfig.METRICS_NUM_SAMPLES_CONFIG, getNoOfMetricsSample()); addPropertyIfNotNull(props, ProducerConfig.METRICS_SAMPLE_WINDOW_MS_CONFIG, getMetricsSampleWindowMs()); addPropertyIfNotNull(props, ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG, getReconnectBackoffMs()); addPropertyIfNotNull(props, ProducerConfig.RETRY_BACKOFF_MS_CONFIG, getRetryBackoffMs()); //SASL addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_SERVICE_NAME, getSaslKerberosServiceName()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_KINIT_CMD, getKerberosInitCmd()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN, getKerberosBeforeReloginMinTime()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_JITTER, getKerberosRenewJitter()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR, getKerberosRenewWindowFactor()); addListPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_PRINCIPAL_TO_LOCAL_RULES, getKerberosPrincipalToLocalRules()); addPropertyIfNotNull(props, SaslConfigs.SASL_MECHANISM, getSaslMechanism()); //SSL addPropertyIfNotNull(props, SslConfigs.SSL_CIPHER_SUITES_CONFIG, getSslCipherSuites()); addPropertyIfNotNull(props, SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, getSslEndpointAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, getSslKeymanagerAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, getSslTrustmanagerAlgorithm()); return props; } public Properties createConsumerProperties() { Properties props = new Properties(); addPropertyIfNotNull(props, ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, getKeyDeserializer()); addPropertyIfNotNull(props, ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, getValueDeserializer()); addPropertyIfNotNull(props, ConsumerConfig.FETCH_MIN_BYTES_CONFIG, getFetchMinBytes()); addPropertyIfNotNull(props, ConsumerConfig.FETCH_MAX_BYTES_CONFIG, getFetchMaxBytes()); addPropertyIfNotNull(props, ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, getHeartbeatIntervalMs()); addPropertyIfNotNull(props, ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, getMaxPartitionFetchBytes()); addPropertyIfNotNull(props, ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, getSessionTimeoutMs()); addPropertyIfNotNull(props, ConsumerConfig.MAX_POLL_RECORDS_CONFIG, getMaxPollRecords()); addPropertyIfNotNull(props, ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, getInterceptorClasses()); // SSL applySslConfiguration(props, getSslContextParameters()); addPropertyIfNotNull(props, SslConfigs.SSL_KEY_PASSWORD_CONFIG, getSslKeyPassword()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, getSslKeystoreLocation()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, getSslKeystorePassword()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, getSslTruststoreLocation()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, getSslTruststorePassword()); addPropertyIfNotNull(props, ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, getAutoOffsetReset()); addPropertyIfNotNull(props, ConsumerConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG, getConnectionMaxIdleMs()); addPropertyIfNotNull(props, ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, isAutoCommitEnable()); addPropertyIfNotNull(props, ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, getPartitionAssignor()); addPropertyIfNotNull(props, ConsumerConfig.RECEIVE_BUFFER_CONFIG, getReceiveBufferBytes()); addPropertyIfNotNull(props, ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, getConsumerRequestTimeoutMs()); // Security protocol addPropertyIfNotNull(props, CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, getSecurityProtocol()); addPropertyIfNotNull(props, ProducerConfig.SEND_BUFFER_CONFIG, getSendBufferBytes()); //SSL addPropertyIfNotNull(props, SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, getSslEnabledProtocols()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, getSslKeystoreType()); addPropertyIfNotNull(props, SslConfigs.SSL_PROTOCOL_CONFIG, getSslProtocol()); addPropertyIfNotNull(props, SslConfigs.SSL_PROVIDER_CONFIG, getSslProvider()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, getSslTruststoreType()); addPropertyIfNotNull(props, ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, getAutoCommitIntervalMs()); addPropertyIfNotNull(props, ConsumerConfig.CHECK_CRCS_CONFIG, getCheckCrcs()); addPropertyIfNotNull(props, ConsumerConfig.CLIENT_ID_CONFIG, getClientId()); addPropertyIfNotNull(props, ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, getFetchWaitMaxMs()); addPropertyIfNotNull(props, ConsumerConfig.METADATA_MAX_AGE_CONFIG, getMetadataMaxAgeMs()); addPropertyIfNotNull(props, ConsumerConfig.METRIC_REPORTER_CLASSES_CONFIG, getMetricReporters()); addPropertyIfNotNull(props, ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, getNoOfMetricsSample()); addPropertyIfNotNull(props, ConsumerConfig.METRICS_SAMPLE_WINDOW_MS_CONFIG, getMetricsSampleWindowMs()); addPropertyIfNotNull(props, ConsumerConfig.RECONNECT_BACKOFF_MS_CONFIG, getReconnectBackoffMs()); addPropertyIfNotNull(props, ConsumerConfig.RETRY_BACKOFF_MS_CONFIG, getRetryBackoffMs()); //SASL addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_SERVICE_NAME, getSaslKerberosServiceName()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_KINIT_CMD, getKerberosInitCmd()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN, getKerberosBeforeReloginMinTime()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_JITTER, getKerberosRenewJitter()); addPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR, getKerberosRenewWindowFactor()); addListPropertyIfNotNull(props, SaslConfigs.SASL_KERBEROS_PRINCIPAL_TO_LOCAL_RULES, getKerberosPrincipalToLocalRules()); addPropertyIfNotNull(props, SaslConfigs.SASL_MECHANISM, getSaslMechanism()); //SSL addPropertyIfNotNull(props, SslConfigs.SSL_CIPHER_SUITES_CONFIG, getSslCipherSuites()); addPropertyIfNotNull(props, SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, getSslEndpointAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, getSslKeymanagerAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, getSslTrustmanagerAlgorithm()); return props; } /** * Uses the standard camel {@link SSLContextParameters} object to fill the Kafka SSL properties * * @param props Kafka properties * @param sslContextParameters SSL configuration */ private void applySslConfiguration(Properties props, SSLContextParameters sslContextParameters) { if (sslContextParameters != null) { addPropertyIfNotNull(props, SslConfigs.SSL_PROTOCOL_CONFIG, sslContextParameters.getSecureSocketProtocol()); addPropertyIfNotNull(props, SslConfigs.SSL_PROVIDER_CONFIG, sslContextParameters.getProvider()); CipherSuitesParameters cipherSuites = sslContextParameters.getCipherSuites(); if (cipherSuites != null) { addCommaSeparatedList(props, SslConfigs.SSL_CIPHER_SUITES_CONFIG, cipherSuites.getCipherSuite()); } SecureSocketProtocolsParameters secureSocketProtocols = sslContextParameters.getSecureSocketProtocols(); if (secureSocketProtocols != null) { addCommaSeparatedList(props, SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, secureSocketProtocols.getSecureSocketProtocol()); } KeyManagersParameters keyManagers = sslContextParameters.getKeyManagers(); if (keyManagers != null) { addPropertyIfNotNull(props, SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, keyManagers.getAlgorithm()); addPropertyIfNotNull(props, SslConfigs.SSL_KEY_PASSWORD_CONFIG, keyManagers.getKeyPassword()); KeyStoreParameters keyStore = keyManagers.getKeyStore(); if (keyStore != null) { addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, keyStore.getType()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, keyStore.getResource()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, keyStore.getPassword()); } } TrustManagersParameters trustManagers = sslContextParameters.getTrustManagers(); if (trustManagers != null) { addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, trustManagers.getAlgorithm()); KeyStoreParameters keyStore = trustManagers.getKeyStore(); if (keyStore != null) { addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, keyStore.getType()); addPropertyIfNotNull(props, SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, keyStore.getResource()); addPropertyIfNotNull(props, SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, keyStore.getPassword()); } } } } private static <T> void addPropertyIfNotNull(Properties props, String key, T value) { if (value != null) { // Kafka expects all properties as String props.put(key, value.toString()); } } private static <T> void addListPropertyIfNotNull(Properties props, String key, T value) { if (value != null) { // Kafka expects all properties as String String[] values = value.toString().split(","); List<String> list = Arrays.asList(values); props.put(key, list); } } private static void addCommaSeparatedList(Properties props, String key, List<String> values) { if (values != null && !values.isEmpty()) { props.put(key, values.stream().collect(Collectors.joining(","))); } } public String getGroupId() { return groupId; } /** * A string that uniquely identifies the group of consumer processes to which this consumer belongs. * By setting the same group id multiple processes indicate that they are all part of the same consumer group. * * This option is required for consumers. */ public void setGroupId(String groupId) { this.groupId = groupId; } public boolean isBridgeEndpoint() { return bridgeEndpoint; } /** * If the option is true, then KafkaProducer will ignore the KafkaConstants.TOPIC header setting of the inbound message. */ public void setBridgeEndpoint(boolean bridgeEndpoint) { this.bridgeEndpoint = bridgeEndpoint; } public boolean isCircularTopicDetection() { return circularTopicDetection; } /** * If the option is true, then KafkaProducer will detect if the message is attempted to be sent back to the same topic * it may come from, if the message was original from a kafka consumer. If the KafkaConstants.TOPIC header is the * same as the original kafka consumer topic, then the header setting is ignored, and the topic of the producer * endpoint is used. In other words this avoids sending the same message back to where it came from. * This option is not in use if the option bridgeEndpoint is set to true. */ public void setCircularTopicDetection(boolean circularTopicDetection) { this.circularTopicDetection = circularTopicDetection; } public String getPartitioner() { return partitioner; } /** * The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. */ public void setPartitioner(String partitioner) { this.partitioner = partitioner; } public String getTopic() { return topic; } /** * Name of the topic to use. * * On the consumer you can use comma to separate multiple topics. * A producer can only send a message to a single topic. */ public void setTopic(String topic) { this.topic = topic; } public int getConsumerStreams() { return consumerStreams; } /** * Number of concurrent consumers on the consumer */ public void setConsumerStreams(int consumerStreams) { this.consumerStreams = consumerStreams; } public int getConsumersCount() { return consumersCount; } /** * The number of consumers that connect to kafka server */ public void setConsumersCount(int consumersCount) { this.consumersCount = consumersCount; } public String getClientId() { return clientId; } /** * The client id is a user-specified string sent in each request to help trace calls. * It should logically identify the application making the request. */ public void setClientId(String clientId) { this.clientId = clientId; } public Boolean isAutoCommitEnable() { return offsetRepository == null ? autoCommitEnable : false; } /** * If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. * This committed offset will be used when the process fails as the position from which the new consumer will begin. */ public void setAutoCommitEnable(Boolean autoCommitEnable) { this.autoCommitEnable = autoCommitEnable; } public StateRepository<String, String> getOffsetRepository() { return offsetRepository; } /** * The offset repository to use in order to locally store the offset of each partition of the topic. * Defining one will disable the autocommit. */ public void setOffsetRepository(StateRepository<String, String> offsetRepository) { this.offsetRepository = offsetRepository; } public Integer getAutoCommitIntervalMs() { return autoCommitIntervalMs; } /** * The frequency in ms that the consumer offsets are committed to zookeeper. */ public void setAutoCommitIntervalMs(Integer autoCommitIntervalMs) { this.autoCommitIntervalMs = autoCommitIntervalMs; } public Integer getFetchMinBytes() { return fetchMinBytes; } /** * The minimum amount of data the server should return for a fetch request. * If insufficient data is available the request will wait for that much data to accumulate before answering the request. */ public void setFetchMinBytes(Integer fetchMinBytes) { this.fetchMinBytes = fetchMinBytes; } /** * The maximum amount of data the server should return for a fetch request * This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than * this value, the message will still be returned to ensure that the consumer can make progress. * The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or * max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. */ public Integer getFetchMaxBytes() { return fetchMaxBytes; } public void setFetchMaxBytes(Integer fetchMaxBytes) { this.fetchMaxBytes = fetchMaxBytes; } public Integer getFetchWaitMaxMs() { return fetchWaitMaxMs; } /** * The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes */ public void setFetchWaitMaxMs(Integer fetchWaitMaxMs) { this.fetchWaitMaxMs = fetchWaitMaxMs; } public String getAutoOffsetReset() { return autoOffsetReset; } /** * What to do when there is no initial offset in ZooKeeper or if an offset is out of range: * smallest : automatically reset the offset to the smallest offset * largest : automatically reset the offset to the largest offset * fail: throw exception to the consumer */ public void setAutoOffsetReset(String autoOffsetReset) { this.autoOffsetReset = autoOffsetReset; } public String getAutoCommitOnStop() { return autoCommitOnStop; } /** * Whether to perform an explicit auto commit when the consumer stops to ensure the broker * has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. * The possible values are: sync, async, or none. And sync is the default value. */ public void setAutoCommitOnStop(String autoCommitOnStop) { this.autoCommitOnStop = autoCommitOnStop; } public boolean isBreakOnFirstError() { return breakOnFirstError; } /** * This options controls what happens when a consumer is processing an exchange and it fails. * If the option is <tt>false</tt> then the consumer continues to the next message and processes it. * If the option is <tt>true</tt> then the consumer breaks out, and will seek back to offset of the * message that caused a failure, and then re-attempt to process this message. However this can lead * to endless processing of the same message if its bound to fail every time, eg a poison message. * Therefore its recommended to deal with that for example by using Camel's error handler. */ public void setBreakOnFirstError(boolean breakOnFirstError) { this.breakOnFirstError = breakOnFirstError; } public String getBrokers() { return brokers; } /** * URL of the Kafka brokers to use. * The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. * <p/> * This option is known as <tt>bootstrap.servers</tt> in the Kafka documentation. */ public void setBrokers(String brokers) { this.brokers = brokers; } public String getCompressionCodec() { return compressionCodec; } /** * This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are "none", "gzip" and "snappy". */ public void setCompressionCodec(String compressionCodec) { this.compressionCodec = compressionCodec; } public Integer getRetryBackoffMs() { return retryBackoffMs; } /** * Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. * Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. */ public void setRetryBackoffMs(Integer retryBackoffMs) { this.retryBackoffMs = retryBackoffMs; } public Integer getSendBufferBytes() { return sendBufferBytes; } /** * Socket write buffer size */ public void setSendBufferBytes(Integer sendBufferBytes) { this.sendBufferBytes = sendBufferBytes; } public Integer getRequestTimeoutMs() { return requestTimeoutMs; } /** * The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. */ public void setRequestTimeoutMs(Integer requestTimeoutMs) { this.requestTimeoutMs = requestTimeoutMs; } public Integer getQueueBufferingMaxMessages() { return queueBufferingMaxMessages; } /** * The maximum number of unsent messages that can be queued up the producer when using async * mode before either the producer must be blocked or data must be dropped. */ public void setQueueBufferingMaxMessages(Integer queueBufferingMaxMessages) { this.queueBufferingMaxMessages = queueBufferingMaxMessages; } public String getSerializerClass() { return serializerClass; } /** * The serializer class for messages. */ public void setSerializerClass(String serializerClass) { this.serializerClass = serializerClass; } public String getKeySerializerClass() { return keySerializerClass; } /** * The serializer class for keys (defaults to the same as for messages if nothing is given). */ public void setKeySerializerClass(String keySerializerClass) { this.keySerializerClass = keySerializerClass; } public String getKerberosInitCmd() { return kerberosInitCmd; } /** * Kerberos kinit command path. Default is /usr/bin/kinit */ public void setKerberosInitCmd(String kerberosInitCmd) { this.kerberosInitCmd = kerberosInitCmd; } public Integer getKerberosBeforeReloginMinTime() { return kerberosBeforeReloginMinTime; } /** * Login thread sleep time between refresh attempts. */ public void setKerberosBeforeReloginMinTime(Integer kerberosBeforeReloginMinTime) { this.kerberosBeforeReloginMinTime = kerberosBeforeReloginMinTime; } public Double getKerberosRenewJitter() { return kerberosRenewJitter; } /** * Percentage of random jitter added to the renewal time. */ public void setKerberosRenewJitter(Double kerberosRenewJitter) { this.kerberosRenewJitter = kerberosRenewJitter; } public Double getKerberosRenewWindowFactor() { return kerberosRenewWindowFactor; } /** * Login thread will sleep until the specified window factor of time from last * refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. */ public void setKerberosRenewWindowFactor(Double kerberosRenewWindowFactor) { this.kerberosRenewWindowFactor = kerberosRenewWindowFactor; } public String getKerberosPrincipalToLocalRules() { return kerberosPrincipalToLocalRules; } /** * A list of rules for mapping from principal names to short names (typically operating system usernames). * The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. * By default, principal names of the form {username}/{hostname}@{REALM} are mapped to {username}. * For more details on the format please see <a href=\"#security_authz\"> security authorization and acls</a>. * <p/> * Multiple values can be separated by comma */ public void setKerberosPrincipalToLocalRules(String kerberosPrincipalToLocalRules) { this.kerberosPrincipalToLocalRules = kerberosPrincipalToLocalRules; } public String getSslCipherSuites() { return sslCipherSuites; } /** * A list of cipher suites. This is a named combination of authentication, encryption, * MAC and key exchange algorithm used to negotiate the security settings for a network connection * using TLS or SSL network protocol.By default all the available cipher suites are supported. */ public void setSslCipherSuites(String sslCipherSuites) { this.sslCipherSuites = sslCipherSuites; } public String getSslEndpointAlgorithm() { return sslEndpointAlgorithm; } /** * The endpoint identification algorithm to validate server hostname using server certificate. */ public void setSslEndpointAlgorithm(String sslEndpointAlgorithm) { this.sslEndpointAlgorithm = sslEndpointAlgorithm; } public String getSslKeymanagerAlgorithm() { return sslKeymanagerAlgorithm; } /** * The algorithm used by key manager factory for SSL connections. Default value is the key * manager factory algorithm configured for the Java Virtual Machine. */ public void setSslKeymanagerAlgorithm(String sslKeymanagerAlgorithm) { this.sslKeymanagerAlgorithm = sslKeymanagerAlgorithm; } public String getSslTrustmanagerAlgorithm() { return sslTrustmanagerAlgorithm; } /** * The algorithm used by trust manager factory for SSL connections. Default value is the * trust manager factory algorithm configured for the Java Virtual Machine. */ public void setSslTrustmanagerAlgorithm(String sslTrustmanagerAlgorithm) { this.sslTrustmanagerAlgorithm = sslTrustmanagerAlgorithm; } public String getSslEnabledProtocols() { return sslEnabledProtocols; } /** * The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. */ public void setSslEnabledProtocols(String sslEnabledProtocols) { this.sslEnabledProtocols = sslEnabledProtocols; } public String getSslKeystoreType() { return sslKeystoreType; } /** * The file format of the key store file. This is optional for client. Default value is JKS */ public void setSslKeystoreType(String sslKeystoreType) { this.sslKeystoreType = sslKeystoreType; } public String getSslProtocol() { return sslProtocol; } /** * The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. * Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, * but their usage is discouraged due to known security vulnerabilities. */ public void setSslProtocol(String sslProtocol) { this.sslProtocol = sslProtocol; } public String getSslProvider() { return sslProvider; } /** * The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. */ public void setSslProvider(String sslProvider) { this.sslProvider = sslProvider; } public String getSslTruststoreType() { return sslTruststoreType; } /** * The file format of the trust store file. Default value is JKS. */ public void setSslTruststoreType(String sslTruststoreType) { this.sslTruststoreType = sslTruststoreType; } public String getSaslKerberosServiceName() { return saslKerberosServiceName; } /** * The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS * config or in Kafka's config. */ public void setSaslKerberosServiceName(String saslKerberosServiceName) { this.saslKerberosServiceName = saslKerberosServiceName; } public String getSaslMechanism() { return saslMechanism; } /** * The Simple Authentication and Security Layer (SASL) Mechanism used. * For the valid values see <a href="http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml">http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml</a> */ public void setSaslMechanism(String saslMechanism) { this.saslMechanism = saslMechanism; } public String getSecurityProtocol() { return securityProtocol; } /** * Protocol used to communicate with brokers. Currently only PLAINTEXT and SSL are supported. */ public void setSecurityProtocol(String securityProtocol) { this.securityProtocol = securityProtocol; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * SSL configuration using a Camel {@link SSLContextParameters} object. If configured it's applied before the other SSL endpoint parameters. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public String getSslKeyPassword() { return sslKeyPassword; } /** * The password of the private key in the key store file. This is optional for client. */ public void setSslKeyPassword(String sslKeyPassword) { this.sslKeyPassword = sslKeyPassword; } public String getSslKeystoreLocation() { return sslKeystoreLocation; } /** * The location of the key store file. This is optional for client and can be used for two-way * authentication for client. */ public void setSslKeystoreLocation(String sslKeystoreLocation) { this.sslKeystoreLocation = sslKeystoreLocation; } public String getSslKeystorePassword() { return sslKeystorePassword; } /** * The store password for the key store file.This is optional for client and only needed * if ssl.keystore.location is configured. */ public void setSslKeystorePassword(String sslKeystorePassword) { this.sslKeystorePassword = sslKeystorePassword; } public String getSslTruststoreLocation() { return sslTruststoreLocation; } /** * The location of the trust store file. */ public void setSslTruststoreLocation(String sslTruststoreLocation) { this.sslTruststoreLocation = sslTruststoreLocation; } public String getSslTruststorePassword() { return sslTruststorePassword; } /** * The password for the trust store file. */ public void setSslTruststorePassword(String sslTruststorePassword) { this.sslTruststorePassword = sslTruststorePassword; } public Integer getBufferMemorySize() { return bufferMemorySize; } /** * The total bytes of memory the producer can use to buffer records waiting to be sent to the server. * If records are sent faster than they can be delivered to the server the producer will either block * or throw an exception based on the preference specified by block.on.buffer.full.This setting should * correspond roughly to the total memory the producer will use, but is not a hard bound since not all * memory the producer uses is used for buffering. Some additional memory will be used for compression * (if compression is enabled) as well as for maintaining in-flight requests. */ public void setBufferMemorySize(Integer bufferMemorySize) { this.bufferMemorySize = bufferMemorySize; } public String getKey() { return key; } /** * The record key (or null if no key is specified). * If this option has been configured then it take precedence over header {@link KafkaConstants#KEY} */ public void setKey(String key) { this.key = key; } public Integer getPartitionKey() { return partitionKey; } /** * The partition to which the record will be sent (or null if no partition was specified). * If this option has been configured then it take precedence over header {@link KafkaConstants#PARTITION_KEY} */ public void setPartitionKey(Integer partitionKey) { this.partitionKey = partitionKey; } public String getRequestRequiredAcks() { return requestRequiredAcks; } /** * The number of acknowledgments the producer requires the leader to have received before considering a request complete. * This controls the durability of records that are sent. The following settings are common: * acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. * The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server * has received the record in this case, and the retries configuration will not take effect (as the client won't generally * know of any failures). The offset given back for each record will always be set to -1. * acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement * from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have * replicated it then the record will be lost. * acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the * record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. */ public void setRequestRequiredAcks(String requestRequiredAcks) { this.requestRequiredAcks = requestRequiredAcks; } public Integer getRetries() { return retries; } /** * Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. * Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially * change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second * succeeds, then the second record may appear first. */ public void setRetries(Integer retries) { this.retries = retries; } public Integer getProducerBatchSize() { return producerBatchSize; } /** * The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. * This helps performance on both the client and the server. This configuration controls the default batch size in bytes. * No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each * partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero * will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the * specified batch size in anticipation of additional records. */ public void setProducerBatchSize(Integer producerBatchSize) { this.producerBatchSize = producerBatchSize; } public Integer getConnectionMaxIdleMs() { return connectionMaxIdleMs; } /** * Close idle connections after the number of milliseconds specified by this config. */ public void setConnectionMaxIdleMs(Integer connectionMaxIdleMs) { this.connectionMaxIdleMs = connectionMaxIdleMs; } public Integer getLingerMs() { return lingerMs; } /** * The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this * occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce * the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delay—that is, * rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that * the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on * the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, * however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more * records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the * number of requests sent but would add up to 5ms of latency to records sent in the absense of load. */ public void setLingerMs(Integer lingerMs) { this.lingerMs = lingerMs; } public Integer getMaxBlockMs() { return maxBlockMs; } /** * The configuration controls how long sending to kafka will block. These methods can be * blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent * in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of * partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata */ public void setMaxBlockMs(Integer maxBlockMs) { this.maxBlockMs = maxBlockMs; } public Integer getMaxRequestSize() { return maxRequestSize; } /** * The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size * which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid * sending huge requests. */ public void setMaxRequestSize(Integer maxRequestSize) { this.maxRequestSize = maxRequestSize; } public Integer getReceiveBufferBytes() { return receiveBufferBytes; } /** * The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. */ public void setReceiveBufferBytes(Integer receiveBufferBytes) { this.receiveBufferBytes = receiveBufferBytes; } public Integer getMaxInFlightRequest() { return maxInFlightRequest; } /** * The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting * is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). */ public void setMaxInFlightRequest(Integer maxInFlightRequest) { this.maxInFlightRequest = maxInFlightRequest; } public Integer getMetadataMaxAgeMs() { return metadataMaxAgeMs; } /** * The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership * changes to proactively discover any new brokers or partitions. */ public void setMetadataMaxAgeMs(Integer metadataMaxAgeMs) { this.metadataMaxAgeMs = metadataMaxAgeMs; } public String getMetricReporters() { return metricReporters; } /** * A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be * notified of new metric creation. The JmxReporter is always included to register JMX statistics. */ public void setMetricReporters(String metricReporters) { this.metricReporters = metricReporters; } public Integer getNoOfMetricsSample() { return noOfMetricsSample; } /** * The number of samples maintained to compute metrics. */ public void setNoOfMetricsSample(Integer noOfMetricsSample) { this.noOfMetricsSample = noOfMetricsSample; } public Integer getMetricsSampleWindowMs() { return metricsSampleWindowMs; } /** * The number of samples maintained to compute metrics. */ public void setMetricsSampleWindowMs(Integer metricsSampleWindowMs) { this.metricsSampleWindowMs = metricsSampleWindowMs; } public Integer getReconnectBackoffMs() { return reconnectBackoffMs; } /** * The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host * in a tight loop. This backoff applies to all requests sent by the consumer to the broker. */ public void setReconnectBackoffMs(Integer reconnectBackoffMs) { this.reconnectBackoffMs = reconnectBackoffMs; } public Integer getHeartbeatIntervalMs() { return heartbeatIntervalMs; } /** * The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. * Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new * consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set * no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. */ public void setHeartbeatIntervalMs(Integer heartbeatIntervalMs) { this.heartbeatIntervalMs = heartbeatIntervalMs; } public Integer getMaxPartitionFetchBytes() { return maxPartitionFetchBytes; } /** * The maximum amount of data per-partition the server will return. The maximum total memory used for * a request will be #partitions * max.partition.fetch.bytes. This size must be at least as large as the * maximum message size the server allows or else it is possible for the producer to send messages larger * than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message * on a certain partition. */ public void setMaxPartitionFetchBytes(Integer maxPartitionFetchBytes) { this.maxPartitionFetchBytes = maxPartitionFetchBytes; } public Integer getSessionTimeoutMs() { return sessionTimeoutMs; } /** * The timeout used to detect failures when using Kafka's group management facilities. */ public void setSessionTimeoutMs(Integer sessionTimeoutMs) { this.sessionTimeoutMs = sessionTimeoutMs; } public Integer getMaxPollRecords() { return maxPollRecords; } /** * The maximum number of records returned in a single call to poll() */ public void setMaxPollRecords(Integer maxPollRecords) { this.maxPollRecords = maxPollRecords; } public Long getPollTimeoutMs() { return pollTimeoutMs; } /** * The timeout used when polling the KafkaConsumer. */ public void setPollTimeoutMs(Long pollTimeoutMs) { this.pollTimeoutMs = pollTimeoutMs; } public String getPartitionAssignor() { return partitionAssignor; } /** * The class name of the partition assignment strategy that the client will use to distribute * partition ownership amongst consumer instances when group management is used */ public void setPartitionAssignor(String partitionAssignor) { this.partitionAssignor = partitionAssignor; } public Integer getConsumerRequestTimeoutMs() { return consumerRequestTimeoutMs; } /** * The configuration controls the maximum amount of time the client will wait for the response * of a request. If the response is not received before the timeout elapses the client will resend * the request if necessary or fail the request if retries are exhausted. */ public void setConsumerRequestTimeoutMs(Integer consumerRequestTimeoutMs) { this.consumerRequestTimeoutMs = consumerRequestTimeoutMs; } public Boolean getCheckCrcs() { return checkCrcs; } /** * Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk * corruption to the messages occurred. This check adds some overhead, so it may be disabled in * cases seeking extreme performance. */ public void setCheckCrcs(Boolean checkCrcs) { this.checkCrcs = checkCrcs; } public String getKeyDeserializer() { return keyDeserializer; } /** * Deserializer class for key that implements the Deserializer interface. */ public void setKeyDeserializer(String keyDeserializer) { this.keyDeserializer = keyDeserializer; } public String getValueDeserializer() { return valueDeserializer; } /** * Deserializer class for value that implements the Deserializer interface. */ public void setValueDeserializer(String valueDeserializer) { this.valueDeserializer = valueDeserializer; } public String getSeekTo() { return seekTo; } /** * Set if KafkaConsumer will read from beginning or end on startup: * beginning : read from beginning * end : read from end * * This is replacing the earlier property seekToBeginning */ public void setSeekTo(String seekTo) { this.seekTo = seekTo; } public ExecutorService getWorkerPool() { return workerPool; } /** * To use a custom worker pool for continue routing {@link Exchange} after kafka server has acknowledge * the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. */ public void setWorkerPool(ExecutorService workerPool) { this.workerPool = workerPool; } public Integer getWorkerPoolCoreSize() { return workerPoolCoreSize; } /** * Number of core threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge * the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. */ public void setWorkerPoolCoreSize(Integer workerPoolCoreSize) { this.workerPoolCoreSize = workerPoolCoreSize; } public Integer getWorkerPoolMaxSize() { return workerPoolMaxSize; } /** * Maximum number of threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge * the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. */ public void setWorkerPoolMaxSize(Integer workerPoolMaxSize) { this.workerPoolMaxSize = workerPoolMaxSize; } public boolean isRecordMetadata() { return recordMetadata; } /** * Whether the producer should store the {@link RecordMetadata} results from sending to Kafka. * * The results are stored in a {@link List} containing the {@link RecordMetadata} metadata's. * The list is stored on a header with the key {@link KafkaConstants#KAFKA_RECORDMETA} */ public void setRecordMetadata(boolean recordMetadata) { this.recordMetadata = recordMetadata; } public String getInterceptorClasses() { return interceptorClasses; } /** * Sets interceptors for producer or consumers. * Producer interceptors have to be classes implementing {@link org.apache.kafka.clients.producer.ProducerInterceptor} * Consumer interceptors have to be classes implementing {@link org.apache.kafka.clients.consumer.ConsumerInterceptor} * Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime */ public void setInterceptorClasses(String interceptorClasses) { this.interceptorClasses = interceptorClasses; } }
CAMEL-11215: The breakOnError should not be default enable so we keep current behavior
components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConfiguration.java
CAMEL-11215: The breakOnError should not be default enable so we keep current behavior
Java
apache-2.0
83977e32616f9b9d611ea1459809feea6a4c1c19
0
adedayo/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,petteyg/intellij-community,samthor/intellij-community,da1z/intellij-community,jagguli/intellij-community,retomerz/intellij-community,allotria/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,slisson/intellij-community,signed/intellij-community,apixandru/intellij-community,blademainer/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,holmes/intellij-community,dslomov/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,signed/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,kool79/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,xfournet/intellij-community,gnuhub/intellij-community,caot/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,fitermay/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,allotria/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,kdwink/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,gnuhub/intellij-community,holmes/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,signed/intellij-community,da1z/intellij-community,blademainer/intellij-community,dslomov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,adedayo/intellij-community,kdwink/intellij-community,vladmm/intellij-community,FHannes/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,slisson/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,izonder/intellij-community,allotria/intellij-community,diorcety/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,clumsy/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,blademainer/intellij-community,robovm/robovm-studio,robovm/robovm-studio,da1z/intellij-community,da1z/intellij-community,jagguli/intellij-community,semonte/intellij-community,signed/intellij-community,da1z/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,supersven/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,fnouama/intellij-community,clumsy/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,clumsy/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,dslomov/intellij-community,izonder/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,kool79/intellij-community,allotria/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,izonder/intellij-community,xfournet/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ryano144/intellij-community,slisson/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,signed/intellij-community,blademainer/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,holmes/intellij-community,xfournet/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,ibinti/intellij-community,semonte/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,caot/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,ftomassetti/intellij-community,caot/intellij-community,amith01994/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ftomassetti/intellij-community,caot/intellij-community,semonte/intellij-community,adedayo/intellij-community,vladmm/intellij-community,kdwink/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,supersven/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,samthor/intellij-community,apixandru/intellij-community,semonte/intellij-community,dslomov/intellij-community,ryano144/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,slisson/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,fnouama/intellij-community,allotria/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,supersven/intellij-community,clumsy/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,amith01994/intellij-community,amith01994/intellij-community,fitermay/intellij-community,fnouama/intellij-community,samthor/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,slisson/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,ibinti/intellij-community,amith01994/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,izonder/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,da1z/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,caot/intellij-community,ryano144/intellij-community,semonte/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,izonder/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,kool79/intellij-community,caot/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,caot/intellij-community,clumsy/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,fnouama/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,caot/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,samthor/intellij-community,jagguli/intellij-community,vladmm/intellij-community,fitermay/intellij-community,signed/intellij-community,signed/intellij-community,caot/intellij-community,apixandru/intellij-community,slisson/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,kdwink/intellij-community,fitermay/intellij-community,signed/intellij-community,petteyg/intellij-community,semonte/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,robovm/robovm-studio,robovm/robovm-studio,wreckJ/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,caot/intellij-community,holmes/intellij-community,hurricup/intellij-community,kool79/intellij-community,kool79/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,holmes/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,samthor/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,FHannes/intellij-community,clumsy/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,amith01994/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,samthor/intellij-community,ibinti/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,semonte/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,izonder/intellij-community,signed/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,samthor/intellij-community,apixandru/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,slisson/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,jagguli/intellij-community,slisson/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,supersven/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,allotria/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,izonder/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,kool79/intellij-community,ryano144/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,da1z/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,amith01994/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,adedayo/intellij-community,da1z/intellij-community,hurricup/intellij-community,FHannes/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,da1z/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,vladmm/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,tmpgit/intellij-community,signed/intellij-community,caot/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,apixandru/intellij-community,allotria/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,asedunov/intellij-community,retomerz/intellij-community,izonder/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,gnuhub/intellij-community,supersven/intellij-community,allotria/intellij-community,amith01994/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,fitermay/intellij-community,amith01994/intellij-community,jagguli/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,caot/intellij-community,ryano144/intellij-community,wreckJ/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs; import com.intellij.openapi.Disposable; import com.intellij.openapi.command.CommandAdapter; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.actions.VcsContextFactory; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; /** * @author yole */ public abstract class VcsVFSListener implements Disposable { protected static final Logger LOG = Logger.getInstance(VcsVFSListener.class); private final VcsDirtyScopeManager myDirtyScopeManager; private final ProjectLevelVcsManager myVcsManager; private final VcsFileListenerContextHelper myVcsFileListenerContextHelper; protected static class MovedFileInfo { public final String myOldPath; public String myNewPath; private final VirtualFile myFile; protected MovedFileInfo(VirtualFile file, final String newPath) { myOldPath = file.getPath(); myNewPath = newPath; myFile = file; } @Override public String toString() { return "MovedFileInfo{myNewPath=" + myNewPath + ", myFile=" + myFile + '}'; } } protected final Project myProject; protected final AbstractVcs myVcs; protected final ChangeListManager myChangeListManager; protected final VcsShowConfirmationOption myAddOption; protected final VcsShowConfirmationOption myRemoveOption; protected final List<VirtualFile> myAddedFiles = new ArrayList<VirtualFile>(); protected final Map<VirtualFile, VirtualFile> myCopyFromMap = new HashMap<VirtualFile, VirtualFile>(); protected final List<VcsException> myExceptions = new SmartList<VcsException>(); protected final List<FilePath> myDeletedFiles = new ArrayList<FilePath>(); protected final List<FilePath> myDeletedWithoutConfirmFiles = new ArrayList<FilePath>(); protected final List<MovedFileInfo> myMovedFiles = new ArrayList<MovedFileInfo>(); protected final LinkedHashSet<VirtualFile> myDirtyFiles = ContainerUtil.newLinkedHashSet(); protected enum VcsDeleteType {SILENT, CONFIRM, IGNORE} protected VcsVFSListener(@NotNull Project project, @NotNull AbstractVcs vcs) { myProject = project; myVcs = vcs; myChangeListManager = ChangeListManager.getInstance(project); myDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject); final MyVirtualFileAdapter myVFSListener = new MyVirtualFileAdapter(); final MyCommandAdapter myCommandListener = new MyCommandAdapter(); myVcsManager = ProjectLevelVcsManager.getInstance(project); myAddOption = myVcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.ADD, vcs); myRemoveOption = myVcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.REMOVE, vcs); VirtualFileManager.getInstance().addVirtualFileListener(myVFSListener, this); CommandProcessor.getInstance().addCommandListener(myCommandListener, this); myVcsFileListenerContextHelper = VcsFileListenerContextHelper.getInstance(myProject); } @Override public void dispose() { } protected boolean isEventIgnored(final VirtualFileEvent event, boolean putInDirty) { if (event.isFromRefresh()) return true; boolean vcsIgnored = !isUnderMyVcs(event.getFile()); if (vcsIgnored) { myDirtyFiles.add(event.getFile()); } return vcsIgnored; } private boolean isUnderMyVcs(VirtualFile file) { return myVcsManager.getVcsFor(file) == myVcs && myVcsManager.isFileInContent(file) && !myChangeListManager.isIgnoredFile(file); } protected void executeAdd() { final List<VirtualFile> addedFiles = acquireAddedFiles(); LOG.debug("executeAdd. addedFiles: " + addedFiles); for (Iterator<VirtualFile> iterator = addedFiles.iterator(); iterator.hasNext(); ) { VirtualFile file = iterator.next(); if (myVcsFileListenerContextHelper.isAdditionIgnored(file)) { iterator.remove(); } } final Map<VirtualFile, VirtualFile> copyFromMap = acquireCopiedFiles(); if (! addedFiles.isEmpty()) { executeAdd(addedFiles, copyFromMap); } } /** * @return get map of copied files and clear the map */ protected Map<VirtualFile, VirtualFile> acquireCopiedFiles() { final Map<VirtualFile, VirtualFile> copyFromMap = new HashMap<VirtualFile, VirtualFile>(myCopyFromMap); myCopyFromMap.clear(); return copyFromMap; } /** * @return get list of added files and clear previous list */ protected List<VirtualFile> acquireAddedFiles() { final List<VirtualFile> addedFiles = new ArrayList<VirtualFile>(myAddedFiles); myAddedFiles.clear(); return addedFiles; } /** * Execute add that performs adding from specific collections * * @param addedFiles the added files * @param copyFromMap the copied files */ protected void executeAdd(List<VirtualFile> addedFiles, Map<VirtualFile, VirtualFile> copyFromMap) { LOG.debug("executeAdd. add-option: " + myAddOption.getValue() + ", files to add: " + addedFiles); if (myAddOption.getValue() == VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY) return; if (myAddOption.getValue() == VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY) { performAdding(addedFiles, copyFromMap); } else { final AbstractVcsHelper helper = AbstractVcsHelper.getInstance(myProject); // TODO[yole]: nice and clean description label Collection<VirtualFile> filesToProcess = helper.selectFilesToProcess(addedFiles, getAddTitle(), null, getSingleFileAddTitle(), getSingleFileAddPromptTemplate(), myAddOption); if (filesToProcess != null) { performAdding(new ArrayList<VirtualFile>(filesToProcess), copyFromMap); } } } private void addFileToDelete(VirtualFile file) { if (file.isDirectory() && file instanceof NewVirtualFile && !isDirectoryVersioningSupported()) { for (VirtualFile child : ((NewVirtualFile)file).getCachedChildren()) { addFileToDelete(child); } } else { final VcsDeleteType type = needConfirmDeletion(file); final FilePath filePath = VcsContextFactory.SERVICE.getInstance().createFilePathOnDeleted(new File(file.getPath()), file.isDirectory()); if (type == VcsDeleteType.CONFIRM) { myDeletedFiles.add(filePath); } else if (type == VcsDeleteType.SILENT) { myDeletedWithoutConfirmFiles.add(filePath); } } } protected void executeDelete() { final List<FilePath> filesToDelete = new ArrayList<FilePath>(myDeletedWithoutConfirmFiles); final List<FilePath> deletedFiles = new ArrayList<FilePath>(myDeletedFiles); myDeletedWithoutConfirmFiles.clear(); myDeletedFiles.clear(); for (Iterator<FilePath> iterator = filesToDelete.iterator(); iterator.hasNext(); ) { FilePath file = iterator.next(); if (myVcsFileListenerContextHelper.isDeletionIgnored(file)) { iterator.remove(); } } for (Iterator<FilePath> iterator = deletedFiles.iterator(); iterator.hasNext(); ) { FilePath file = iterator.next(); if (myVcsFileListenerContextHelper.isDeletionIgnored(file)) { iterator.remove(); } } if (deletedFiles.isEmpty() &&filesToDelete.isEmpty()) return; if (myRemoveOption.getValue() != VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY) { if (myRemoveOption.getValue() == VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY || deletedFiles.isEmpty()) { filesToDelete.addAll(deletedFiles); } else { Collection<FilePath> filePaths = selectFilePathsToDelete(deletedFiles); if (filePaths != null) { filesToDelete.addAll(filePaths); } } } performDeletion(filesToDelete); } /** * Select file paths to delete * * @param deletedFiles deleted files set * @return selected files or null (that is considered as empty file set) */ @Nullable protected Collection<FilePath> selectFilePathsToDelete(final List<FilePath> deletedFiles) { AbstractVcsHelper helper = AbstractVcsHelper.getInstance(myProject); return helper.selectFilePathsToProcess(deletedFiles, getDeleteTitle(), null, getSingleFileDeleteTitle(), getSingleFileDeletePromptTemplate(), myRemoveOption); } protected void beforeContentsChange(VirtualFileEvent event, VirtualFile file) { } protected void fileAdded(VirtualFileEvent event, VirtualFile file) { if (!isEventIgnored(event, true) && !myChangeListManager.isIgnoredFile(file) && (isDirectoryVersioningSupported() || !file.isDirectory())) { LOG.debug("Adding [" + file.getPresentableUrl() + "] to added files"); myAddedFiles.add(event.getFile()); } } private void addFileToMove(final VirtualFile file, final String newParentPath, final String newName) { if (file.isDirectory() && !file.is(VFileProperty.SYMLINK) && !isDirectoryVersioningSupported()) { @SuppressWarnings("UnsafeVfsRecursion") VirtualFile[] children = file.getChildren(); if (children != null) { for (VirtualFile child : children) { addFileToMove(child, newParentPath + "/" + newName, child.getName()); } } } else { processMovedFile(file, newParentPath, newName); } } protected boolean filterOutUnknownFiles() { return true; } protected void processMovedFile(VirtualFile file, String newParentPath, String newName) { final FileStatus status = FileStatusManager.getInstance(myProject).getStatus(file); LOG.debug("Checking moved file " + file + "; status=" + status); if (status == FileStatus.IGNORED) { if (file.getParent() != null) { myDirtyFiles.add(file.getParent()); myDirtyFiles.add(file); // will be at new path } } if (!(filterOutUnknownFiles() && status == FileStatus.UNKNOWN) && status != FileStatus.IGNORED) { final String newPath = newParentPath + "/" + newName; boolean foundExistingInfo = false; for (MovedFileInfo info : myMovedFiles) { if (Comparing.equal(info.myFile, file)) { info.myNewPath = newPath; foundExistingInfo = true; break; } } if (!foundExistingInfo) { LOG.debug("Registered moved file " + file); myMovedFiles.add(new MovedFileInfo(file, newPath)); } } } private void executeMoveRename() { final List<MovedFileInfo> movedFiles = new ArrayList<MovedFileInfo>(myMovedFiles); LOG.debug("executeMoveRename " + movedFiles); myMovedFiles.clear(); performMoveRename(movedFiles); } protected VcsDeleteType needConfirmDeletion(final VirtualFile file) { return VcsDeleteType.CONFIRM; } protected abstract String getAddTitle(); protected abstract String getSingleFileAddTitle(); protected abstract String getSingleFileAddPromptTemplate(); protected abstract void performAdding(final Collection<VirtualFile> addedFiles, final Map<VirtualFile, VirtualFile> copyFromMap) ; protected abstract String getDeleteTitle(); protected abstract String getSingleFileDeleteTitle(); protected abstract String getSingleFileDeletePromptTemplate(); protected abstract void performDeletion(List<FilePath> filesToDelete); protected abstract void performMoveRename(List<MovedFileInfo> movedFiles); protected abstract boolean isDirectoryVersioningSupported(); private class MyVirtualFileAdapter extends VirtualFileAdapter { @Override public void fileCreated(@NotNull final VirtualFileEvent event) { VirtualFile file = event.getFile(); LOG.debug("fileCreated: " + file.getPresentableUrl()); if (isUnderMyVcs(file)) { fileAdded(event, file); } } @Override public void fileCopied(@NotNull final VirtualFileCopyEvent event) { if (isEventIgnored(event, true) || myChangeListManager.isIgnoredFile(event.getFile())) return; final AbstractVcs oldVcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(event.getOriginalFile()); if (oldVcs == myVcs) { final VirtualFile parent = event.getFile().getParent(); if (parent != null) { myAddedFiles.add(event.getFile()); myCopyFromMap.put(event.getFile(), event.getOriginalFile()); } } else { myAddedFiles.add(event.getFile()); } } @Override public void beforeFileDeletion(@NotNull final VirtualFileEvent event) { final VirtualFile file = event.getFile(); if (isEventIgnored(event, true)) { return; } if (!myChangeListManager.isIgnoredFile(file)) { addFileToDelete(file); return; } // files are ignored, directories are handled recursively if (event.getFile().isDirectory()) { final List<VirtualFile> list = new LinkedList<VirtualFile>(); VcsUtil.collectFiles(file, list, true, isDirectoryVersioningSupported()); for (VirtualFile child : list) { if (!myChangeListManager.isIgnoredFile(child)) { addFileToDelete(child); } } } } @Override public void beforeFileMovement(@NotNull final VirtualFileMoveEvent event) { if (isEventIgnored(event, true)) return; final VirtualFile file = event.getFile(); final AbstractVcs newVcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(event.getNewParent()); LOG.debug("beforeFileMovement " + event + " into " + newVcs); if (newVcs == myVcs) { addFileToMove(file, event.getNewParent().getPath(), file.getName()); } else { addFileToDelete(event.getFile()); } } @Override public void fileMoved(@NotNull final VirtualFileMoveEvent event) { if (isEventIgnored(event, true)) return; final AbstractVcs oldVcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(event.getOldParent()); if (oldVcs != myVcs) { myAddedFiles.add(event.getFile()); } } @Override public void beforePropertyChange(@NotNull final VirtualFilePropertyEvent event) { if (!isEventIgnored(event, false) && event.getPropertyName().equalsIgnoreCase(VirtualFile.PROP_NAME)) { LOG.debug("before file rename " + event); String oldName = (String)event.getOldValue(); String newName = (String)event.getNewValue(); // in order to force a reparse of a file, the rename event can be fired with old name equal to new name - // such events needn't be handled by the VCS if (!Comparing.equal(oldName, newName)) { final VirtualFile file = event.getFile(); final VirtualFile parent = file.getParent(); if (parent != null) { addFileToMove(file, parent.getPath(), newName); } } } } @Override public void beforeContentsChange(@NotNull VirtualFileEvent event) { VirtualFile file = event.getFile(); assert !file.isDirectory(); if (isUnderMyVcs(file)) { VcsVFSListener.this.beforeContentsChange(event, file); } } } private class MyCommandAdapter extends CommandAdapter { private int myCommandLevel; @Override public void commandStarted(final CommandEvent event) { if (myProject != event.getProject()) return; myCommandLevel++; } private void checkMovedAddedSourceBack() { if (myAddedFiles.isEmpty() || myMovedFiles.isEmpty()) return; final Map<String, VirtualFile> addedPaths = new HashMap<String, VirtualFile>(myAddedFiles.size()); for (VirtualFile file : myAddedFiles) { addedPaths.put(file.getPath(), file); } for (Iterator<MovedFileInfo> iterator = myMovedFiles.iterator(); iterator.hasNext();) { final MovedFileInfo movedFile = iterator.next(); if (addedPaths.containsKey(movedFile.myOldPath)) { iterator.remove(); final VirtualFile oldAdded = addedPaths.get(movedFile.myOldPath); myAddedFiles.remove(oldAdded); myAddedFiles.add(movedFile.myFile); myCopyFromMap.put(oldAdded, movedFile.myFile); } } } // If a file is scheduled for deletion, and at the same time for copying or addition, don't delete it. // It happens during Overwrite command or undo of overwrite. private void doNotDeleteAddedCopiedOrMovedFiles() { Collection<String> copiedAddedMoved = new ArrayList<String>(); for (VirtualFile file : myCopyFromMap.keySet()) { copiedAddedMoved.add(file.getPath()); } for (VirtualFile file : myAddedFiles) { copiedAddedMoved.add(file.getPath()); } for (MovedFileInfo movedFileInfo : myMovedFiles) { copiedAddedMoved.add(movedFileInfo.myNewPath); } for (Iterator<FilePath> iterator = myDeletedFiles.iterator(); iterator.hasNext(); ) { if (copiedAddedMoved.contains(FileUtil.toSystemIndependentName(iterator.next().getPath()))) { iterator.remove(); } } for (Iterator<FilePath> iterator = myDeletedWithoutConfirmFiles.iterator(); iterator.hasNext(); ) { if (copiedAddedMoved.contains(FileUtil.toSystemIndependentName(iterator.next().getPath()))) { iterator.remove(); } } } @Override public void commandFinished(final CommandEvent event) { if (myProject != event.getProject()) return; myCommandLevel--; if (myCommandLevel == 0) { if (!myAddedFiles.isEmpty() || !myDeletedFiles.isEmpty() || !myDeletedWithoutConfirmFiles.isEmpty() || !myMovedFiles.isEmpty() || ! myDirtyFiles.isEmpty()) { // avoid reentering commandFinished handler - saving the documents may cause a "before file deletion" event firing, // which will cause closing the text editor, which will itself run a command that will be caught by this listener myCommandLevel++; try { FileDocumentManager.getInstance().saveAllDocuments(); } finally { myCommandLevel--; } doNotDeleteAddedCopiedOrMovedFiles(); checkMovedAddedSourceBack(); if (!myAddedFiles.isEmpty()) { executeAdd(); myAddedFiles.clear(); } if (!myDeletedFiles.isEmpty() || !myDeletedWithoutConfirmFiles.isEmpty()) { executeDelete(); myDeletedFiles.clear(); myDeletedWithoutConfirmFiles.clear(); } if (!myMovedFiles.isEmpty()) { executeMoveRename(); myMovedFiles.clear(); } if (! myDirtyFiles.isEmpty()) { final List<VirtualFile> files = new ArrayList<VirtualFile>(); final List<VirtualFile> dirs = new ArrayList<VirtualFile>(); for (VirtualFile dirtyFile : myDirtyFiles) { if (dirtyFile != null) { if (dirtyFile.isDirectory()) { dirs.add(dirtyFile); } else { files.add(dirtyFile); } } } myDirtyScopeManager.filesDirty(files, dirs); myDirtyFiles.clear(); } if (! myExceptions.isEmpty()) { AbstractVcsHelper.getInstance(myProject).showErrors(myExceptions, myVcs.getDisplayName() + " operations errors"); } } } } } }
platform/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs; import com.intellij.openapi.Disposable; import com.intellij.openapi.command.CommandAdapter; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.actions.VcsContextFactory; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.util.SmartList; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; /** * @author yole */ public abstract class VcsVFSListener implements Disposable { protected static final Logger LOG = Logger.getInstance(VcsVFSListener.class); private final VcsDirtyScopeManager myDirtyScopeManager; private final ProjectLevelVcsManager myVcsManager; private final VcsFileListenerContextHelper myVcsFileListenerContextHelper; protected static class MovedFileInfo { public final String myOldPath; public String myNewPath; private final VirtualFile myFile; protected MovedFileInfo(VirtualFile file, final String newPath) { myOldPath = file.getPath(); myNewPath = newPath; myFile = file; } @Override public String toString() { return "MovedFileInfo{myNewPath=" + myNewPath + ", myFile=" + myFile + '}'; } } protected final Project myProject; protected final AbstractVcs myVcs; protected final ChangeListManager myChangeListManager; protected final VcsShowConfirmationOption myAddOption; protected final VcsShowConfirmationOption myRemoveOption; protected final List<VirtualFile> myAddedFiles = new ArrayList<VirtualFile>(); protected final Map<VirtualFile, VirtualFile> myCopyFromMap = new HashMap<VirtualFile, VirtualFile>(); protected final List<VcsException> myExceptions = new SmartList<VcsException>(); protected final List<FilePath> myDeletedFiles = new ArrayList<FilePath>(); protected final List<FilePath> myDeletedWithoutConfirmFiles = new ArrayList<FilePath>(); protected final List<MovedFileInfo> myMovedFiles = new ArrayList<MovedFileInfo>(); protected final List<VirtualFile> myDirtyFiles = new ArrayList<VirtualFile>(); protected enum VcsDeleteType {SILENT, CONFIRM, IGNORE} protected VcsVFSListener(@NotNull Project project, @NotNull AbstractVcs vcs) { myProject = project; myVcs = vcs; myChangeListManager = ChangeListManager.getInstance(project); myDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject); final MyVirtualFileAdapter myVFSListener = new MyVirtualFileAdapter(); final MyCommandAdapter myCommandListener = new MyCommandAdapter(); myVcsManager = ProjectLevelVcsManager.getInstance(project); myAddOption = myVcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.ADD, vcs); myRemoveOption = myVcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.REMOVE, vcs); VirtualFileManager.getInstance().addVirtualFileListener(myVFSListener, this); CommandProcessor.getInstance().addCommandListener(myCommandListener, this); myVcsFileListenerContextHelper = VcsFileListenerContextHelper.getInstance(myProject); } @Override public void dispose() { } protected boolean isEventIgnored(final VirtualFileEvent event, boolean putInDirty) { if (event.isFromRefresh()) return true; boolean vcsIgnored = !isUnderMyVcs(event.getFile()); if (vcsIgnored) { myDirtyFiles.add(event.getFile()); } return vcsIgnored; } private boolean isUnderMyVcs(VirtualFile file) { return myVcsManager.getVcsFor(file) == myVcs && myVcsManager.isFileInContent(file) && !myChangeListManager.isIgnoredFile(file); } protected void executeAdd() { final List<VirtualFile> addedFiles = acquireAddedFiles(); LOG.debug("executeAdd. addedFiles: " + addedFiles); for (Iterator<VirtualFile> iterator = addedFiles.iterator(); iterator.hasNext(); ) { VirtualFile file = iterator.next(); if (myVcsFileListenerContextHelper.isAdditionIgnored(file)) { iterator.remove(); } } final Map<VirtualFile, VirtualFile> copyFromMap = acquireCopiedFiles(); if (! addedFiles.isEmpty()) { executeAdd(addedFiles, copyFromMap); } } /** * @return get map of copied files and clear the map */ protected Map<VirtualFile, VirtualFile> acquireCopiedFiles() { final Map<VirtualFile, VirtualFile> copyFromMap = new HashMap<VirtualFile, VirtualFile>(myCopyFromMap); myCopyFromMap.clear(); return copyFromMap; } /** * @return get list of added files and clear previous list */ protected List<VirtualFile> acquireAddedFiles() { final List<VirtualFile> addedFiles = new ArrayList<VirtualFile>(myAddedFiles); myAddedFiles.clear(); return addedFiles; } /** * Execute add that performs adding from specific collections * * @param addedFiles the added files * @param copyFromMap the copied files */ protected void executeAdd(List<VirtualFile> addedFiles, Map<VirtualFile, VirtualFile> copyFromMap) { LOG.debug("executeAdd. add-option: " + myAddOption.getValue() + ", files to add: " + addedFiles); if (myAddOption.getValue() == VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY) return; if (myAddOption.getValue() == VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY) { performAdding(addedFiles, copyFromMap); } else { final AbstractVcsHelper helper = AbstractVcsHelper.getInstance(myProject); // TODO[yole]: nice and clean description label Collection<VirtualFile> filesToProcess = helper.selectFilesToProcess(addedFiles, getAddTitle(), null, getSingleFileAddTitle(), getSingleFileAddPromptTemplate(), myAddOption); if (filesToProcess != null) { performAdding(new ArrayList<VirtualFile>(filesToProcess), copyFromMap); } } } private void addFileToDelete(VirtualFile file) { if (file.isDirectory() && file instanceof NewVirtualFile && !isDirectoryVersioningSupported()) { for (VirtualFile child : ((NewVirtualFile)file).getCachedChildren()) { addFileToDelete(child); } } else { final VcsDeleteType type = needConfirmDeletion(file); final FilePath filePath = VcsContextFactory.SERVICE.getInstance().createFilePathOnDeleted(new File(file.getPath()), file.isDirectory()); if (type == VcsDeleteType.CONFIRM) { myDeletedFiles.add(filePath); } else if (type == VcsDeleteType.SILENT) { myDeletedWithoutConfirmFiles.add(filePath); } } } protected void executeDelete() { final List<FilePath> filesToDelete = new ArrayList<FilePath>(myDeletedWithoutConfirmFiles); final List<FilePath> deletedFiles = new ArrayList<FilePath>(myDeletedFiles); myDeletedWithoutConfirmFiles.clear(); myDeletedFiles.clear(); for (Iterator<FilePath> iterator = filesToDelete.iterator(); iterator.hasNext(); ) { FilePath file = iterator.next(); if (myVcsFileListenerContextHelper.isDeletionIgnored(file)) { iterator.remove(); } } for (Iterator<FilePath> iterator = deletedFiles.iterator(); iterator.hasNext(); ) { FilePath file = iterator.next(); if (myVcsFileListenerContextHelper.isDeletionIgnored(file)) { iterator.remove(); } } if (deletedFiles.isEmpty() &&filesToDelete.isEmpty()) return; if (myRemoveOption.getValue() != VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY) { if (myRemoveOption.getValue() == VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY || deletedFiles.isEmpty()) { filesToDelete.addAll(deletedFiles); } else { Collection<FilePath> filePaths = selectFilePathsToDelete(deletedFiles); if (filePaths != null) { filesToDelete.addAll(filePaths); } } } performDeletion(filesToDelete); } /** * Select file paths to delete * * @param deletedFiles deleted files set * @return selected files or null (that is considered as empty file set) */ @Nullable protected Collection<FilePath> selectFilePathsToDelete(final List<FilePath> deletedFiles) { AbstractVcsHelper helper = AbstractVcsHelper.getInstance(myProject); return helper.selectFilePathsToProcess(deletedFiles, getDeleteTitle(), null, getSingleFileDeleteTitle(), getSingleFileDeletePromptTemplate(), myRemoveOption); } protected void beforeContentsChange(VirtualFileEvent event, VirtualFile file) { } protected void fileAdded(VirtualFileEvent event, VirtualFile file) { if (!isEventIgnored(event, true) && !myChangeListManager.isIgnoredFile(file) && (isDirectoryVersioningSupported() || !file.isDirectory())) { LOG.debug("Adding [" + file.getPresentableUrl() + "] to added files"); myAddedFiles.add(event.getFile()); } } private void addFileToMove(final VirtualFile file, final String newParentPath, final String newName) { if (file.isDirectory() && !file.is(VFileProperty.SYMLINK) && !isDirectoryVersioningSupported()) { @SuppressWarnings("UnsafeVfsRecursion") VirtualFile[] children = file.getChildren(); if (children != null) { for (VirtualFile child : children) { addFileToMove(child, newParentPath + "/" + newName, child.getName()); } } } else { processMovedFile(file, newParentPath, newName); } } protected boolean filterOutUnknownFiles() { return true; } protected void processMovedFile(VirtualFile file, String newParentPath, String newName) { final FileStatus status = FileStatusManager.getInstance(myProject).getStatus(file); LOG.debug("Checking moved file " + file + "; status=" + status); if (status == FileStatus.IGNORED) { if (file.getParent() != null) { myDirtyFiles.add(file.getParent()); myDirtyFiles.add(file); // will be at new path } } if (!(filterOutUnknownFiles() && status == FileStatus.UNKNOWN) && status != FileStatus.IGNORED) { final String newPath = newParentPath + "/" + newName; boolean foundExistingInfo = false; for (MovedFileInfo info : myMovedFiles) { if (Comparing.equal(info.myFile, file)) { info.myNewPath = newPath; foundExistingInfo = true; break; } } if (!foundExistingInfo) { LOG.debug("Registered moved file " + file); myMovedFiles.add(new MovedFileInfo(file, newPath)); } } } private void executeMoveRename() { final List<MovedFileInfo> movedFiles = new ArrayList<MovedFileInfo>(myMovedFiles); LOG.debug("executeMoveRename " + movedFiles); myMovedFiles.clear(); performMoveRename(movedFiles); } protected VcsDeleteType needConfirmDeletion(final VirtualFile file) { return VcsDeleteType.CONFIRM; } protected abstract String getAddTitle(); protected abstract String getSingleFileAddTitle(); protected abstract String getSingleFileAddPromptTemplate(); protected abstract void performAdding(final Collection<VirtualFile> addedFiles, final Map<VirtualFile, VirtualFile> copyFromMap) ; protected abstract String getDeleteTitle(); protected abstract String getSingleFileDeleteTitle(); protected abstract String getSingleFileDeletePromptTemplate(); protected abstract void performDeletion(List<FilePath> filesToDelete); protected abstract void performMoveRename(List<MovedFileInfo> movedFiles); protected abstract boolean isDirectoryVersioningSupported(); private class MyVirtualFileAdapter extends VirtualFileAdapter { @Override public void fileCreated(@NotNull final VirtualFileEvent event) { VirtualFile file = event.getFile(); LOG.debug("fileCreated: " + file.getPresentableUrl()); if (isUnderMyVcs(file)) { fileAdded(event, file); } } @Override public void fileCopied(@NotNull final VirtualFileCopyEvent event) { if (isEventIgnored(event, true) || myChangeListManager.isIgnoredFile(event.getFile())) return; final AbstractVcs oldVcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(event.getOriginalFile()); if (oldVcs == myVcs) { final VirtualFile parent = event.getFile().getParent(); if (parent != null) { myAddedFiles.add(event.getFile()); myCopyFromMap.put(event.getFile(), event.getOriginalFile()); } } else { myAddedFiles.add(event.getFile()); } } @Override public void beforeFileDeletion(@NotNull final VirtualFileEvent event) { final VirtualFile file = event.getFile(); if (isEventIgnored(event, true)) { return; } if (!myChangeListManager.isIgnoredFile(file)) { addFileToDelete(file); return; } // files are ignored, directories are handled recursively if (event.getFile().isDirectory()) { final List<VirtualFile> list = new LinkedList<VirtualFile>(); VcsUtil.collectFiles(file, list, true, isDirectoryVersioningSupported()); for (VirtualFile child : list) { if (!myChangeListManager.isIgnoredFile(child)) { addFileToDelete(child); } } } } @Override public void beforeFileMovement(@NotNull final VirtualFileMoveEvent event) { if (isEventIgnored(event, true)) return; final VirtualFile file = event.getFile(); final AbstractVcs newVcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(event.getNewParent()); LOG.debug("beforeFileMovement " + event + " into " + newVcs); if (newVcs == myVcs) { addFileToMove(file, event.getNewParent().getPath(), file.getName()); } else { addFileToDelete(event.getFile()); } } @Override public void fileMoved(@NotNull final VirtualFileMoveEvent event) { if (isEventIgnored(event, true)) return; final AbstractVcs oldVcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(event.getOldParent()); if (oldVcs != myVcs) { myAddedFiles.add(event.getFile()); } } @Override public void beforePropertyChange(@NotNull final VirtualFilePropertyEvent event) { if (!isEventIgnored(event, false) && event.getPropertyName().equalsIgnoreCase(VirtualFile.PROP_NAME)) { LOG.debug("before file rename " + event); String oldName = (String)event.getOldValue(); String newName = (String)event.getNewValue(); // in order to force a reparse of a file, the rename event can be fired with old name equal to new name - // such events needn't be handled by the VCS if (!Comparing.equal(oldName, newName)) { final VirtualFile file = event.getFile(); final VirtualFile parent = file.getParent(); if (parent != null) { addFileToMove(file, parent.getPath(), newName); } } } } @Override public void beforeContentsChange(@NotNull VirtualFileEvent event) { VirtualFile file = event.getFile(); assert !file.isDirectory(); if (isUnderMyVcs(file)) { VcsVFSListener.this.beforeContentsChange(event, file); } } } private class MyCommandAdapter extends CommandAdapter { private int myCommandLevel; @Override public void commandStarted(final CommandEvent event) { if (myProject != event.getProject()) return; myCommandLevel++; } private void checkMovedAddedSourceBack() { if (myAddedFiles.isEmpty() || myMovedFiles.isEmpty()) return; final Map<String, VirtualFile> addedPaths = new HashMap<String, VirtualFile>(myAddedFiles.size()); for (VirtualFile file : myAddedFiles) { addedPaths.put(file.getPath(), file); } for (Iterator<MovedFileInfo> iterator = myMovedFiles.iterator(); iterator.hasNext();) { final MovedFileInfo movedFile = iterator.next(); if (addedPaths.containsKey(movedFile.myOldPath)) { iterator.remove(); final VirtualFile oldAdded = addedPaths.get(movedFile.myOldPath); myAddedFiles.remove(oldAdded); myAddedFiles.add(movedFile.myFile); myCopyFromMap.put(oldAdded, movedFile.myFile); } } } // If a file is scheduled for deletion, and at the same time for copying or addition, don't delete it. // It happens during Overwrite command or undo of overwrite. private void doNotDeleteAddedCopiedOrMovedFiles() { Collection<String> copiedAddedMoved = new ArrayList<String>(); for (VirtualFile file : myCopyFromMap.keySet()) { copiedAddedMoved.add(file.getPath()); } for (VirtualFile file : myAddedFiles) { copiedAddedMoved.add(file.getPath()); } for (MovedFileInfo movedFileInfo : myMovedFiles) { copiedAddedMoved.add(movedFileInfo.myNewPath); } for (Iterator<FilePath> iterator = myDeletedFiles.iterator(); iterator.hasNext(); ) { if (copiedAddedMoved.contains(FileUtil.toSystemIndependentName(iterator.next().getPath()))) { iterator.remove(); } } for (Iterator<FilePath> iterator = myDeletedWithoutConfirmFiles.iterator(); iterator.hasNext(); ) { if (copiedAddedMoved.contains(FileUtil.toSystemIndependentName(iterator.next().getPath()))) { iterator.remove(); } } } @Override public void commandFinished(final CommandEvent event) { if (myProject != event.getProject()) return; myCommandLevel--; if (myCommandLevel == 0) { if (!myAddedFiles.isEmpty() || !myDeletedFiles.isEmpty() || !myDeletedWithoutConfirmFiles.isEmpty() || !myMovedFiles.isEmpty() || ! myDirtyFiles.isEmpty()) { // avoid reentering commandFinished handler - saving the documents may cause a "before file deletion" event firing, // which will cause closing the text editor, which will itself run a command that will be caught by this listener myCommandLevel++; try { FileDocumentManager.getInstance().saveAllDocuments(); } finally { myCommandLevel--; } doNotDeleteAddedCopiedOrMovedFiles(); checkMovedAddedSourceBack(); if (!myAddedFiles.isEmpty()) { executeAdd(); myAddedFiles.clear(); } if (!myDeletedFiles.isEmpty() || !myDeletedWithoutConfirmFiles.isEmpty()) { executeDelete(); myDeletedFiles.clear(); myDeletedWithoutConfirmFiles.clear(); } if (!myMovedFiles.isEmpty()) { executeMoveRename(); myMovedFiles.clear(); } if (! myDirtyFiles.isEmpty()) { final List<VirtualFile> files = new ArrayList<VirtualFile>(); final List<VirtualFile> dirs = new ArrayList<VirtualFile>(); for (VirtualFile dirtyFile : myDirtyFiles) { if (dirtyFile != null) { if (dirtyFile.isDirectory()) { dirs.add(dirtyFile); } else { files.add(dirtyFile); } } } myDirtyScopeManager.filesDirty(files, dirs); myDirtyFiles.clear(); } if (! myExceptions.isEmpty()) { AbstractVcsHelper.getInstance(myProject).showErrors(myExceptions, myVcs.getDisplayName() + " operations errors"); } } } } } }
don't repeatedly mark duplicate files dirty (IDEA-132648)
platform/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java
don't repeatedly mark duplicate files dirty (IDEA-132648)
Java
apache-2.0
7364fb3c24d98df925de48b862bc9b48aedc75dd
0
ProjectKaiser/pk-vcs-test
package org.scm4j.vcs.api.abstracttest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.util.List; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.exceptions.verification.WantedButNotInvoked; import org.scm4j.vcs.api.*; import org.scm4j.vcs.api.exceptions.EVCSBranchExists; import org.scm4j.vcs.api.exceptions.EVCSFileNotFound; import org.scm4j.vcs.api.workingcopy.IVCSLockedWorkingCopy; import org.scm4j.vcs.api.workingcopy.IVCSRepositoryWorkspace; import org.scm4j.vcs.api.workingcopy.IVCSWorkspace; import org.scm4j.vcs.api.workingcopy.VCSWorkspace; public abstract class VCSAbstractTest { private static final String WORKSPACE_DIR = System.getProperty("java.io.tmpdir") + "scm4j-vcs-workspaces"; private static final String NEW_BRANCH = "new-branch"; private static final String NEW_BRANCH_2 = "new-branch-2"; private static final String CREATED_DST_BRANCH_COMMIT_MESSAGE = "created dst branch"; private static final String DELETE_BRANCH_COMMIT_MESSAGE = "deleted"; private static final String FILE1_NAME = "file1.txt"; private static final String FILE2_NAME = "file2.txt"; private static final String FILE3_IN_FOLDER_NAME = "folder/file3.txt"; private static final String MOD_FILE_NAME = "mod file.txt"; private static final String FILE1_ADDED_COMMIT_MESSAGE = FILE1_NAME + " file added"; private static final String FILE2_ADDED_COMMIT_MESSAGE = FILE2_NAME + " file added"; private static final String FILE3_ADDED_COMMIT_MESSAGE = FILE3_IN_FOLDER_NAME + " file added"; private static final String MOD_FILE_ADDED_COMMIT_MESSAGE = MOD_FILE_NAME + " file added"; private static final String FILE1_CONTENT_CHANGED_COMMIT_MESSAGE = FILE1_NAME + " content changed"; private static final String MOD_FILE_CONTENT_CHANGED_COMMIT_MESSAGE = MOD_FILE_NAME + " content changed"; private static final String MERGE_COMMIT_MESSAGE = "merged."; private static final String LINE_1 = "line 1"; private static final String LINE_2 = "line 2"; private static final String LINE_3 = "line 3"; private static final String MOD_LINE_1= "original line"; private static final String MOD_LINE_2= "modified line"; private static final String CONTENT_CHANGED_COMMIT_MESSAGE = "content changed"; private static final String FILE2_REMOVED_COMMIT_MESSAGE = FILE2_NAME + " removed"; private static final Integer DEFAULT_COMMITS_LIMIT = 100; protected String repoName; protected String repoUrl; protected IVCSWorkspace localVCSWorkspace; protected IVCSRepositoryWorkspace localVCSRepo; protected IVCSRepositoryWorkspace mockedVCSRepo; protected IVCSLockedWorkingCopy mockedLWC; protected IVCS vcs; public IVCS getVcs() { return vcs; } public void setVcs(IVCS vcs) { this.vcs = vcs; } @After public void setUpAndTearDown() throws Exception { mockedLWC.close(); FileUtils.deleteDirectory(new File(WORKSPACE_DIR)); } @Before public void setUp() throws Exception { FileUtils.deleteDirectory(new File(WORKSPACE_DIR)); repoName = "scm4j-vcs-" + getVCSTypeString() + "-testrepo"; String uuid = UUID.randomUUID().toString(); repoName = (repoName + "_" + uuid); localVCSWorkspace = new VCSWorkspace(WORKSPACE_DIR); repoUrl = getTestRepoUrl() + repoName; localVCSRepo = localVCSWorkspace.getVCSRepositoryWorkspace(repoUrl); mockedVCSRepo = Mockito.spy(localVCSWorkspace.getVCSRepositoryWorkspace(repoUrl)); vcs = getVCS(mockedVCSRepo); resetMocks(); setMakeFailureOnVCSReset(false); } protected void resetMocks() throws Exception { if (mockedLWC != null) { mockedLWC.close(); } Mockito.reset(mockedVCSRepo); mockedLWC = Mockito.spy(localVCSRepo.getVCSLockedWorkingCopy()); Mockito.doReturn(mockedLWC).when(mockedVCSRepo).getVCSLockedWorkingCopy(); } @Test public void testCreateAndDeleteBranch() throws Exception { vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_1, FILE3_ADDED_COMMIT_MESSAGE); resetMocks(); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); verifyMocks(); assertTrue(vcs.getBranches().contains(NEW_BRANCH)); verifyMocks(); assertTrue(vcs.getBranches().size() == 2); // Master + NEW_BRANCH, no Folder verifyMocks(); assertTrue(vcs.getFileContent(NEW_BRANCH, FILE3_IN_FOLDER_NAME).equals(LINE_1)); resetMocks(); vcs.createBranch(NEW_BRANCH, NEW_BRANCH_2, CREATED_DST_BRANCH_COMMIT_MESSAGE); verifyMocks(); assertTrue(vcs.getBranches().contains(NEW_BRANCH)); verifyMocks(); assertTrue(vcs.getBranches().contains(NEW_BRANCH_2)); verifyMocks(); assertTrue(vcs.getBranches().size() == 3); verifyMocks(); try { vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); fail("\"Branch exists\" situation not detected"); } catch (EVCSBranchExists e) { } resetMocks(); vcs.deleteBranch(NEW_BRANCH, DELETE_BRANCH_COMMIT_MESSAGE); verifyMocks(); assertTrue(vcs.getBranches().size() == 2); } private void verifyMocks() throws Exception { try { Mockito.verify(mockedVCSRepo).getVCSLockedWorkingCopy(); } catch (WantedButNotInvoked e) { resetMocks(); return; } Mockito.verify(mockedLWC).close(); resetMocks(); } @Test public void testGetSetFileContent() throws Exception { vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_1, FILE3_ADDED_COMMIT_MESSAGE); verifyMocks(); assertTrue(vcs.getCommitMessages(null, DEFAULT_COMMITS_LIMIT).contains(FILE3_ADDED_COMMIT_MESSAGE)); verifyMocks(); assertEquals(vcs.getFileContent(null, FILE3_IN_FOLDER_NAME), LINE_1); verifyMocks(); assertEquals(vcs.getFileContent(null, FILE3_IN_FOLDER_NAME, "UTF-8"), LINE_1); verifyMocks(); vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_2, CONTENT_CHANGED_COMMIT_MESSAGE); assertEquals(vcs.getFileContent(null, FILE3_IN_FOLDER_NAME), LINE_2); assertEquals(vcs.getFileContent(null, FILE3_IN_FOLDER_NAME, "UTF-8"), LINE_2); try { vcs.getFileContent(null, "sdfsdf1.txt"); fail("EVCSFileNotFound is not thrown"); } catch (EVCSFileNotFound e) { } } @Test public void testMerge() throws Exception { vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE2_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE); resetMocks(); VCSMergeResult res = vcs.merge(NEW_BRANCH, null, MERGE_COMMIT_MESSAGE); verifyMocks(); assertFalse(mockedLWC.getCorrupted()); assertTrue(res.getSuccess()); assertTrue(res.getConflictingFiles().size() == 0); String content = vcs.getFileContent(null, FILE1_NAME); assertEquals(content, LINE_1); content = vcs.getFileContent(null, FILE2_NAME); assertEquals(content, LINE_2); } @Test public void testMergeConflict() { vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE1_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE); VCSMergeResult res = vcs.merge(NEW_BRANCH, null, MERGE_COMMIT_MESSAGE); assertFalse(res.getSuccess()); assertFalse(mockedLWC.getCorrupted()); assertTrue(res.getConflictingFiles().size() == 1); assertTrue(res.getConflictingFiles().contains(FILE1_NAME)); } @Test public void testMergeConflictWCCorruption() throws Exception { vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE1_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE); resetMocks(); setMakeFailureOnVCSReset(true); VCSMergeResult res = vcs.merge(NEW_BRANCH, null, MERGE_COMMIT_MESSAGE); assertFalse(res.getSuccess()); assertTrue(mockedLWC.getCorrupted()); assertTrue(res.getConflictingFiles().size() == 1); assertTrue(res.getConflictingFiles().contains(FILE1_NAME)); assertFalse(mockedLWC.getFolder().exists()); assertFalse(mockedLWC.getLockFile().exists()); } @Test public void testBranchesDiff() throws Exception { /** * Master Branch * f1- * | f2- * | mfm * | mf+ (merge) * | / * mf+ * | tf+ (merge) * | / | * tf+ f1m * | f3+ * f2+ / * f1+ * * Result should be: f3+, f1+, f2-, mfm. * But: Result of merge operation for f1 is missing file even by TortouiseSVN */ vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(null, FILE2_NAME, LINE_1, FILE2_ADDED_COMMIT_MESSAGE); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE3_IN_FOLDER_NAME, LINE_2, FILE3_ADDED_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE1_NAME, LINE_3, FILE1_CONTENT_CHANGED_COMMIT_MESSAGE); vcs.setFileContent(null, "trunk file.txt", "dfdfsdf", "trunk file added"); vcs.setFileContent(null, MOD_FILE_NAME, MOD_LINE_1, MOD_FILE_ADDED_COMMIT_MESSAGE); vcs.merge(null, NEW_BRANCH, MERGE_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, MOD_FILE_NAME, MOD_LINE_2, MOD_FILE_CONTENT_CHANGED_COMMIT_MESSAGE); vcs.merge(null, NEW_BRANCH, "merged from trunk"); vcs.removeFile(NEW_BRANCH, FILE2_NAME, FILE2_REMOVED_COMMIT_MESSAGE); vcs.removeFile(null, FILE1_NAME, "file1 removed"); //vcs.setFileContent(null, "folder/file 2 in folder.txt", "file 2 in folder line", "conflicting folder added"); vcs.setFileContent(null, "moved file trunk.txt", "file 2 in folder line", "moved file added"); //vcs.merge(null, NEW_BRANCH, "merged moved file trunk.txt from trunk"); resetMocks(); List<VCSDiffEntry> diffs = vcs.getBranchesDiff(NEW_BRANCH, null); verifyMocks(); assertNotNull(diffs); VCSDiffEntry diff; diff = getEntryDiffForFile(diffs, FILE3_IN_FOLDER_NAME); assertNotNull(diff); assertTrue(diff.getChangeType() == VCSChangeType.ADD); assertTrue(diff.getUnifiedDiff().contains("+" + LINE_2)); diff = getEntryDiffForFile(diffs, MOD_FILE_NAME); assertNotNull(diff); assertTrue(diff.getChangeType() == VCSChangeType.MODIFY); assertTrue(diff.getUnifiedDiff().contains("-" + MOD_LINE_1)); assertTrue(diff.getUnifiedDiff().contains("+" + MOD_LINE_2)); diff = getEntryDiffForFile(diffs, FILE1_NAME); assertNotNull(diff); assertTrue(diff.getChangeType() == VCSChangeType.ADD); assertTrue(diff.getUnifiedDiff().contains("+" + LINE_3)); diff = getEntryDiffForFile(diffs, FILE2_NAME); assertNotNull(diff); assertTrue(diff.getChangeType() == VCSChangeType.DELETE); assertTrue(diff.getUnifiedDiff().contains("-" + LINE_1)); } private VCSDiffEntry getEntryDiffForFile(List<VCSDiffEntry> entries, String filePath) { for (VCSDiffEntry entry : entries) { if (entry.getFilePath().equals(filePath)) { return entry; } } return null; } @Test public void testRemoveFile() throws Exception { vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_1, FILE3_ADDED_COMMIT_MESSAGE); resetMocks(); vcs.removeFile(null, FILE3_IN_FOLDER_NAME, FILE2_REMOVED_COMMIT_MESSAGE); verifyMocks(); try { vcs.getFileContent(null, FILE3_IN_FOLDER_NAME); fail(); } catch (EVCSFileNotFound e) { } List<String> commits = vcs.getCommitMessages(null, DEFAULT_COMMITS_LIMIT); assertTrue(commits.contains(FILE2_REMOVED_COMMIT_MESSAGE)); } @Test public void testGetCommitMessages() throws Exception { vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_3, FILE3_ADDED_COMMIT_MESSAGE); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE2_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE); resetMocks(); List<String> commits = vcs.getCommitMessages(null, DEFAULT_COMMITS_LIMIT); verifyMocks(); assertTrue(commits.contains(FILE1_ADDED_COMMIT_MESSAGE)); assertTrue(commits.contains(FILE3_ADDED_COMMIT_MESSAGE)); commits = vcs.getCommitMessages(null, 1); assertFalse(commits.contains(FILE1_ADDED_COMMIT_MESSAGE)); commits = vcs.getCommitMessages(NEW_BRANCH, DEFAULT_COMMITS_LIMIT); assertTrue(commits.contains(FILE2_ADDED_COMMIT_MESSAGE)); } @Test public void testGetCommitsRange() throws Exception { /** * Master Branch * * f11+ * f2+ * f5+ | * f4+ | * | / * f3+ * f1+ */ String c1 = vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE).getRevision(); String c3 = vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_3, FILE3_ADDED_COMMIT_MESSAGE).getRevision(); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); String c4 = vcs.setFileContent(null, "file 4.txt", "dfdfsdf", "File 4 master added").getRevision(); String c5 = vcs.setFileContent(null, "file 5.txt", "dfdfsdf", "File 5 master added").getRevision(); String c2 = vcs.setFileContent(NEW_BRANCH, FILE2_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE).getRevision(); String c11 = vcs.setFileContent(NEW_BRANCH, FILE1_NAME, LINE_2, "file 1 branch added").getRevision(); resetMocks(); List<VCSCommit> commits = vcs.getCommitsRange(null, c1, null); verifyMocks(); assertTrue(commitsConsistsOfIds(commits, c3, c4, c5)); commits = vcs.getCommitsRange(null, null, null); assertTrue(commitsConsistsOfIds(commits, c3, c4, c5)); commits = vcs.getCommitsRange(NEW_BRANCH, c1, null); assertTrue(commitsContainsIds(commits, c2, c11)); commits = vcs.getCommitsRange(null, c1, c4); assertTrue(commitsConsistsOfIds(commits, c3, c4)); resetMocks(); commits = vcs.getCommitsRange(null, c1, WalkDirection.ASC, 0); verifyMocks(); assertTrue(commitsContainsSequenceOfIds(commits, c1, c3, c4, c5)); commits = vcs.getCommitsRange(null, c1, WalkDirection.ASC, 2); verifyMocks(); assertTrue(commitsContainsSequenceOfIds(commits, c1, c3)); assertTrue(commits.get(0).getRevision().equals(c1)); commits = vcs.getCommitsRange(null, null, WalkDirection.ASC, 0); assertTrue(commitsContainsSequenceOfIds(commits, c1, c3, c4, c5)); commits = vcs.getCommitsRange(NEW_BRANCH, c1, WalkDirection.ASC, 0); assertTrue(commitsContainsSequenceOfIds(commits, c2, c11)); commits = vcs.getCommitsRange(null, c5, WalkDirection.DESC, 0); verifyMocks(); assertTrue(commitsContainsSequenceOfIds(commits, c5, c4, c3, c1)); commits = vcs.getCommitsRange(null, c1, WalkDirection.DESC, 1); verifyMocks(); assertTrue(commits.get(0).getRevision().equals(c1)); commits = vcs.getCommitsRange(null, null, WalkDirection.DESC, 0); assertTrue(commitsContainsSequenceOfIds(commits, c5, c4, c3, c1)); assertTrue(commits.get(0).getRevision().equals(c5)); commits = vcs.getCommitsRange(NEW_BRANCH, c11, WalkDirection.DESC, 0); assertTrue(commitsContainsSequenceOfIds(commits, c11, c2)); assertTrue(commits.get(0).getRevision().equals(c11)); } @Test public void testGetHeadCommit() { VCSCommit commit1 = vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); VCSCommit commit2 = vcs.setFileContent(null, FILE2_NAME, LINE_1, FILE2_ADDED_COMMIT_MESSAGE); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); VCSCommit commit3 = vcs.setFileContent(NEW_BRANCH, FILE3_IN_FOLDER_NAME, LINE_2, FILE3_ADDED_COMMIT_MESSAGE); assertTrue(vcs.getHeadCommit(null).equals(commit2)); assertTrue(vcs.getHeadCommit(NEW_BRANCH).equals(commit3)); } private Boolean commitsContainsIds(List<VCSCommit> commits, String... ids) { if (commits.size() == 0 || ids.length == 0) { return false; } Integer count = 0; for (String id : ids) { for(VCSCommit commit : commits) { if (commit.getRevision().equals(id)) { count++; break; } } } return count == ids.length; } private Boolean commitsContainsSequenceOfIds(List<VCSCommit> commits,String... ids) { if (commits.size() == 0 || ids.length == 0) { return false; } Integer idIndex = 0; for (VCSCommit commit : commits) { if (commit.getRevision().equals(ids[idIndex])) { idIndex++; } else if (idIndex != 0) { return false; } if (idIndex >= ids.length) { return true; } } return idIndex == ids.length; } private Boolean commitsConsistsOfIds(List<VCSCommit> commits, String... ids) { if (commits.size() == 0 || ids.length == 0) { return false; } Integer count = 0; Boolean found = false; for (String id : ids) { found = false; for(VCSCommit commit : commits) { if (commit.getRevision().equals(id)) { count++; found = true; break; } } if (!found) { return false; } } return count == ids.length; } protected abstract String getTestRepoUrl(); protected abstract IVCS getVCS(IVCSRepositoryWorkspace mockedVCSRepo); protected abstract void setMakeFailureOnVCSReset(Boolean doMakeFailure); protected abstract String getVCSTypeString(); }
src/main/java/org/scm4j/vcs/api/abstracttest/VCSAbstractTest.java
package org.scm4j.vcs.api.abstracttest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.util.List; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.exceptions.verification.WantedButNotInvoked; import org.scm4j.vcs.api.IVCS; import org.scm4j.vcs.api.VCSChangeType; import org.scm4j.vcs.api.VCSCommit; import org.scm4j.vcs.api.VCSDiffEntry; import org.scm4j.vcs.api.VCSMergeResult; import org.scm4j.vcs.api.exceptions.EVCSBranchExists; import org.scm4j.vcs.api.exceptions.EVCSFileNotFound; import org.scm4j.vcs.api.workingcopy.IVCSLockedWorkingCopy; import org.scm4j.vcs.api.workingcopy.IVCSRepositoryWorkspace; import org.scm4j.vcs.api.workingcopy.IVCSWorkspace; import org.scm4j.vcs.api.workingcopy.VCSWorkspace; public abstract class VCSAbstractTest { private static final String WORKSPACE_DIR = System.getProperty("java.io.tmpdir") + "scm4j-vcs-workspaces"; private static final String NEW_BRANCH = "new-branch"; private static final String NEW_BRANCH_2 = "new-branch-2"; private static final String CREATED_DST_BRANCH_COMMIT_MESSAGE = "created dst branch"; private static final String DELETE_BRANCH_COMMIT_MESSAGE = "deleted"; private static final String FILE1_NAME = "file1.txt"; private static final String FILE2_NAME = "file2.txt"; private static final String FILE3_IN_FOLDER_NAME = "folder/file3.txt"; private static final String MOD_FILE_NAME = "mod file.txt"; private static final String FILE1_ADDED_COMMIT_MESSAGE = FILE1_NAME + " file added"; private static final String FILE2_ADDED_COMMIT_MESSAGE = FILE2_NAME + " file added"; private static final String FILE3_ADDED_COMMIT_MESSAGE = FILE3_IN_FOLDER_NAME + " file added"; private static final String MOD_FILE_ADDED_COMMIT_MESSAGE = MOD_FILE_NAME + " file added"; private static final String FILE1_CONTENT_CHANGED_COMMIT_MESSAGE = FILE1_NAME + " content changed"; private static final String MOD_FILE_CONTENT_CHANGED_COMMIT_MESSAGE = MOD_FILE_NAME + " content changed"; private static final String MERGE_COMMIT_MESSAGE = "merged."; private static final String LINE_1 = "line 1"; private static final String LINE_2 = "line 2"; private static final String LINE_3 = "line 3"; private static final String MOD_LINE_1= "original line"; private static final String MOD_LINE_2= "modified line"; private static final String CONTENT_CHANGED_COMMIT_MESSAGE = "content changed"; private static final String FILE2_REMOVED_COMMIT_MESSAGE = FILE2_NAME + " removed"; private static final Integer DEFAULT_COMMITS_LIMIT = 100; protected String repoName; protected String repoUrl; protected IVCSWorkspace localVCSWorkspace; protected IVCSRepositoryWorkspace localVCSRepo; protected IVCSRepositoryWorkspace mockedVCSRepo; protected IVCSLockedWorkingCopy mockedLWC; protected IVCS vcs; public IVCS getVcs() { return vcs; } public void setVcs(IVCS vcs) { this.vcs = vcs; } @After public void setUpAndTearDown() throws Exception { mockedLWC.close(); FileUtils.deleteDirectory(new File(WORKSPACE_DIR)); } @Before public void setUp() throws Exception { FileUtils.deleteDirectory(new File(WORKSPACE_DIR)); repoName = "scm4j-vcs-" + getVCSTypeString() + "-testrepo"; String uuid = UUID.randomUUID().toString(); repoName = (repoName + "_" + uuid); localVCSWorkspace = new VCSWorkspace(WORKSPACE_DIR); repoUrl = getTestRepoUrl() + repoName; localVCSRepo = localVCSWorkspace.getVCSRepositoryWorkspace(repoUrl); mockedVCSRepo = Mockito.spy(localVCSWorkspace.getVCSRepositoryWorkspace(repoUrl)); vcs = getVCS(mockedVCSRepo); resetMocks(); setMakeFailureOnVCSReset(false); } protected void resetMocks() throws Exception { if (mockedLWC != null) { mockedLWC.close(); } Mockito.reset(mockedVCSRepo); mockedLWC = Mockito.spy(localVCSRepo.getVCSLockedWorkingCopy()); Mockito.doReturn(mockedLWC).when(mockedVCSRepo).getVCSLockedWorkingCopy(); } @Test public void testCreateAndDeleteBranch() throws Exception { vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_1, FILE3_ADDED_COMMIT_MESSAGE); resetMocks(); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); verifyMocks(); assertTrue(vcs.getBranches().contains(NEW_BRANCH)); verifyMocks(); assertTrue(vcs.getBranches().size() == 2); // Master + NEW_BRANCH, no Folder verifyMocks(); assertTrue(vcs.getFileContent(NEW_BRANCH, FILE3_IN_FOLDER_NAME).equals(LINE_1)); resetMocks(); vcs.createBranch(NEW_BRANCH, NEW_BRANCH_2, CREATED_DST_BRANCH_COMMIT_MESSAGE); verifyMocks(); assertTrue(vcs.getBranches().contains(NEW_BRANCH)); verifyMocks(); assertTrue(vcs.getBranches().contains(NEW_BRANCH_2)); verifyMocks(); assertTrue(vcs.getBranches().size() == 3); verifyMocks(); try { vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); fail("\"Branch exists\" situation not detected"); } catch (EVCSBranchExists e) { } resetMocks(); vcs.deleteBranch(NEW_BRANCH, DELETE_BRANCH_COMMIT_MESSAGE); verifyMocks(); assertTrue(vcs.getBranches().size() == 2); } private void verifyMocks() throws Exception { try { Mockito.verify(mockedVCSRepo).getVCSLockedWorkingCopy(); } catch (WantedButNotInvoked e) { resetMocks(); return; } Mockito.verify(mockedLWC).close(); resetMocks(); } @Test public void testGetSetFileContent() throws Exception { vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_1, FILE3_ADDED_COMMIT_MESSAGE); verifyMocks(); assertTrue(vcs.getCommitMessages(null, DEFAULT_COMMITS_LIMIT).contains(FILE3_ADDED_COMMIT_MESSAGE)); verifyMocks(); assertEquals(vcs.getFileContent(null, FILE3_IN_FOLDER_NAME), LINE_1); verifyMocks(); assertEquals(vcs.getFileContent(null, FILE3_IN_FOLDER_NAME, "UTF-8"), LINE_1); verifyMocks(); vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_2, CONTENT_CHANGED_COMMIT_MESSAGE); assertEquals(vcs.getFileContent(null, FILE3_IN_FOLDER_NAME), LINE_2); assertEquals(vcs.getFileContent(null, FILE3_IN_FOLDER_NAME, "UTF-8"), LINE_2); try { vcs.getFileContent(null, "sdfsdf1.txt"); fail("EVCSFileNotFound is not thrown"); } catch (EVCSFileNotFound e) { } } @Test public void testMerge() throws Exception { vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE2_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE); resetMocks(); VCSMergeResult res = vcs.merge(NEW_BRANCH, null, MERGE_COMMIT_MESSAGE); verifyMocks(); assertFalse(mockedLWC.getCorrupted()); assertTrue(res.getSuccess()); assertTrue(res.getConflictingFiles().size() == 0); String content = vcs.getFileContent(null, FILE1_NAME); assertEquals(content, LINE_1); content = vcs.getFileContent(null, FILE2_NAME); assertEquals(content, LINE_2); } @Test public void testMergeConflict() { vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE1_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE); VCSMergeResult res = vcs.merge(NEW_BRANCH, null, MERGE_COMMIT_MESSAGE); assertFalse(res.getSuccess()); assertFalse(mockedLWC.getCorrupted()); assertTrue(res.getConflictingFiles().size() == 1); assertTrue(res.getConflictingFiles().contains(FILE1_NAME)); } @Test public void testMergeConflictWCCorruption() throws Exception { vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE1_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE); resetMocks(); setMakeFailureOnVCSReset(true); VCSMergeResult res = vcs.merge(NEW_BRANCH, null, MERGE_COMMIT_MESSAGE); assertFalse(res.getSuccess()); assertTrue(mockedLWC.getCorrupted()); assertTrue(res.getConflictingFiles().size() == 1); assertTrue(res.getConflictingFiles().contains(FILE1_NAME)); assertFalse(mockedLWC.getFolder().exists()); assertFalse(mockedLWC.getLockFile().exists()); } @Test public void testBranchesDiff() throws Exception { /** * Master Branch * f1- * | f2- * | mfm * | mf+ (merge) * | / * mf+ * | tf+ (merge) * | / | * tf+ f1m * | f3+ * f2+ / * f1+ * * Result should be: f3+, f1+, f2-, mfm. * But: Result of merge operation for f1 is missing file even by TortouiseSVN */ vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(null, FILE2_NAME, LINE_1, FILE2_ADDED_COMMIT_MESSAGE); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE3_IN_FOLDER_NAME, LINE_2, FILE3_ADDED_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE1_NAME, LINE_3, FILE1_CONTENT_CHANGED_COMMIT_MESSAGE); vcs.setFileContent(null, "trunk file.txt", "dfdfsdf", "trunk file added"); vcs.setFileContent(null, MOD_FILE_NAME, MOD_LINE_1, MOD_FILE_ADDED_COMMIT_MESSAGE); vcs.merge(null, NEW_BRANCH, MERGE_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, MOD_FILE_NAME, MOD_LINE_2, MOD_FILE_CONTENT_CHANGED_COMMIT_MESSAGE); vcs.merge(null, NEW_BRANCH, "merged from trunk"); vcs.removeFile(NEW_BRANCH, FILE2_NAME, FILE2_REMOVED_COMMIT_MESSAGE); vcs.removeFile(null, FILE1_NAME, "file1 removed"); //vcs.setFileContent(null, "folder/file 2 in folder.txt", "file 2 in folder line", "conflicting folder added"); vcs.setFileContent(null, "moved file trunk.txt", "file 2 in folder line", "moved file added"); //vcs.merge(null, NEW_BRANCH, "merged moved file trunk.txt from trunk"); resetMocks(); List<VCSDiffEntry> diffs = vcs.getBranchesDiff(NEW_BRANCH, null); verifyMocks(); assertNotNull(diffs); VCSDiffEntry diff; diff = getEntryDiffForFile(diffs, FILE3_IN_FOLDER_NAME); assertNotNull(diff); assertTrue(diff.getChangeType() == VCSChangeType.ADD); assertTrue(diff.getUnifiedDiff().contains("+" + LINE_2)); diff = getEntryDiffForFile(diffs, MOD_FILE_NAME); assertNotNull(diff); assertTrue(diff.getChangeType() == VCSChangeType.MODIFY); assertTrue(diff.getUnifiedDiff().contains("-" + MOD_LINE_1)); assertTrue(diff.getUnifiedDiff().contains("+" + MOD_LINE_2)); diff = getEntryDiffForFile(diffs, FILE1_NAME); assertNotNull(diff); assertTrue(diff.getChangeType() == VCSChangeType.ADD); assertTrue(diff.getUnifiedDiff().contains("+" + LINE_3)); diff = getEntryDiffForFile(diffs, FILE2_NAME); assertNotNull(diff); assertTrue(diff.getChangeType() == VCSChangeType.DELETE); assertTrue(diff.getUnifiedDiff().contains("-" + LINE_1)); } private VCSDiffEntry getEntryDiffForFile(List<VCSDiffEntry> entries, String filePath) { for (VCSDiffEntry entry : entries) { if (entry.getFilePath().equals(filePath)) { return entry; } } return null; } @Test public void testRemoveFile() throws Exception { vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_1, FILE3_ADDED_COMMIT_MESSAGE); resetMocks(); vcs.removeFile(null, FILE3_IN_FOLDER_NAME, FILE2_REMOVED_COMMIT_MESSAGE); verifyMocks(); try { vcs.getFileContent(null, FILE3_IN_FOLDER_NAME); fail(); } catch (EVCSFileNotFound e) { } List<String> commits = vcs.getCommitMessages(null, DEFAULT_COMMITS_LIMIT); assertTrue(commits.contains(FILE2_REMOVED_COMMIT_MESSAGE)); } @Test public void testGetCommitMessages() throws Exception { vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE); vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_3, FILE3_ADDED_COMMIT_MESSAGE); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); vcs.setFileContent(NEW_BRANCH, FILE2_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE); resetMocks(); List<String> commits = vcs.getCommitMessages(null, DEFAULT_COMMITS_LIMIT); verifyMocks(); assertTrue(commits.contains(FILE1_ADDED_COMMIT_MESSAGE)); assertTrue(commits.contains(FILE3_ADDED_COMMIT_MESSAGE)); commits = vcs.getCommitMessages(null, 1); assertFalse(commits.contains(FILE1_ADDED_COMMIT_MESSAGE)); commits = vcs.getCommitMessages(NEW_BRANCH, DEFAULT_COMMITS_LIMIT); assertTrue(commits.contains(FILE2_ADDED_COMMIT_MESSAGE)); } @Test public void testGetCommitsRange() throws Exception { /** * Master Branch * * f11+ * f2+ * f5+ | * f4+ | * | / * f3+ * f1+ */ String c1 = vcs.setFileContent(null, FILE1_NAME, LINE_1, FILE1_ADDED_COMMIT_MESSAGE).getRevision(); String c3 = vcs.setFileContent(null, FILE3_IN_FOLDER_NAME, LINE_3, FILE3_ADDED_COMMIT_MESSAGE).getRevision(); vcs.createBranch(null, NEW_BRANCH, CREATED_DST_BRANCH_COMMIT_MESSAGE); String c4 = vcs.setFileContent(null, "file 4.txt", "dfdfsdf", "File 4 master added").getRevision(); String c5 = vcs.setFileContent(null, "file 5.txt", "dfdfsdf", "File 5 master added").getRevision(); String c2 = vcs.setFileContent(NEW_BRANCH, FILE2_NAME, LINE_2, FILE2_ADDED_COMMIT_MESSAGE).getRevision(); String c11 = vcs.setFileContent(NEW_BRANCH, FILE1_NAME, LINE_2, "file 1 branch added").getRevision(); resetMocks(); List<VCSCommit> commits = vcs.getCommitsRange(null, c1, null); verifyMocks(); assertTrue(commitsConsistsOfIds(commits, c3, c4, c5)); commits = vcs.getCommitsRange(null, null, null); assertTrue(commitsConsistsOfIds(commits, c3, c4, c5)); commits = vcs.getCommitsRange(NEW_BRANCH, c1, null); assertTrue(commitsContainsIds(commits, c2, c11)); commits = vcs.getCommitsRange(null, c1, c4); assertTrue(commitsConsistsOfIds(commits, c3, c4)); } private Boolean commitsContainsIds(List<VCSCommit> commits, String... ids) { if (commits.size() == 0 || ids.length == 0) { return false; } Integer count = 0; for (String id : ids) { for(VCSCommit commit : commits) { if (commit.getRevision().equals(id)) { count++; break; } } } return count == ids.length; } private Boolean commitsConsistsOfIds(List<VCSCommit> commits, String... ids) { if (commits.size() == 0 || ids.length == 0) { return false; } Integer count = 0; Boolean found = false; for (String id : ids) { found = false; for(VCSCommit commit : commits) { if (commit.getRevision().equals(id)) { count++; found = true; break; } } if (!found) { return false; } } return count == ids.length; } protected abstract String getTestRepoUrl(); protected abstract IVCS getVCS(IVCSRepositoryWorkspace mockedVCSRepo); protected abstract void setMakeFailureOnVCSReset(Boolean doMakeFailure); protected abstract String getVCSTypeString(); }
getCommitsRange() test implemented getBranchHeadCommit() test implemented documentation updated
src/main/java/org/scm4j/vcs/api/abstracttest/VCSAbstractTest.java
getCommitsRange() test implemented getBranchHeadCommit() test implemented documentation updated
Java
apache-2.0
875672afd05b8079aa031ca43bfff2f268d485a1
0
enisher/summarly,enisher/summarly
package org.summarly.lib; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.summarly.lib.common.RankedSentence; import org.summarly.lib.common.Text; import org.summarly.lib.segmentation.LuceneSplitter; import org.summarly.lib.segmentation.StanfordNLPSplitter; import org.summarly.lib.segmentation.TextSplitter; import org.summarly.lib.summarizing.Filter; import org.summarly.lib.summarizing.LexRankRanker; import org.summarly.lib.summarizing.PreFilter; import org.summarly.lib.summarizing.modifiers.RankModifier; import org.summarly.lib.summarizing.Ranker; import org.summarly.lib.common.Sentence; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.stream.Collectors; import org.apache.tika.language.LanguageIdentifier; /** * Created by Anton Chernetskij */ public class LexRankSummarizationService implements SummarizationService { private static final Logger LOGGER = LoggerFactory.getLogger(LexRankSummarizationService.class); private Ranker ranker; private TextSplitter enSplitter; private TextSplitter ruSplitter; private Filter filter; private List<RankModifier> rankModifiers; public LexRankSummarizationService() { enSplitter = new StanfordNLPSplitter(); ruSplitter = new LuceneSplitter(); ranker = new LexRankRanker(); filter = new Filter(); rankModifiers = Arrays.<RankModifier>asList(text -> text); } public List<String> summarise(String s, double ratio) throws UnsupportedLanguageException { long start = System.currentTimeMillis(); Text text; PreFilter preFilter = new PreFilter(); s = preFilter.filterBrackets(s); text = splitText(s); if (text.numSentences() < 6) { throw new RuntimeException("The text is too small to apply extractive summary"); } List<RankedSentence> rankedText = ranker.rank(text); rankedText = modifyRank(rankedText); long finish = System.currentTimeMillis(); LOGGER.info(String.format( "Processed text of %d sentences in %d ms", text.numSentences(), (finish - start))); List<Sentence> summary = filter.filter(rankedText, ratio) .stream().map(RankedSentence::getSentence) .collect(Collectors.<Sentence>toList()); List<String> paragraphs = new ArrayList<String>(); StringBuilder builder = new StringBuilder(); int currentParagraph = 0; for (Sentence sentence : summary) { builder.append(sentence.getText()); if (sentence.getParagraphNum() != currentParagraph) { currentParagraph = sentence.getParagraphNum(); paragraphs.add(builder.toString()); builder.setLength(0); } else { builder.append(" "); } } return paragraphs; } private Text splitText(String s) throws UnsupportedLanguageException { Text text;LanguageIdentifier languageIdentifier = new LanguageIdentifier(s); String lang = languageIdentifier.getLanguage(); switch (lang) { case "en": text = enSplitter.split(s, ""); break; case "ru": text = ruSplitter.split(s, ""); break; default: throw new UnsupportedLanguageException(lang); } return text; } private List<RankedSentence> modifyRank(List<RankedSentence> text) { for (RankModifier modifier : rankModifiers) { text = modifier.modify(text); } return text; } public Ranker getRanker() { return ranker; } public void setRanker(Ranker ranker) { this.ranker = ranker; } public TextSplitter getSplitter() { return enSplitter; } public void setSplitter(TextSplitter splitter) { this.enSplitter = splitter; } }
src/main/java/org/summarly/lib/LexRankSummarizationService.java
package org.summarly.lib; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.summarly.lib.common.RankedSentence; import org.summarly.lib.common.Text; import org.summarly.lib.segmentation.LuceneSplitter; import org.summarly.lib.segmentation.StanfordNLPSplitter; import org.summarly.lib.segmentation.TextSplitter; import org.summarly.lib.summarizing.Filter; import org.summarly.lib.summarizing.LexRankRanker; import org.summarly.lib.summarizing.PreFilter; import org.summarly.lib.summarizing.modifiers.RankModifier; import org.summarly.lib.summarizing.Ranker; import org.summarly.lib.common.Sentence; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.stream.Collectors; import org.apache.tika.language.LanguageIdentifier; /** * Created by Anton Chernetskij */ public class LexRankSummarizationService implements SummarizationService { private static final Logger LOGGER = LoggerFactory.getLogger(LexRankSummarizationService.class); private Ranker ranker; private TextSplitter enSplitter; private TextSplitter ruSplitter; private Filter filter; private List<RankModifier> rankModifiers; public LexRankSummarizationService() { enSplitter = new StanfordNLPSplitter(); ruSplitter = new LuceneSplitter(); ranker = new LexRankRanker(); filter = new Filter(); rankModifiers = Arrays.<RankModifier>asList(text -> text); } public List<String> summarise(String s, double ratio) throws UnsupportedLanguageException { long start = System.currentTimeMillis(); Text text; LanguageIdentifier languageIdentifier = new LanguageIdentifier(s); String lang = languageIdentifier.getLanguage(); PreFilter preFilter = new PreFilter(); s = preFilter.filterBrackets(s); switch (lang) { case "en": text = enSplitter.split(s, ""); break; case "ru": text = ruSplitter.split(s, ""); break; default: throw new UnsupportedLanguageException(lang); } if (text.numSentences() < 6) { throw new RuntimeException("The text is too small to apply extractive summary"); } List<RankedSentence> rankedText = ranker.rank(text); rankedText = modifyRank(rankedText); long finish = System.currentTimeMillis(); LOGGER.info(String.format( "Processed text of %d sentences in %d ms", text.numSentences(), (finish - start))); List<Sentence> summary = filter.filter(rankedText, ratio) .stream().map(RankedSentence::getSentence) .collect(Collectors.<Sentence>toList()); List<String> paragraphs = new ArrayList<String>(); StringBuilder builder = new StringBuilder(); int currentParagraph = 0; for (Sentence sentence : summary) { builder.append(sentence.getText()); if (sentence.getParagraphNum() != currentParagraph) { currentParagraph = sentence.getParagraphNum(); paragraphs.add(builder.toString()); builder.setLength(0); } else { builder.append(" "); } } return paragraphs; } private List<RankedSentence> modifyRank(List<RankedSentence> text) { for (RankModifier modifier : rankModifiers) { text = modifier.modify(text); } return text; } public Ranker getRanker() { return ranker; } public void setRanker(Ranker ranker) { this.ranker = ranker; } public TextSplitter getSplitter() { return enSplitter; } public void setSplitter(TextSplitter splitter) { this.enSplitter = splitter; } }
Refactor
src/main/java/org/summarly/lib/LexRankSummarizationService.java
Refactor
Java
apache-2.0
dcd38eeb4edd91f25c114ce1ac718fa12833b115
0
SergeevPavel/intellij-scala,LPTK/intellij-scala,JetBrains/intellij-scala-historical,triggerNZ/intellij-scala,LPTK/intellij-scala,SergeevPavel/intellij-scala,LPTK/intellij-scala,triggerNZ/intellij-scala,triggerNZ/intellij-scala,SergeevPavel/intellij-scala,JetBrains/intellij-scala-historical,JetBrains/intellij-scala-historical,consulo/consulo-scala
package org.jetbrains.plugins.scala.config.ui; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.ui.DocumentAdapter; import org.jetbrains.plugins.scala.config.ScalaDistribution; import org.jetbrains.plugins.scala.config.ScalaLibrary; import org.jetbrains.plugins.scala.icons.Icons; import scala.Option; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.*; import java.io.File; public class ScalaFacetEditor { private static final Color DEFAULT_COLOR = UIManager.getColor("TextField.foreground"); private JPanel contentPane; private JRadioButton buttonExistingSDK; private JRadioButton buttonNewSDK; private JRadioButton buttonNoSDK; private JComboBox comboLibrary; private TextFieldWithBrowseButton fieldHome; private JTextField fieldName; private JComboBox comboLevel; private JLabel labelState; private JLabel labelHome; private JLabel labelLevel; private JLabel labelName; private JLabel labelVersion; private Project myProject; private boolean homeIsValid; public ScalaFacetEditor(Project project) { myProject = project; ButtonsListener buttonsListener = new ButtonsListener(); buttonExistingSDK.addActionListener(buttonsListener); buttonNewSDK.addActionListener(buttonsListener); buttonNoSDK.addActionListener(buttonsListener); fieldHome.getTextField().getDocument().addDocumentListener(new HomeListener()); fieldHome.addBrowseFolderListener("Scala home", null, myProject, new FileChooserDescriptor(false, true, false, false, false, false)); fieldName.getDocument().addDocumentListener(new NameListener()); comboLibrary.setModel(new DefaultComboBoxModel(ScalaLibrary.findAll(myProject))); comboLibrary.setRenderer(new LibraryRenderer()); comboLevel.setModel(new DefaultComboBoxModel(LibrariesContainer.LibraryLevel.values())); comboLevel.setRenderer(new LevelRenderer()); comboLevel.addActionListener(new LevelListener()); } public void init() { chooseActiveSection(); updateExistingButtonState(); guessHome(); updateSectionsState(); } public void updateExistingButtonState() { boolean exists = hasExistingLibrary(); buttonExistingSDK.setEnabled(exists); if(!exists) { comboLibrary.setSelectedItem(null); } } public Choice getChoice() { if(buttonExistingSDK.isSelected()) return Choice.UseExisting; if(buttonNewSDK.isSelected()) return Choice.AddNew; if(buttonNoSDK.isSelected()) return Choice.DoNothing; throw new RuntimeException("Unknown selected section"); } private boolean hasExistingLibrary() { return getExistingLibrary() != null; } public ScalaLibrary getExistingLibrary() { return ((ScalaLibrary) comboLibrary.getModel().getSelectedItem()); } public String getHome() { return fieldHome.getText().trim(); } public LibrariesContainer.LibraryLevel getLevel() { return (LibrariesContainer.LibraryLevel) comboLevel.getSelectedItem(); } public String getName() { return fieldName.getText().trim(); } public void chooseActiveSection() { if(hasExistingLibrary()) { buttonExistingSDK.setSelected(true); } else { buttonNewSDK.setSelected(true); } } public void updateSectionsState() { comboLibrary.setEnabled(buttonExistingSDK.isSelected()); setNewSectionEnabled(buttonNewSDK.isSelected()); } private void setNewSectionEnabled(boolean b) { labelHome.setEnabled(b); fieldHome.setEnabled(b); labelVersion.setEnabled(b); labelState.setEnabled(b); labelLevel.setEnabled(b); comboLevel.setEnabled(b); labelName.setEnabled(b); fieldName.setEnabled(b); } private void guessHome() { Option<String> home = ScalaDistribution.findHome(); if(home.isDefined()) { fieldHome.setText(home.get()); } } private void updateHomeState() { homeIsValid = false; fieldHome.getTextField().setForeground(DEFAULT_COLOR); fieldHome.getTextField().setToolTipText(null); labelState.setIcon(null); labelState.setText(""); String path = fieldHome.getText(); if(path.isEmpty()) { labelState.setText("Please, provide a path to Scala SDK"); return; } File home = new File(path); if(!home.exists()) { fieldHome.getTextField().setForeground(Color.RED); fieldHome.getTextField().setToolTipText("Path not found"); return; } labelState.setIcon(Icons.ERROR); ScalaDistribution distribution = new ScalaDistribution(home); if(!distribution.valid()) { labelState.setText("Not valid Scala SDK"); return; } String missing = distribution.missing(); if(missing.length() > 0) { labelState.setText("<html><body>Missing SDK files:<br>" + missing + "</html></body>"); return; } if(!distribution.consistent()) { labelState.setText("Mismatch of SDK file versions"); return; } if(!distribution.supported()) { labelState.setText(distribution.version().get() + " (unsupported, 2.8+ required)"); labelState.setIcon(Icons.WARNING); return; } homeIsValid = true; String version = distribution.version().get().toString(); if(!distribution.hasDocs()) { labelState.setText(version + " (no /docs/api found)"); labelState.setIcon(Icons.WARNING); } else { labelState.setText(version); labelState.setIcon(null); } fieldName.setText(ScalaLibrary.uniqueName(distribution.name(), getLevel(), myProject)); } private void makeNameUnique() { if(nameClashes()) { fieldName.setText(ScalaLibrary.uniqueName(getName(), getLevel(), myProject)); } } private void updateNameState() { boolean clashes = nameClashes(); fieldName.setForeground(clashes ? Color.RED : DEFAULT_COLOR); fieldName.setToolTipText(clashes ? "Name is already in use" : null); } private boolean nameClashes() { return ScalaLibrary.nameClashes(getName(), getLevel(), myProject); } public JComponent getComponent() { return contentPane; } private class ButtonsListener implements ActionListener { public void actionPerformed(ActionEvent e) { updateSectionsState(); } } private class HomeListener extends DocumentAdapter { @Override protected void textChanged(DocumentEvent e) { updateHomeState(); } } private class NameListener extends DocumentAdapter { @Override protected void textChanged(DocumentEvent e) { updateNameState(); } } private class LevelListener implements ActionListener { public void actionPerformed(ActionEvent e) { makeNameUnique(); updateNameState(); } } }
src/org/jetbrains/plugins/scala/config/ui/ScalaFacetEditor.java
package org.jetbrains.plugins.scala.config.ui; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.ui.DocumentAdapter; import org.jetbrains.plugins.scala.config.ScalaDistribution; import org.jetbrains.plugins.scala.config.ScalaLibrary; import org.jetbrains.plugins.scala.icons.Icons; import scala.Option; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.*; import java.io.File; public class ScalaFacetEditor { private static final Color DEFAULT_COLOR = UIManager.getColor("TextField.foreground"); private JPanel contentPane; private JRadioButton buttonExistingSDK; private JRadioButton buttonNewSDK; private JRadioButton buttonNoSDK; private JComboBox comboLibrary; private TextFieldWithBrowseButton fieldHome; private JTextField fieldName; private JComboBox comboLevel; private JLabel labelState; private JLabel labelHome; private JLabel labelLevel; private JLabel labelName; private JLabel labelVersion; private Project myProject; private boolean homeIsValid; public ScalaFacetEditor(Project project) { myProject = project; } public void init() { ButtonsListener buttonsListener = new ButtonsListener(); buttonExistingSDK.addActionListener(buttonsListener); buttonNewSDK.addActionListener(buttonsListener); buttonNoSDK.addActionListener(buttonsListener); fieldHome.getTextField().getDocument().addDocumentListener(new HomeListener()); fieldHome.addBrowseFolderListener("Scala home", null, myProject, new FileChooserDescriptor(false, true, false, false, false, false)); fieldName.getDocument().addDocumentListener(new NameListener()); comboLibrary.setModel(new DefaultComboBoxModel(ScalaLibrary.findAll(myProject))); comboLibrary.setRenderer(new LibraryRenderer()); comboLevel.setModel(new DefaultComboBoxModel(LibrariesContainer.LibraryLevel.values())); comboLevel.setRenderer(new LevelRenderer()); comboLevel.addActionListener(new LevelListener()); chooseActiveSection(); updateExistingButtonState(); guessHome(); updateSectionsState(); } public void updateExistingButtonState() { boolean exists = hasExistingLibrary(); buttonExistingSDK.setEnabled(exists); if(!exists) { comboLibrary.setSelectedItem(null); } } public Choice getChoice() { if(buttonExistingSDK.isSelected()) return Choice.UseExisting; if(buttonNewSDK.isSelected()) return Choice.AddNew; if(buttonNoSDK.isSelected()) return Choice.DoNothing; throw new RuntimeException("Unknown selected section"); } private boolean hasExistingLibrary() { return getExistingLibrary() != null; } public ScalaLibrary getExistingLibrary() { return ((ScalaLibrary) comboLibrary.getModel().getSelectedItem()); } public String getHome() { return fieldHome.getText().trim(); } public LibrariesContainer.LibraryLevel getLevel() { return (LibrariesContainer.LibraryLevel) comboLevel.getSelectedItem(); } public String getName() { return fieldName.getText().trim(); } public void chooseActiveSection() { if(hasExistingLibrary()) { buttonExistingSDK.setSelected(true); } else { buttonNewSDK.setSelected(true); } } public void updateSectionsState() { comboLibrary.setEnabled(buttonExistingSDK.isSelected()); setNewSectionEnabled(buttonNewSDK.isSelected()); } private void setNewSectionEnabled(boolean b) { labelHome.setEnabled(b); fieldHome.setEnabled(b); labelVersion.setEnabled(b); labelState.setEnabled(b); labelLevel.setEnabled(b); comboLevel.setEnabled(b); labelName.setEnabled(b); fieldName.setEnabled(b); } private void guessHome() { Option<String> home = ScalaDistribution.findHome(); if(home.isDefined()) { fieldHome.setText(home.get()); } } private void updateHomeState() { homeIsValid = false; fieldHome.getTextField().setForeground(DEFAULT_COLOR); fieldHome.getTextField().setToolTipText(null); labelState.setIcon(null); labelState.setText(""); String path = fieldHome.getText(); if(path.isEmpty()) { labelState.setText("Please, provide a path to Scala SDK"); return; } File home = new File(path); if(!home.exists()) { fieldHome.getTextField().setForeground(Color.RED); fieldHome.getTextField().setToolTipText("Path not found"); return; } labelState.setIcon(Icons.ERROR); ScalaDistribution distribution = new ScalaDistribution(home); if(!distribution.valid()) { labelState.setText("Not valid Scala SDK"); return; } String missing = distribution.missing(); if(missing.length() > 0) { labelState.setText("<html><body>Missing SDK files:<br>" + missing + "</html></body>"); return; } if(!distribution.consistent()) { labelState.setText("Mismatch of SDK file versions"); return; } if(!distribution.supported()) { labelState.setText(distribution.version().get() + " (unsupported, 2.8+ required)"); labelState.setIcon(Icons.WARNING); return; } homeIsValid = true; String version = distribution.version().get().toString(); if(!distribution.hasDocs()) { labelState.setText(version + " (no /docs/api found)"); labelState.setIcon(Icons.WARNING); } else { labelState.setText(version); labelState.setIcon(null); } fieldName.setText(ScalaLibrary.uniqueName(distribution.name(), getLevel(), myProject)); } private void makeNameUnique() { if(nameClashes()) { fieldName.setText(ScalaLibrary.uniqueName(getName(), getLevel(), myProject)); } } private void updateNameState() { boolean clashes = nameClashes(); fieldName.setForeground(clashes ? Color.RED : DEFAULT_COLOR); fieldName.setToolTipText(clashes ? "Name is already in use" : null); } private boolean nameClashes() { return ScalaLibrary.nameClashes(getName(), getLevel(), myProject); } public JComponent getComponent() { return contentPane; } private class ButtonsListener implements ActionListener { public void actionPerformed(ActionEvent e) { updateSectionsState(); } } private class HomeListener extends DocumentAdapter { @Override protected void textChanged(DocumentEvent e) { updateHomeState(); } } private class NameListener extends DocumentAdapter { @Override protected void textChanged(DocumentEvent e) { updateNameState(); } } private class LevelListener implements ActionListener { public void actionPerformed(ActionEvent e) { makeNameUnique(); updateNameState(); } } }
SCL-2199 Fix multiple path choosers
src/org/jetbrains/plugins/scala/config/ui/ScalaFacetEditor.java
SCL-2199 Fix multiple path choosers
Java
apache-2.0
a19986d475f4f4fdc7234f14baf4d129f7bea0c4
0
bitcoinj/bitcoinj,bitcoinj/bitcoinj,natzei/bitcoinj,natzei/bitcoinj
/* * Copyright 2013 Google Inc. * Copyright 2018 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.core.Block; import java.math.BigInteger; import static com.google.common.base.Preconditions.checkState; /** * Network parameters for the regression test mode of bitcoind in which all blocks are trivially solvable. */ public class RegTestParams extends AbstractBitcoinNetParams { private static final BigInteger MAX_TARGET = new BigInteger("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16); public RegTestParams() { super(); id = ID_REGTEST; targetTimespan = TARGET_TIMESPAN; maxTarget = MAX_TARGET; // Difficulty adjustments are disabled for regtest. // By setting the block interval for difficulty adjustments to Integer.MAX_VALUE we make sure difficulty never // changes. interval = Integer.MAX_VALUE; subsidyDecreaseBlockCount = 150; genesisBlock.setDifficultyTarget(0x207fFFFFL); genesisBlock.setTime(1296688602L); genesisBlock.setNonce(2); port = 18444; packetMagic = 0xfabfb5daL; dumpedPrivateKeyHeader = 239; addressHeader = 111; p2shHeader = 196; segwitAddressHrp = "bcrt"; spendableCoinbaseDepth = 100; bip32HeaderP2PKHpub = 0x043587cf; // The 4 byte header that serializes in base58 to "tpub". bip32HeaderP2PKHpriv = 0x04358394; // The 4 byte header that serializes in base58 to "tprv" bip32HeaderP2WPKHpub = 0x045f1cf6; // The 4 byte header that serializes in base58 to "vpub". bip32HeaderP2WPKHpriv = 0x045f18bc; // The 4 byte header that serializes in base58 to "vprv" majorityEnforceBlockUpgrade = MainNetParams.MAINNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; majorityRejectBlockOutdated = MainNetParams.MAINNET_MAJORITY_REJECT_BLOCK_OUTDATED; majorityWindow = MainNetParams.MAINNET_MAJORITY_WINDOW; String genesisHash = genesisBlock.getHashAsString(); checkState(genesisHash.equals("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); dnsSeeds = null; addrSeeds = null; } @Override public boolean allowEmptyPeerChain() { return true; } private static RegTestParams instance; public static synchronized RegTestParams get() { if (instance == null) { instance = new RegTestParams(); } return instance; } @Override public String getPaymentProtocolId() { return PAYMENT_PROTOCOL_ID_REGTEST; } }
core/src/main/java/org/bitcoinj/params/RegTestParams.java
/* * Copyright 2013 Google Inc. * Copyright 2018 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.core.Block; import java.math.BigInteger; import static com.google.common.base.Preconditions.checkState; /** * Network parameters for the regression test mode of bitcoind in which all blocks are trivially solvable. */ public class RegTestParams extends AbstractBitcoinNetParams { private static final BigInteger MAX_TARGET = new BigInteger("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16); public RegTestParams() { super(); id = ID_REGTEST; targetTimespan = TARGET_TIMESPAN; maxTarget = MAX_TARGET; // Difficulty adjustments are disabled for regtest. // By setting the block interval for difficulty adjustments to Integer.MAX_VALUE we make sure difficulty never // changes. interval = Integer.MAX_VALUE; subsidyDecreaseBlockCount = 150; genesisBlock.setDifficultyTarget(0x1d07fff8L); genesisBlock.setTime(1296688602L); genesisBlock.setNonce(384568319); port = 18444; packetMagic = 0xfabfb5daL; dumpedPrivateKeyHeader = 239; addressHeader = 111; p2shHeader = 196; segwitAddressHrp = "bcrt"; spendableCoinbaseDepth = 100; bip32HeaderP2PKHpub = 0x043587cf; // The 4 byte header that serializes in base58 to "tpub". bip32HeaderP2PKHpriv = 0x04358394; // The 4 byte header that serializes in base58 to "tprv" bip32HeaderP2WPKHpub = 0x045f1cf6; // The 4 byte header that serializes in base58 to "vpub". bip32HeaderP2WPKHpriv = 0x045f18bc; // The 4 byte header that serializes in base58 to "vprv" majorityEnforceBlockUpgrade = MainNetParams.MAINNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; majorityRejectBlockOutdated = MainNetParams.MAINNET_MAJORITY_REJECT_BLOCK_OUTDATED; majorityWindow = MainNetParams.MAINNET_MAJORITY_WINDOW; String genesisHash = genesisBlock.getHashAsString(); checkState(genesisHash.equals("00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008")); dnsSeeds = null; addrSeeds = null; } @Override public boolean allowEmptyPeerChain() { return true; } private static Block genesis; @Override public Block getGenesisBlock() { synchronized (RegTestParams.class) { if (genesis == null) { genesis = super.getGenesisBlock(); genesis.setNonce(2); genesis.setDifficultyTarget(0x207fFFFFL); genesis.setTime(1296688602L); checkState(genesis.getHashAsString().toLowerCase().equals("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); } return genesis; } } private static RegTestParams instance; public static synchronized RegTestParams get() { if (instance == null) { instance = new RegTestParams(); } return instance; } @Override public String getPaymentProtocolId() { return PAYMENT_PROTOCOL_ID_REGTEST; } }
RegTestParams: remove redundant init of genesis block (It looks like the override of getGenesisBlock() was added back in 2013 when RegTestParams was a subclass of TestNet2Params.)
core/src/main/java/org/bitcoinj/params/RegTestParams.java
RegTestParams: remove redundant init of genesis block
Java
apache-2.0
fb395ecc0a76a080e086e6b59b390d4e74f9c10f
0
arks-api/arks-api,arks-api/arks-api
package org.cbsa.testing.api; import java.util.Scanner; import org.cbsa.api.ContentBasedSearch; public class CBSTest { public static void main(String[] args) { ContentBasedSearch contentBasedSearch = new ContentBasedSearch(); Scanner scanner = new Scanner(System.in); System.out.println("Enter Query : "); String query = scanner.nextLine(); contentBasedSearch.searchForPages(query); } }
source/cbsa-testing/src/org/cbsa/testing/api/CBSTest.java
package org.cbsa.testing.api; import java.util.Scanner; import org.cbsa.api.ContentBasedSearch; public class CBSTest { public static void main(String[] args) { ContentBasedSearch contentBasedSearch = new ContentBasedSearch(); Scanner scanner = new Scanner(System.in); System.out.println("Enter Query : "); String query = scanner.next(); contentBasedSearch.searchForPages(query); } }
Multiple word search query fixed
source/cbsa-testing/src/org/cbsa/testing/api/CBSTest.java
Multiple word search query fixed
Java
apache-2.0
bff3d7b0cf073ccc061db30af6d52fa4a9f21c05
0
mapr/hadoop-common,GeLiXin/hadoop,apurtell/hadoop,wwjiang007/hadoop,ucare-uchicago/hadoop,szegedim/hadoop,nandakumar131/hadoop,steveloughran/hadoop,lukmajercak/hadoop,szegedim/hadoop,dierobotsdie/hadoop,ucare-uchicago/hadoop,dierobotsdie/hadoop,mapr/hadoop-common,nandakumar131/hadoop,plusplusjiajia/hadoop,dierobotsdie/hadoop,GeLiXin/hadoop,apache/hadoop,plusplusjiajia/hadoop,plusplusjiajia/hadoop,szegedim/hadoop,apurtell/hadoop,lukmajercak/hadoop,ucare-uchicago/hadoop,steveloughran/hadoop,xiao-chen/hadoop,wwjiang007/hadoop,apurtell/hadoop,xiao-chen/hadoop,szegedim/hadoop,littlezhou/hadoop,apache/hadoop,szegedim/hadoop,nandakumar131/hadoop,GeLiXin/hadoop,mapr/hadoop-common,apurtell/hadoop,mapr/hadoop-common,littlezhou/hadoop,lukmajercak/hadoop,littlezhou/hadoop,plusplusjiajia/hadoop,wwjiang007/hadoop,steveloughran/hadoop,plusplusjiajia/hadoop,xiao-chen/hadoop,apache/hadoop,lukmajercak/hadoop,szegedim/hadoop,apurtell/hadoop,littlezhou/hadoop,lukmajercak/hadoop,ucare-uchicago/hadoop,xiao-chen/hadoop,JingchengDu/hadoop,steveloughran/hadoop,dierobotsdie/hadoop,apurtell/hadoop,JingchengDu/hadoop,JingchengDu/hadoop,ucare-uchicago/hadoop,szegedim/hadoop,GeLiXin/hadoop,plusplusjiajia/hadoop,JingchengDu/hadoop,GeLiXin/hadoop,mapr/hadoop-common,JingchengDu/hadoop,ucare-uchicago/hadoop,GeLiXin/hadoop,apache/hadoop,mapr/hadoop-common,mapr/hadoop-common,wwjiang007/hadoop,steveloughran/hadoop,littlezhou/hadoop,littlezhou/hadoop,dierobotsdie/hadoop,JingchengDu/hadoop,apache/hadoop,nandakumar131/hadoop,apache/hadoop,xiao-chen/hadoop,GeLiXin/hadoop,nandakumar131/hadoop,ucare-uchicago/hadoop,JingchengDu/hadoop,nandakumar131/hadoop,nandakumar131/hadoop,dierobotsdie/hadoop,littlezhou/hadoop,wwjiang007/hadoop,lukmajercak/hadoop,plusplusjiajia/hadoop,apache/hadoop,xiao-chen/hadoop,wwjiang007/hadoop,wwjiang007/hadoop,apurtell/hadoop,lukmajercak/hadoop,steveloughran/hadoop,steveloughran/hadoop,dierobotsdie/hadoop,xiao-chen/hadoop
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.security; import static org.apache.hadoop.fs.CommonConfigurationKeys.HADOOP_USER_GROUP_METRICS_PERCENTILES_INTERVALS; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN_DEFAULT; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_TOKEN_FILES; import static org.apache.hadoop.security.UGIExceptionMessages.*; import static org.apache.hadoop.util.PlatformName.IBM_JAVA; import com.google.common.annotations.VisibleForTesting; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; import java.security.AccessControlContext; import java.security.AccessController; import java.security.Principal; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.security.auth.DestroyFailedException; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.kerberos.KerberosPrincipal; import javax.security.auth.kerberos.KerberosTicket; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; import javax.security.auth.login.Configuration.Parameters; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; import org.apache.hadoop.io.retry.RetryPolicies; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.metrics2.annotation.Metric; import org.apache.hadoop.metrics2.annotation.Metrics; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.lib.MetricsRegistry; import org.apache.hadoop.metrics2.lib.MutableGaugeInt; import org.apache.hadoop.metrics2.lib.MutableGaugeLong; import org.apache.hadoop.metrics2.lib.MutableQuantiles; import org.apache.hadoop.metrics2.lib.MutableRate; import org.apache.hadoop.security.SaslRpcServer.AuthMethod; import org.apache.hadoop.security.authentication.util.KerberosUtil; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.util.Shell; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * User and group information for Hadoop. * This class wraps around a JAAS Subject and provides methods to determine the * user's username and groups. It supports both the Windows, Unix and Kerberos * login modules. */ @InterfaceAudience.Public @InterfaceStability.Evolving public class UserGroupInformation { @VisibleForTesting static final Logger LOG = LoggerFactory.getLogger( UserGroupInformation.class); /** * Percentage of the ticket window to use before we renew ticket. */ private static final float TICKET_RENEW_WINDOW = 0.80f; private static boolean shouldRenewImmediatelyForTests = false; static final String HADOOP_USER_NAME = "HADOOP_USER_NAME"; static final String HADOOP_PROXY_USER = "HADOOP_PROXY_USER"; /** * For the purposes of unit tests, we want to test login * from keytab and don't want to wait until the renew * window (controlled by TICKET_RENEW_WINDOW). * @param immediate true if we should login without waiting for ticket window */ @VisibleForTesting public static void setShouldRenewImmediatelyForTests(boolean immediate) { shouldRenewImmediatelyForTests = immediate; } /** * UgiMetrics maintains UGI activity statistics * and publishes them through the metrics interfaces. */ @Metrics(about="User and group related metrics", context="ugi") static class UgiMetrics { final MetricsRegistry registry = new MetricsRegistry("UgiMetrics"); @Metric("Rate of successful kerberos logins and latency (milliseconds)") MutableRate loginSuccess; @Metric("Rate of failed kerberos logins and latency (milliseconds)") MutableRate loginFailure; @Metric("GetGroups") MutableRate getGroups; MutableQuantiles[] getGroupsQuantiles; @Metric("Renewal failures since startup") private MutableGaugeLong renewalFailuresTotal; @Metric("Renewal failures since last successful login") private MutableGaugeInt renewalFailures; static UgiMetrics create() { return DefaultMetricsSystem.instance().register(new UgiMetrics()); } static void reattach() { metrics = UgiMetrics.create(); } void addGetGroups(long latency) { getGroups.add(latency); if (getGroupsQuantiles != null) { for (MutableQuantiles q : getGroupsQuantiles) { q.add(latency); } } } MutableGaugeInt getRenewalFailures() { return renewalFailures; } } /** * A login module that looks at the Kerberos, Unix, or Windows principal and * adds the corresponding UserName. */ @InterfaceAudience.Private public static class HadoopLoginModule implements LoginModule { private Subject subject; @Override public boolean abort() throws LoginException { return true; } private <T extends Principal> T getCanonicalUser(Class<T> cls) { for(T user: subject.getPrincipals(cls)) { return user; } return null; } @Override public boolean commit() throws LoginException { if (LOG.isDebugEnabled()) { LOG.debug("hadoop login commit"); } // if we already have a user, we are done. if (!subject.getPrincipals(User.class).isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("using existing subject:"+subject.getPrincipals()); } return true; } Principal user = getCanonicalUser(KerberosPrincipal.class); if (user != null) { if (LOG.isDebugEnabled()) { LOG.debug("using kerberos user:"+user); } } //If we don't have a kerberos user and security is disabled, check //if user is specified in the environment or properties if (!isSecurityEnabled() && (user == null)) { String envUser = System.getenv(HADOOP_USER_NAME); if (envUser == null) { envUser = System.getProperty(HADOOP_USER_NAME); } user = envUser == null ? null : new User(envUser); } // use the OS user if (user == null) { user = getCanonicalUser(OS_PRINCIPAL_CLASS); if (LOG.isDebugEnabled()) { LOG.debug("using local user:"+user); } } // if we found the user, add our principal if (user != null) { if (LOG.isDebugEnabled()) { LOG.debug("Using user: \"" + user + "\" with name " + user.getName()); } User userEntry = null; try { // LoginContext will be attached later unless it's an external // subject. AuthenticationMethod authMethod = (user instanceof KerberosPrincipal) ? AuthenticationMethod.KERBEROS : AuthenticationMethod.SIMPLE; userEntry = new User(user.getName(), authMethod, null); } catch (Exception e) { throw (LoginException)(new LoginException(e.toString()).initCause(e)); } if (LOG.isDebugEnabled()) { LOG.debug("User entry: \"" + userEntry.toString() + "\"" ); } subject.getPrincipals().add(userEntry); return true; } LOG.error("Can't find user in " + subject); throw new LoginException("Can't find user name"); } @Override public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { this.subject = subject; } @Override public boolean login() throws LoginException { if (LOG.isDebugEnabled()) { LOG.debug("hadoop login"); } return true; } @Override public boolean logout() throws LoginException { if (LOG.isDebugEnabled()) { LOG.debug("hadoop logout"); } return true; } } /** * Reattach the class's metrics to a new metric system. */ public static void reattachMetrics() { UgiMetrics.reattach(); } /** Metrics to track UGI activity */ static UgiMetrics metrics = UgiMetrics.create(); /** The auth method to use */ private static AuthenticationMethod authenticationMethod; /** Server-side groups fetching service */ private static Groups groups; /** Min time (in seconds) before relogin for Kerberos */ private static long kerberosMinSecondsBeforeRelogin; /** The configuration to use */ private static Configuration conf; /**Environment variable pointing to the token cache file*/ public static final String HADOOP_TOKEN_FILE_LOCATION = "HADOOP_TOKEN_FILE_LOCATION"; /** * A method to initialize the fields that depend on a configuration. * Must be called before useKerberos or groups is used. */ private static void ensureInitialized() { if (conf == null) { synchronized(UserGroupInformation.class) { if (conf == null) { // someone might have beat us initialize(new Configuration(), false); } } } } /** * Initialize UGI and related classes. * @param conf the configuration to use */ private static synchronized void initialize(Configuration conf, boolean overrideNameRules) { authenticationMethod = SecurityUtil.getAuthenticationMethod(conf); if (overrideNameRules || !HadoopKerberosName.hasRulesBeenSet()) { try { HadoopKerberosName.setConfiguration(conf); } catch (IOException ioe) { throw new RuntimeException( "Problem with Kerberos auth_to_local name configuration", ioe); } } try { kerberosMinSecondsBeforeRelogin = 1000L * conf.getLong( HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN, HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN_DEFAULT); } catch(NumberFormatException nfe) { throw new IllegalArgumentException("Invalid attribute value for " + HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN + " of " + conf.get(HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN)); } // If we haven't set up testing groups, use the configuration to find it if (!(groups instanceof TestingGroups)) { groups = Groups.getUserToGroupsMappingService(conf); } UserGroupInformation.conf = conf; if (metrics.getGroupsQuantiles == null) { int[] intervals = conf.getInts(HADOOP_USER_GROUP_METRICS_PERCENTILES_INTERVALS); if (intervals != null && intervals.length > 0) { final int length = intervals.length; MutableQuantiles[] getGroupsQuantiles = new MutableQuantiles[length]; for (int i = 0; i < length; i++) { getGroupsQuantiles[i] = metrics.registry.newQuantiles( "getGroups" + intervals[i] + "s", "Get groups", "ops", "latency", intervals[i]); } metrics.getGroupsQuantiles = getGroupsQuantiles; } } } /** * Set the static configuration for UGI. * In particular, set the security authentication mechanism and the * group look up service. * @param conf the configuration to use */ @InterfaceAudience.Public @InterfaceStability.Evolving public static void setConfiguration(Configuration conf) { initialize(conf, true); } @InterfaceAudience.Private @VisibleForTesting public static void reset() { authenticationMethod = null; conf = null; groups = null; kerberosMinSecondsBeforeRelogin = 0; setLoginUser(null); HadoopKerberosName.setRules(null); } /** * Determine if UserGroupInformation is using Kerberos to determine * user identities or is relying on simple authentication * * @return true if UGI is working in a secure environment */ public static boolean isSecurityEnabled() { return !isAuthenticationMethodEnabled(AuthenticationMethod.SIMPLE); } @InterfaceAudience.Private @InterfaceStability.Evolving private static boolean isAuthenticationMethodEnabled(AuthenticationMethod method) { ensureInitialized(); return (authenticationMethod == method); } /** * Information about the logged in user. */ private static final AtomicReference<UserGroupInformation> loginUserRef = new AtomicReference<>(); private final Subject subject; // All non-static fields must be read-only caches that come from the subject. private final User user; private static String OS_LOGIN_MODULE_NAME; private static Class<? extends Principal> OS_PRINCIPAL_CLASS; private static final boolean windows = System.getProperty("os.name").startsWith("Windows"); private static final boolean is64Bit = System.getProperty("os.arch").contains("64") || System.getProperty("os.arch").contains("s390x"); private static final boolean aix = System.getProperty("os.name").equals("AIX"); /* Return the OS login module class name */ private static String getOSLoginModuleName() { if (IBM_JAVA) { if (windows) { return is64Bit ? "com.ibm.security.auth.module.Win64LoginModule" : "com.ibm.security.auth.module.NTLoginModule"; } else if (aix) { return is64Bit ? "com.ibm.security.auth.module.AIX64LoginModule" : "com.ibm.security.auth.module.AIXLoginModule"; } else { return "com.ibm.security.auth.module.LinuxLoginModule"; } } else { return windows ? "com.sun.security.auth.module.NTLoginModule" : "com.sun.security.auth.module.UnixLoginModule"; } } /* Return the OS principal class */ @SuppressWarnings("unchecked") private static Class<? extends Principal> getOsPrincipalClass() { ClassLoader cl = ClassLoader.getSystemClassLoader(); try { String principalClass = null; if (IBM_JAVA) { if (is64Bit) { principalClass = "com.ibm.security.auth.UsernamePrincipal"; } else { if (windows) { principalClass = "com.ibm.security.auth.NTUserPrincipal"; } else if (aix) { principalClass = "com.ibm.security.auth.AIXPrincipal"; } else { principalClass = "com.ibm.security.auth.LinuxPrincipal"; } } } else { principalClass = windows ? "com.sun.security.auth.NTUserPrincipal" : "com.sun.security.auth.UnixPrincipal"; } return (Class<? extends Principal>) cl.loadClass(principalClass); } catch (ClassNotFoundException e) { LOG.error("Unable to find JAAS classes:" + e.getMessage()); } return null; } static { OS_LOGIN_MODULE_NAME = getOSLoginModuleName(); OS_PRINCIPAL_CLASS = getOsPrincipalClass(); } private static class RealUser implements Principal { private final UserGroupInformation realUser; RealUser(UserGroupInformation realUser) { this.realUser = realUser; } @Override public String getName() { return realUser.getUserName(); } public UserGroupInformation getRealUser() { return realUser; } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o == null || getClass() != o.getClass()) { return false; } else { return realUser.equals(((RealUser) o).realUser); } } @Override public int hashCode() { return realUser.hashCode(); } @Override public String toString() { return realUser.toString(); } } private static HadoopLoginContext newLoginContext(String appName, Subject subject, HadoopConfiguration loginConf) throws LoginException { // Temporarily switch the thread's ContextClassLoader to match this // class's classloader, so that we can properly load HadoopLoginModule // from the JAAS libraries. Thread t = Thread.currentThread(); ClassLoader oldCCL = t.getContextClassLoader(); t.setContextClassLoader(HadoopLoginModule.class.getClassLoader()); try { return new HadoopLoginContext(appName, subject, loginConf); } finally { t.setContextClassLoader(oldCCL); } } // return the LoginContext only if it's managed by the ugi. externally // managed login contexts will be ignored. private HadoopLoginContext getLogin() { LoginContext login = user.getLogin(); return (login instanceof HadoopLoginContext) ? (HadoopLoginContext)login : null; } private void setLogin(LoginContext login) { user.setLogin(login); } /** * Create a UserGroupInformation for the given subject. * This does not change the subject or acquire new credentials. * * The creator of subject is responsible for renewing credentials. * @param subject the user's subject */ UserGroupInformation(Subject subject) { this.subject = subject; // do not access ANY private credentials since they are mutable // during a relogin. no principal locking necessary since // relogin/logout does not remove User principal. this.user = subject.getPrincipals(User.class).iterator().next(); if (user == null || user.getName() == null) { throw new IllegalStateException("Subject does not contain a valid User"); } } /** * checks if logged in using kerberos * @return true if the subject logged via keytab or has a Kerberos TGT */ public boolean hasKerberosCredentials() { return user.getAuthenticationMethod() == AuthenticationMethod.KERBEROS; } /** * Return the current user, including any doAs in the current stack. * @return the current user * @throws IOException if login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation getCurrentUser() throws IOException { AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null || subject.getPrincipals(User.class).isEmpty()) { return getLoginUser(); } else { return new UserGroupInformation(subject); } } /** * Find the most appropriate UserGroupInformation to use * * @param ticketCachePath The Kerberos ticket cache path, or NULL * if none is specfied * @param user The user name, or NULL if none is specified. * * @return The most appropriate UserGroupInformation */ public static UserGroupInformation getBestUGI( String ticketCachePath, String user) throws IOException { if (ticketCachePath != null) { return getUGIFromTicketCache(ticketCachePath, user); } else if (user == null) { return getCurrentUser(); } else { return createRemoteUser(user); } } /** * Create a UserGroupInformation from a Kerberos ticket cache. * * @param user The principal name to load from the ticket * cache * @param ticketCache the path to the ticket cache file * * @throws IOException if the kerberos login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation getUGIFromTicketCache( String ticketCache, String user) throws IOException { if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) { return getBestUGI(null, user); } LoginParams params = new LoginParams(); params.put(LoginParam.PRINCIPAL, user); params.put(LoginParam.CCACHE, ticketCache); return doSubjectLogin(null, params); } /** * Create a UserGroupInformation from a Subject with Kerberos principal. * * @param subject The KerberosPrincipal to use in UGI. * The creator of subject is responsible for * renewing credentials. * * @throws IOException * @throws KerberosAuthException if the kerberos login fails */ public static UserGroupInformation getUGIFromSubject(Subject subject) throws IOException { if (subject == null) { throw new KerberosAuthException(SUBJECT_MUST_NOT_BE_NULL); } if (subject.getPrincipals(KerberosPrincipal.class).isEmpty()) { throw new KerberosAuthException(SUBJECT_MUST_CONTAIN_PRINCIPAL); } // null params indicate external subject login. no login context will // be attached. return doSubjectLogin(subject, null); } /** * Get the currently logged in user. If no explicit login has occurred, * the user will automatically be logged in with either kerberos credentials * if available, or as the local OS user, based on security settings. * @return the logged in user * @throws IOException if login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation getLoginUser() throws IOException { UserGroupInformation loginUser = loginUserRef.get(); // a potential race condition exists only for the initial creation of // the login user. there's no need to penalize all subsequent calls // with sychronization overhead so optimistically create a login user // and discard if we lose the race. if (loginUser == null) { UserGroupInformation newLoginUser = createLoginUser(null); do { // it's extremely unlikely that the login user will be non-null // (lost CAS race), but be nulled before the subsequent get, but loop // for correctness. if (loginUserRef.compareAndSet(null, newLoginUser)) { loginUser = newLoginUser; // only spawn renewal if this login user is the winner. loginUser.spawnAutoRenewalThreadForUserCreds(false); } else { loginUser = loginUserRef.get(); } } while (loginUser == null); } return loginUser; } /** * remove the login method that is followed by a space from the username * e.g. "jack (auth:SIMPLE)" -> "jack" * * @param userName * @return userName without login method */ public static String trimLoginMethod(String userName) { int spaceIndex = userName.indexOf(' '); if (spaceIndex >= 0) { userName = userName.substring(0, spaceIndex); } return userName; } /** * Log in a user using the given subject * @param subject the subject to use when logging in a user, or null to * create a new subject. * * If subject is not null, the creator of subject is responsible for renewing * credentials. * * @throws IOException if login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public static void loginUserFromSubject(Subject subject) throws IOException { setLoginUser(createLoginUser(subject)); } private static UserGroupInformation createLoginUser(Subject subject) throws IOException { UserGroupInformation realUser = doSubjectLogin(subject, null); UserGroupInformation loginUser = null; try { // If the HADOOP_PROXY_USER environment variable or property // is specified, create a proxy user as the logged in user. String proxyUser = System.getenv(HADOOP_PROXY_USER); if (proxyUser == null) { proxyUser = System.getProperty(HADOOP_PROXY_USER); } loginUser = proxyUser == null ? realUser : createProxyUser(proxyUser, realUser); String tokenFileLocation = System.getProperty(HADOOP_TOKEN_FILES); if (tokenFileLocation == null) { tokenFileLocation = conf.get(HADOOP_TOKEN_FILES); } if (tokenFileLocation != null) { for (String tokenFileName: StringUtils.getTrimmedStrings(tokenFileLocation)) { if (tokenFileName.length() > 0) { File tokenFile = new File(tokenFileName); if (tokenFile.exists() && tokenFile.isFile()) { Credentials cred = Credentials.readTokenStorageFile( tokenFile, conf); loginUser.addCredentials(cred); } else { LOG.info("tokenFile("+tokenFileName+") does not exist"); } } } } String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION); if (fileLocation != null) { // Load the token storage file and put all of the tokens into the // user. Don't use the FileSystem API for reading since it has a lock // cycle (HADOOP-9212). File source = new File(fileLocation); LOG.debug("Reading credentials from location set in {}: {}", HADOOP_TOKEN_FILE_LOCATION, source.getCanonicalPath()); if (!source.isFile()) { throw new FileNotFoundException("Source file " + source.getCanonicalPath() + " from " + HADOOP_TOKEN_FILE_LOCATION + " not found"); } Credentials cred = Credentials.readTokenStorageFile( source, conf); LOG.debug("Loaded {} tokens", cred.numberOfTokens()); loginUser.addCredentials(cred); } } catch (IOException ioe) { LOG.debug("failure to load login credentials", ioe); throw ioe; } if (LOG.isDebugEnabled()) { LOG.debug("UGI loginUser:"+loginUser); } return loginUser; } @InterfaceAudience.Private @InterfaceStability.Unstable @VisibleForTesting public static void setLoginUser(UserGroupInformation ugi) { // if this is to become stable, should probably logout the currently // logged in ugi if it's different loginUserRef.set(ugi); } private String getKeytab() { HadoopLoginContext login = getLogin(); return (login != null) ? login.getConfiguration().getParameters().get(LoginParam.KEYTAB) : null; } /** * Is the ugi managed by the UGI or an external subject? * @return true if managed by UGI. */ private boolean isHadoopLogin() { // checks if the private hadoop login context is managing the ugi. return getLogin() != null; } /** * Is this user logged in from a keytab file managed by the UGI? * @return true if the credentials are from a keytab file. */ public boolean isFromKeytab() { // can't simply check if keytab is present since a relogin failure will // have removed the keytab from priv creds. instead, check login params. return hasKerberosCredentials() && isHadoopLogin() && getKeytab() != null; } /** * Is this user logged in from a ticket (but no keytab) managed by the UGI? * @return true if the credentials are from a ticket cache. */ private boolean isFromTicket() { return hasKerberosCredentials() && isHadoopLogin() && getKeytab() == null; } /** * Get the Kerberos TGT * @return the user's TGT or null if none was found */ private KerberosTicket getTGT() { Set<KerberosTicket> tickets = subject .getPrivateCredentials(KerberosTicket.class); for (KerberosTicket ticket : tickets) { if (SecurityUtil.isOriginalTGT(ticket)) { return ticket; } } return null; } private long getRefreshTime(KerberosTicket tgt) { long start = tgt.getStartTime().getTime(); long end = tgt.getEndTime().getTime(); return start + (long) ((end - start) * TICKET_RENEW_WINDOW); } private boolean shouldRelogin() { return hasKerberosCredentials() && isHadoopLogin(); } @InterfaceAudience.Private @InterfaceStability.Unstable @VisibleForTesting /** * Spawn a thread to do periodic renewals of kerberos credentials from * a ticket cache. NEVER directly call this method. * @param force - used by tests to forcibly spawn thread */ void spawnAutoRenewalThreadForUserCreds(boolean force) { if (!force && (!shouldRelogin() || isFromKeytab())) { return; } //spawn thread only if we have kerb credentials Thread t = new Thread(new Runnable() { @Override public void run() { String cmd = conf.get("hadoop.kerberos.kinit.command", "kinit"); KerberosTicket tgt = getTGT(); if (tgt == null) { return; } long nextRefresh = getRefreshTime(tgt); RetryPolicy rp = null; while (true) { try { long now = Time.now(); if (LOG.isDebugEnabled()) { LOG.debug("Current time is " + now); LOG.debug("Next refresh is " + nextRefresh); } if (now < nextRefresh) { Thread.sleep(nextRefresh - now); } String output = Shell.execCommand(cmd, "-R"); if (LOG.isDebugEnabled()) { LOG.debug("Renewed ticket. kinit output: {}", output); } reloginFromTicketCache(); tgt = getTGT(); if (tgt == null) { LOG.warn("No TGT after renewal. Aborting renew thread for " + getUserName()); return; } nextRefresh = Math.max(getRefreshTime(tgt), now + kerberosMinSecondsBeforeRelogin); metrics.renewalFailures.set(0); rp = null; } catch (InterruptedException ie) { LOG.warn("Terminating renewal thread"); return; } catch (IOException ie) { metrics.renewalFailuresTotal.incr(); final long tgtEndTime = tgt.getEndTime().getTime(); LOG.warn("Exception encountered while running the renewal " + "command for {}. (TGT end time:{}, renewalFailures: {}," + "renewalFailuresTotal: {})", getUserName(), tgtEndTime, metrics.renewalFailures, metrics.renewalFailuresTotal, ie); final long now = Time.now(); if (rp == null) { // Use a dummy maxRetries to create the policy. The policy will // only be used to get next retry time with exponential back-off. // The final retry time will be later limited within the // tgt endTime in getNextTgtRenewalTime. rp = RetryPolicies.exponentialBackoffRetry(Long.SIZE - 2, kerberosMinSecondsBeforeRelogin, TimeUnit.MILLISECONDS); } try { nextRefresh = getNextTgtRenewalTime(tgtEndTime, now, rp); } catch (Exception e) { LOG.error("Exception when calculating next tgt renewal time", e); return; } metrics.renewalFailures.incr(); // retry until close enough to tgt endTime. if (now > nextRefresh) { LOG.error("TGT is expired. Aborting renew thread for {}.", getUserName()); return; } } } } }); t.setDaemon(true); t.setName("TGT Renewer for " + getUserName()); t.start(); } /** * Get time for next login retry. This will allow the thread to retry with * exponential back-off, until tgt endtime. * Last retry is {@link #kerberosMinSecondsBeforeRelogin} before endtime. * * @param tgtEndTime EndTime of the tgt. * @param now Current time. * @param rp The retry policy. * @return Time for next login retry. */ @VisibleForTesting static long getNextTgtRenewalTime(final long tgtEndTime, final long now, final RetryPolicy rp) throws Exception { final long lastRetryTime = tgtEndTime - kerberosMinSecondsBeforeRelogin; final RetryPolicy.RetryAction ra = rp.shouldRetry(null, metrics.renewalFailures.value(), 0, false); return Math.min(lastRetryTime, now + ra.delayMillis); } /** * Log a user in from a keytab file. Loads a user identity from a keytab * file and logs them in. They become the currently logged-in user. * @param user the principal name to load from the keytab * @param path the path to the keytab file * @throws IOException * @throws KerberosAuthException if it's a kerberos login exception. */ @InterfaceAudience.Public @InterfaceStability.Evolving public static void loginUserFromKeytab(String user, String path ) throws IOException { if (!isSecurityEnabled()) return; setLoginUser(loginUserFromKeytabAndReturnUGI(user, path)); LOG.info("Login successful for user " + user + " using keytab file " + path); } /** * Log the current user out who previously logged in using keytab. * This method assumes that the user logged in by calling * {@link #loginUserFromKeytab(String, String)}. * * @throws IOException * @throws KerberosAuthException if a failure occurred in logout, * or if the user did not log in by invoking loginUserFromKeyTab() before. */ @InterfaceAudience.Public @InterfaceStability.Evolving public void logoutUserFromKeytab() throws IOException { if (!hasKerberosCredentials()) { return; } HadoopLoginContext login = getLogin(); String keytabFile = getKeytab(); if (login == null || keytabFile == null) { throw new KerberosAuthException(MUST_FIRST_LOGIN_FROM_KEYTAB); } try { if (LOG.isDebugEnabled()) { LOG.debug("Initiating logout for " + getUserName()); } // hadoop login context internally locks credentials. login.logout(); } catch (LoginException le) { KerberosAuthException kae = new KerberosAuthException(LOGOUT_FAILURE, le); kae.setUser(user.toString()); kae.setKeytabFile(keytabFile); throw kae; } LOG.info("Logout successful for user " + getUserName() + " using keytab file " + keytabFile); } /** * Re-login a user from keytab if TGT is expired or is close to expiry. * * @throws IOException * @throws KerberosAuthException if it's a kerberos login exception. */ public void checkTGTAndReloginFromKeytab() throws IOException { reloginFromKeytab(true); } // if the first kerberos ticket is not TGT, then remove and destroy it since // the kerberos library of jdk always use the first kerberos ticket as TGT. // See HADOOP-13433 for more details. @VisibleForTesting void fixKerberosTicketOrder() { Set<Object> creds = getSubject().getPrivateCredentials(); synchronized (creds) { for (Iterator<Object> iter = creds.iterator(); iter.hasNext();) { Object cred = iter.next(); if (cred instanceof KerberosTicket) { KerberosTicket ticket = (KerberosTicket) cred; if (ticket.isDestroyed() || ticket.getServer() == null) { LOG.warn("Ticket is already destroyed, remove it."); iter.remove(); } else if (!ticket.getServer().getName().startsWith("krbtgt")) { LOG.warn( "The first kerberos ticket is not TGT" + "(the server principal is {}), remove and destroy it.", ticket.getServer()); iter.remove(); try { ticket.destroy(); } catch (DestroyFailedException e) { LOG.warn("destroy ticket failed", e); } } else { return; } } } } LOG.warn("Warning, no kerberos ticket found while attempting to renew ticket"); } /** * Re-Login a user in from a keytab file. Loads a user identity from a keytab * file and logs them in. They become the currently logged-in user. This * method assumes that {@link #loginUserFromKeytab(String, String)} had * happened already. * The Subject field of this UserGroupInformation object is updated to have * the new credentials. * @throws IOException * @throws KerberosAuthException on a failure */ @InterfaceAudience.Public @InterfaceStability.Evolving public void reloginFromKeytab() throws IOException { reloginFromKeytab(false); } private void reloginFromKeytab(boolean checkTGT) throws IOException { if (!shouldRelogin() || !isFromKeytab()) { return; } HadoopLoginContext login = getLogin(); if (login == null) { throw new KerberosAuthException(MUST_FIRST_LOGIN_FROM_KEYTAB); } if (checkTGT) { KerberosTicket tgt = getTGT(); if (tgt != null && !shouldRenewImmediatelyForTests && Time.now() < getRefreshTime(tgt)) { return; } } relogin(login); } /** * Re-Login a user in from the ticket cache. This * method assumes that login had happened already. * The Subject field of this UserGroupInformation object is updated to have * the new credentials. * @throws IOException * @throws KerberosAuthException on a failure */ @InterfaceAudience.Public @InterfaceStability.Evolving public void reloginFromTicketCache() throws IOException { if (!shouldRelogin() || !isFromTicket()) { return; } HadoopLoginContext login = getLogin(); if (login == null) { throw new KerberosAuthException(MUST_FIRST_LOGIN); } relogin(login); } private void relogin(HadoopLoginContext login) throws IOException { // ensure the relogin is atomic to avoid leaving credentials in an // inconsistent state. prevents other ugi instances, SASL, and SPNEGO // from accessing or altering credentials during the relogin. synchronized(login.getSubjectLock()) { // another racing thread may have beat us to the relogin. if (login == getLogin()) { unprotectedRelogin(login); } } } private void unprotectedRelogin(HadoopLoginContext login) throws IOException { assert Thread.holdsLock(login.getSubjectLock()); long now = Time.now(); if (!hasSufficientTimeElapsed(now)) { return; } // register most recent relogin attempt user.setLastLogin(now); try { if (LOG.isDebugEnabled()) { LOG.debug("Initiating logout for " + getUserName()); } //clear up the kerberos state. But the tokens are not cleared! As per //the Java kerberos login module code, only the kerberos credentials //are cleared login.logout(); //login and also update the subject field of this instance to //have the new credentials (pass it to the LoginContext constructor) login = newLoginContext( login.getAppName(), login.getSubject(), login.getConfiguration()); if (LOG.isDebugEnabled()) { LOG.debug("Initiating re-login for " + getUserName()); } login.login(); // this should be unnecessary. originally added due to improper locking // of the subject during relogin. fixKerberosTicketOrder(); setLogin(login); } catch (LoginException le) { KerberosAuthException kae = new KerberosAuthException(LOGIN_FAILURE, le); kae.setUser(getUserName()); throw kae; } } /** * Log a user in from a keytab file. Loads a user identity from a keytab * file and login them in. This new user does not affect the currently * logged-in user. * @param user the principal name to load from the keytab * @param path the path to the keytab file * @throws IOException if the keytab file can't be read */ public static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path ) throws IOException { if (!isSecurityEnabled()) return UserGroupInformation.getCurrentUser(); LoginParams params = new LoginParams(); params.put(LoginParam.PRINCIPAL, user); params.put(LoginParam.KEYTAB, path); return doSubjectLogin(null, params); } private boolean hasSufficientTimeElapsed(long now) { if (!shouldRenewImmediatelyForTests && now - user.getLastLogin() < kerberosMinSecondsBeforeRelogin ) { LOG.warn("Not attempting to re-login since the last re-login was " + "attempted less than " + (kerberosMinSecondsBeforeRelogin/1000) + " seconds before. Last Login=" + user.getLastLogin()); return false; } return true; } /** * Did the login happen via keytab * @return true or false */ @InterfaceAudience.Public @InterfaceStability.Evolving public static boolean isLoginKeytabBased() throws IOException { return getLoginUser().isFromKeytab(); } /** * Did the login happen via ticket cache * @return true or false */ public static boolean isLoginTicketBased() throws IOException { return getLoginUser().isFromTicket(); } /** * Create a user from a login name. It is intended to be used for remote * users in RPC, since it won't have any credentials. * @param user the full user principal name, must not be empty or null * @return the UserGroupInformation for the remote user. */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation createRemoteUser(String user) { return createRemoteUser(user, AuthMethod.SIMPLE); } /** * Create a user from a login name. It is intended to be used for remote * users in RPC, since it won't have any credentials. * @param user the full user principal name, must not be empty or null * @return the UserGroupInformation for the remote user. */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation createRemoteUser(String user, AuthMethod authMethod) { if (user == null || user.isEmpty()) { throw new IllegalArgumentException("Null user"); } Subject subject = new Subject(); subject.getPrincipals().add(new User(user)); UserGroupInformation result = new UserGroupInformation(subject); result.setAuthenticationMethod(authMethod); return result; } /** * existing types of authentications' methods */ @InterfaceAudience.Public @InterfaceStability.Evolving public enum AuthenticationMethod { // currently we support only one auth per method, but eventually a // subtype is needed to differentiate, ex. if digest is token or ldap SIMPLE(AuthMethod.SIMPLE, HadoopConfiguration.SIMPLE_CONFIG_NAME), KERBEROS(AuthMethod.KERBEROS, HadoopConfiguration.KERBEROS_CONFIG_NAME), TOKEN(AuthMethod.TOKEN), CERTIFICATE(null), KERBEROS_SSL(null), PROXY(null); private final AuthMethod authMethod; private final String loginAppName; private AuthenticationMethod(AuthMethod authMethod) { this(authMethod, null); } private AuthenticationMethod(AuthMethod authMethod, String loginAppName) { this.authMethod = authMethod; this.loginAppName = loginAppName; } public AuthMethod getAuthMethod() { return authMethod; } String getLoginAppName() { if (loginAppName == null) { throw new UnsupportedOperationException( this + " login authentication is not supported"); } return loginAppName; } public static AuthenticationMethod valueOf(AuthMethod authMethod) { for (AuthenticationMethod value : values()) { if (value.getAuthMethod() == authMethod) { return value; } } throw new IllegalArgumentException( "no authentication method for " + authMethod); } }; /** * Create a proxy user using username of the effective user and the ugi of the * real user. * @param user * @param realUser * @return proxyUser ugi */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation createProxyUser(String user, UserGroupInformation realUser) { if (user == null || user.isEmpty()) { throw new IllegalArgumentException("Null user"); } if (realUser == null) { throw new IllegalArgumentException("Null real user"); } Subject subject = new Subject(); Set<Principal> principals = subject.getPrincipals(); principals.add(new User(user, AuthenticationMethod.PROXY, null)); principals.add(new RealUser(realUser)); return new UserGroupInformation(subject); } /** * get RealUser (vs. EffectiveUser) * @return realUser running over proxy user */ @InterfaceAudience.Public @InterfaceStability.Evolving public UserGroupInformation getRealUser() { for (RealUser p: subject.getPrincipals(RealUser.class)) { return p.getRealUser(); } return null; } /** * This class is used for storing the groups for testing. It stores a local * map that has the translation of usernames to groups. */ private static class TestingGroups extends Groups { private final Map<String, List<String>> userToGroupsMapping = new HashMap<String,List<String>>(); private Groups underlyingImplementation; private TestingGroups(Groups underlyingImplementation) { super(new org.apache.hadoop.conf.Configuration()); this.underlyingImplementation = underlyingImplementation; } @Override public List<String> getGroups(String user) throws IOException { List<String> result = userToGroupsMapping.get(user); if (result == null) { result = underlyingImplementation.getGroups(user); } return result; } private void setUserGroups(String user, String[] groups) { userToGroupsMapping.put(user, Arrays.asList(groups)); } } /** * Create a UGI for testing HDFS and MapReduce * @param user the full user principal name * @param userGroups the names of the groups that the user belongs to * @return a fake user for running unit tests */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation createUserForTesting(String user, String[] userGroups) { ensureInitialized(); UserGroupInformation ugi = createRemoteUser(user); // make sure that the testing object is setup if (!(groups instanceof TestingGroups)) { groups = new TestingGroups(groups); } // add the user groups ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups); return ugi; } /** * Create a proxy user UGI for testing HDFS and MapReduce * * @param user * the full user principal name for effective user * @param realUser * UGI of the real user * @param userGroups * the names of the groups that the user belongs to * @return a fake user for running unit tests */ public static UserGroupInformation createProxyUserForTesting(String user, UserGroupInformation realUser, String[] userGroups) { ensureInitialized(); UserGroupInformation ugi = createProxyUser(user, realUser); // make sure that the testing object is setup if (!(groups instanceof TestingGroups)) { groups = new TestingGroups(groups); } // add the user groups ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups); return ugi; } /** * Get the user's login name. * @return the user's name up to the first '/' or '@'. */ public String getShortUserName() { return user.getShortName(); } public String getPrimaryGroupName() throws IOException { List<String> groups = getGroups(); if (groups.isEmpty()) { throw new IOException("There is no primary group for UGI " + this); } return groups.get(0); } /** * Get the user's full principal name. * @return the user's full principal name. */ @InterfaceAudience.Public @InterfaceStability.Evolving public String getUserName() { return user.getName(); } /** * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been * authenticated by the RPC layer as belonging to the user represented by this * UGI. * * @param tokenId * tokenIdentifier to be added * @return true on successful add of new tokenIdentifier */ public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) { return subject.getPublicCredentials().add(tokenId); } /** * Get the set of TokenIdentifiers belonging to this UGI * * @return the set of TokenIdentifiers belonging to this UGI */ public synchronized Set<TokenIdentifier> getTokenIdentifiers() { return subject.getPublicCredentials(TokenIdentifier.class); } /** * Add a token to this UGI * * @param token Token to be added * @return true on successful add of new token */ public boolean addToken(Token<? extends TokenIdentifier> token) { return (token != null) ? addToken(token.getService(), token) : false; } /** * Add a named token to this UGI * * @param alias Name of the token * @param token Token to be added * @return true on successful add of new token */ public boolean addToken(Text alias, Token<? extends TokenIdentifier> token) { synchronized (subject) { getCredentialsInternal().addToken(alias, token); return true; } } /** * Obtain the collection of tokens associated with this user. * * @return an unmodifiable collection of tokens associated with user */ public Collection<Token<? extends TokenIdentifier>> getTokens() { synchronized (subject) { return Collections.unmodifiableCollection( new ArrayList<Token<?>>(getCredentialsInternal().getAllTokens())); } } /** * Obtain the tokens in credentials form associated with this user. * * @return Credentials of tokens associated with this user */ public Credentials getCredentials() { synchronized (subject) { Credentials creds = new Credentials(getCredentialsInternal()); Iterator<Token<?>> iter = creds.getAllTokens().iterator(); while (iter.hasNext()) { if (iter.next().isPrivate()) { iter.remove(); } } return creds; } } /** * Add the given Credentials to this user. * @param credentials of tokens and secrets */ public void addCredentials(Credentials credentials) { synchronized (subject) { getCredentialsInternal().addAll(credentials); } } private synchronized Credentials getCredentialsInternal() { final Credentials credentials; final Set<Credentials> credentialsSet = subject.getPrivateCredentials(Credentials.class); if (!credentialsSet.isEmpty()){ credentials = credentialsSet.iterator().next(); } else { credentials = new Credentials(); subject.getPrivateCredentials().add(credentials); } return credentials; } /** * Get the group names for this user. {@link #getGroups()} is less * expensive alternative when checking for a contained element. * @return the list of users with the primary group first. If the command * fails, it returns an empty list. */ public String[] getGroupNames() { List<String> groups = getGroups(); return groups.toArray(new String[groups.size()]); } /** * Get the group names for this user. * @return the list of users with the primary group first. If the command * fails, it returns an empty list. */ public List<String> getGroups() { ensureInitialized(); try { return groups.getGroups(getShortUserName()); } catch (IOException ie) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to get groups for user " + getShortUserName() + " by " + ie); LOG.trace("TRACE", ie); } return Collections.emptyList(); } } /** * Return the username. */ @Override public String toString() { StringBuilder sb = new StringBuilder(getUserName()); sb.append(" (auth:"+getAuthenticationMethod()+")"); if (getRealUser() != null) { sb.append(" via ").append(getRealUser().toString()); } return sb.toString(); } /** * Sets the authentication method in the subject * * @param authMethod */ public synchronized void setAuthenticationMethod(AuthenticationMethod authMethod) { user.setAuthenticationMethod(authMethod); } /** * Sets the authentication method in the subject * * @param authMethod */ public void setAuthenticationMethod(AuthMethod authMethod) { user.setAuthenticationMethod(AuthenticationMethod.valueOf(authMethod)); } /** * Get the authentication method from the subject * * @return AuthenticationMethod in the subject, null if not present. */ public synchronized AuthenticationMethod getAuthenticationMethod() { return user.getAuthenticationMethod(); } /** * Get the authentication method from the real user's subject. If there * is no real user, return the given user's authentication method. * * @return AuthenticationMethod in the subject, null if not present. */ public synchronized AuthenticationMethod getRealAuthenticationMethod() { UserGroupInformation ugi = getRealUser(); if (ugi == null) { ugi = this; } return ugi.getAuthenticationMethod(); } /** * Returns the authentication method of a ugi. If the authentication method is * PROXY, returns the authentication method of the real user. * * @param ugi * @return AuthenticationMethod */ public static AuthenticationMethod getRealAuthenticationMethod( UserGroupInformation ugi) { AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); if (authMethod == AuthenticationMethod.PROXY) { authMethod = ugi.getRealUser().getAuthenticationMethod(); } return authMethod; } /** * Compare the subjects to see if they are equal to each other. */ @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o == null || getClass() != o.getClass()) { return false; } else { return subject == ((UserGroupInformation) o).subject; } } /** * Return the hash of the subject. */ @Override public int hashCode() { return System.identityHashCode(subject); } /** * Get the underlying subject from this ugi. * @return the subject that represents this user. */ protected Subject getSubject() { return subject; } /** * Run the given action as the user. * @param <T> the return type of the run method * @param action the method to execute * @return the value from the run method */ @InterfaceAudience.Public @InterfaceStability.Evolving public <T> T doAs(PrivilegedAction<T> action) { logPrivilegedAction(subject, action); return Subject.doAs(subject, action); } /** * Run the given action as the user, potentially throwing an exception. * @param <T> the return type of the run method * @param action the method to execute * @return the value from the run method * @throws IOException if the action throws an IOException * @throws Error if the action throws an Error * @throws RuntimeException if the action throws a RuntimeException * @throws InterruptedException if the action throws an InterruptedException * @throws UndeclaredThrowableException if the action throws something else */ @InterfaceAudience.Public @InterfaceStability.Evolving public <T> T doAs(PrivilegedExceptionAction<T> action ) throws IOException, InterruptedException { try { logPrivilegedAction(subject, action); return Subject.doAs(subject, action); } catch (PrivilegedActionException pae) { Throwable cause = pae.getCause(); if (LOG.isDebugEnabled()) { LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause); } if (cause == null) { throw new RuntimeException("PrivilegedActionException with no " + "underlying cause. UGI [" + this + "]" +": " + pae, pae); } else if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof InterruptedException) { throw (InterruptedException) cause; } else { throw new UndeclaredThrowableException(cause); } } } private void logPrivilegedAction(Subject subject, Object action) { if (LOG.isDebugEnabled()) { // would be nice if action included a descriptive toString() String where = new Throwable().getStackTrace()[2].toString(); LOG.debug("PrivilegedAction as:"+this+" from:"+where); } } /** * Log current UGI and token information into specified log. * @param ugi - UGI * @throws IOException */ @InterfaceAudience.LimitedPrivate({"HDFS", "KMS"}) @InterfaceStability.Unstable public static void logUserInfo(Logger log, String caption, UserGroupInformation ugi) throws IOException { if (log.isDebugEnabled()) { log.debug(caption + " UGI: " + ugi); for (Token<?> token : ugi.getTokens()) { log.debug("+token:" + token); } } } /** * Log all (current, real, login) UGI and token info into specified log. * @param ugi - UGI * @throws IOException */ @InterfaceAudience.LimitedPrivate({"HDFS", "KMS"}) @InterfaceStability.Unstable public static void logAllUserInfo(Logger log, UserGroupInformation ugi) throws IOException { if (log.isDebugEnabled()) { logUserInfo(log, "Current", ugi.getCurrentUser()); if (ugi.getRealUser() != null) { logUserInfo(log, "Real", ugi.getRealUser()); } logUserInfo(log, "Login", ugi.getLoginUser()); } } /** * Log all (current, real, login) UGI and token info into UGI debug log. * @param ugi - UGI * @throws IOException */ public static void logAllUserInfo(UserGroupInformation ugi) throws IOException { logAllUserInfo(LOG, ugi); } private void print() throws IOException { System.out.println("User: " + getUserName()); System.out.print("Group Ids: "); System.out.println(); String[] groups = getGroupNames(); System.out.print("Groups: "); for(int i=0; i < groups.length; i++) { System.out.print(groups[i] + " "); } System.out.println(); } /** * Login a subject with the given parameters. If the subject is null, * the login context used to create the subject will be attached. * @param subject to login, null for new subject. * @param params for login, null for externally managed ugi. * @return UserGroupInformation for subject * @throws IOException */ private static UserGroupInformation doSubjectLogin( Subject subject, LoginParams params) throws IOException { ensureInitialized(); // initial default login. if (subject == null && params == null) { params = LoginParams.getDefaults(); } HadoopConfiguration loginConf = new HadoopConfiguration(params); try { HadoopLoginContext login = newLoginContext( authenticationMethod.getLoginAppName(), subject, loginConf); login.login(); UserGroupInformation ugi = new UserGroupInformation(login.getSubject()); // attach login context for relogin unless this was a pre-existing // subject. if (subject == null) { params.put(LoginParam.PRINCIPAL, ugi.getUserName()); ugi.setLogin(login); } return ugi; } catch (LoginException le) { KerberosAuthException kae = new KerberosAuthException(FAILURE_TO_LOGIN, le); if (params != null) { kae.setPrincipal(params.get(LoginParam.PRINCIPAL)); kae.setKeytabFile(params.get(LoginParam.KEYTAB)); kae.setTicketCacheFile(params.get(LoginParam.CCACHE)); } throw kae; } } // parameters associated with kerberos logins. may be extended to support // additional authentication methods. enum LoginParam { PRINCIPAL, KEYTAB, CCACHE, } // explicitly private to prevent external tampering. private static class LoginParams extends EnumMap<LoginParam,String> implements Parameters { LoginParams() { super(LoginParam.class); } // do not add null values, nor allow existing values to be overriden. @Override public String put(LoginParam param, String val) { boolean add = val != null && !containsKey(param); return add ? super.put(param, val) : null; } static LoginParams getDefaults() { LoginParams params = new LoginParams(); params.put(LoginParam.PRINCIPAL, System.getenv("KRB5PRINCIPAL")); params.put(LoginParam.KEYTAB, System.getenv("KRB5KEYTAB")); params.put(LoginParam.CCACHE, System.getenv("KRB5CCNAME")); return params; } } // wrapper to allow access to fields necessary to recreate the same login // context for relogin. explicitly private to prevent external tampering. private static class HadoopLoginContext extends LoginContext { private final String appName; private final HadoopConfiguration conf; private AtomicBoolean isLoggedIn = new AtomicBoolean(); HadoopLoginContext(String appName, Subject subject, HadoopConfiguration conf) throws LoginException { super(appName, subject, null, conf); this.appName = appName; this.conf = conf; } String getAppName() { return appName; } HadoopConfiguration getConfiguration() { return conf; } // the locking model for logins cannot rely on ugi instance synchronization // since a subject will be referenced by multiple ugi instances. Object getSubjectLock() { Subject subject = getSubject(); // if subject is null, the login context will create the subject // so just lock on this context. return (subject == null) ? this : subject.getPrivateCredentials(); } @Override public void login() throws LoginException { synchronized(getSubjectLock()) { MutableRate metric = metrics.loginFailure; long start = Time.monotonicNow(); try { super.login(); isLoggedIn.set(true); metric = metrics.loginSuccess; } finally { metric.add(Time.monotonicNow() - start); } } } @Override public void logout() throws LoginException { synchronized(getSubjectLock()) { if (isLoggedIn.compareAndSet(true, false)) { super.logout(); } } } } /** * A JAAS configuration that defines the login modules that we want * to use for login. */ @InterfaceAudience.Private @InterfaceStability.Unstable private static class HadoopConfiguration extends javax.security.auth.login.Configuration { static final String KRB5_LOGIN_MODULE = KerberosUtil.getKrb5LoginModuleName(); static final String SIMPLE_CONFIG_NAME = "hadoop-simple"; static final String KERBEROS_CONFIG_NAME = "hadoop-kerberos"; private static final Map<String, String> BASIC_JAAS_OPTIONS = new HashMap<String,String>(); static { if ("true".equalsIgnoreCase(System.getenv("HADOOP_JAAS_DEBUG"))) { BASIC_JAAS_OPTIONS.put("debug", "true"); } } static final AppConfigurationEntry OS_SPECIFIC_LOGIN = new AppConfigurationEntry( OS_LOGIN_MODULE_NAME, LoginModuleControlFlag.REQUIRED, BASIC_JAAS_OPTIONS); static final AppConfigurationEntry HADOOP_LOGIN = new AppConfigurationEntry( HadoopLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, BASIC_JAAS_OPTIONS); private final LoginParams params; HadoopConfiguration(LoginParams params) { this.params = params; } @Override public LoginParams getParameters() { return params; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { ArrayList<AppConfigurationEntry> entries = new ArrayList<>(); // login of external subject passes no params. technically only // existing credentials should be used but other components expect // the login to succeed with local user fallback if no principal. if (params == null || appName.equals(SIMPLE_CONFIG_NAME)) { entries.add(OS_SPECIFIC_LOGIN); } else if (appName.equals(KERBEROS_CONFIG_NAME)) { // existing semantics are the initial default login allows local user // fallback. this is not allowed when a principal explicitly // specified or during a relogin. if (!params.containsKey(LoginParam.PRINCIPAL)) { entries.add(OS_SPECIFIC_LOGIN); } entries.add(getKerberosEntry()); } entries.add(HADOOP_LOGIN); return entries.toArray(new AppConfigurationEntry[0]); } private AppConfigurationEntry getKerberosEntry() { final Map<String,String> options = new HashMap<>(BASIC_JAAS_OPTIONS); LoginModuleControlFlag controlFlag = LoginModuleControlFlag.OPTIONAL; // kerberos login is mandatory if principal is specified. principal // will not be set for initial default login, but will always be set // for relogins. final String principal = params.get(LoginParam.PRINCIPAL); if (principal != null) { options.put("principal", principal); controlFlag = LoginModuleControlFlag.REQUIRED; } // use keytab if given else fallback to ticket cache. if (IBM_JAVA) { if (params.containsKey(LoginParam.KEYTAB)) { final String keytab = params.get(LoginParam.KEYTAB); if (keytab != null) { options.put("useKeytab", prependFileAuthority(keytab)); } else { options.put("useDefaultKeytab", "true"); } options.put("credsType", "both"); } else { String ticketCache = params.get(LoginParam.CCACHE); if (ticketCache != null) { options.put("useCcache", prependFileAuthority(ticketCache)); } else { options.put("useDefaultCcache", "true"); } options.put("renewTGT", "true"); } } else { if (params.containsKey(LoginParam.KEYTAB)) { options.put("useKeyTab", "true"); final String keytab = params.get(LoginParam.KEYTAB); if (keytab != null) { options.put("keyTab", keytab); } options.put("storeKey", "true"); } else { options.put("useTicketCache", "true"); String ticketCache = params.get(LoginParam.CCACHE); if (ticketCache != null) { options.put("ticketCache", ticketCache); } options.put("renewTGT", "true"); } options.put("doNotPrompt", "true"); } options.put("refreshKrb5Config", "true"); return new AppConfigurationEntry( KRB5_LOGIN_MODULE, controlFlag, options); } private static String prependFileAuthority(String keytabPath) { return keytabPath.startsWith("file://") ? keytabPath : "file://" + keytabPath; } } /** * A test method to print out the current user's UGI. * @param args if there are two arguments, read the user from the keytab * and print it out. * @throws Exception */ public static void main(String [] args) throws Exception { System.out.println("Getting UGI for current user"); UserGroupInformation ugi = getCurrentUser(); ugi.print(); System.out.println("UGI: " + ugi); System.out.println("Auth method " + ugi.user.getAuthenticationMethod()); System.out.println("Keytab " + ugi.isFromKeytab()); System.out.println("============================================================"); if (args.length == 2) { System.out.println("Getting UGI from keytab...."); loginUserFromKeytab(args[0], args[1]); getCurrentUser().print(); System.out.println("Keytab: " + ugi); UserGroupInformation loginUgi = getLoginUser(); System.out.println("Auth method " + loginUgi.getAuthenticationMethod()); System.out.println("Keytab " + loginUgi.isFromKeytab()); } } }
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/UserGroupInformation.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.security; import static org.apache.hadoop.fs.CommonConfigurationKeys.HADOOP_USER_GROUP_METRICS_PERCENTILES_INTERVALS; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN_DEFAULT; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_TOKEN_FILES; import static org.apache.hadoop.security.UGIExceptionMessages.*; import static org.apache.hadoop.util.PlatformName.IBM_JAVA; import com.google.common.annotations.VisibleForTesting; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; import java.security.AccessControlContext; import java.security.AccessController; import java.security.Principal; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.security.auth.DestroyFailedException; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.kerberos.KerberosPrincipal; import javax.security.auth.kerberos.KerberosTicket; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; import javax.security.auth.login.Configuration.Parameters; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; import org.apache.hadoop.io.retry.RetryPolicies; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.metrics2.annotation.Metric; import org.apache.hadoop.metrics2.annotation.Metrics; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.lib.MetricsRegistry; import org.apache.hadoop.metrics2.lib.MutableGaugeInt; import org.apache.hadoop.metrics2.lib.MutableGaugeLong; import org.apache.hadoop.metrics2.lib.MutableQuantiles; import org.apache.hadoop.metrics2.lib.MutableRate; import org.apache.hadoop.security.SaslRpcServer.AuthMethod; import org.apache.hadoop.security.authentication.util.KerberosUtil; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.util.Shell; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * User and group information for Hadoop. * This class wraps around a JAAS Subject and provides methods to determine the * user's username and groups. It supports both the Windows, Unix and Kerberos * login modules. */ @InterfaceAudience.Public @InterfaceStability.Evolving public class UserGroupInformation { @VisibleForTesting static final Logger LOG = LoggerFactory.getLogger( UserGroupInformation.class); /** * Percentage of the ticket window to use before we renew ticket. */ private static final float TICKET_RENEW_WINDOW = 0.80f; private static boolean shouldRenewImmediatelyForTests = false; static final String HADOOP_USER_NAME = "HADOOP_USER_NAME"; static final String HADOOP_PROXY_USER = "HADOOP_PROXY_USER"; /** * For the purposes of unit tests, we want to test login * from keytab and don't want to wait until the renew * window (controlled by TICKET_RENEW_WINDOW). * @param immediate true if we should login without waiting for ticket window */ @VisibleForTesting public static void setShouldRenewImmediatelyForTests(boolean immediate) { shouldRenewImmediatelyForTests = immediate; } /** * UgiMetrics maintains UGI activity statistics * and publishes them through the metrics interfaces. */ @Metrics(about="User and group related metrics", context="ugi") static class UgiMetrics { final MetricsRegistry registry = new MetricsRegistry("UgiMetrics"); @Metric("Rate of successful kerberos logins and latency (milliseconds)") MutableRate loginSuccess; @Metric("Rate of failed kerberos logins and latency (milliseconds)") MutableRate loginFailure; @Metric("GetGroups") MutableRate getGroups; MutableQuantiles[] getGroupsQuantiles; @Metric("Renewal failures since startup") private MutableGaugeLong renewalFailuresTotal; @Metric("Renewal failures since last successful login") private MutableGaugeInt renewalFailures; static UgiMetrics create() { return DefaultMetricsSystem.instance().register(new UgiMetrics()); } static void reattach() { metrics = UgiMetrics.create(); } void addGetGroups(long latency) { getGroups.add(latency); if (getGroupsQuantiles != null) { for (MutableQuantiles q : getGroupsQuantiles) { q.add(latency); } } } MutableGaugeInt getRenewalFailures() { return renewalFailures; } } /** * A login module that looks at the Kerberos, Unix, or Windows principal and * adds the corresponding UserName. */ @InterfaceAudience.Private public static class HadoopLoginModule implements LoginModule { private Subject subject; @Override public boolean abort() throws LoginException { return true; } private <T extends Principal> T getCanonicalUser(Class<T> cls) { for(T user: subject.getPrincipals(cls)) { return user; } return null; } @Override public boolean commit() throws LoginException { if (LOG.isDebugEnabled()) { LOG.debug("hadoop login commit"); } // if we already have a user, we are done. if (!subject.getPrincipals(User.class).isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("using existing subject:"+subject.getPrincipals()); } return true; } Principal user = getCanonicalUser(KerberosPrincipal.class); if (user != null) { if (LOG.isDebugEnabled()) { LOG.debug("using kerberos user:"+user); } } //If we don't have a kerberos user and security is disabled, check //if user is specified in the environment or properties if (!isSecurityEnabled() && (user == null)) { String envUser = System.getenv(HADOOP_USER_NAME); if (envUser == null) { envUser = System.getProperty(HADOOP_USER_NAME); } user = envUser == null ? null : new User(envUser); } // use the OS user if (user == null) { user = getCanonicalUser(OS_PRINCIPAL_CLASS); if (LOG.isDebugEnabled()) { LOG.debug("using local user:"+user); } } // if we found the user, add our principal if (user != null) { if (LOG.isDebugEnabled()) { LOG.debug("Using user: \"" + user + "\" with name " + user.getName()); } User userEntry = null; try { // LoginContext will be attached later unless it's an external // subject. AuthenticationMethod authMethod = (user instanceof KerberosPrincipal) ? AuthenticationMethod.KERBEROS : AuthenticationMethod.SIMPLE; userEntry = new User(user.getName(), authMethod, null); } catch (Exception e) { throw (LoginException)(new LoginException(e.toString()).initCause(e)); } if (LOG.isDebugEnabled()) { LOG.debug("User entry: \"" + userEntry.toString() + "\"" ); } subject.getPrincipals().add(userEntry); return true; } LOG.error("Can't find user in " + subject); throw new LoginException("Can't find user name"); } @Override public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { this.subject = subject; } @Override public boolean login() throws LoginException { if (LOG.isDebugEnabled()) { LOG.debug("hadoop login"); } return true; } @Override public boolean logout() throws LoginException { if (LOG.isDebugEnabled()) { LOG.debug("hadoop logout"); } return true; } } /** * Reattach the class's metrics to a new metric system. */ public static void reattachMetrics() { UgiMetrics.reattach(); } /** Metrics to track UGI activity */ static UgiMetrics metrics = UgiMetrics.create(); /** The auth method to use */ private static AuthenticationMethod authenticationMethod; /** Server-side groups fetching service */ private static Groups groups; /** Min time (in seconds) before relogin for Kerberos */ private static long kerberosMinSecondsBeforeRelogin; /** The configuration to use */ private static Configuration conf; /**Environment variable pointing to the token cache file*/ public static final String HADOOP_TOKEN_FILE_LOCATION = "HADOOP_TOKEN_FILE_LOCATION"; /** * A method to initialize the fields that depend on a configuration. * Must be called before useKerberos or groups is used. */ private static void ensureInitialized() { if (conf == null) { synchronized(UserGroupInformation.class) { if (conf == null) { // someone might have beat us initialize(new Configuration(), false); } } } } /** * Initialize UGI and related classes. * @param conf the configuration to use */ private static synchronized void initialize(Configuration conf, boolean overrideNameRules) { authenticationMethod = SecurityUtil.getAuthenticationMethod(conf); if (overrideNameRules || !HadoopKerberosName.hasRulesBeenSet()) { try { HadoopKerberosName.setConfiguration(conf); } catch (IOException ioe) { throw new RuntimeException( "Problem with Kerberos auth_to_local name configuration", ioe); } } try { kerberosMinSecondsBeforeRelogin = 1000L * conf.getLong( HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN, HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN_DEFAULT); } catch(NumberFormatException nfe) { throw new IllegalArgumentException("Invalid attribute value for " + HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN + " of " + conf.get(HADOOP_KERBEROS_MIN_SECONDS_BEFORE_RELOGIN)); } // If we haven't set up testing groups, use the configuration to find it if (!(groups instanceof TestingGroups)) { groups = Groups.getUserToGroupsMappingService(conf); } UserGroupInformation.conf = conf; if (metrics.getGroupsQuantiles == null) { int[] intervals = conf.getInts(HADOOP_USER_GROUP_METRICS_PERCENTILES_INTERVALS); if (intervals != null && intervals.length > 0) { final int length = intervals.length; MutableQuantiles[] getGroupsQuantiles = new MutableQuantiles[length]; for (int i = 0; i < length; i++) { getGroupsQuantiles[i] = metrics.registry.newQuantiles( "getGroups" + intervals[i] + "s", "Get groups", "ops", "latency", intervals[i]); } metrics.getGroupsQuantiles = getGroupsQuantiles; } } } /** * Set the static configuration for UGI. * In particular, set the security authentication mechanism and the * group look up service. * @param conf the configuration to use */ @InterfaceAudience.Public @InterfaceStability.Evolving public static void setConfiguration(Configuration conf) { initialize(conf, true); } @InterfaceAudience.Private @VisibleForTesting public static void reset() { authenticationMethod = null; conf = null; groups = null; kerberosMinSecondsBeforeRelogin = 0; setLoginUser(null); HadoopKerberosName.setRules(null); } /** * Determine if UserGroupInformation is using Kerberos to determine * user identities or is relying on simple authentication * * @return true if UGI is working in a secure environment */ public static boolean isSecurityEnabled() { return !isAuthenticationMethodEnabled(AuthenticationMethod.SIMPLE); } @InterfaceAudience.Private @InterfaceStability.Evolving private static boolean isAuthenticationMethodEnabled(AuthenticationMethod method) { ensureInitialized(); return (authenticationMethod == method); } /** * Information about the logged in user. */ private static final AtomicReference<UserGroupInformation> loginUserRef = new AtomicReference<>(); private final Subject subject; // All non-static fields must be read-only caches that come from the subject. private final User user; private static String OS_LOGIN_MODULE_NAME; private static Class<? extends Principal> OS_PRINCIPAL_CLASS; private static final boolean windows = System.getProperty("os.name").startsWith("Windows"); private static final boolean is64Bit = System.getProperty("os.arch").contains("64") || System.getProperty("os.arch").contains("s390x"); private static final boolean aix = System.getProperty("os.name").equals("AIX"); /* Return the OS login module class name */ private static String getOSLoginModuleName() { if (IBM_JAVA) { if (windows) { return is64Bit ? "com.ibm.security.auth.module.Win64LoginModule" : "com.ibm.security.auth.module.NTLoginModule"; } else if (aix) { return is64Bit ? "com.ibm.security.auth.module.AIX64LoginModule" : "com.ibm.security.auth.module.AIXLoginModule"; } else { return "com.ibm.security.auth.module.LinuxLoginModule"; } } else { return windows ? "com.sun.security.auth.module.NTLoginModule" : "com.sun.security.auth.module.UnixLoginModule"; } } /* Return the OS principal class */ @SuppressWarnings("unchecked") private static Class<? extends Principal> getOsPrincipalClass() { ClassLoader cl = ClassLoader.getSystemClassLoader(); try { String principalClass = null; if (IBM_JAVA) { if (is64Bit) { principalClass = "com.ibm.security.auth.UsernamePrincipal"; } else { if (windows) { principalClass = "com.ibm.security.auth.NTUserPrincipal"; } else if (aix) { principalClass = "com.ibm.security.auth.AIXPrincipal"; } else { principalClass = "com.ibm.security.auth.LinuxPrincipal"; } } } else { principalClass = windows ? "com.sun.security.auth.NTUserPrincipal" : "com.sun.security.auth.UnixPrincipal"; } return (Class<? extends Principal>) cl.loadClass(principalClass); } catch (ClassNotFoundException e) { LOG.error("Unable to find JAAS classes:" + e.getMessage()); } return null; } static { OS_LOGIN_MODULE_NAME = getOSLoginModuleName(); OS_PRINCIPAL_CLASS = getOsPrincipalClass(); } private static class RealUser implements Principal { private final UserGroupInformation realUser; RealUser(UserGroupInformation realUser) { this.realUser = realUser; } @Override public String getName() { return realUser.getUserName(); } public UserGroupInformation getRealUser() { return realUser; } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o == null || getClass() != o.getClass()) { return false; } else { return realUser.equals(((RealUser) o).realUser); } } @Override public int hashCode() { return realUser.hashCode(); } @Override public String toString() { return realUser.toString(); } } private static HadoopLoginContext newLoginContext(String appName, Subject subject, HadoopConfiguration loginConf) throws LoginException { // Temporarily switch the thread's ContextClassLoader to match this // class's classloader, so that we can properly load HadoopLoginModule // from the JAAS libraries. Thread t = Thread.currentThread(); ClassLoader oldCCL = t.getContextClassLoader(); t.setContextClassLoader(HadoopLoginModule.class.getClassLoader()); try { return new HadoopLoginContext(appName, subject, loginConf); } finally { t.setContextClassLoader(oldCCL); } } // return the LoginContext only if it's managed by the ugi. externally // managed login contexts will be ignored. private HadoopLoginContext getLogin() { LoginContext login = user.getLogin(); return (login instanceof HadoopLoginContext) ? (HadoopLoginContext)login : null; } private void setLogin(LoginContext login) { user.setLogin(login); } /** * Create a UserGroupInformation for the given subject. * This does not change the subject or acquire new credentials. * * The creator of subject is responsible for renewing credentials. * @param subject the user's subject */ UserGroupInformation(Subject subject) { this.subject = subject; // do not access ANY private credentials since they are mutable // during a relogin. no principal locking necessary since // relogin/logout does not remove User principal. this.user = subject.getPrincipals(User.class).iterator().next(); if (user == null || user.getName() == null) { throw new IllegalStateException("Subject does not contain a valid User"); } } /** * checks if logged in using kerberos * @return true if the subject logged via keytab or has a Kerberos TGT */ public boolean hasKerberosCredentials() { return user.getAuthenticationMethod() == AuthenticationMethod.KERBEROS; } /** * Return the current user, including any doAs in the current stack. * @return the current user * @throws IOException if login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation getCurrentUser() throws IOException { AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null || subject.getPrincipals(User.class).isEmpty()) { return getLoginUser(); } else { return new UserGroupInformation(subject); } } /** * Find the most appropriate UserGroupInformation to use * * @param ticketCachePath The Kerberos ticket cache path, or NULL * if none is specfied * @param user The user name, or NULL if none is specified. * * @return The most appropriate UserGroupInformation */ public static UserGroupInformation getBestUGI( String ticketCachePath, String user) throws IOException { if (ticketCachePath != null) { return getUGIFromTicketCache(ticketCachePath, user); } else if (user == null) { return getCurrentUser(); } else { return createRemoteUser(user); } } /** * Create a UserGroupInformation from a Kerberos ticket cache. * * @param user The principal name to load from the ticket * cache * @param ticketCache the path to the ticket cache file * * @throws IOException if the kerberos login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation getUGIFromTicketCache( String ticketCache, String user) throws IOException { if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) { return getBestUGI(null, user); } LoginParams params = new LoginParams(); params.put(LoginParam.PRINCIPAL, user); params.put(LoginParam.CCACHE, ticketCache); return doSubjectLogin(null, params); } /** * Create a UserGroupInformation from a Subject with Kerberos principal. * * @param subject The KerberosPrincipal to use in UGI. * The creator of subject is responsible for * renewing credentials. * * @throws IOException * @throws KerberosAuthException if the kerberos login fails */ public static UserGroupInformation getUGIFromSubject(Subject subject) throws IOException { if (subject == null) { throw new KerberosAuthException(SUBJECT_MUST_NOT_BE_NULL); } if (subject.getPrincipals(KerberosPrincipal.class).isEmpty()) { throw new KerberosAuthException(SUBJECT_MUST_CONTAIN_PRINCIPAL); } // null params indicate external subject login. no login context will // be attached. return doSubjectLogin(subject, null); } /** * Get the currently logged in user. If no explicit login has occurred, * the user will automatically be logged in with either kerberos credentials * if available, or as the local OS user, based on security settings. * @return the logged in user * @throws IOException if login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation getLoginUser() throws IOException { UserGroupInformation loginUser = loginUserRef.get(); // a potential race condition exists only for the initial creation of // the login user. there's no need to penalize all subsequent calls // with sychronization overhead so optimistically create a login user // and discard if we lose the race. if (loginUser == null) { UserGroupInformation newLoginUser = createLoginUser(null); do { // it's extremely unlikely that the login user will be non-null // (lost CAS race), but be nulled before the subsequent get, but loop // for correctness. if (loginUserRef.compareAndSet(null, newLoginUser)) { loginUser = newLoginUser; // only spawn renewal if this login user is the winner. loginUser.spawnAutoRenewalThreadForUserCreds(false); } else { loginUser = loginUserRef.get(); } } while (loginUser == null); } return loginUser; } /** * remove the login method that is followed by a space from the username * e.g. "jack (auth:SIMPLE)" -> "jack" * * @param userName * @return userName without login method */ public static String trimLoginMethod(String userName) { int spaceIndex = userName.indexOf(' '); if (spaceIndex >= 0) { userName = userName.substring(0, spaceIndex); } return userName; } /** * Log in a user using the given subject * @param subject the subject to use when logging in a user, or null to * create a new subject. * * If subject is not null, the creator of subject is responsible for renewing * credentials. * * @throws IOException if login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public static void loginUserFromSubject(Subject subject) throws IOException { setLoginUser(createLoginUser(subject)); } private static UserGroupInformation createLoginUser(Subject subject) throws IOException { UserGroupInformation realUser = doSubjectLogin(subject, null); UserGroupInformation loginUser = null; try { // If the HADOOP_PROXY_USER environment variable or property // is specified, create a proxy user as the logged in user. String proxyUser = System.getenv(HADOOP_PROXY_USER); if (proxyUser == null) { proxyUser = System.getProperty(HADOOP_PROXY_USER); } loginUser = proxyUser == null ? realUser : createProxyUser(proxyUser, realUser); String tokenFileLocation = System.getProperty(HADOOP_TOKEN_FILES); if (tokenFileLocation == null) { tokenFileLocation = conf.get(HADOOP_TOKEN_FILES); } if (tokenFileLocation != null) { for (String tokenFileName: StringUtils.getTrimmedStrings(tokenFileLocation)) { if (tokenFileName.length() > 0) { File tokenFile = new File(tokenFileName); if (tokenFile.exists() && tokenFile.isFile()) { Credentials cred = Credentials.readTokenStorageFile( tokenFile, conf); loginUser.addCredentials(cred); } else { LOG.info("tokenFile("+tokenFileName+") does not exist"); } } } } String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION); if (fileLocation != null) { // Load the token storage file and put all of the tokens into the // user. Don't use the FileSystem API for reading since it has a lock // cycle (HADOOP-9212). File source = new File(fileLocation); LOG.debug("Reading credentials from location set in {}: {}", HADOOP_TOKEN_FILE_LOCATION, source.getCanonicalPath()); if (!source.isFile()) { throw new FileNotFoundException("Source file " + source.getCanonicalPath() + " from " + HADOOP_TOKEN_FILE_LOCATION + " not found"); } Credentials cred = Credentials.readTokenStorageFile( source, conf); LOG.debug("Loaded {} tokens", cred.numberOfTokens()); loginUser.addCredentials(cred); } } catch (IOException ioe) { LOG.debug("failure to load login credentials", ioe); throw ioe; } if (LOG.isDebugEnabled()) { LOG.debug("UGI loginUser:"+loginUser); } return loginUser; } @InterfaceAudience.Private @InterfaceStability.Unstable @VisibleForTesting public static void setLoginUser(UserGroupInformation ugi) { // if this is to become stable, should probably logout the currently // logged in ugi if it's different loginUserRef.set(ugi); } private String getKeytab() { HadoopLoginContext login = getLogin(); return (login != null) ? login.getConfiguration().getParameters().get(LoginParam.KEYTAB) : null; } /** * Is the ugi managed by the UGI or an external subject? * @return true if managed by UGI. */ private boolean isHadoopLogin() { // checks if the private hadoop login context is managing the ugi. return getLogin() != null; } /** * Is this user logged in from a keytab file managed by the UGI? * @return true if the credentials are from a keytab file. */ public boolean isFromKeytab() { // can't simply check if keytab is present since a relogin failure will // have removed the keytab from priv creds. instead, check login params. return hasKerberosCredentials() && isHadoopLogin() && getKeytab() != null; } /** * Is this user logged in from a ticket (but no keytab) managed by the UGI? * @return true if the credentials are from a ticket cache. */ private boolean isFromTicket() { return hasKerberosCredentials() && isHadoopLogin() && getKeytab() == null; } /** * Get the Kerberos TGT * @return the user's TGT or null if none was found */ private KerberosTicket getTGT() { Set<KerberosTicket> tickets = subject .getPrivateCredentials(KerberosTicket.class); for (KerberosTicket ticket : tickets) { if (SecurityUtil.isOriginalTGT(ticket)) { return ticket; } } return null; } private long getRefreshTime(KerberosTicket tgt) { long start = tgt.getStartTime().getTime(); long end = tgt.getEndTime().getTime(); return start + (long) ((end - start) * TICKET_RENEW_WINDOW); } private boolean shouldRelogin() { return hasKerberosCredentials() && isHadoopLogin(); } @InterfaceAudience.Private @InterfaceStability.Unstable @VisibleForTesting /** * Spawn a thread to do periodic renewals of kerberos credentials from * a ticket cache. NEVER directly call this method. * @param force - used by tests to forcibly spawn thread */ void spawnAutoRenewalThreadForUserCreds(boolean force) { if (!force && (!shouldRelogin() || isFromKeytab())) { return; } //spawn thread only if we have kerb credentials Thread t = new Thread(new Runnable() { @Override public void run() { String cmd = conf.get("hadoop.kerberos.kinit.command", "kinit"); KerberosTicket tgt = getTGT(); if (tgt == null) { return; } long nextRefresh = getRefreshTime(tgt); RetryPolicy rp = null; while (true) { try { long now = Time.now(); if (LOG.isDebugEnabled()) { LOG.debug("Current time is " + now); LOG.debug("Next refresh is " + nextRefresh); } if (now < nextRefresh) { Thread.sleep(nextRefresh - now); } Shell.execCommand(cmd, "-R"); if (LOG.isDebugEnabled()) { LOG.debug("renewed ticket"); } reloginFromTicketCache(); tgt = getTGT(); if (tgt == null) { LOG.warn("No TGT after renewal. Aborting renew thread for " + getUserName()); return; } nextRefresh = Math.max(getRefreshTime(tgt), now + kerberosMinSecondsBeforeRelogin); metrics.renewalFailures.set(0); rp = null; } catch (InterruptedException ie) { LOG.warn("Terminating renewal thread"); return; } catch (IOException ie) { metrics.renewalFailuresTotal.incr(); final long tgtEndTime = tgt.getEndTime().getTime(); LOG.warn("Exception encountered while running the renewal " + "command for {}. (TGT end time:{}, renewalFailures: {}," + "renewalFailuresTotal: {})", getUserName(), tgtEndTime, metrics.renewalFailures, metrics.renewalFailuresTotal, ie); final long now = Time.now(); if (rp == null) { // Use a dummy maxRetries to create the policy. The policy will // only be used to get next retry time with exponential back-off. // The final retry time will be later limited within the // tgt endTime in getNextTgtRenewalTime. rp = RetryPolicies.exponentialBackoffRetry(Long.SIZE - 2, kerberosMinSecondsBeforeRelogin, TimeUnit.MILLISECONDS); } try { nextRefresh = getNextTgtRenewalTime(tgtEndTime, now, rp); } catch (Exception e) { LOG.error("Exception when calculating next tgt renewal time", e); return; } metrics.renewalFailures.incr(); // retry until close enough to tgt endTime. if (now > nextRefresh) { LOG.error("TGT is expired. Aborting renew thread for {}.", getUserName()); return; } } } } }); t.setDaemon(true); t.setName("TGT Renewer for " + getUserName()); t.start(); } /** * Get time for next login retry. This will allow the thread to retry with * exponential back-off, until tgt endtime. * Last retry is {@link #kerberosMinSecondsBeforeRelogin} before endtime. * * @param tgtEndTime EndTime of the tgt. * @param now Current time. * @param rp The retry policy. * @return Time for next login retry. */ @VisibleForTesting static long getNextTgtRenewalTime(final long tgtEndTime, final long now, final RetryPolicy rp) throws Exception { final long lastRetryTime = tgtEndTime - kerberosMinSecondsBeforeRelogin; final RetryPolicy.RetryAction ra = rp.shouldRetry(null, metrics.renewalFailures.value(), 0, false); return Math.min(lastRetryTime, now + ra.delayMillis); } /** * Log a user in from a keytab file. Loads a user identity from a keytab * file and logs them in. They become the currently logged-in user. * @param user the principal name to load from the keytab * @param path the path to the keytab file * @throws IOException * @throws KerberosAuthException if it's a kerberos login exception. */ @InterfaceAudience.Public @InterfaceStability.Evolving public static void loginUserFromKeytab(String user, String path ) throws IOException { if (!isSecurityEnabled()) return; setLoginUser(loginUserFromKeytabAndReturnUGI(user, path)); LOG.info("Login successful for user " + user + " using keytab file " + path); } /** * Log the current user out who previously logged in using keytab. * This method assumes that the user logged in by calling * {@link #loginUserFromKeytab(String, String)}. * * @throws IOException * @throws KerberosAuthException if a failure occurred in logout, * or if the user did not log in by invoking loginUserFromKeyTab() before. */ @InterfaceAudience.Public @InterfaceStability.Evolving public void logoutUserFromKeytab() throws IOException { if (!hasKerberosCredentials()) { return; } HadoopLoginContext login = getLogin(); String keytabFile = getKeytab(); if (login == null || keytabFile == null) { throw new KerberosAuthException(MUST_FIRST_LOGIN_FROM_KEYTAB); } try { if (LOG.isDebugEnabled()) { LOG.debug("Initiating logout for " + getUserName()); } // hadoop login context internally locks credentials. login.logout(); } catch (LoginException le) { KerberosAuthException kae = new KerberosAuthException(LOGOUT_FAILURE, le); kae.setUser(user.toString()); kae.setKeytabFile(keytabFile); throw kae; } LOG.info("Logout successful for user " + getUserName() + " using keytab file " + keytabFile); } /** * Re-login a user from keytab if TGT is expired or is close to expiry. * * @throws IOException * @throws KerberosAuthException if it's a kerberos login exception. */ public void checkTGTAndReloginFromKeytab() throws IOException { reloginFromKeytab(true); } // if the first kerberos ticket is not TGT, then remove and destroy it since // the kerberos library of jdk always use the first kerberos ticket as TGT. // See HADOOP-13433 for more details. @VisibleForTesting void fixKerberosTicketOrder() { Set<Object> creds = getSubject().getPrivateCredentials(); synchronized (creds) { for (Iterator<Object> iter = creds.iterator(); iter.hasNext();) { Object cred = iter.next(); if (cred instanceof KerberosTicket) { KerberosTicket ticket = (KerberosTicket) cred; if (ticket.isDestroyed() || ticket.getServer() == null) { LOG.warn("Ticket is already destroyed, remove it."); iter.remove(); } else if (!ticket.getServer().getName().startsWith("krbtgt")) { LOG.warn( "The first kerberos ticket is not TGT" + "(the server principal is {}), remove and destroy it.", ticket.getServer()); iter.remove(); try { ticket.destroy(); } catch (DestroyFailedException e) { LOG.warn("destroy ticket failed", e); } } else { return; } } } } LOG.warn("Warning, no kerberos ticket found while attempting to renew ticket"); } /** * Re-Login a user in from a keytab file. Loads a user identity from a keytab * file and logs them in. They become the currently logged-in user. This * method assumes that {@link #loginUserFromKeytab(String, String)} had * happened already. * The Subject field of this UserGroupInformation object is updated to have * the new credentials. * @throws IOException * @throws KerberosAuthException on a failure */ @InterfaceAudience.Public @InterfaceStability.Evolving public void reloginFromKeytab() throws IOException { reloginFromKeytab(false); } private void reloginFromKeytab(boolean checkTGT) throws IOException { if (!shouldRelogin() || !isFromKeytab()) { return; } HadoopLoginContext login = getLogin(); if (login == null) { throw new KerberosAuthException(MUST_FIRST_LOGIN_FROM_KEYTAB); } if (checkTGT) { KerberosTicket tgt = getTGT(); if (tgt != null && !shouldRenewImmediatelyForTests && Time.now() < getRefreshTime(tgt)) { return; } } relogin(login); } /** * Re-Login a user in from the ticket cache. This * method assumes that login had happened already. * The Subject field of this UserGroupInformation object is updated to have * the new credentials. * @throws IOException * @throws KerberosAuthException on a failure */ @InterfaceAudience.Public @InterfaceStability.Evolving public void reloginFromTicketCache() throws IOException { if (!shouldRelogin() || !isFromTicket()) { return; } HadoopLoginContext login = getLogin(); if (login == null) { throw new KerberosAuthException(MUST_FIRST_LOGIN); } relogin(login); } private void relogin(HadoopLoginContext login) throws IOException { // ensure the relogin is atomic to avoid leaving credentials in an // inconsistent state. prevents other ugi instances, SASL, and SPNEGO // from accessing or altering credentials during the relogin. synchronized(login.getSubjectLock()) { // another racing thread may have beat us to the relogin. if (login == getLogin()) { unprotectedRelogin(login); } } } private void unprotectedRelogin(HadoopLoginContext login) throws IOException { assert Thread.holdsLock(login.getSubjectLock()); long now = Time.now(); if (!hasSufficientTimeElapsed(now)) { return; } // register most recent relogin attempt user.setLastLogin(now); try { if (LOG.isDebugEnabled()) { LOG.debug("Initiating logout for " + getUserName()); } //clear up the kerberos state. But the tokens are not cleared! As per //the Java kerberos login module code, only the kerberos credentials //are cleared login.logout(); //login and also update the subject field of this instance to //have the new credentials (pass it to the LoginContext constructor) login = newLoginContext( login.getAppName(), login.getSubject(), login.getConfiguration()); if (LOG.isDebugEnabled()) { LOG.debug("Initiating re-login for " + getUserName()); } login.login(); // this should be unnecessary. originally added due to improper locking // of the subject during relogin. fixKerberosTicketOrder(); setLogin(login); } catch (LoginException le) { KerberosAuthException kae = new KerberosAuthException(LOGIN_FAILURE, le); kae.setUser(getUserName()); throw kae; } } /** * Log a user in from a keytab file. Loads a user identity from a keytab * file and login them in. This new user does not affect the currently * logged-in user. * @param user the principal name to load from the keytab * @param path the path to the keytab file * @throws IOException if the keytab file can't be read */ public static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path ) throws IOException { if (!isSecurityEnabled()) return UserGroupInformation.getCurrentUser(); LoginParams params = new LoginParams(); params.put(LoginParam.PRINCIPAL, user); params.put(LoginParam.KEYTAB, path); return doSubjectLogin(null, params); } private boolean hasSufficientTimeElapsed(long now) { if (!shouldRenewImmediatelyForTests && now - user.getLastLogin() < kerberosMinSecondsBeforeRelogin ) { LOG.warn("Not attempting to re-login since the last re-login was " + "attempted less than " + (kerberosMinSecondsBeforeRelogin/1000) + " seconds before. Last Login=" + user.getLastLogin()); return false; } return true; } /** * Did the login happen via keytab * @return true or false */ @InterfaceAudience.Public @InterfaceStability.Evolving public static boolean isLoginKeytabBased() throws IOException { return getLoginUser().isFromKeytab(); } /** * Did the login happen via ticket cache * @return true or false */ public static boolean isLoginTicketBased() throws IOException { return getLoginUser().isFromTicket(); } /** * Create a user from a login name. It is intended to be used for remote * users in RPC, since it won't have any credentials. * @param user the full user principal name, must not be empty or null * @return the UserGroupInformation for the remote user. */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation createRemoteUser(String user) { return createRemoteUser(user, AuthMethod.SIMPLE); } /** * Create a user from a login name. It is intended to be used for remote * users in RPC, since it won't have any credentials. * @param user the full user principal name, must not be empty or null * @return the UserGroupInformation for the remote user. */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation createRemoteUser(String user, AuthMethod authMethod) { if (user == null || user.isEmpty()) { throw new IllegalArgumentException("Null user"); } Subject subject = new Subject(); subject.getPrincipals().add(new User(user)); UserGroupInformation result = new UserGroupInformation(subject); result.setAuthenticationMethod(authMethod); return result; } /** * existing types of authentications' methods */ @InterfaceAudience.Public @InterfaceStability.Evolving public enum AuthenticationMethod { // currently we support only one auth per method, but eventually a // subtype is needed to differentiate, ex. if digest is token or ldap SIMPLE(AuthMethod.SIMPLE, HadoopConfiguration.SIMPLE_CONFIG_NAME), KERBEROS(AuthMethod.KERBEROS, HadoopConfiguration.KERBEROS_CONFIG_NAME), TOKEN(AuthMethod.TOKEN), CERTIFICATE(null), KERBEROS_SSL(null), PROXY(null); private final AuthMethod authMethod; private final String loginAppName; private AuthenticationMethod(AuthMethod authMethod) { this(authMethod, null); } private AuthenticationMethod(AuthMethod authMethod, String loginAppName) { this.authMethod = authMethod; this.loginAppName = loginAppName; } public AuthMethod getAuthMethod() { return authMethod; } String getLoginAppName() { if (loginAppName == null) { throw new UnsupportedOperationException( this + " login authentication is not supported"); } return loginAppName; } public static AuthenticationMethod valueOf(AuthMethod authMethod) { for (AuthenticationMethod value : values()) { if (value.getAuthMethod() == authMethod) { return value; } } throw new IllegalArgumentException( "no authentication method for " + authMethod); } }; /** * Create a proxy user using username of the effective user and the ugi of the * real user. * @param user * @param realUser * @return proxyUser ugi */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation createProxyUser(String user, UserGroupInformation realUser) { if (user == null || user.isEmpty()) { throw new IllegalArgumentException("Null user"); } if (realUser == null) { throw new IllegalArgumentException("Null real user"); } Subject subject = new Subject(); Set<Principal> principals = subject.getPrincipals(); principals.add(new User(user, AuthenticationMethod.PROXY, null)); principals.add(new RealUser(realUser)); return new UserGroupInformation(subject); } /** * get RealUser (vs. EffectiveUser) * @return realUser running over proxy user */ @InterfaceAudience.Public @InterfaceStability.Evolving public UserGroupInformation getRealUser() { for (RealUser p: subject.getPrincipals(RealUser.class)) { return p.getRealUser(); } return null; } /** * This class is used for storing the groups for testing. It stores a local * map that has the translation of usernames to groups. */ private static class TestingGroups extends Groups { private final Map<String, List<String>> userToGroupsMapping = new HashMap<String,List<String>>(); private Groups underlyingImplementation; private TestingGroups(Groups underlyingImplementation) { super(new org.apache.hadoop.conf.Configuration()); this.underlyingImplementation = underlyingImplementation; } @Override public List<String> getGroups(String user) throws IOException { List<String> result = userToGroupsMapping.get(user); if (result == null) { result = underlyingImplementation.getGroups(user); } return result; } private void setUserGroups(String user, String[] groups) { userToGroupsMapping.put(user, Arrays.asList(groups)); } } /** * Create a UGI for testing HDFS and MapReduce * @param user the full user principal name * @param userGroups the names of the groups that the user belongs to * @return a fake user for running unit tests */ @InterfaceAudience.Public @InterfaceStability.Evolving public static UserGroupInformation createUserForTesting(String user, String[] userGroups) { ensureInitialized(); UserGroupInformation ugi = createRemoteUser(user); // make sure that the testing object is setup if (!(groups instanceof TestingGroups)) { groups = new TestingGroups(groups); } // add the user groups ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups); return ugi; } /** * Create a proxy user UGI for testing HDFS and MapReduce * * @param user * the full user principal name for effective user * @param realUser * UGI of the real user * @param userGroups * the names of the groups that the user belongs to * @return a fake user for running unit tests */ public static UserGroupInformation createProxyUserForTesting(String user, UserGroupInformation realUser, String[] userGroups) { ensureInitialized(); UserGroupInformation ugi = createProxyUser(user, realUser); // make sure that the testing object is setup if (!(groups instanceof TestingGroups)) { groups = new TestingGroups(groups); } // add the user groups ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups); return ugi; } /** * Get the user's login name. * @return the user's name up to the first '/' or '@'. */ public String getShortUserName() { return user.getShortName(); } public String getPrimaryGroupName() throws IOException { List<String> groups = getGroups(); if (groups.isEmpty()) { throw new IOException("There is no primary group for UGI " + this); } return groups.get(0); } /** * Get the user's full principal name. * @return the user's full principal name. */ @InterfaceAudience.Public @InterfaceStability.Evolving public String getUserName() { return user.getName(); } /** * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been * authenticated by the RPC layer as belonging to the user represented by this * UGI. * * @param tokenId * tokenIdentifier to be added * @return true on successful add of new tokenIdentifier */ public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) { return subject.getPublicCredentials().add(tokenId); } /** * Get the set of TokenIdentifiers belonging to this UGI * * @return the set of TokenIdentifiers belonging to this UGI */ public synchronized Set<TokenIdentifier> getTokenIdentifiers() { return subject.getPublicCredentials(TokenIdentifier.class); } /** * Add a token to this UGI * * @param token Token to be added * @return true on successful add of new token */ public boolean addToken(Token<? extends TokenIdentifier> token) { return (token != null) ? addToken(token.getService(), token) : false; } /** * Add a named token to this UGI * * @param alias Name of the token * @param token Token to be added * @return true on successful add of new token */ public boolean addToken(Text alias, Token<? extends TokenIdentifier> token) { synchronized (subject) { getCredentialsInternal().addToken(alias, token); return true; } } /** * Obtain the collection of tokens associated with this user. * * @return an unmodifiable collection of tokens associated with user */ public Collection<Token<? extends TokenIdentifier>> getTokens() { synchronized (subject) { return Collections.unmodifiableCollection( new ArrayList<Token<?>>(getCredentialsInternal().getAllTokens())); } } /** * Obtain the tokens in credentials form associated with this user. * * @return Credentials of tokens associated with this user */ public Credentials getCredentials() { synchronized (subject) { Credentials creds = new Credentials(getCredentialsInternal()); Iterator<Token<?>> iter = creds.getAllTokens().iterator(); while (iter.hasNext()) { if (iter.next().isPrivate()) { iter.remove(); } } return creds; } } /** * Add the given Credentials to this user. * @param credentials of tokens and secrets */ public void addCredentials(Credentials credentials) { synchronized (subject) { getCredentialsInternal().addAll(credentials); } } private synchronized Credentials getCredentialsInternal() { final Credentials credentials; final Set<Credentials> credentialsSet = subject.getPrivateCredentials(Credentials.class); if (!credentialsSet.isEmpty()){ credentials = credentialsSet.iterator().next(); } else { credentials = new Credentials(); subject.getPrivateCredentials().add(credentials); } return credentials; } /** * Get the group names for this user. {@link #getGroups()} is less * expensive alternative when checking for a contained element. * @return the list of users with the primary group first. If the command * fails, it returns an empty list. */ public String[] getGroupNames() { List<String> groups = getGroups(); return groups.toArray(new String[groups.size()]); } /** * Get the group names for this user. * @return the list of users with the primary group first. If the command * fails, it returns an empty list. */ public List<String> getGroups() { ensureInitialized(); try { return groups.getGroups(getShortUserName()); } catch (IOException ie) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to get groups for user " + getShortUserName() + " by " + ie); LOG.trace("TRACE", ie); } return Collections.emptyList(); } } /** * Return the username. */ @Override public String toString() { StringBuilder sb = new StringBuilder(getUserName()); sb.append(" (auth:"+getAuthenticationMethod()+")"); if (getRealUser() != null) { sb.append(" via ").append(getRealUser().toString()); } return sb.toString(); } /** * Sets the authentication method in the subject * * @param authMethod */ public synchronized void setAuthenticationMethod(AuthenticationMethod authMethod) { user.setAuthenticationMethod(authMethod); } /** * Sets the authentication method in the subject * * @param authMethod */ public void setAuthenticationMethod(AuthMethod authMethod) { user.setAuthenticationMethod(AuthenticationMethod.valueOf(authMethod)); } /** * Get the authentication method from the subject * * @return AuthenticationMethod in the subject, null if not present. */ public synchronized AuthenticationMethod getAuthenticationMethod() { return user.getAuthenticationMethod(); } /** * Get the authentication method from the real user's subject. If there * is no real user, return the given user's authentication method. * * @return AuthenticationMethod in the subject, null if not present. */ public synchronized AuthenticationMethod getRealAuthenticationMethod() { UserGroupInformation ugi = getRealUser(); if (ugi == null) { ugi = this; } return ugi.getAuthenticationMethod(); } /** * Returns the authentication method of a ugi. If the authentication method is * PROXY, returns the authentication method of the real user. * * @param ugi * @return AuthenticationMethod */ public static AuthenticationMethod getRealAuthenticationMethod( UserGroupInformation ugi) { AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); if (authMethod == AuthenticationMethod.PROXY) { authMethod = ugi.getRealUser().getAuthenticationMethod(); } return authMethod; } /** * Compare the subjects to see if they are equal to each other. */ @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o == null || getClass() != o.getClass()) { return false; } else { return subject == ((UserGroupInformation) o).subject; } } /** * Return the hash of the subject. */ @Override public int hashCode() { return System.identityHashCode(subject); } /** * Get the underlying subject from this ugi. * @return the subject that represents this user. */ protected Subject getSubject() { return subject; } /** * Run the given action as the user. * @param <T> the return type of the run method * @param action the method to execute * @return the value from the run method */ @InterfaceAudience.Public @InterfaceStability.Evolving public <T> T doAs(PrivilegedAction<T> action) { logPrivilegedAction(subject, action); return Subject.doAs(subject, action); } /** * Run the given action as the user, potentially throwing an exception. * @param <T> the return type of the run method * @param action the method to execute * @return the value from the run method * @throws IOException if the action throws an IOException * @throws Error if the action throws an Error * @throws RuntimeException if the action throws a RuntimeException * @throws InterruptedException if the action throws an InterruptedException * @throws UndeclaredThrowableException if the action throws something else */ @InterfaceAudience.Public @InterfaceStability.Evolving public <T> T doAs(PrivilegedExceptionAction<T> action ) throws IOException, InterruptedException { try { logPrivilegedAction(subject, action); return Subject.doAs(subject, action); } catch (PrivilegedActionException pae) { Throwable cause = pae.getCause(); if (LOG.isDebugEnabled()) { LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause); } if (cause == null) { throw new RuntimeException("PrivilegedActionException with no " + "underlying cause. UGI [" + this + "]" +": " + pae, pae); } else if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof InterruptedException) { throw (InterruptedException) cause; } else { throw new UndeclaredThrowableException(cause); } } } private void logPrivilegedAction(Subject subject, Object action) { if (LOG.isDebugEnabled()) { // would be nice if action included a descriptive toString() String where = new Throwable().getStackTrace()[2].toString(); LOG.debug("PrivilegedAction as:"+this+" from:"+where); } } /** * Log current UGI and token information into specified log. * @param ugi - UGI * @throws IOException */ @InterfaceAudience.LimitedPrivate({"HDFS", "KMS"}) @InterfaceStability.Unstable public static void logUserInfo(Logger log, String caption, UserGroupInformation ugi) throws IOException { if (log.isDebugEnabled()) { log.debug(caption + " UGI: " + ugi); for (Token<?> token : ugi.getTokens()) { log.debug("+token:" + token); } } } /** * Log all (current, real, login) UGI and token info into specified log. * @param ugi - UGI * @throws IOException */ @InterfaceAudience.LimitedPrivate({"HDFS", "KMS"}) @InterfaceStability.Unstable public static void logAllUserInfo(Logger log, UserGroupInformation ugi) throws IOException { if (log.isDebugEnabled()) { logUserInfo(log, "Current", ugi.getCurrentUser()); if (ugi.getRealUser() != null) { logUserInfo(log, "Real", ugi.getRealUser()); } logUserInfo(log, "Login", ugi.getLoginUser()); } } /** * Log all (current, real, login) UGI and token info into UGI debug log. * @param ugi - UGI * @throws IOException */ public static void logAllUserInfo(UserGroupInformation ugi) throws IOException { logAllUserInfo(LOG, ugi); } private void print() throws IOException { System.out.println("User: " + getUserName()); System.out.print("Group Ids: "); System.out.println(); String[] groups = getGroupNames(); System.out.print("Groups: "); for(int i=0; i < groups.length; i++) { System.out.print(groups[i] + " "); } System.out.println(); } /** * Login a subject with the given parameters. If the subject is null, * the login context used to create the subject will be attached. * @param subject to login, null for new subject. * @param params for login, null for externally managed ugi. * @return UserGroupInformation for subject * @throws IOException */ private static UserGroupInformation doSubjectLogin( Subject subject, LoginParams params) throws IOException { ensureInitialized(); // initial default login. if (subject == null && params == null) { params = LoginParams.getDefaults(); } HadoopConfiguration loginConf = new HadoopConfiguration(params); try { HadoopLoginContext login = newLoginContext( authenticationMethod.getLoginAppName(), subject, loginConf); login.login(); UserGroupInformation ugi = new UserGroupInformation(login.getSubject()); // attach login context for relogin unless this was a pre-existing // subject. if (subject == null) { params.put(LoginParam.PRINCIPAL, ugi.getUserName()); ugi.setLogin(login); } return ugi; } catch (LoginException le) { KerberosAuthException kae = new KerberosAuthException(FAILURE_TO_LOGIN, le); if (params != null) { kae.setPrincipal(params.get(LoginParam.PRINCIPAL)); kae.setKeytabFile(params.get(LoginParam.KEYTAB)); kae.setTicketCacheFile(params.get(LoginParam.CCACHE)); } throw kae; } } // parameters associated with kerberos logins. may be extended to support // additional authentication methods. enum LoginParam { PRINCIPAL, KEYTAB, CCACHE, } // explicitly private to prevent external tampering. private static class LoginParams extends EnumMap<LoginParam,String> implements Parameters { LoginParams() { super(LoginParam.class); } // do not add null values, nor allow existing values to be overriden. @Override public String put(LoginParam param, String val) { boolean add = val != null && !containsKey(param); return add ? super.put(param, val) : null; } static LoginParams getDefaults() { LoginParams params = new LoginParams(); params.put(LoginParam.PRINCIPAL, System.getenv("KRB5PRINCIPAL")); params.put(LoginParam.KEYTAB, System.getenv("KRB5KEYTAB")); params.put(LoginParam.CCACHE, System.getenv("KRB5CCNAME")); return params; } } // wrapper to allow access to fields necessary to recreate the same login // context for relogin. explicitly private to prevent external tampering. private static class HadoopLoginContext extends LoginContext { private final String appName; private final HadoopConfiguration conf; private AtomicBoolean isLoggedIn = new AtomicBoolean(); HadoopLoginContext(String appName, Subject subject, HadoopConfiguration conf) throws LoginException { super(appName, subject, null, conf); this.appName = appName; this.conf = conf; } String getAppName() { return appName; } HadoopConfiguration getConfiguration() { return conf; } // the locking model for logins cannot rely on ugi instance synchronization // since a subject will be referenced by multiple ugi instances. Object getSubjectLock() { Subject subject = getSubject(); // if subject is null, the login context will create the subject // so just lock on this context. return (subject == null) ? this : subject.getPrivateCredentials(); } @Override public void login() throws LoginException { synchronized(getSubjectLock()) { MutableRate metric = metrics.loginFailure; long start = Time.monotonicNow(); try { super.login(); isLoggedIn.set(true); metric = metrics.loginSuccess; } finally { metric.add(Time.monotonicNow() - start); } } } @Override public void logout() throws LoginException { synchronized(getSubjectLock()) { if (isLoggedIn.compareAndSet(true, false)) { super.logout(); } } } } /** * A JAAS configuration that defines the login modules that we want * to use for login. */ @InterfaceAudience.Private @InterfaceStability.Unstable private static class HadoopConfiguration extends javax.security.auth.login.Configuration { static final String KRB5_LOGIN_MODULE = KerberosUtil.getKrb5LoginModuleName(); static final String SIMPLE_CONFIG_NAME = "hadoop-simple"; static final String KERBEROS_CONFIG_NAME = "hadoop-kerberos"; private static final Map<String, String> BASIC_JAAS_OPTIONS = new HashMap<String,String>(); static { if ("true".equalsIgnoreCase(System.getenv("HADOOP_JAAS_DEBUG"))) { BASIC_JAAS_OPTIONS.put("debug", "true"); } } static final AppConfigurationEntry OS_SPECIFIC_LOGIN = new AppConfigurationEntry( OS_LOGIN_MODULE_NAME, LoginModuleControlFlag.REQUIRED, BASIC_JAAS_OPTIONS); static final AppConfigurationEntry HADOOP_LOGIN = new AppConfigurationEntry( HadoopLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, BASIC_JAAS_OPTIONS); private final LoginParams params; HadoopConfiguration(LoginParams params) { this.params = params; } @Override public LoginParams getParameters() { return params; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { ArrayList<AppConfigurationEntry> entries = new ArrayList<>(); // login of external subject passes no params. technically only // existing credentials should be used but other components expect // the login to succeed with local user fallback if no principal. if (params == null || appName.equals(SIMPLE_CONFIG_NAME)) { entries.add(OS_SPECIFIC_LOGIN); } else if (appName.equals(KERBEROS_CONFIG_NAME)) { // existing semantics are the initial default login allows local user // fallback. this is not allowed when a principal explicitly // specified or during a relogin. if (!params.containsKey(LoginParam.PRINCIPAL)) { entries.add(OS_SPECIFIC_LOGIN); } entries.add(getKerberosEntry()); } entries.add(HADOOP_LOGIN); return entries.toArray(new AppConfigurationEntry[0]); } private AppConfigurationEntry getKerberosEntry() { final Map<String,String> options = new HashMap<>(BASIC_JAAS_OPTIONS); LoginModuleControlFlag controlFlag = LoginModuleControlFlag.OPTIONAL; // kerberos login is mandatory if principal is specified. principal // will not be set for initial default login, but will always be set // for relogins. final String principal = params.get(LoginParam.PRINCIPAL); if (principal != null) { options.put("principal", principal); controlFlag = LoginModuleControlFlag.REQUIRED; } // use keytab if given else fallback to ticket cache. if (IBM_JAVA) { if (params.containsKey(LoginParam.KEYTAB)) { final String keytab = params.get(LoginParam.KEYTAB); if (keytab != null) { options.put("useKeytab", prependFileAuthority(keytab)); } else { options.put("useDefaultKeytab", "true"); } options.put("credsType", "both"); } else { String ticketCache = params.get(LoginParam.CCACHE); if (ticketCache != null) { options.put("useCcache", prependFileAuthority(ticketCache)); } else { options.put("useDefaultCcache", "true"); } options.put("renewTGT", "true"); } } else { if (params.containsKey(LoginParam.KEYTAB)) { options.put("useKeyTab", "true"); final String keytab = params.get(LoginParam.KEYTAB); if (keytab != null) { options.put("keyTab", keytab); } options.put("storeKey", "true"); } else { options.put("useTicketCache", "true"); String ticketCache = params.get(LoginParam.CCACHE); if (ticketCache != null) { options.put("ticketCache", ticketCache); } options.put("renewTGT", "true"); } options.put("doNotPrompt", "true"); } options.put("refreshKrb5Config", "true"); return new AppConfigurationEntry( KRB5_LOGIN_MODULE, controlFlag, options); } private static String prependFileAuthority(String keytabPath) { return keytabPath.startsWith("file://") ? keytabPath : "file://" + keytabPath; } } /** * A test method to print out the current user's UGI. * @param args if there are two arguments, read the user from the keytab * and print it out. * @throws Exception */ public static void main(String [] args) throws Exception { System.out.println("Getting UGI for current user"); UserGroupInformation ugi = getCurrentUser(); ugi.print(); System.out.println("UGI: " + ugi); System.out.println("Auth method " + ugi.user.getAuthenticationMethod()); System.out.println("Keytab " + ugi.isFromKeytab()); System.out.println("============================================================"); if (args.length == 2) { System.out.println("Getting UGI from keytab...."); loginUserFromKeytab(args[0], args[1]); getCurrentUser().print(); System.out.println("Keytab: " + ugi); UserGroupInformation loginUgi = getLoginUser(); System.out.println("Auth method " + loginUgi.getAuthenticationMethod()); System.out.println("Keytab " + loginUgi.isFromKeytab()); } } }
HADOOP-15382. Log kinit output in credential renewal thread. Contributed by Gabor Bota.
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/UserGroupInformation.java
HADOOP-15382. Log kinit output in credential renewal thread. Contributed by Gabor Bota.
Java
bsd-3-clause
3adca0b0ccd0a9c7d1429345c115eeb925bddecc
0
joansmith/rultor,linlihai/rultor,krzyk/rultor,maurezen/rultor,pecko/rultor,maurezen/rultor,joansmith/rultor,dalifreire/rultor,krzyk/rultor,pecko/rultor,krzyk/rultor,joansmith/rultor,dalifreire/rultor,maurezen/rultor,pecko/rultor,pecko/rultor,linlihai/rultor,maurezen/rultor,krzyk/rultor,pecko/rultor,dalifreire/rultor,linlihai/rultor,linlihai/rultor,joansmith/rultor,krzyk/rultor,dalifreire/rultor,joansmith/rultor,linlihai/rultor,maurezen/rultor,dalifreire/rultor
/** * Copyright (c) 2009-2013, rultor.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the rultor.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rultor.drain; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.aspects.RetryOnFailure; import com.jcabi.aspects.Tv; import com.jcabi.log.VerboseRunnable; import com.jcabi.log.VerboseThreads; import com.rexsl.test.RestTester; import com.rexsl.test.TestClient; import com.rultor.snapshot.XemblyLine; import com.rultor.spi.Coordinates; import com.rultor.spi.Drain; import com.rultor.spi.Pageable; import com.rultor.spi.Stand; import com.rultor.tools.Exceptions; import com.rultor.tools.Time; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URLEncoder; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.json.Json; import javax.validation.constraints.NotNull; import javax.ws.rs.core.MediaType; import lombok.EqualsAndHashCode; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHeaders; import org.xembly.XemblySyntaxException; /** * Mirrored to a web {@link Stand}. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 1.0 * @todo #162:0.5hr As soon as rexsl #716 is resolved remove * SQSEntry interface and use TestClient directly. * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Immutable @EqualsAndHashCode(of = { "origin", "work", "stand", "key" }) @Loggable(Loggable.DEBUG) @SuppressWarnings({ "PMD.ExcessiveImports", "PMD.TooManyMethods" }) public final class Standed implements Drain { /** * Randomizer for nanos. */ public static final Random RND = new SecureRandom(); /** * Number of threads to use for sending to queue. */ public static final int THREADS = 10; /** * Max message batch size. */ private static final int MAX = 10; /** * SQS client connection container. */ @Immutable private interface SQSEntry { /** * Provide SQS connection. * @return SQS connection. */ TestClient get(); } /** * Executor container. */ @Immutable private interface Exec { /** * Provide executor. * @return ExecutorService */ ExecutorService get(); } /** * Coordinates we're in. */ private final transient Coordinates work; /** * Original drain. */ private final transient Drain origin; /** * Name of stand. */ private final transient String stand; /** * Secret key of it. */ private final transient String key; /** * HTTP queue that will receive data. */ private final transient Standed.SQSEntry entry; /** * Executor that runs tasks. */ private final transient Standed.Exec exec; /** * Public ctor. * @param wrk Coordinates we're in * @param name Name of stand * @param secret Secret key of the stand * @param drain Main drain * @checkstyle ParameterNumber (8 lines) */ public Standed( @NotNull(message = "work can't be NULL") final Coordinates wrk, @NotNull(message = "name of stand can't be NULL") final String name, @NotNull(message = "key can't be NULL") final String secret, @NotNull(message = "drain can't be NULL") final Drain drain) { this( wrk, name, secret, drain, RestTester.start(Stand.QUEUE), Executors.newFixedThreadPool(Standed.THREADS, new VerboseThreads()) ); } /** * Constructor for tests. * @param wrk Coordinates we're in * @param name Name of stand * @param secret Secret key of the stand * @param drain Main drain * @param client HTTP queue * @param executor Executor to use * @checkstyle ParameterNumber (8 lines) */ public Standed(final Coordinates wrk, final String name, final String secret, final Drain drain, final TestClient client, final ExecutorService executor) { this.work = wrk; this.stand = name; this.key = secret; this.origin = drain; this.entry = new Standed.SQSEntry() { @Override public TestClient get() { return client; } }; this.exec = new Standed.Exec() { @Override public ExecutorService get() { return executor; } }; } /** * {@inheritDoc} */ @Override public String toString() { return String.format( "%s standed at `%s`", this.origin, this.stand ); } /** * {@inheritDoc} */ @Override public Pageable<Time, Time> pulses() throws IOException { return this.origin.pulses(); } /** * {@inheritDoc} */ @Override public void append(final Iterable<String> lines) throws IOException { final Iterable<List<String>> batches = Iterables.partition( FluentIterable.from(lines) .filter( new Predicate<String>() { @Override public boolean apply(final String line) { return XemblyLine.existsIn(line); } } ) .transform( new Function<String, String>() { @Override public String apply(final String line) { try { return XemblyLine.parse(line).xembly(); } catch (XemblySyntaxException ex) { Exceptions.warn(this, ex); } return null; } } ) .filter(Predicates.notNull()), Standed.MAX ); for (List<String> batch : batches) { this.send(batch); } this.origin.append(lines); } /** * {@inheritDoc} */ @Override public InputStream read() throws IOException { return new SequenceInputStream( IOUtils.toInputStream( String.format( "Standed: stand='%s'\n", this.stand ), CharEncoding.UTF_8 ), this.origin.read() ); } /** * Send lines to stand. * @param xemblies The xembly scripts * @throws IOException If fails */ private void send(final Iterable<String> xemblies) throws IOException { this.exec.get().submit( new VerboseRunnable( new Callable<Void>() { @Override public Void call() throws Exception { Standed.this.send(Standed.this.body(xemblies)); return null; } }, true, false ) ); } /** * Send the message. * @param body POST request body * @throws IOException If fails */ @RetryOnFailure(verbose = false) private void send(final String body) throws IOException { final Collection<String> missed = Standed.this.enqueue( this.entry.get(), body ); if (!missed.isEmpty()) { throw new IOException( String.format( "Problem with sending of %d message(s): %s", missed.size(), StringUtils.join(missed, ", ") ) ); } } /** * Create POST request body. * @param xemblies The xembly scripts * @return POST request body * @throws IOException If fails */ private String body(final Iterable<String> xemblies) throws IOException { final List<String> msgs = new ArrayList<String>(0); for (String xembly : xemblies) { msgs.add(this.json(xembly)); } final StringBuilder body = new StringBuilder() .append("Action=SendMessageBatch") .append("&Version=2011-10-01"); for (int idx = 0; idx < msgs.size(); ++idx) { final int ent = idx + 1; body.append('&') .append("SendMessageBatchRequestEntry.") .append(ent) .append(".Id=") .append(ent) .append("&SendMessageBatchRequestEntry.") .append(ent) .append(".MessageBody=") .append(URLEncoder.encode(msgs.get(idx), CharEncoding.UTF_8)); } return body.toString(); } /** * Put messages on SQS. * @param client HTTP client to use. * @param body Body of the POST. * @return List of message IDs that were not enqueued. * @throws UnsupportedEncodingException When unable to find UTF-8 encoding. */ private List<String> enqueue(final TestClient client, final String body) throws UnsupportedEncodingException { return client.header(HttpHeaders.CONTENT_ENCODING, CharEncoding.UTF_8) .header( HttpHeaders.CONTENT_LENGTH, body.getBytes(CharEncoding.UTF_8).length ) .header( HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED ) .post("sending batch of lines to stand SQS queue", body) .assertStatus(HttpURLConnection.HTTP_OK) // @checkstyle LineLength (1 line) .xpath("/SendMessageBatchResponse/BatchResultError/BatchResultErrorEntry/Id/text()"); } /** * Create a JSON representation of xembly. * @param xembly Xembly to change into JSON. * @return JSON of xembly. */ private String json(final String xembly) { final StringWriter writer = new StringWriter(); final long nano = System.nanoTime() * Tv.HUNDRED + Standed.RND.nextInt(Tv.HUNDRED); Json.createGenerator(writer) .writeStartObject() .write("stand", this.stand) .write("nano", nano) .write("key", this.key) .write("xembly", xembly) .writeStartObject("work") .write("owner", this.work.owner().toString()) .write("rule", this.work.rule()) .write("scheduled", this.work.scheduled().toString()) .writeEnd() .writeEnd() .close(); return writer.toString(); } }
rultor-drain/src/main/java/com/rultor/drain/Standed.java
/** * Copyright (c) 2009-2013, rultor.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the rultor.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rultor.drain; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.aspects.RetryOnFailure; import com.jcabi.aspects.Tv; import com.jcabi.log.VerboseRunnable; import com.jcabi.log.VerboseThreads; import com.rexsl.test.RestTester; import com.rexsl.test.TestClient; import com.rultor.snapshot.XemblyLine; import com.rultor.spi.Coordinates; import com.rultor.spi.Drain; import com.rultor.spi.Pageable; import com.rultor.spi.Stand; import com.rultor.tools.Exceptions; import com.rultor.tools.Time; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URLEncoder; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.json.Json; import javax.validation.constraints.NotNull; import javax.ws.rs.core.MediaType; import lombok.EqualsAndHashCode; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHeaders; import org.xembly.XemblySyntaxException; /** * Mirrored to a web {@link Stand}. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 1.0 * @todo #162:0.5hr As soon as rexsl #716 is resolved remove * SQSEntry interface and use TestClient directly. * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Immutable @EqualsAndHashCode(of = { "origin", "work", "stand", "key" }) @Loggable(Loggable.DEBUG) @SuppressWarnings({ "PMD.ExcessiveImports", "PMD.TooManyMethods" }) public final class Standed implements Drain { /** * Randomizer for nanos. */ public static final Random RND = new SecureRandom(); /** * Number of threads to use for sending to queue. */ public static final int THREADS = 10; /** * Max message batch size. */ private static final int MAX_BATCH_SIZE = 10; /** * SQS client connection container. */ @Immutable private interface SQSEntry { /** * Provide SQS connection. * @return SQS connection. */ TestClient get(); } /** * Executor container. */ @Immutable private interface Exec { /** * Provide executor. * @return ExecutorService */ ExecutorService get(); } /** * Coordinates we're in. */ private final transient Coordinates work; /** * Original drain. */ private final transient Drain origin; /** * Name of stand. */ private final transient String stand; /** * Secret key of it. */ private final transient String key; /** * HTTP queue that will receive data. */ private final transient Standed.SQSEntry entry; /** * Executor that runs tasks. */ private final transient Standed.Exec exec; /** * Public ctor. * @param wrk Coordinates we're in * @param name Name of stand * @param secret Secret key of the stand * @param drain Main drain * @checkstyle ParameterNumber (8 lines) */ public Standed( @NotNull(message = "work can't be NULL") final Coordinates wrk, @NotNull(message = "name of stand can't be NULL") final String name, @NotNull(message = "key can't be NULL") final String secret, @NotNull(message = "drain can't be NULL") final Drain drain) { this( wrk, name, secret, drain, RestTester.start(Stand.QUEUE), Executors.newFixedThreadPool(Standed.THREADS, new VerboseThreads()) ); } /** * Constructor for tests. * @param wrk Coordinates we're in * @param name Name of stand * @param secret Secret key of the stand * @param drain Main drain * @param client HTTP queue * @param executor Executor to use * @checkstyle ParameterNumber (8 lines) */ public Standed(final Coordinates wrk, final String name, final String secret, final Drain drain, final TestClient client, final ExecutorService executor) { this.work = wrk; this.stand = name; this.key = secret; this.origin = drain; this.entry = new Standed.SQSEntry() { @Override public TestClient get() { return client; } }; this.exec = new Standed.Exec() { @Override public ExecutorService get() { return executor; } }; } /** * {@inheritDoc} */ @Override public String toString() { return String.format( "%s standed at `%s`", this.origin, this.stand ); } /** * {@inheritDoc} */ @Override public Pageable<Time, Time> pulses() throws IOException { return this.origin.pulses(); } /** * {@inheritDoc} */ @Override public void append(final Iterable<String> lines) throws IOException { final Iterable<List<String>> batches = Iterables.partition( FluentIterable.from(lines) .filter( new Predicate<String>() { @Override public boolean apply(final String line) { return XemblyLine.existsIn(line); } } ) .transform( new Function<String, String>() { @Override public String apply(final String line) { try { return XemblyLine.parse(line).xembly(); } catch (XemblySyntaxException ex) { Exceptions.warn(this, ex); } return null; } } ) .filter(Predicates.notNull()), Standed.MAX_BATCH_SIZE ); for (List<String> batch : batches) { this.send(batch); } this.origin.append(lines); } /** * {@inheritDoc} */ @Override public InputStream read() throws IOException { return new SequenceInputStream( IOUtils.toInputStream( String.format( "Standed: stand='%s'\n", this.stand ), CharEncoding.UTF_8 ), this.origin.read() ); } /** * Send lines to stand. * @param xemblies The xembly scripts * @throws IOException If fails */ private void send(final Iterable<String> xemblies) throws IOException { this.exec.get().submit( new VerboseRunnable( new Callable<Void>() { @Override public Void call() throws Exception { Standed.this.send(Standed.this.body(xemblies)); return null; } }, true, false ) ); } /** * Send the message. * @param body POST request body * @throws IOException If fails */ @RetryOnFailure(verbose = false) private void send(final String body) throws IOException { final Collection<String> missed = Standed.this.enqueue( this.entry.get(), body ); if (!missed.isEmpty()) { throw new IOException( String.format( "Problem with sending of %d message(s): %s", missed.size(), StringUtils.join(missed, ", ") ) ); } } /** * Create POST request body. * @param xemblies The xembly scripts * @return POST request body * @throws IOException If fails */ private String body(final Iterable<String> xemblies) throws IOException { final List<String> msgs = new ArrayList<String>(0); for (String xembly : xemblies) { msgs.add(this.json(xembly)); } final StringBuilder body = new StringBuilder() .append("Action=SendMessageBatch") .append("&Version=2011-10-01"); for (int idx = 0; idx < msgs.size(); ++idx) { final int ent = idx + 1; body.append('&') .append("SendMessageBatchRequestEntry.") .append(ent) .append(".Id=") .append(ent) .append("&SendMessageBatchRequestEntry.") .append(ent) .append(".MessageBody=") .append(URLEncoder.encode(msgs.get(idx), CharEncoding.UTF_8)); } return body.toString(); } /** * Put messages on SQS. * @param client HTTP client to use. * @param body Body of the POST. * @return List of message IDs that were not enqueued. * @throws UnsupportedEncodingException When unable to find UTF-8 encoding. */ private List<String> enqueue(final TestClient client, final String body) throws UnsupportedEncodingException { return client.header(HttpHeaders.CONTENT_ENCODING, CharEncoding.UTF_8) .header( HttpHeaders.CONTENT_LENGTH, body.getBytes(CharEncoding.UTF_8).length ) .header( HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED ) .post("sending batch of lines to stand SQS queue", body) .assertStatus(HttpURLConnection.HTTP_OK) // @checkstyle LineLength (1 line) .xpath("/SendMessageBatchResponse/BatchResultError/BatchResultErrorEntry/Id/text()"); } /** * Create a JSON representation of xembly. * @param xembly Xembly to change into JSON. * @return JSON of xembly. */ private String json(final String xembly) { final StringWriter writer = new StringWriter(); final long nano = System.nanoTime() * Tv.HUNDRED + Standed.RND.nextInt(Tv.HUNDRED); Json.createGenerator(writer) .writeStartObject() .write("stand", this.stand) .write("nano", nano) .write("key", this.key) .write("xembly", xembly) .writeStartObject("work") .write("owner", this.work.owner().toString()) .write("rule", this.work.rule()) .write("scheduled", this.work.scheduled().toString()) .writeEnd() .writeEnd() .close(); return writer.toString(); } }
const renamed
rultor-drain/src/main/java/com/rultor/drain/Standed.java
const renamed
Java
bsd-3-clause
98c7fae9c243cdff99869f2e1b19eb99b1e059e4
0
CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers
package gov.nih.nci.cabig.caaers.domain; import gov.nih.nci.cabig.caaers.domain.meddra.LowLevelTerm; import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; /** * @author Ion C. Olaru */ @Entity @DiscriminatorValue("meddra") public class ExpectedAEMeddraLowLevelTerm extends AbstractExpectedAE<LowLevelTerm> { private String meddraCode; public String getMeddraCode() { return meddraCode; } public void setMeddraCode(String meddraCode) { this.meddraCode = meddraCode; } @Transient public String getFullName() { if(getTerm() == null) return ""; return getTerm().getFullName(); } @ManyToOne @JoinColumn(name = "term_id") @Override public LowLevelTerm getTerm() { return super.getTerm(); } @Transient public void setLowLevelTerm(LowLevelTerm lowlevelTerm) { super.setTerm(lowlevelTerm); } @Override public ExpectedAEMeddraLowLevelTerm copy() { return (ExpectedAEMeddraLowLevelTerm) super.copy(); } @Override @Transient public boolean isMedDRA() { return true; } @Override @Transient public boolean isOtherRequired() { return false; } }
projects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/ExpectedAEMeddraLowLevelTerm.java
package gov.nih.nci.cabig.caaers.domain; import gov.nih.nci.cabig.caaers.domain.meddra.LowLevelTerm; import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; /** * @author Ion C. Olaru */ @Entity @DiscriminatorValue("meddra") public class ExpectedAEMeddraLowLevelTerm extends AbstractExpectedAE<LowLevelTerm> { private String meddraCode; public String getMeddraCode() { return meddraCode; } public void setMeddraCode(String meddraCode) { this.meddraCode = meddraCode; } @Transient public String getFullName() { if(getTerm() == null) return ""; return getTerm().getFullName(); } @OneToOne @JoinColumn(name = "term_id") @Override public LowLevelTerm getTerm() { return super.getTerm(); } @Transient public void setLowLevelTerm(LowLevelTerm lowlevelTerm) { super.setTerm(lowlevelTerm); } @Override public ExpectedAEMeddraLowLevelTerm copy() { return (ExpectedAEMeddraLowLevelTerm) super.copy(); } @Override @Transient public boolean isMedDRA() { return true; } @Override @Transient public boolean isOtherRequired() { return false; } }
Hibernate Cascading & Relation fix SVN-Revision: 7428
projects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/ExpectedAEMeddraLowLevelTerm.java
Hibernate Cascading & Relation fix
Java
mit
9f8958613db42d2ee60183c3e500e91f80f5782d
0
csimons/jenkins,ChrisA89/jenkins,escoem/jenkins,NehemiahMi/jenkins,iterate/coding-dojo,DanielWeber/jenkins,ikedam/jenkins,iterate/coding-dojo,DoctorQ/jenkins,luoqii/jenkins,aldaris/jenkins,everyonce/jenkins,FTG-003/jenkins,shahharsh/jenkins,ChrisA89/jenkins,tfennelly/jenkins,christ66/jenkins,Jimilian/jenkins,morficus/jenkins,ajshastri/jenkins,SebastienGllmt/jenkins,noikiy/jenkins,Jochen-A-Fuerbacher/jenkins,akshayabd/jenkins,ndeloof/jenkins,Wilfred/jenkins,ns163/jenkins,FarmGeek4Life/jenkins,FarmGeek4Life/jenkins,vivek/hudson,vlajos/jenkins,my7seven/jenkins,patbos/jenkins,azweb76/jenkins,csimons/jenkins,stephenc/jenkins,rashmikanta-1984/jenkins,varmenise/jenkins,FarmGeek4Life/jenkins,scoheb/jenkins,andresrc/jenkins,ajshastri/jenkins,verbitan/jenkins,huybrechts/hudson,escoem/jenkins,rashmikanta-1984/jenkins,jcsirot/jenkins,tfennelly/jenkins,ErikVerheul/jenkins,MichaelPranovich/jenkins_sc,FTG-003/jenkins,Ykus/jenkins,tastatur/jenkins,vjuranek/jenkins,hudson/hudson-2.x,jglick/jenkins,ikedam/jenkins,rsandell/jenkins,pjanouse/jenkins,morficus/jenkins,elkingtonmcb/jenkins,292388900/jenkins,andresrc/jenkins,keyurpatankar/hudson,everyonce/jenkins,aldaris/jenkins,lvotypko/jenkins,liorhson/jenkins,Vlatombe/jenkins,tangkun75/jenkins,maikeffi/hudson,noikiy/jenkins,aheritier/jenkins,damianszczepanik/jenkins,CodeShane/jenkins,bpzhang/jenkins,CodeShane/jenkins,ajshastri/jenkins,ErikVerheul/jenkins,sathiya-mit/jenkins,hemantojhaa/jenkins,christ66/jenkins,nandan4/Jenkins,christ66/jenkins,hashar/jenkins,292388900/jenkins,liupugong/jenkins,keyurpatankar/hudson,jpbriend/jenkins,samatdav/jenkins,jtnord/jenkins,stefanbrausch/hudson-main,dariver/jenkins,khmarbaise/jenkins,arunsingh/jenkins,singh88/jenkins,olivergondza/jenkins,shahharsh/jenkins,wuwen5/jenkins,liorhson/jenkins,vjuranek/jenkins,hemantojhaa/jenkins,mpeltonen/jenkins,lordofthejars/jenkins,tfennelly/jenkins,batmat/jenkins,DoctorQ/jenkins,jk47/jenkins,viqueen/jenkins,Krasnyanskiy/jenkins,tastatur/jenkins,paulmillar/jenkins,Wilfred/jenkins,292388900/jenkins,duzifang/my-jenkins,hplatou/jenkins,ikedam/jenkins,sathiya-mit/jenkins,duzifang/my-jenkins,Jimilian/jenkins,mattclark/jenkins,intelchen/jenkins,akshayabd/jenkins,ydubreuil/jenkins,maikeffi/hudson,mattclark/jenkins,akshayabd/jenkins,batmat/jenkins,andresrc/jenkins,verbitan/jenkins,morficus/jenkins,csimons/jenkins,synopsys-arc-oss/jenkins,alvarolobato/jenkins,ndeloof/jenkins,iterate/coding-dojo,bkmeneguello/jenkins,recena/jenkins,pjanouse/jenkins,pselle/jenkins,jglick/jenkins,MadsNielsen/jtemp,akshayabd/jenkins,maikeffi/hudson,Jochen-A-Fuerbacher/jenkins,CodeShane/jenkins,mrooney/jenkins,1and1/jenkins,DoctorQ/jenkins,Ykus/jenkins,my7seven/jenkins,arcivanov/jenkins,lindzh/jenkins,seanlin816/jenkins,morficus/jenkins,lvotypko/jenkins,duzifang/my-jenkins,petermarcoen/jenkins,abayer/jenkins,vijayto/jenkins,KostyaSha/jenkins,tastatur/jenkins,azweb76/jenkins,kohsuke/hudson,iqstack/jenkins,dennisjlee/jenkins,damianszczepanik/jenkins,pantheon-systems/jenkins,292388900/jenkins,mattclark/jenkins,protazy/jenkins,aduprat/jenkins,Krasnyanskiy/jenkins,AustinKwang/jenkins,vivek/hudson,tangkun75/jenkins,MadsNielsen/jtemp,FarmGeek4Life/jenkins,jtnord/jenkins,iterate/coding-dojo,patbos/jenkins,my7seven/jenkins,my7seven/jenkins,varmenise/jenkins,jpederzolli/jenkins-1,alvarolobato/jenkins,hemantojhaa/jenkins,my7seven/jenkins,deadmoose/jenkins,lvotypko/jenkins2,alvarolobato/jenkins,pjanouse/jenkins,arunsingh/jenkins,lvotypko/jenkins3,ndeloof/jenkins,batmat/jenkins,pselle/jenkins,khmarbaise/jenkins,hudson/hudson-2.x,lordofthejars/jenkins,kohsuke/hudson,soenter/jenkins,singh88/jenkins,jpbriend/jenkins,intelchen/jenkins,lvotypko/jenkins3,vvv444/jenkins,msrb/jenkins,1and1/jenkins,KostyaSha/jenkins,ndeloof/jenkins,hashar/jenkins,kohsuke/hudson,svanoort/jenkins,recena/jenkins,mrooney/jenkins,Jimilian/jenkins,viqueen/jenkins,AustinKwang/jenkins,vlajos/jenkins,vvv444/jenkins,amruthsoft9/Jenkis,liupugong/jenkins,daniel-beck/jenkins,amruthsoft9/Jenkis,seanlin816/jenkins,protazy/jenkins,jhoblitt/jenkins,wangyikai/jenkins,amuniz/jenkins,oleg-nenashev/jenkins,daniel-beck/jenkins,hemantojhaa/jenkins,aquarellian/jenkins,singh88/jenkins,everyonce/jenkins,bkmeneguello/jenkins,MarkEWaite/jenkins,SebastienGllmt/jenkins,FarmGeek4Life/jenkins,vivek/hudson,Ykus/jenkins,Jochen-A-Fuerbacher/jenkins,lilyJi/jenkins,Wilfred/jenkins,bpzhang/jenkins,vijayto/jenkins,lvotypko/jenkins2,jcarrothers-sap/jenkins,MarkEWaite/jenkins,dennisjlee/jenkins,amruthsoft9/Jenkis,singh88/jenkins,arunsingh/jenkins,lindzh/jenkins,ChrisA89/jenkins,jenkinsci/jenkins,lvotypko/jenkins,dbroady1/jenkins,my7seven/jenkins,abayer/jenkins,chbiel/jenkins,lindzh/jenkins,github-api-test-org/jenkins,nandan4/Jenkins,ChrisA89/jenkins,kohsuke/hudson,mrobinet/jenkins,jglick/jenkins,aheritier/jenkins,ns163/jenkins,tfennelly/jenkins,jtnord/jenkins,paulmillar/jenkins,intelchen/jenkins,CodeShane/jenkins,damianszczepanik/jenkins,lvotypko/jenkins2,msrb/jenkins,keyurpatankar/hudson,evernat/jenkins,patbos/jenkins,hplatou/jenkins,vjuranek/jenkins,lvotypko/jenkins2,synopsys-arc-oss/jenkins,duzifang/my-jenkins,rlugojr/jenkins,lordofthejars/jenkins,vivek/hudson,aheritier/jenkins,hudson/hudson-2.x,msrb/jenkins,hashar/jenkins,rsandell/jenkins,aquarellian/jenkins,dennisjlee/jenkins,svanoort/jenkins,liorhson/jenkins,olivergondza/jenkins,chbiel/jenkins,FarmGeek4Life/jenkins,aquarellian/jenkins,azweb76/jenkins,duzifang/my-jenkins,jzjzjzj/jenkins,pselle/jenkins,vjuranek/jenkins,Krasnyanskiy/jenkins,jzjzjzj/jenkins,v1v/jenkins,SenolOzer/jenkins,gusreiber/jenkins,fbelzunc/jenkins,viqueen/jenkins,ns163/jenkins,dbroady1/jenkins,aquarellian/jenkins,ydubreuil/jenkins,ajshastri/jenkins,soenter/jenkins,chbiel/jenkins,akshayabd/jenkins,daniel-beck/jenkins,gusreiber/jenkins,DanielWeber/jenkins,oleg-nenashev/jenkins,arcivanov/jenkins,vlajos/jenkins,everyonce/jenkins,guoxu0514/jenkins,guoxu0514/jenkins,pjanouse/jenkins,escoem/jenkins,dennisjlee/jenkins,ydubreuil/jenkins,godfath3r/jenkins,gorcz/jenkins,ydubreuil/jenkins,dbroady1/jenkins,seanlin816/jenkins,luoqii/jenkins,vlajos/jenkins,6WIND/jenkins,damianszczepanik/jenkins,lvotypko/jenkins2,mattclark/jenkins,jhoblitt/jenkins,shahharsh/jenkins,noikiy/jenkins,jcarrothers-sap/jenkins,luoqii/jenkins,yonglehou/jenkins,andresrc/jenkins,tangkun75/jenkins,kzantow/jenkins,duzifang/my-jenkins,fbelzunc/jenkins,lordofthejars/jenkins,DoctorQ/jenkins,soenter/jenkins,lindzh/jenkins,thomassuckow/jenkins,github-api-test-org/jenkins,tastatur/jenkins,KostyaSha/jenkins,Vlatombe/jenkins,kzantow/jenkins,gusreiber/jenkins,gorcz/jenkins,pselle/jenkins,jhoblitt/jenkins,fbelzunc/jenkins,NehemiahMi/jenkins,rsandell/jenkins,azweb76/jenkins,vjuranek/jenkins,mcanthony/jenkins,jpederzolli/jenkins-1,petermarcoen/jenkins,FTG-003/jenkins,pselle/jenkins,kohsuke/hudson,jk47/jenkins,mrooney/jenkins,jtnord/jenkins,aduprat/jenkins,DanielWeber/jenkins,albers/jenkins,gorcz/jenkins,noikiy/jenkins,aheritier/jenkins,mcanthony/jenkins,lordofthejars/jenkins,mpeltonen/jenkins,gitaccountforprashant/gittest,KostyaSha/jenkins,DanielWeber/jenkins,iterate/coding-dojo,gorcz/jenkins,yonglehou/jenkins,wangyikai/jenkins,AustinKwang/jenkins,Wilfred/jenkins,andresrc/jenkins,stephenc/jenkins,arcivanov/jenkins,amuniz/jenkins,gorcz/jenkins,huybrechts/hudson,elkingtonmcb/jenkins,oleg-nenashev/jenkins,luoqii/jenkins,huybrechts/hudson,292388900/jenkins,azweb76/jenkins,thomassuckow/jenkins,liupugong/jenkins,Jochen-A-Fuerbacher/jenkins,shahharsh/jenkins,oleg-nenashev/jenkins,hplatou/jenkins,aldaris/jenkins,paulmillar/jenkins,shahharsh/jenkins,paulmillar/jenkins,stefanbrausch/hudson-main,christ66/jenkins,damianszczepanik/jenkins,stefanbrausch/hudson-main,khmarbaise/jenkins,ndeloof/jenkins,jcsirot/jenkins,github-api-test-org/jenkins,brunocvcunha/jenkins,bpzhang/jenkins,guoxu0514/jenkins,rsandell/jenkins,yonglehou/jenkins,6WIND/jenkins,CodeShane/jenkins,csimons/jenkins,intelchen/jenkins,deadmoose/jenkins,Jimilian/jenkins,vivek/hudson,daniel-beck/jenkins,rlugojr/jenkins,MadsNielsen/jtemp,jpederzolli/jenkins-1,amruthsoft9/Jenkis,deadmoose/jenkins,Krasnyanskiy/jenkins,vijayto/jenkins,jglick/jenkins,ErikVerheul/jenkins,liupugong/jenkins,dbroady1/jenkins,lindzh/jenkins,stefanbrausch/hudson-main,elkingtonmcb/jenkins,Wilfred/jenkins,Jochen-A-Fuerbacher/jenkins,daniel-beck/jenkins,amuniz/jenkins,jpbriend/jenkins,mattclark/jenkins,MichaelPranovich/jenkins_sc,jpbriend/jenkins,ns163/jenkins,viqueen/jenkins,sathiya-mit/jenkins,varmenise/jenkins,hplatou/jenkins,vijayto/jenkins,SenolOzer/jenkins,stephenc/jenkins,vijayto/jenkins,rlugojr/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,seanlin816/jenkins,rashmikanta-1984/jenkins,1and1/jenkins,evernat/jenkins,mdonohue/jenkins,scoheb/jenkins,samatdav/jenkins,lvotypko/jenkins,ChrisA89/jenkins,AustinKwang/jenkins,gusreiber/jenkins,mcanthony/jenkins,patbos/jenkins,jhoblitt/jenkins,liorhson/jenkins,singh88/jenkins,arcivanov/jenkins,paulwellnerbou/jenkins,FTG-003/jenkins,batmat/jenkins,v1v/jenkins,maikeffi/hudson,Ykus/jenkins,wuwen5/jenkins,mcanthony/jenkins,liorhson/jenkins,pantheon-systems/jenkins,goldchang/jenkins,mcanthony/jenkins,bkmeneguello/jenkins,ErikVerheul/jenkins,lvotypko/jenkins3,nandan4/Jenkins,1and1/jenkins,shahharsh/jenkins,my7seven/jenkins,rsandell/jenkins,olivergondza/jenkins,amuniz/jenkins,amuniz/jenkins,SebastienGllmt/jenkins,csimons/jenkins,jzjzjzj/jenkins,gitaccountforprashant/gittest,tfennelly/jenkins,aquarellian/jenkins,brunocvcunha/jenkins,daspilker/jenkins,gitaccountforprashant/gittest,huybrechts/hudson,daniel-beck/jenkins,v1v/jenkins,gusreiber/jenkins,deadmoose/jenkins,elkingtonmcb/jenkins,kzantow/jenkins,godfath3r/jenkins,abayer/jenkins,vijayto/jenkins,hudson/hudson-2.x,luoqii/jenkins,lindzh/jenkins,wuwen5/jenkins,tangkun75/jenkins,abayer/jenkins,morficus/jenkins,wuwen5/jenkins,6WIND/jenkins,scoheb/jenkins,vvv444/jenkins,dbroady1/jenkins,patbos/jenkins,aduprat/jenkins,yonglehou/jenkins,jk47/jenkins,fbelzunc/jenkins,aduprat/jenkins,MichaelPranovich/jenkins_sc,vlajos/jenkins,CodeShane/jenkins,yonglehou/jenkins,vvv444/jenkins,gitaccountforprashant/gittest,deadmoose/jenkins,everyonce/jenkins,mcanthony/jenkins,sathiya-mit/jenkins,varmenise/jenkins,hashar/jenkins,pantheon-systems/jenkins,bkmeneguello/jenkins,hplatou/jenkins,jcarrothers-sap/jenkins,evernat/jenkins,scoheb/jenkins,nandan4/Jenkins,mpeltonen/jenkins,samatdav/jenkins,iqstack/jenkins,pantheon-systems/jenkins,akshayabd/jenkins,jk47/jenkins,ikedam/jenkins,jpederzolli/jenkins-1,h4ck3rm1k3/jenkins,nandan4/Jenkins,vvv444/jenkins,huybrechts/hudson,amruthsoft9/Jenkis,verbitan/jenkins,lvotypko/jenkins3,1and1/jenkins,aquarellian/jenkins,ErikVerheul/jenkins,h4ck3rm1k3/jenkins,gitaccountforprashant/gittest,kzantow/jenkins,Jimilian/jenkins,keyurpatankar/hudson,mdonohue/jenkins,iterate/coding-dojo,amuniz/jenkins,tangkun75/jenkins,stephenc/jenkins,lilyJi/jenkins,SebastienGllmt/jenkins,mrobinet/jenkins,protazy/jenkins,wuwen5/jenkins,lvotypko/jenkins2,ikedam/jenkins,morficus/jenkins,gusreiber/jenkins,mdonohue/jenkins,kohsuke/hudson,protazy/jenkins,rlugojr/jenkins,h4ck3rm1k3/jenkins,dariver/jenkins,keyurpatankar/hudson,amruthsoft9/Jenkis,ChrisA89/jenkins,yonglehou/jenkins,sathiya-mit/jenkins,mcanthony/jenkins,olivergondza/jenkins,h4ck3rm1k3/jenkins,scoheb/jenkins,scoheb/jenkins,deadmoose/jenkins,andresrc/jenkins,bpzhang/jenkins,mrobinet/jenkins,maikeffi/hudson,varmenise/jenkins,deadmoose/jenkins,6WIND/jenkins,akshayabd/jenkins,pantheon-systems/jenkins,jenkinsci/jenkins,bpzhang/jenkins,svanoort/jenkins,maikeffi/hudson,dariver/jenkins,jenkinsci/jenkins,6WIND/jenkins,escoem/jenkins,fbelzunc/jenkins,NehemiahMi/jenkins,pjanouse/jenkins,jhoblitt/jenkins,MadsNielsen/jtemp,NehemiahMi/jenkins,aduprat/jenkins,MarkEWaite/jenkins,daspilker/jenkins,jglick/jenkins,rashmikanta-1984/jenkins,jpederzolli/jenkins-1,v1v/jenkins,DoctorQ/jenkins,noikiy/jenkins,nandan4/Jenkins,lilyJi/jenkins,MadsNielsen/jtemp,noikiy/jenkins,viqueen/jenkins,ndeloof/jenkins,rashmikanta-1984/jenkins,mdonohue/jenkins,damianszczepanik/jenkins,SebastienGllmt/jenkins,h4ck3rm1k3/jenkins,abayer/jenkins,synopsys-arc-oss/jenkins,soenter/jenkins,csimons/jenkins,v1v/jenkins,amruthsoft9/Jenkis,jtnord/jenkins,Krasnyanskiy/jenkins,jcsirot/jenkins,ajshastri/jenkins,hashar/jenkins,keyurpatankar/hudson,mpeltonen/jenkins,godfath3r/jenkins,paulmillar/jenkins,DoctorQ/jenkins,evernat/jenkins,khmarbaise/jenkins,pjanouse/jenkins,liupugong/jenkins,synopsys-arc-oss/jenkins,patbos/jenkins,wangyikai/jenkins,synopsys-arc-oss/jenkins,aheritier/jenkins,maikeffi/hudson,paulwellnerbou/jenkins,evernat/jenkins,mrooney/jenkins,hemantojhaa/jenkins,varmenise/jenkins,ns163/jenkins,Ykus/jenkins,DanielWeber/jenkins,jzjzjzj/jenkins,liorhson/jenkins,csimons/jenkins,aduprat/jenkins,batmat/jenkins,liorhson/jenkins,mdonohue/jenkins,v1v/jenkins,vvv444/jenkins,jcarrothers-sap/jenkins,MarkEWaite/jenkins,Jochen-A-Fuerbacher/jenkins,v1v/jenkins,lvotypko/jenkins3,ydubreuil/jenkins,KostyaSha/jenkins,vivek/hudson,duzifang/my-jenkins,escoem/jenkins,guoxu0514/jenkins,alvarolobato/jenkins,lilyJi/jenkins,amuniz/jenkins,SenolOzer/jenkins,recena/jenkins,luoqii/jenkins,DanielWeber/jenkins,pselle/jenkins,github-api-test-org/jenkins,petermarcoen/jenkins,MarkEWaite/jenkins,dennisjlee/jenkins,mrobinet/jenkins,github-api-test-org/jenkins,synopsys-arc-oss/jenkins,paulmillar/jenkins,jcsirot/jenkins,protazy/jenkins,stefanbrausch/hudson-main,ErikVerheul/jenkins,jcsirot/jenkins,godfath3r/jenkins,hemantojhaa/jenkins,ErikVerheul/jenkins,samatdav/jenkins,SebastienGllmt/jenkins,goldchang/jenkins,jenkinsci/jenkins,rsandell/jenkins,singh88/jenkins,chbiel/jenkins,svanoort/jenkins,godfath3r/jenkins,paulwellnerbou/jenkins,dariver/jenkins,elkingtonmcb/jenkins,fbelzunc/jenkins,soenter/jenkins,ns163/jenkins,evernat/jenkins,AustinKwang/jenkins,jk47/jenkins,petermarcoen/jenkins,viqueen/jenkins,abayer/jenkins,vivek/hudson,aldaris/jenkins,olivergondza/jenkins,chbiel/jenkins,abayer/jenkins,sathiya-mit/jenkins,6WIND/jenkins,ndeloof/jenkins,bpzhang/jenkins,samatdav/jenkins,samatdav/jenkins,daspilker/jenkins,MichaelPranovich/jenkins_sc,mpeltonen/jenkins,seanlin816/jenkins,tastatur/jenkins,olivergondza/jenkins,wangyikai/jenkins,bkmeneguello/jenkins,escoem/jenkins,msrb/jenkins,liupugong/jenkins,kzantow/jenkins,paulmillar/jenkins,FTG-003/jenkins,AustinKwang/jenkins,hudson/hudson-2.x,thomassuckow/jenkins,lordofthejars/jenkins,jzjzjzj/jenkins,FTG-003/jenkins,albers/jenkins,hashar/jenkins,Krasnyanskiy/jenkins,ydubreuil/jenkins,CodeShane/jenkins,mrobinet/jenkins,jpbriend/jenkins,jcarrothers-sap/jenkins,maikeffi/hudson,NehemiahMi/jenkins,jpbriend/jenkins,mrobinet/jenkins,albers/jenkins,intelchen/jenkins,jcarrothers-sap/jenkins,wangyikai/jenkins,gusreiber/jenkins,daspilker/jenkins,stefanbrausch/hudson-main,godfath3r/jenkins,protazy/jenkins,chbiel/jenkins,alvarolobato/jenkins,svanoort/jenkins,Jimilian/jenkins,MarkEWaite/jenkins,iqstack/jenkins,MichaelPranovich/jenkins_sc,soenter/jenkins,vvv444/jenkins,MichaelPranovich/jenkins_sc,everyonce/jenkins,vlajos/jenkins,jcarrothers-sap/jenkins,gorcz/jenkins,Ykus/jenkins,dbroady1/jenkins,1and1/jenkins,verbitan/jenkins,h4ck3rm1k3/jenkins,seanlin816/jenkins,FTG-003/jenkins,elkingtonmcb/jenkins,huybrechts/hudson,goldchang/jenkins,pjanouse/jenkins,jzjzjzj/jenkins,luoqii/jenkins,rashmikanta-1984/jenkins,tangkun75/jenkins,Wilfred/jenkins,azweb76/jenkins,Ykus/jenkins,dariver/jenkins,gitaccountforprashant/gittest,daniel-beck/jenkins,aldaris/jenkins,batmat/jenkins,aldaris/jenkins,paulwellnerbou/jenkins,hplatou/jenkins,protazy/jenkins,Vlatombe/jenkins,christ66/jenkins,SenolOzer/jenkins,noikiy/jenkins,arcivanov/jenkins,lvotypko/jenkins,1and1/jenkins,morficus/jenkins,wuwen5/jenkins,iqstack/jenkins,soenter/jenkins,aheritier/jenkins,wuwen5/jenkins,christ66/jenkins,shahharsh/jenkins,mrobinet/jenkins,arunsingh/jenkins,hashar/jenkins,ydubreuil/jenkins,kohsuke/hudson,iqstack/jenkins,keyurpatankar/hudson,FarmGeek4Life/jenkins,evernat/jenkins,tastatur/jenkins,dbroady1/jenkins,paulwellnerbou/jenkins,albers/jenkins,MadsNielsen/jtemp,guoxu0514/jenkins,huybrechts/hudson,paulwellnerbou/jenkins,bpzhang/jenkins,github-api-test-org/jenkins,NehemiahMi/jenkins,nandan4/Jenkins,Jimilian/jenkins,petermarcoen/jenkins,dennisjlee/jenkins,mpeltonen/jenkins,alvarolobato/jenkins,ajshastri/jenkins,Vlatombe/jenkins,pselle/jenkins,mrooney/jenkins,khmarbaise/jenkins,github-api-test-org/jenkins,stephenc/jenkins,thomassuckow/jenkins,godfath3r/jenkins,lordofthejars/jenkins,mdonohue/jenkins,dariver/jenkins,damianszczepanik/jenkins,goldchang/jenkins,pantheon-systems/jenkins,MadsNielsen/jtemp,msrb/jenkins,jk47/jenkins,lindzh/jenkins,thomassuckow/jenkins,stephenc/jenkins,Vlatombe/jenkins,batmat/jenkins,jenkinsci/jenkins,khmarbaise/jenkins,keyurpatankar/hudson,rsandell/jenkins,goldchang/jenkins,rlugojr/jenkins,aheritier/jenkins,thomassuckow/jenkins,shahharsh/jenkins,andresrc/jenkins,6WIND/jenkins,msrb/jenkins,aquarellian/jenkins,kohsuke/hudson,stefanbrausch/hudson-main,jglick/jenkins,liupugong/jenkins,kzantow/jenkins,svanoort/jenkins,lvotypko/jenkins3,jcsirot/jenkins,brunocvcunha/jenkins,vivek/hudson,arcivanov/jenkins,tfennelly/jenkins,vjuranek/jenkins,daspilker/jenkins,oleg-nenashev/jenkins,recena/jenkins,jpederzolli/jenkins-1,DanielWeber/jenkins,damianszczepanik/jenkins,arunsingh/jenkins,KostyaSha/jenkins,rlugojr/jenkins,dariver/jenkins,hplatou/jenkins,oleg-nenashev/jenkins,ikedam/jenkins,samatdav/jenkins,github-api-test-org/jenkins,292388900/jenkins,lilyJi/jenkins,jpbriend/jenkins,intelchen/jenkins,recena/jenkins,tastatur/jenkins,vjuranek/jenkins,goldchang/jenkins,arunsingh/jenkins,albers/jenkins,petermarcoen/jenkins,patbos/jenkins,seanlin816/jenkins,sathiya-mit/jenkins,jk47/jenkins,elkingtonmcb/jenkins,fbelzunc/jenkins,recena/jenkins,KostyaSha/jenkins,verbitan/jenkins,SenolOzer/jenkins,vlajos/jenkins,petermarcoen/jenkins,arcivanov/jenkins,hudson/hudson-2.x,jenkinsci/jenkins,synopsys-arc-oss/jenkins,jtnord/jenkins,rsandell/jenkins,varmenise/jenkins,h4ck3rm1k3/jenkins,brunocvcunha/jenkins,Wilfred/jenkins,alvarolobato/jenkins,ns163/jenkins,lilyJi/jenkins,MarkEWaite/jenkins,msrb/jenkins,SenolOzer/jenkins,thomassuckow/jenkins,rlugojr/jenkins,gorcz/jenkins,verbitan/jenkins,mrooney/jenkins,dennisjlee/jenkins,Jochen-A-Fuerbacher/jenkins,everyonce/jenkins,wangyikai/jenkins,brunocvcunha/jenkins,goldchang/jenkins,olivergondza/jenkins,lvotypko/jenkins3,jzjzjzj/jenkins,gorcz/jenkins,ajshastri/jenkins,albers/jenkins,jenkinsci/jenkins,daspilker/jenkins,jglick/jenkins,jenkinsci/jenkins,KostyaSha/jenkins,goldchang/jenkins,stephenc/jenkins,khmarbaise/jenkins,viqueen/jenkins,mpeltonen/jenkins,escoem/jenkins,mdonohue/jenkins,Krasnyanskiy/jenkins,paulwellnerbou/jenkins,tfennelly/jenkins,Vlatombe/jenkins,brunocvcunha/jenkins,DoctorQ/jenkins,singh88/jenkins,iqstack/jenkins,albers/jenkins,DoctorQ/jenkins,jcsirot/jenkins,scoheb/jenkins,MichaelPranovich/jenkins_sc,jhoblitt/jenkins,svanoort/jenkins,ikedam/jenkins,iterate/coding-dojo,guoxu0514/jenkins,jpederzolli/jenkins-1,verbitan/jenkins,iqstack/jenkins,Vlatombe/jenkins,aldaris/jenkins,arunsingh/jenkins,SenolOzer/jenkins,yonglehou/jenkins,christ66/jenkins,AustinKwang/jenkins,daniel-beck/jenkins,kzantow/jenkins,NehemiahMi/jenkins,ikedam/jenkins,mattclark/jenkins,jzjzjzj/jenkins,tangkun75/jenkins,rashmikanta-1984/jenkins,mrooney/jenkins,hemantojhaa/jenkins,jhoblitt/jenkins,lvotypko/jenkins,bkmeneguello/jenkins,mattclark/jenkins,brunocvcunha/jenkins,lvotypko/jenkins2,wangyikai/jenkins,SebastienGllmt/jenkins,jtnord/jenkins,recena/jenkins,ChrisA89/jenkins,daspilker/jenkins,vijayto/jenkins,azweb76/jenkins,pantheon-systems/jenkins,guoxu0514/jenkins,292388900/jenkins,gitaccountforprashant/gittest,jcarrothers-sap/jenkins,lvotypko/jenkins,bkmeneguello/jenkins,lilyJi/jenkins,intelchen/jenkins,aduprat/jenkins,chbiel/jenkins
package hudson.scm; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.Launcher; import hudson.Proc; import hudson.Util; import hudson.EnvVars; import static hudson.Util.fixEmpty; import static hudson.Util.fixNull; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Hudson; import hudson.model.Job; import hudson.model.LargeText; import hudson.model.ModelObject; import hudson.model.Run; import hudson.model.TaskListener; import hudson.org.apache.tools.ant.taskdefs.cvslib.ChangeLogTask; import hudson.remoting.RemoteOutputStream; import hudson.remoting.VirtualChannel; import hudson.scm.AbstractScmTagAction.AbstractTagWorkerThread; import hudson.util.ArgumentListBuilder; import hudson.util.ByteBuffer; import hudson.util.ForkOutputStream; import hudson.util.FormFieldValidator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.lang.ref.WeakReference; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * CVS. * * <p> * I couldn't call this class "CVS" because that would cause the view folder name * to collide with CVS control files. * * <p> * This object gets shipped to the remote machine to perform some of the work, * so it implements {@link Serializable}. * * @author Kohsuke Kawaguchi */ public class CVSSCM extends SCM implements Serializable { /** * CVSSCM connection string. */ private String cvsroot; /** * Module names. * * This could be a whitespace/NL-separated list of multiple modules. * Modules could be either directories or files. */ private String module; private String branch; private String cvsRsh; private boolean canUseUpdate; /** * True to avoid creating a sub-directory inside the workspace. * (Works only when there's just one module.) */ private boolean flatten; private CVSRepositoryBrowser repositoryBrowser; /** * @stapler-constructor */ public CVSSCM(String cvsroot, String module,String branch,String cvsRsh,boolean canUseUpdate, boolean legacy) { if(fixNull(branch).equals("HEAD")) branch = null; this.cvsroot = cvsroot; this.module = module.trim(); this.branch = nullify(branch); this.cvsRsh = nullify(cvsRsh); this.canUseUpdate = canUseUpdate; this.flatten = !legacy && new StringTokenizer(module).countTokens()==1; } @Override public CVSRepositoryBrowser getBrowser() { return repositoryBrowser; } private String compression() { if(getDescriptor().isNoCompression()) return null; // CVS 1.11.22 manual: // If the access method is omitted, then if the repository starts with // `/', then `:local:' is assumed. If it does not start with `/' then // either `:ext:' or `:server:' is assumed. boolean local = cvsroot.startsWith("/") || cvsroot.startsWith(":local:") || cvsroot.startsWith(":fork:"); // For local access, compression is senseless. For remote, use z3: // http://root.cern.ch/root/CVS.html#checkout return local ? "-z0" : "-z3"; } public String getCvsRoot() { return cvsroot; } /** * If there are multiple modules, return the module directory of the first one. * @param workspace */ public FilePath getModuleRoot(FilePath workspace) { if(flatten) return workspace; return workspace.child(new StringTokenizer(module).nextToken()); } public ChangeLogParser createChangeLogParser() { return new CVSChangeLogParser(); } public String getAllModules() { return module; } private String getAllModulesNormalized() { StringBuilder buf = new StringBuilder(); StringTokenizer tokens = new StringTokenizer(module); while(tokens.hasMoreTokens()) { if(buf.length()>0) buf.append(' '); buf.append(tokens.nextToken()); } return buf.toString(); } /** * Branch to build. Null to indicate the trunk. */ public String getBranch() { return branch; } public String getCvsRsh() { return cvsRsh; } public boolean getCanUseUpdate() { return canUseUpdate; } public boolean isFlatten() { return flatten; } public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath dir, TaskListener listener) throws IOException, InterruptedException { List<String> changedFiles = update(true, launcher, dir, listener, new Date()); return changedFiles!=null && !changedFiles.isEmpty(); } private void configureDate(ArgumentListBuilder cmd, Date date) { // #192 DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US); df.setTimeZone(TimeZone.getTimeZone("UTC")); // #209 cmd.add("-D", df.format(date)); } public boolean checkout(AbstractBuild build, Launcher launcher, FilePath ws, BuildListener listener, File changelogFile) throws IOException, InterruptedException { List<String> changedFiles = null; // files that were affected by update. null this is a check out if(canUseUpdate && isUpdatable(ws)) { changedFiles = update(false, launcher, ws, listener, build.getTimestamp().getTime()); if(changedFiles==null) return false; // failed } else { if(!checkout(launcher,ws,listener,build.getTimestamp().getTime())) return false; } // archive the workspace to support later tagging File archiveFile = getArchiveFile(build); final OutputStream os = new RemoteOutputStream(new FileOutputStream(archiveFile)); ws.act(new FileCallable<Void>() { public Void invoke(File ws, VirtualChannel channel) throws IOException { ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(os)); if(flatten) { archive(ws, module, zos,true); } else { StringTokenizer tokens = new StringTokenizer(module); while(tokens.hasMoreTokens()) { String m = tokens.nextToken(); File mf = new File(ws, m); if(!mf.exists()) // directory doesn't exist. This happens if a directory that was checked out // didn't include any file. continue; if(!mf.isDirectory()) { // this module is just a file, say "foo/bar.txt". // to record "foo/CVS/*", we need to start by archiving "foo". int idx = m.lastIndexOf('/'); if(idx==-1) throw new Error("Kohsuke probe: m="+m); m = m.substring(0, idx); mf = mf.getParentFile(); } archive(mf,m,zos,true); } } zos.close(); return null; } }); // contribute the tag action build.getActions().add(new TagAction(build)); return calcChangeLog(build, ws, changedFiles, changelogFile, listener); } public boolean checkout(Launcher launcher, FilePath dir, TaskListener listener) throws IOException, InterruptedException { Date now = new Date(); if(canUseUpdate && isUpdatable(dir)) { return update(false, launcher, dir, listener, now)!=null; } else { return checkout(launcher,dir,listener, now); } } private boolean checkout(Launcher launcher, FilePath dir, TaskListener listener, Date dt) throws IOException, InterruptedException { dir.deleteContents(); ArgumentListBuilder cmd = new ArgumentListBuilder(); cmd.add(getDescriptor().getCvsExe(),debugLogging?"-t":"-Q",compression(),"-d",cvsroot,"co"); if(branch!=null) cmd.add("-r",branch); if(flatten) cmd.add("-d",dir.getName()); configureDate(cmd,dt); cmd.addTokenized(getAllModulesNormalized()); return run(launcher,cmd,listener, flatten ? dir.getParent() : dir); } /** * Returns the file name used to archive the build. */ private static File getArchiveFile(AbstractBuild build) { return new File(build.getRootDir(),"workspace.zip"); } /** * Archives all the CVS-controlled files in {@code dir}. * * @param relPath * The path name in ZIP to store this directory with. */ private void archive(File dir,String relPath,ZipOutputStream zos, boolean isRoot) throws IOException { Set<String> knownFiles = new HashSet<String>(); // see http://www.monkey.org/openbsd/archive/misc/9607/msg00056.html for what Entries.Log is for parseCVSEntries(new File(dir,"CVS/Entries"),knownFiles); parseCVSEntries(new File(dir,"CVS/Entries.Log"),knownFiles); parseCVSEntries(new File(dir,"CVS/Entries.Extra"),knownFiles); boolean hasCVSdirs = !knownFiles.isEmpty(); knownFiles.add("CVS"); File[] files = dir.listFiles(); if(files==null) { if(isRoot) throw new IOException("No such directory exists. Did you specify the correct branch? Perhaps you specified a tag: "+dir); else throw new IOException("No such directory exists. Looks like someone is modifying the workspace concurrently: "+dir); } for( File f : files ) { String name = relPath+'/'+f.getName(); if(f.isDirectory()) { if(hasCVSdirs && !knownFiles.contains(f.getName())) { // not controlled in CVS. Skip. // but also make sure that we archive CVS/*, which doesn't have CVS/CVS continue; } archive(f,name,zos,false); } else { if(!dir.getName().equals("CVS")) // we only need to archive CVS control files, not the actual workspace files continue; zos.putNextEntry(new ZipEntry(name)); FileInputStream fis = new FileInputStream(f); Util.copyStream(fis,zos); fis.close(); zos.closeEntry(); } } } /** * Parses the CVS/Entries file and adds file/directory names to the list. */ private void parseCVSEntries(File entries, Set<String> knownFiles) throws IOException { if(!entries.exists()) return; BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(entries))); String line; while((line=in.readLine())!=null) { String[] tokens = line.split("/+"); if(tokens==null || tokens.length<2) continue; // invalid format knownFiles.add(tokens[1]); } in.close(); } /** * Updates the workspace as well as locate changes. * * @return * List of affected file names, relative to the workspace directory. * Null if the operation failed. */ private List<String> update(boolean dryRun, Launcher launcher, FilePath workspace, TaskListener listener, Date date) throws IOException, InterruptedException { List<String> changedFileNames = new ArrayList<String>(); // file names relative to the workspace ArgumentListBuilder cmd = new ArgumentListBuilder(); cmd.add(getDescriptor().getCvsExe(),"-q",compression()); if(dryRun) cmd.add("-n"); cmd.add("update","-PdC"); if (branch != null) { cmd.add("-r", branch); } configureDate(cmd, date); if(flatten) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if(!run(launcher,cmd,listener,workspace, new ForkOutputStream(baos,listener.getLogger()))) return null; parseUpdateOutput("",baos, changedFileNames); } else { @SuppressWarnings("unchecked") // StringTokenizer oddly has the wrong type final Set<String> moduleNames = new TreeSet(Collections.list(new StringTokenizer(module))); // Add in any existing CVS dirs, in case project checked out its own. moduleNames.addAll(workspace.act(new FileCallable<Set<String>>() { public Set<String> invoke(File ws, VirtualChannel channel) throws IOException { File[] subdirs = ws.listFiles(); if (subdirs != null) { SUBDIR: for (File s : subdirs) { if (new File(s, "CVS").isDirectory()) { String top = s.getName(); for (String mod : moduleNames) { if (mod.startsWith(top + "/")) { // #190: user asked to check out foo/bar foo/baz quux // Our top-level dirs are "foo" and "quux". // Do not add "foo" to checkout or we will check out foo/*! continue SUBDIR; } } moduleNames.add(top); } } } return moduleNames; } })); for (String moduleName : moduleNames) { // capture the output during update ByteArrayOutputStream baos = new ByteArrayOutputStream(); FilePath modulePath = new FilePath(workspace, moduleName); ArgumentListBuilder actualCmd = cmd; String baseName = moduleName; if(!modulePath.isDirectory()) { // updating just one file, like "foo/bar.txt". // run update command from "foo" directory with "bar.txt" as the command line argument actualCmd = cmd.clone(); actualCmd.add(modulePath.getName()); modulePath = modulePath.getParent(); int slash = baseName.lastIndexOf('/'); if (slash > 0) { baseName = baseName.substring(0, slash); } } if(!run(launcher,actualCmd,listener, modulePath, new ForkOutputStream(baos,listener.getLogger()))) return null; // we'll run one "cvs log" command with workspace as the base, // so use path names that are relative to moduleName. parseUpdateOutput(baseName+'/',baos, changedFileNames); } } return changedFileNames; } // see http://www.network-theory.co.uk/docs/cvsmanual/cvs_153.html for the output format. // we don't care '?' because that's not in the repository private static final Pattern UPDATE_LINE = Pattern.compile("[UPARMC] (.+)"); private static final Pattern REMOVAL_LINE = Pattern.compile("cvs (server|update): `?(.+?)'? is no longer in the repository"); //private static final Pattern NEWDIRECTORY_LINE = Pattern.compile("cvs server: New directory `(.+)' -- ignored"); /** * Parses the output from CVS update and list up files that might have been changed. * * @param result * list of file names whose changelog should be checked. This may include files * that are no longer present. The path names are relative to the workspace, * hence "String", not {@link File}. */ private void parseUpdateOutput(String baseName, ByteArrayOutputStream output, List<String> result) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader( new ByteArrayInputStream(output.toByteArray()))); String line; while((line=in.readLine())!=null) { Matcher matcher = UPDATE_LINE.matcher(line); if(matcher.matches()) { result.add(baseName+matcher.group(1)); continue; } matcher= REMOVAL_LINE.matcher(line); if(matcher.matches()) { result.add(baseName+matcher.group(2)); continue; } // this line is added in an attempt to capture newly created directories in the repository, // but it turns out that this line always hit if the workspace is missing a directory // that the server has, even if that directory contains nothing in it //matcher= NEWDIRECTORY_LINE.matcher(line); //if(matcher.matches()) { // result.add(baseName+matcher.group(1)); //} } } /** * Returns true if we can use "cvs update" instead of "cvs checkout" */ private boolean isUpdatable(FilePath dir) throws IOException, InterruptedException { return dir.act(new FileCallable<Boolean>() { public Boolean invoke(File dir, VirtualChannel channel) throws IOException { if(flatten) { return isUpdatableModule(dir); } else { StringTokenizer tokens = new StringTokenizer(module); while(tokens.hasMoreTokens()) { File module = new File(dir,tokens.nextToken()); if(!isUpdatableModule(module)) return false; } return true; } } }); } private boolean isUpdatableModule(File module) { if(!module.isDirectory()) // module is a file, like "foo/bar.txt". Then CVS information is "foo/CVS". module = module.getParentFile(); File cvs = new File(module,"CVS"); if(!cvs.exists()) return false; // check cvsroot if(!checkContents(new File(cvs,"Root"),cvsroot)) return false; if(branch!=null) { if(!checkContents(new File(cvs,"Tag"),'T'+branch)) return false; } else { File tag = new File(cvs,"Tag"); if (tag.exists()) { try { Reader r = new FileReader(tag); try { String s = new BufferedReader(r).readLine(); return s != null && s.startsWith("D"); } finally { r.close(); } } catch (IOException e) { return false; } } } return true; } /** * Returns true if the contents of the file is equal to the given string. * * @return false in all the other cases. */ private boolean checkContents(File file, String contents) { try { Reader r = new FileReader(file); try { String s = new BufferedReader(r).readLine(); if (s == null) return false; return s.trim().equals(contents.trim()); } finally { r.close(); } } catch (IOException e) { return false; } } /** * Used to communicate the result of the detection in {@link CVSSCM#calcChangeLog(AbstractBuild, FilePath, List, File, BuildListener)} */ class ChangeLogResult implements Serializable { boolean hadError; String errorOutput; public ChangeLogResult(boolean hadError, String errorOutput) { this.hadError = hadError; if(hadError) this.errorOutput = errorOutput; } private static final long serialVersionUID = 1L; } /** * Used to propagate {@link BuildException} and error log at the same time. */ class BuildExceptionWithLog extends RuntimeException { final String errorOutput; public BuildExceptionWithLog(BuildException cause, String errorOutput) { super(cause); this.errorOutput = errorOutput; } private static final long serialVersionUID = 1L; } /** * Computes the changelog into an XML file. * * <p> * When we update the workspace, we'll compute the changelog by using its output to * make it faster. In general case, we'll fall back to the slower approach where * we check all files in the workspace. * * @param changedFiles * Files whose changelog should be checked for updates. * This is provided if the previous operation is update, otherwise null, * which means we have to fall back to the default slow computation. */ private boolean calcChangeLog(AbstractBuild build, FilePath ws, final List<String> changedFiles, File changelogFile, final BuildListener listener) throws InterruptedException { if(build.getPreviousBuild()==null || (changedFiles!=null && changedFiles.isEmpty())) { // nothing to compare against, or no changes // (note that changedFiles==null means fallback, so we have to run cvs log. listener.getLogger().println("$ no changes detected"); return createEmptyChangeLog(changelogFile,listener, "changelog"); } listener.getLogger().println("$ computing changelog"); final String cvspassFile = getDescriptor().getCvspassFile(); final String cvsExe = getDescriptor().getCvsExe(); try { // range of time for detecting changes final Date startTime = build.getPreviousBuild().getTimestamp().getTime(); final Date endTime = build.getTimestamp().getTime(); final OutputStream out = new RemoteOutputStream(new FileOutputStream(changelogFile)); ChangeLogResult result = ws.act(new FileCallable<ChangeLogResult>() { public ChangeLogResult invoke(File ws, VirtualChannel channel) throws IOException { final StringWriter errorOutput = new StringWriter(); final boolean[] hadError = new boolean[1]; ChangeLogTask task = new ChangeLogTask() { public void log(String msg, int msgLevel) { // send error to listener. This seems like the route in which the changelog task // sends output if(msgLevel==org.apache.tools.ant.Project.MSG_ERR) { hadError[0] = true; errorOutput.write(msg); errorOutput.write('\n'); return; } if(debugLogging) { listener.getLogger().println(msg); } } }; task.setProject(new org.apache.tools.ant.Project()); task.setCvsExe(cvsExe); task.setDir(ws); if(cvspassFile.length()!=0) task.setPassfile(new File(cvspassFile)); if (canUseUpdate && cvsroot.startsWith("/")) { // cvs log of built source trees unreliable in local access method: // https://savannah.nongnu.org/bugs/index.php?15223 task.setCvsRoot(":fork:" + cvsroot); } else if (canUseUpdate && cvsroot.startsWith(":local:")) { task.setCvsRoot(":fork:" + cvsroot.substring(7)); } else { task.setCvsRoot(cvsroot); } task.setCvsRsh(cvsRsh); task.setFailOnError(true); task.setDeststream(new BufferedOutputStream(out)); task.setBranch(branch); task.setStart(startTime); task.setEnd(endTime); if(changedFiles!=null) { // we can optimize the processing if we know what files have changed. // but also try not to make the command line too long so as no to hit // the system call limit to the command line length (see issue #389) // the choice of the number is arbitrary, but normally we don't really // expect continuous builds to have too many changes, so this should be OK. if(changedFiles.size()<100 || !Hudson.isWindows()) { // if the directory doesn't exist, cvs changelog will die, so filter them out. // this means we'll lose the log of those changes for (String filePath : changedFiles) { if(new File(ws,filePath).getParentFile().exists()) task.addFile(filePath); } } } else { // fallback if(!flatten) task.setPackage(getAllModulesNormalized()); } try { task.execute(); } catch (BuildException e) { throw new BuildExceptionWithLog(e,errorOutput.toString()); } return new ChangeLogResult(hadError[0],errorOutput.toString()); } }); if(result.hadError) { // non-fatal error must have occurred, such as cvs changelog parsing error.s listener.getLogger().print(result.errorOutput); } return true; } catch( BuildExceptionWithLog e ) { // capture output from the task for diagnosis listener.getLogger().print(e.errorOutput); // then report an error BuildException x = (BuildException) e.getCause(); PrintWriter w = listener.error(x.getMessage()); w.println("Working directory is "+ ws); x.printStackTrace(w); return false; } catch( RuntimeException e ) { // an user reported a NPE inside the changeLog task. // we don't want a bug in Ant to prevent a build. e.printStackTrace(listener.error(e.getMessage())); return true; // so record the message but continue } catch( IOException e ) { e.printStackTrace(listener.error("Failed to detect changlog")); return true; } } public DescriptorImpl getDescriptor() { return DescriptorImpl.DESCRIPTOR; } public void buildEnvVars(AbstractBuild build, Map<String, String> env) { if(cvsRsh!=null) env.put("CVS_RSH",cvsRsh); if(branch!=null) env.put("CVS_BRANCH",branch); String cvspass = getDescriptor().getCvspassFile(); if(cvspass.length()!=0) env.put("CVS_PASSFILE",cvspass); } /** * Invokes the command with the specified command line option and wait for its completion. * * @param dir * if launching locally this is a local path, otherwise a remote path. * @param out * Receives output from the executed program. */ protected final boolean run(Launcher launcher, ArgumentListBuilder cmd, TaskListener listener, FilePath dir, OutputStream out) throws IOException, InterruptedException { Map<String,String> env = createEnvVarMap(true); int r = launcher.launch(cmd.toCommandArray(),env,out,dir).join(); if(r!=0) listener.fatalError(getDescriptor().getDisplayName()+" failed. exit code="+r); return r==0; } protected final boolean run(Launcher launcher, ArgumentListBuilder cmd, TaskListener listener, FilePath dir) throws IOException, InterruptedException { return run(launcher,cmd,listener,dir,listener.getLogger()); } /** * * @param overrideOnly * true to indicate that the returned map shall only contain * properties that need to be overridden. This is for use with {@link Launcher}. * false to indicate that the map should contain complete map. * This is to invoke {@link Proc} directly. */ protected final Map<String,String> createEnvVarMap(boolean overrideOnly) { Map<String,String> env = new HashMap<String,String>(); if(!overrideOnly) env.putAll(EnvVars.masterEnvVars); buildEnvVars(null/*TODO*/,env); return env; } public static final class DescriptorImpl extends SCMDescriptor<CVSSCM> implements ModelObject { static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); /** * Path to <tt>.cvspass</tt>. Null to default. */ private String cvsPassFile; /** * Path to cvs executable. Null to just use "cvs". */ private String cvsExe; /** * Disable CVS compression support. */ private boolean noCompression; // compatibility only private transient Map<String,RepositoryBrowser> browsers; // compatibility only class RepositoryBrowser { String diffURL; String browseURL; } DescriptorImpl() { super(CVSSCM.class,CVSRepositoryBrowser.class); load(); } protected void convert(Map<String, Object> oldPropertyBag) { cvsPassFile = (String)oldPropertyBag.get("cvspass"); } public String getDisplayName() { return "CVS"; } public SCM newInstance(StaplerRequest req) throws FormException { CVSSCM scm = req.bindParameters(CVSSCM.class, "cvs."); scm.repositoryBrowser = RepositoryBrowsers.createInstance(CVSRepositoryBrowser.class,req,"cvs.browser"); return scm; } public String getCvspassFile() { String value = cvsPassFile; if(value==null) value = ""; return value; } public String getCvsExe() { if(cvsExe==null) return "cvs"; else return cvsExe; } public void setCvspassFile(String value) { cvsPassFile = value; save(); } public boolean isNoCompression() { return noCompression; } public boolean configure( StaplerRequest req ) { cvsPassFile = fixEmpty(req.getParameter("cvs_cvspass").trim()); cvsExe = fixEmpty(req.getParameter("cvs_exe").trim()); noCompression = req.getParameter("cvs_noCompression")!=null; save(); return true; } @Override public boolean isBrowserReusable(CVSSCM x, CVSSCM y) { return x.getCvsRoot().equals(y.getCvsRoot()); } // // web methods // public void doCvsPassCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this method can be used to check if a file exists anywhere in the file system, // so it should be protected. new FormFieldValidator(req,rsp,true) { protected void check() throws IOException, ServletException { String v = fixEmpty(request.getParameter("value")); if(v==null) { // default. ok(); } else { File cvsPassFile = new File(v); if(cvsPassFile.exists()) { ok(); } else { error("No such file exists"); } } } }.process(); } /** * Checks if cvs executable exists. */ public void doCvsExeCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this method can be used to check if a file exists anywhere in the file system, // so it should be protected. new FormFieldValidator(req,rsp,true) { protected void check() throws IOException, ServletException { String cvsExe = fixEmpty(request.getParameter("value")); if(cvsExe==null) { ok(); return; } if(cvsExe.indexOf(File.separatorChar)>=0) { // this is full path if(new File(cvsExe).exists()) { ok(); } else { error("There's no such file: "+cvsExe); } } else { // can't really check ok(); } } }.process(); } /** * Displays "cvs --version" for trouble shooting. */ public void doVersion(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { ByteBuffer baos = new ByteBuffer(); try { Proc proc = Hudson.getInstance().createLauncher(TaskListener.NULL).launch( new String[]{getCvsExe(), "--version"}, new String[0], baos, null); proc.join(); rsp.setContentType("text/plain"); baos.writeTo(rsp.getOutputStream()); } catch (IOException e) { req.setAttribute("error",e); rsp.forward(this,"versionCheckError",req); } } /** * Checks the correctness of the branch name. */ public void doBranchCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req,rsp,false) { protected void check() throws IOException, ServletException { String v = fixNull(request.getParameter("value")); if(v.equals("HEAD")) error("Technically, HEAD is not a branch in CVS. Leave this field empty to build the trunk."); else ok(); } }.process(); } /** * Checks the entry to the CVSROOT field. * <p> * Also checks if .cvspass file contains the entry for this. */ public void doCvsrootCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req,rsp,false) { protected void check() throws IOException, ServletException { String v = fixEmpty(request.getParameter("value")); if(v==null) { error("CVSROOT is mandatory"); return; } Matcher m = CVSROOT_PSERVER_PATTERN.matcher(v); // CVSROOT format isn't really that well defined. So it's hard to check this rigorously. if(v.startsWith(":pserver") || v.startsWith(":ext")) { if(!m.matches()) { error("Invalid CVSROOT string"); return; } // I can't really test if the machine name exists, either. // some cvs, such as SOCKS-enabled cvs can resolve host names that Hudson might not // be able to. If :ext is used, all bets are off anyway. } // check .cvspass file to see if it has entry. // CVS handles authentication only if it's pserver. if(v.startsWith(":pserver")) { if(m.group(2)==null) {// if password is not specified in CVSROOT String cvspass = getCvspassFile(); File passfile; if(cvspass.equals("")) { passfile = new File(new File(System.getProperty("user.home")),".cvspass"); } else { passfile = new File(cvspass); } if(passfile.exists()) { // It's possible that we failed to locate the correct .cvspass file location, // so don't report an error if we couldn't locate this file. // // if this is explicitly specified, then our system config page should have // reported an error. if(!scanCvsPassFile(passfile, v)) { error("It doesn't look like this CVSROOT has its password set." + " Would you like to set it now?"); return; } } } } // all tests passed so far ok(); } }.process(); } /** * Checks if the given pserver CVSROOT value exists in the pass file. */ private boolean scanCvsPassFile(File passfile, String cvsroot) throws IOException { cvsroot += ' '; String cvsroot2 = "/1 "+cvsroot; // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5006835 BufferedReader in = new BufferedReader(new FileReader(passfile)); try { String line; while((line=in.readLine())!=null) { // "/1 " version always have the port number in it, so examine a much with // default port 2401 left out int portIndex = line.indexOf(":2401/"); String line2 = ""; if(portIndex>=0) line2 = line.substring(0,portIndex+1)+line.substring(portIndex+5); // leave '/' if(line.startsWith(cvsroot) || line.startsWith(cvsroot2) || line2.startsWith(cvsroot2)) return true; } return false; } finally { in.close(); } } private static final Pattern CVSROOT_PSERVER_PATTERN = Pattern.compile(":(ext|pserver):[^@:]+(:[^@:]+)?@[^:]+:(\\d+:)?.+"); /** * Runs cvs login command. * * TODO: this apparently doesn't work. Probably related to the fact that * cvs does some tty magic to disable echo back or whatever. */ public void doPostPassword(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException { if(!Hudson.adminCheck(req,rsp)) return; String cvsroot = req.getParameter("cvsroot"); String password = req.getParameter("password"); if(cvsroot==null || password==null) { rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } rsp.setContentType("text/plain"); Proc proc = Hudson.getInstance().createLauncher(TaskListener.NULL).launch( new String[]{getCvsExe(), "-d",cvsroot,"login"}, new String[0], new ByteArrayInputStream((password+"\n").getBytes()), rsp.getOutputStream()); proc.join(); } } /** * Action for a build that performs the tagging. */ public final class TagAction extends AbstractScmTagAction { /** * If non-null, that means the build is already tagged. * If multiple tags are created, those are whitespace-separated. */ private volatile String tagName; public TagAction(AbstractBuild build) { super(build); } public String getIconFileName() { if(tagName==null && !Hudson.isAdmin()) return null; return "save.gif"; } public String getDisplayName() { if(tagName==null) return "Tag this build"; if(tagName.indexOf(' ')>=0) return "CVS tags"; else return "CVS tag"; } public String[] getTagNames() { if(tagName==null) return new String[0]; return tagName.split(" "); } /** * Checks if the value is a valid CVS tag name. */ public synchronized void doCheckTag(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req,rsp,false) { protected void check() throws IOException, ServletException { String tag = fixNull(request.getParameter("value")).trim(); if(tag.length()==0) {// nothing entered yet ok(); return; } error(isInvalidTag(tag)); } }.check(); } /** * Invoked to actually tag the workspace. */ public synchronized void doSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if(!Hudson.adminCheck(req,rsp)) return; Map<AbstractBuild,String> tagSet = new HashMap<AbstractBuild,String>(); String name = fixNull(req.getParameter("name")).trim(); String reason = isInvalidTag(name); if(reason!=null) { sendError(reason,req,rsp); return; } tagSet.put(build,name); if(req.getParameter("upstream")!=null) { // tag all upstream builds Enumeration e = req.getParameterNames(); Map<AbstractProject, Integer> upstreams = build.getUpstreamBuilds(); // TODO: define them at AbstractBuild level while(e.hasMoreElements()) { String upName = (String) e.nextElement(); if(!upName.startsWith("upstream.")) continue; String tag = fixNull(req.getParameter(upName)).trim(); reason = isInvalidTag(tag); if(reason!=null) { sendError("No valid tag name given for "+upName+" : "+reason,req,rsp); return; } upName = upName.substring(9); // trim off 'upstream.' Job p = Hudson.getInstance().getItemByFullName(upName,Job.class); Run build = p.getBuildByNumber(upstreams.get(p)); tagSet.put((AbstractBuild) build,tag); } } new TagWorkerThread(tagSet).start(); doIndex(req,rsp); } /** * Checks if the given value is a valid CVS tag. * * If it's invalid, this method gives you the reason as string. */ private String isInvalidTag(String name) { // source code from CVS rcs.c //void //RCS_check_tag (tag) // const char *tag; //{ // char *invalid = "$,.:;@"; /* invalid RCS tag characters */ // const char *cp; // // /* // * The first character must be an alphabetic letter. The remaining // * characters cannot be non-visible graphic characters, and must not be // * in the set of "invalid" RCS identifier characters. // */ // if (isalpha ((unsigned char) *tag)) // { // for (cp = tag; *cp; cp++) // { // if (!isgraph ((unsigned char) *cp)) // error (1, 0, "tag `%s' has non-visible graphic characters", // tag); // if (strchr (invalid, *cp)) // error (1, 0, "tag `%s' must not contain the characters `%s'", // tag, invalid); // } // } // else // error (1, 0, "tag `%s' must start with a letter", tag); //} if(name==null || name.length()==0) return "Tag is empty"; char ch = name.charAt(0); if(!(('A'<=ch && ch<='Z') || ('a'<=ch && ch<='z'))) return "Tag needs to start with alphabet"; for( char invalid : "$,.:;@".toCharArray() ) { if(name.indexOf(invalid)>=0) return "Tag contains illegal '"+invalid+"' character"; } return null; } /** * Performs tagging. */ public void perform(String tagName, TaskListener listener) { File destdir = null; try { destdir = Util.createTempDir(); // unzip the archive listener.getLogger().println("expanding the workspace archive into "+destdir); Expand e = new Expand(); e.setProject(new org.apache.tools.ant.Project()); e.setDest(destdir); e.setSrc(getArchiveFile(build)); e.setTaskType("unzip"); e.execute(); // run cvs tag command listener.getLogger().println("tagging the workspace"); StringTokenizer tokens = new StringTokenizer(CVSSCM.this.module); while(tokens.hasMoreTokens()) { String m = tokens.nextToken(); FilePath path = new FilePath(destdir).child(m); boolean isDir = path.isDirectory(); ArgumentListBuilder cmd = new ArgumentListBuilder(); cmd.add(getDescriptor().getCvsExe(),"tag"); if(isDir) { cmd.add("-R"); } cmd.add(tagName); if(!isDir) { cmd.add(path.getName()); path = path.getParent(); } if(!CVSSCM.this.run(new Launcher.LocalLauncher(listener),cmd,listener, path)) { listener.getLogger().println("tagging failed"); return; } } // completed successfully onTagCompleted(tagName); build.save(); } catch (Throwable e) { e.printStackTrace(listener.fatalError(e.getMessage())); } finally { try { if(destdir!=null) { listener.getLogger().println("cleaning up "+destdir); Util.deleteRecursive(destdir); } } catch (IOException e) { e.printStackTrace(listener.fatalError(e.getMessage())); } } } /** * Atomically set the tag name and then be done with {@link TagWorkerThread}. */ private synchronized void onTagCompleted(String tagName) { if(this.tagName!=null) this.tagName += ' '+tagName; else this.tagName = tagName; this.workerThread = null; } } public static final class TagWorkerThread extends AbstractTagWorkerThread { private final Map<AbstractBuild,String> tagSet; public TagWorkerThread(Map<AbstractBuild,String> tagSet) { this.tagSet = tagSet; } public synchronized void start() { for (Entry<AbstractBuild, String> e : tagSet.entrySet()) { TagAction ta = e.getKey().getAction(TagAction.class); if(ta!=null) { ta.workerThread = this; ta.log = new WeakReference<LargeText>(text); } } super.start(); } protected void perform(TaskListener listener) { for (Entry<AbstractBuild, String> e : tagSet.entrySet()) { TagAction ta = e.getKey().getAction(TagAction.class); if(ta==null) { listener.error(e.getKey()+" doesn't have CVS tag associated with it. Skipping"); continue; } listener.getLogger().println("Tagging "+e.getKey()+" to "+e.getValue()); try { e.getKey().keepLog(); } catch (IOException x) { x.printStackTrace(listener.error("Failed to mark "+e.getKey()+" for keep")); } ta.perform(e.getValue(), listener); listener.getLogger().println(); } } } /** * Temporary hack for assisting trouble-shooting. * * <p> * Setting this property to true would cause <tt>cvs log</tt> to dump a lot of messages. */ public static boolean debugLogging = false; private static final long serialVersionUID = 1L; }
core/src/main/java/hudson/scm/CVSSCM.java
package hudson.scm; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.Launcher; import hudson.Proc; import hudson.Util; import hudson.EnvVars; import static hudson.Util.fixEmpty; import static hudson.Util.fixNull; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Hudson; import hudson.model.Job; import hudson.model.LargeText; import hudson.model.ModelObject; import hudson.model.Run; import hudson.model.TaskListener; import hudson.org.apache.tools.ant.taskdefs.cvslib.ChangeLogTask; import hudson.remoting.RemoteOutputStream; import hudson.remoting.VirtualChannel; import hudson.scm.AbstractScmTagAction.AbstractTagWorkerThread; import hudson.util.ArgumentListBuilder; import hudson.util.ByteBuffer; import hudson.util.ForkOutputStream; import hudson.util.FormFieldValidator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.lang.ref.WeakReference; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * CVS. * * <p> * I couldn't call this class "CVS" because that would cause the view folder name * to collide with CVS control files. * * <p> * This object gets shipped to the remote machine to perform some of the work, * so it implements {@link Serializable}. * * @author Kohsuke Kawaguchi */ public class CVSSCM extends SCM implements Serializable { /** * CVSSCM connection string. */ private String cvsroot; /** * Module names. * * This could be a whitespace/NL-separated list of multiple modules. * Modules could be either directories or files. */ private String module; private String branch; private String cvsRsh; private boolean canUseUpdate; /** * True to avoid creating a sub-directory inside the workspace. * (Works only when there's just one module.) */ private boolean flatten; private CVSRepositoryBrowser repositoryBrowser; /** * @stapler-constructor */ public CVSSCM(String cvsroot, String module,String branch,String cvsRsh,boolean canUseUpdate, boolean legacy) { if(fixNull(branch).equals("HEAD")) branch = null; this.cvsroot = cvsroot; this.module = module.trim(); this.branch = nullify(branch); this.cvsRsh = nullify(cvsRsh); this.canUseUpdate = canUseUpdate; this.flatten = !legacy && new StringTokenizer(module).countTokens()==1; } @Override public CVSRepositoryBrowser getBrowser() { return repositoryBrowser; } private String compression() { if(getDescriptor().isNoCompression()) return null; // CVS 1.11.22 manual: // If the access method is omitted, then if the repository starts with // `/', then `:local:' is assumed. If it does not start with `/' then // either `:ext:' or `:server:' is assumed. boolean local = cvsroot.startsWith("/") || cvsroot.startsWith(":local:") || cvsroot.startsWith(":fork:"); // For local access, compression is senseless. For remote, use z3: // http://root.cern.ch/root/CVS.html#checkout return local ? "-z0" : "-z3"; } public String getCvsRoot() { return cvsroot; } /** * If there are multiple modules, return the module directory of the first one. * @param workspace */ public FilePath getModuleRoot(FilePath workspace) { if(flatten) return workspace; return workspace.child(new StringTokenizer(module).nextToken()); } public ChangeLogParser createChangeLogParser() { return new CVSChangeLogParser(); } public String getAllModules() { return module; } private String getAllModulesNormalized() { StringBuilder buf = new StringBuilder(); StringTokenizer tokens = new StringTokenizer(module); while(tokens.hasMoreTokens()) { if(buf.length()>0) buf.append(' '); buf.append(tokens.nextToken()); } return buf.toString(); } /** * Branch to build. Null to indicate the trunk. */ public String getBranch() { return branch; } public String getCvsRsh() { return cvsRsh; } public boolean getCanUseUpdate() { return canUseUpdate; } public boolean isFlatten() { return flatten; } public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath dir, TaskListener listener) throws IOException, InterruptedException { List<String> changedFiles = update(true, launcher, dir, listener, new Date()); return changedFiles!=null && !changedFiles.isEmpty(); } private void configureDate(ArgumentListBuilder cmd, Date date) { // #192 DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US); df.setTimeZone(TimeZone.getTimeZone("UTC")); // #209 cmd.add("-D", df.format(date)); } public boolean checkout(AbstractBuild build, Launcher launcher, FilePath ws, BuildListener listener, File changelogFile) throws IOException, InterruptedException { List<String> changedFiles = null; // files that were affected by update. null this is a check out if(canUseUpdate && isUpdatable(ws)) { changedFiles = update(false, launcher, ws, listener, build.getTimestamp().getTime()); if(changedFiles==null) return false; // failed } else { if(!checkout(launcher,ws,listener,build.getTimestamp().getTime())) return false; } // archive the workspace to support later tagging File archiveFile = getArchiveFile(build); final OutputStream os = new RemoteOutputStream(new FileOutputStream(archiveFile)); ws.act(new FileCallable<Void>() { public Void invoke(File ws, VirtualChannel channel) throws IOException { ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(os)); if(flatten) { archive(ws, module, zos,true); } else { StringTokenizer tokens = new StringTokenizer(module); while(tokens.hasMoreTokens()) { String m = tokens.nextToken(); File mf = new File(ws, m); if(!mf.exists()) // directory doesn't exist. This happens if a directory that was checked out // didn't include any file. continue; if(!mf.isDirectory()) { // this module is just a file, say "foo/bar.txt". // to record "foo/CVS/*", we need to start by archiving "foo". int idx = m.lastIndexOf('/'); if(idx==-1) throw new Error("Kohsuke probe: m="+m); m = m.substring(0, idx); mf = mf.getParentFile(); } archive(mf,m,zos,true); } } zos.close(); return null; } }); // contribute the tag action build.getActions().add(new TagAction(build)); return calcChangeLog(build, ws, changedFiles, changelogFile, listener); } public boolean checkout(Launcher launcher, FilePath dir, TaskListener listener) throws IOException, InterruptedException { Date now = new Date(); if(canUseUpdate && isUpdatable(dir)) { return update(false, launcher, dir, listener, now)!=null; } else { return checkout(launcher,dir,listener, now); } } private boolean checkout(Launcher launcher, FilePath dir, TaskListener listener, Date dt) throws IOException, InterruptedException { dir.deleteContents(); ArgumentListBuilder cmd = new ArgumentListBuilder(); cmd.add(getDescriptor().getCvsExe(),debugLogging?"-t":"-Q",compression(),"-d",cvsroot,"co"); if(branch!=null) cmd.add("-r",branch); if(flatten) cmd.add("-d",dir.getName()); configureDate(cmd,dt); cmd.addTokenized(getAllModulesNormalized()); return run(launcher,cmd,listener, flatten ? dir.getParent() : dir); } /** * Returns the file name used to archive the build. */ private static File getArchiveFile(AbstractBuild build) { return new File(build.getRootDir(),"workspace.zip"); } /** * Archives all the CVS-controlled files in {@code dir}. * * @param relPath * The path name in ZIP to store this directory with. */ private void archive(File dir,String relPath,ZipOutputStream zos, boolean isRoot) throws IOException { Set<String> knownFiles = new HashSet<String>(); // see http://www.monkey.org/openbsd/archive/misc/9607/msg00056.html for what Entries.Log is for parseCVSEntries(new File(dir,"CVS/Entries"),knownFiles); parseCVSEntries(new File(dir,"CVS/Entries.Log"),knownFiles); parseCVSEntries(new File(dir,"CVS/Entries.Extra"),knownFiles); boolean hasCVSdirs = !knownFiles.isEmpty(); knownFiles.add("CVS"); File[] files = dir.listFiles(); if(files==null) { if(isRoot) throw new IOException("No such directory exists. Did you specify the correct branch/tag?: "+dir); else throw new IOException("No such directory exists. Looks like someone is modifying the workspace concurrently: "+dir); } for( File f : files ) { String name = relPath+'/'+f.getName(); if(f.isDirectory()) { if(hasCVSdirs && !knownFiles.contains(f.getName())) { // not controlled in CVS. Skip. // but also make sure that we archive CVS/*, which doesn't have CVS/CVS continue; } archive(f,name,zos,false); } else { if(!dir.getName().equals("CVS")) // we only need to archive CVS control files, not the actual workspace files continue; zos.putNextEntry(new ZipEntry(name)); FileInputStream fis = new FileInputStream(f); Util.copyStream(fis,zos); fis.close(); zos.closeEntry(); } } } /** * Parses the CVS/Entries file and adds file/directory names to the list. */ private void parseCVSEntries(File entries, Set<String> knownFiles) throws IOException { if(!entries.exists()) return; BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(entries))); String line; while((line=in.readLine())!=null) { String[] tokens = line.split("/+"); if(tokens==null || tokens.length<2) continue; // invalid format knownFiles.add(tokens[1]); } in.close(); } /** * Updates the workspace as well as locate changes. * * @return * List of affected file names, relative to the workspace directory. * Null if the operation failed. */ private List<String> update(boolean dryRun, Launcher launcher, FilePath workspace, TaskListener listener, Date date) throws IOException, InterruptedException { List<String> changedFileNames = new ArrayList<String>(); // file names relative to the workspace ArgumentListBuilder cmd = new ArgumentListBuilder(); cmd.add(getDescriptor().getCvsExe(),"-q",compression()); if(dryRun) cmd.add("-n"); cmd.add("update","-PdC"); if (branch != null) { cmd.add("-r", branch); } configureDate(cmd, date); if(flatten) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if(!run(launcher,cmd,listener,workspace, new ForkOutputStream(baos,listener.getLogger()))) return null; parseUpdateOutput("",baos, changedFileNames); } else { @SuppressWarnings("unchecked") // StringTokenizer oddly has the wrong type final Set<String> moduleNames = new TreeSet(Collections.list(new StringTokenizer(module))); // Add in any existing CVS dirs, in case project checked out its own. moduleNames.addAll(workspace.act(new FileCallable<Set<String>>() { public Set<String> invoke(File ws, VirtualChannel channel) throws IOException { File[] subdirs = ws.listFiles(); if (subdirs != null) { SUBDIR: for (File s : subdirs) { if (new File(s, "CVS").isDirectory()) { String top = s.getName(); for (String mod : moduleNames) { if (mod.startsWith(top + "/")) { // #190: user asked to check out foo/bar foo/baz quux // Our top-level dirs are "foo" and "quux". // Do not add "foo" to checkout or we will check out foo/*! continue SUBDIR; } } moduleNames.add(top); } } } return moduleNames; } })); for (String moduleName : moduleNames) { // capture the output during update ByteArrayOutputStream baos = new ByteArrayOutputStream(); FilePath modulePath = new FilePath(workspace, moduleName); ArgumentListBuilder actualCmd = cmd; String baseName = moduleName; if(!modulePath.isDirectory()) { // updating just one file, like "foo/bar.txt". // run update command from "foo" directory with "bar.txt" as the command line argument actualCmd = cmd.clone(); actualCmd.add(modulePath.getName()); modulePath = modulePath.getParent(); int slash = baseName.lastIndexOf('/'); if (slash > 0) { baseName = baseName.substring(0, slash); } } if(!run(launcher,actualCmd,listener, modulePath, new ForkOutputStream(baos,listener.getLogger()))) return null; // we'll run one "cvs log" command with workspace as the base, // so use path names that are relative to moduleName. parseUpdateOutput(baseName+'/',baos, changedFileNames); } } return changedFileNames; } // see http://www.network-theory.co.uk/docs/cvsmanual/cvs_153.html for the output format. // we don't care '?' because that's not in the repository private static final Pattern UPDATE_LINE = Pattern.compile("[UPARMC] (.+)"); private static final Pattern REMOVAL_LINE = Pattern.compile("cvs (server|update): `?(.+?)'? is no longer in the repository"); //private static final Pattern NEWDIRECTORY_LINE = Pattern.compile("cvs server: New directory `(.+)' -- ignored"); /** * Parses the output from CVS update and list up files that might have been changed. * * @param result * list of file names whose changelog should be checked. This may include files * that are no longer present. The path names are relative to the workspace, * hence "String", not {@link File}. */ private void parseUpdateOutput(String baseName, ByteArrayOutputStream output, List<String> result) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader( new ByteArrayInputStream(output.toByteArray()))); String line; while((line=in.readLine())!=null) { Matcher matcher = UPDATE_LINE.matcher(line); if(matcher.matches()) { result.add(baseName+matcher.group(1)); continue; } matcher= REMOVAL_LINE.matcher(line); if(matcher.matches()) { result.add(baseName+matcher.group(2)); continue; } // this line is added in an attempt to capture newly created directories in the repository, // but it turns out that this line always hit if the workspace is missing a directory // that the server has, even if that directory contains nothing in it //matcher= NEWDIRECTORY_LINE.matcher(line); //if(matcher.matches()) { // result.add(baseName+matcher.group(1)); //} } } /** * Returns true if we can use "cvs update" instead of "cvs checkout" */ private boolean isUpdatable(FilePath dir) throws IOException, InterruptedException { return dir.act(new FileCallable<Boolean>() { public Boolean invoke(File dir, VirtualChannel channel) throws IOException { if(flatten) { return isUpdatableModule(dir); } else { StringTokenizer tokens = new StringTokenizer(module); while(tokens.hasMoreTokens()) { File module = new File(dir,tokens.nextToken()); if(!isUpdatableModule(module)) return false; } return true; } } }); } private boolean isUpdatableModule(File module) { if(!module.isDirectory()) // module is a file, like "foo/bar.txt". Then CVS information is "foo/CVS". module = module.getParentFile(); File cvs = new File(module,"CVS"); if(!cvs.exists()) return false; // check cvsroot if(!checkContents(new File(cvs,"Root"),cvsroot)) return false; if(branch!=null) { if(!checkContents(new File(cvs,"Tag"),'T'+branch)) return false; } else { File tag = new File(cvs,"Tag"); if (tag.exists()) { try { Reader r = new FileReader(tag); try { String s = new BufferedReader(r).readLine(); return s != null && s.startsWith("D"); } finally { r.close(); } } catch (IOException e) { return false; } } } return true; } /** * Returns true if the contents of the file is equal to the given string. * * @return false in all the other cases. */ private boolean checkContents(File file, String contents) { try { Reader r = new FileReader(file); try { String s = new BufferedReader(r).readLine(); if (s == null) return false; return s.trim().equals(contents.trim()); } finally { r.close(); } } catch (IOException e) { return false; } } /** * Used to communicate the result of the detection in {@link CVSSCM#calcChangeLog(AbstractBuild, FilePath, List, File, BuildListener)} */ class ChangeLogResult implements Serializable { boolean hadError; String errorOutput; public ChangeLogResult(boolean hadError, String errorOutput) { this.hadError = hadError; if(hadError) this.errorOutput = errorOutput; } private static final long serialVersionUID = 1L; } /** * Used to propagate {@link BuildException} and error log at the same time. */ class BuildExceptionWithLog extends RuntimeException { final String errorOutput; public BuildExceptionWithLog(BuildException cause, String errorOutput) { super(cause); this.errorOutput = errorOutput; } private static final long serialVersionUID = 1L; } /** * Computes the changelog into an XML file. * * <p> * When we update the workspace, we'll compute the changelog by using its output to * make it faster. In general case, we'll fall back to the slower approach where * we check all files in the workspace. * * @param changedFiles * Files whose changelog should be checked for updates. * This is provided if the previous operation is update, otherwise null, * which means we have to fall back to the default slow computation. */ private boolean calcChangeLog(AbstractBuild build, FilePath ws, final List<String> changedFiles, File changelogFile, final BuildListener listener) throws InterruptedException { if(build.getPreviousBuild()==null || (changedFiles!=null && changedFiles.isEmpty())) { // nothing to compare against, or no changes // (note that changedFiles==null means fallback, so we have to run cvs log. listener.getLogger().println("$ no changes detected"); return createEmptyChangeLog(changelogFile,listener, "changelog"); } listener.getLogger().println("$ computing changelog"); final String cvspassFile = getDescriptor().getCvspassFile(); final String cvsExe = getDescriptor().getCvsExe(); try { // range of time for detecting changes final Date startTime = build.getPreviousBuild().getTimestamp().getTime(); final Date endTime = build.getTimestamp().getTime(); final OutputStream out = new RemoteOutputStream(new FileOutputStream(changelogFile)); ChangeLogResult result = ws.act(new FileCallable<ChangeLogResult>() { public ChangeLogResult invoke(File ws, VirtualChannel channel) throws IOException { final StringWriter errorOutput = new StringWriter(); final boolean[] hadError = new boolean[1]; ChangeLogTask task = new ChangeLogTask() { public void log(String msg, int msgLevel) { // send error to listener. This seems like the route in which the changelog task // sends output if(msgLevel==org.apache.tools.ant.Project.MSG_ERR) { hadError[0] = true; errorOutput.write(msg); errorOutput.write('\n'); return; } if(debugLogging) { listener.getLogger().println(msg); } } }; task.setProject(new org.apache.tools.ant.Project()); task.setCvsExe(cvsExe); task.setDir(ws); if(cvspassFile.length()!=0) task.setPassfile(new File(cvspassFile)); if (canUseUpdate && cvsroot.startsWith("/")) { // cvs log of built source trees unreliable in local access method: // https://savannah.nongnu.org/bugs/index.php?15223 task.setCvsRoot(":fork:" + cvsroot); } else if (canUseUpdate && cvsroot.startsWith(":local:")) { task.setCvsRoot(":fork:" + cvsroot.substring(7)); } else { task.setCvsRoot(cvsroot); } task.setCvsRsh(cvsRsh); task.setFailOnError(true); task.setDeststream(new BufferedOutputStream(out)); task.setBranch(branch); task.setStart(startTime); task.setEnd(endTime); if(changedFiles!=null) { // we can optimize the processing if we know what files have changed. // but also try not to make the command line too long so as no to hit // the system call limit to the command line length (see issue #389) // the choice of the number is arbitrary, but normally we don't really // expect continuous builds to have too many changes, so this should be OK. if(changedFiles.size()<100 || !Hudson.isWindows()) { // if the directory doesn't exist, cvs changelog will die, so filter them out. // this means we'll lose the log of those changes for (String filePath : changedFiles) { if(new File(ws,filePath).getParentFile().exists()) task.addFile(filePath); } } } else { // fallback if(!flatten) task.setPackage(getAllModulesNormalized()); } try { task.execute(); } catch (BuildException e) { throw new BuildExceptionWithLog(e,errorOutput.toString()); } return new ChangeLogResult(hadError[0],errorOutput.toString()); } }); if(result.hadError) { // non-fatal error must have occurred, such as cvs changelog parsing error.s listener.getLogger().print(result.errorOutput); } return true; } catch( BuildExceptionWithLog e ) { // capture output from the task for diagnosis listener.getLogger().print(e.errorOutput); // then report an error BuildException x = (BuildException) e.getCause(); PrintWriter w = listener.error(x.getMessage()); w.println("Working directory is "+ ws); x.printStackTrace(w); return false; } catch( RuntimeException e ) { // an user reported a NPE inside the changeLog task. // we don't want a bug in Ant to prevent a build. e.printStackTrace(listener.error(e.getMessage())); return true; // so record the message but continue } catch( IOException e ) { e.printStackTrace(listener.error("Failed to detect changlog")); return true; } } public DescriptorImpl getDescriptor() { return DescriptorImpl.DESCRIPTOR; } public void buildEnvVars(AbstractBuild build, Map<String, String> env) { if(cvsRsh!=null) env.put("CVS_RSH",cvsRsh); if(branch!=null) env.put("CVS_BRANCH",branch); String cvspass = getDescriptor().getCvspassFile(); if(cvspass.length()!=0) env.put("CVS_PASSFILE",cvspass); } /** * Invokes the command with the specified command line option and wait for its completion. * * @param dir * if launching locally this is a local path, otherwise a remote path. * @param out * Receives output from the executed program. */ protected final boolean run(Launcher launcher, ArgumentListBuilder cmd, TaskListener listener, FilePath dir, OutputStream out) throws IOException, InterruptedException { Map<String,String> env = createEnvVarMap(true); int r = launcher.launch(cmd.toCommandArray(),env,out,dir).join(); if(r!=0) listener.fatalError(getDescriptor().getDisplayName()+" failed. exit code="+r); return r==0; } protected final boolean run(Launcher launcher, ArgumentListBuilder cmd, TaskListener listener, FilePath dir) throws IOException, InterruptedException { return run(launcher,cmd,listener,dir,listener.getLogger()); } /** * * @param overrideOnly * true to indicate that the returned map shall only contain * properties that need to be overridden. This is for use with {@link Launcher}. * false to indicate that the map should contain complete map. * This is to invoke {@link Proc} directly. */ protected final Map<String,String> createEnvVarMap(boolean overrideOnly) { Map<String,String> env = new HashMap<String,String>(); if(!overrideOnly) env.putAll(EnvVars.masterEnvVars); buildEnvVars(null/*TODO*/,env); return env; } public static final class DescriptorImpl extends SCMDescriptor<CVSSCM> implements ModelObject { static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); /** * Path to <tt>.cvspass</tt>. Null to default. */ private String cvsPassFile; /** * Path to cvs executable. Null to just use "cvs". */ private String cvsExe; /** * Disable CVS compression support. */ private boolean noCompression; // compatibility only private transient Map<String,RepositoryBrowser> browsers; // compatibility only class RepositoryBrowser { String diffURL; String browseURL; } DescriptorImpl() { super(CVSSCM.class,CVSRepositoryBrowser.class); load(); } protected void convert(Map<String, Object> oldPropertyBag) { cvsPassFile = (String)oldPropertyBag.get("cvspass"); } public String getDisplayName() { return "CVS"; } public SCM newInstance(StaplerRequest req) throws FormException { CVSSCM scm = req.bindParameters(CVSSCM.class, "cvs."); scm.repositoryBrowser = RepositoryBrowsers.createInstance(CVSRepositoryBrowser.class,req,"cvs.browser"); return scm; } public String getCvspassFile() { String value = cvsPassFile; if(value==null) value = ""; return value; } public String getCvsExe() { if(cvsExe==null) return "cvs"; else return cvsExe; } public void setCvspassFile(String value) { cvsPassFile = value; save(); } public boolean isNoCompression() { return noCompression; } public boolean configure( StaplerRequest req ) { cvsPassFile = fixEmpty(req.getParameter("cvs_cvspass").trim()); cvsExe = fixEmpty(req.getParameter("cvs_exe").trim()); noCompression = req.getParameter("cvs_noCompression")!=null; save(); return true; } @Override public boolean isBrowserReusable(CVSSCM x, CVSSCM y) { return x.getCvsRoot().equals(y.getCvsRoot()); } // // web methods // public void doCvsPassCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this method can be used to check if a file exists anywhere in the file system, // so it should be protected. new FormFieldValidator(req,rsp,true) { protected void check() throws IOException, ServletException { String v = fixEmpty(request.getParameter("value")); if(v==null) { // default. ok(); } else { File cvsPassFile = new File(v); if(cvsPassFile.exists()) { ok(); } else { error("No such file exists"); } } } }.process(); } /** * Checks if cvs executable exists. */ public void doCvsExeCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this method can be used to check if a file exists anywhere in the file system, // so it should be protected. new FormFieldValidator(req,rsp,true) { protected void check() throws IOException, ServletException { String cvsExe = fixEmpty(request.getParameter("value")); if(cvsExe==null) { ok(); return; } if(cvsExe.indexOf(File.separatorChar)>=0) { // this is full path if(new File(cvsExe).exists()) { ok(); } else { error("There's no such file: "+cvsExe); } } else { // can't really check ok(); } } }.process(); } /** * Displays "cvs --version" for trouble shooting. */ public void doVersion(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { ByteBuffer baos = new ByteBuffer(); try { Proc proc = Hudson.getInstance().createLauncher(TaskListener.NULL).launch( new String[]{getCvsExe(), "--version"}, new String[0], baos, null); proc.join(); rsp.setContentType("text/plain"); baos.writeTo(rsp.getOutputStream()); } catch (IOException e) { req.setAttribute("error",e); rsp.forward(this,"versionCheckError",req); } } /** * Checks the correctness of the branch name. */ public void doBranchCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req,rsp,false) { protected void check() throws IOException, ServletException { String v = fixNull(request.getParameter("value")); if(v.equals("HEAD")) error("Technically, HEAD is not a branch in CVS. Leave this field empty to build the trunk."); else ok(); } }.process(); } /** * Checks the entry to the CVSROOT field. * <p> * Also checks if .cvspass file contains the entry for this. */ public void doCvsrootCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req,rsp,false) { protected void check() throws IOException, ServletException { String v = fixEmpty(request.getParameter("value")); if(v==null) { error("CVSROOT is mandatory"); return; } Matcher m = CVSROOT_PSERVER_PATTERN.matcher(v); // CVSROOT format isn't really that well defined. So it's hard to check this rigorously. if(v.startsWith(":pserver") || v.startsWith(":ext")) { if(!m.matches()) { error("Invalid CVSROOT string"); return; } // I can't really test if the machine name exists, either. // some cvs, such as SOCKS-enabled cvs can resolve host names that Hudson might not // be able to. If :ext is used, all bets are off anyway. } // check .cvspass file to see if it has entry. // CVS handles authentication only if it's pserver. if(v.startsWith(":pserver")) { if(m.group(2)==null) {// if password is not specified in CVSROOT String cvspass = getCvspassFile(); File passfile; if(cvspass.equals("")) { passfile = new File(new File(System.getProperty("user.home")),".cvspass"); } else { passfile = new File(cvspass); } if(passfile.exists()) { // It's possible that we failed to locate the correct .cvspass file location, // so don't report an error if we couldn't locate this file. // // if this is explicitly specified, then our system config page should have // reported an error. if(!scanCvsPassFile(passfile, v)) { error("It doesn't look like this CVSROOT has its password set." + " Would you like to set it now?"); return; } } } } // all tests passed so far ok(); } }.process(); } /** * Checks if the given pserver CVSROOT value exists in the pass file. */ private boolean scanCvsPassFile(File passfile, String cvsroot) throws IOException { cvsroot += ' '; String cvsroot2 = "/1 "+cvsroot; // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5006835 BufferedReader in = new BufferedReader(new FileReader(passfile)); try { String line; while((line=in.readLine())!=null) { // "/1 " version always have the port number in it, so examine a much with // default port 2401 left out int portIndex = line.indexOf(":2401/"); String line2 = ""; if(portIndex>=0) line2 = line.substring(0,portIndex+1)+line.substring(portIndex+5); // leave '/' if(line.startsWith(cvsroot) || line.startsWith(cvsroot2) || line2.startsWith(cvsroot2)) return true; } return false; } finally { in.close(); } } private static final Pattern CVSROOT_PSERVER_PATTERN = Pattern.compile(":(ext|pserver):[^@:]+(:[^@:]+)?@[^:]+:(\\d+:)?.+"); /** * Runs cvs login command. * * TODO: this apparently doesn't work. Probably related to the fact that * cvs does some tty magic to disable echo back or whatever. */ public void doPostPassword(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException { if(!Hudson.adminCheck(req,rsp)) return; String cvsroot = req.getParameter("cvsroot"); String password = req.getParameter("password"); if(cvsroot==null || password==null) { rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } rsp.setContentType("text/plain"); Proc proc = Hudson.getInstance().createLauncher(TaskListener.NULL).launch( new String[]{getCvsExe(), "-d",cvsroot,"login"}, new String[0], new ByteArrayInputStream((password+"\n").getBytes()), rsp.getOutputStream()); proc.join(); } } /** * Action for a build that performs the tagging. */ public final class TagAction extends AbstractScmTagAction { /** * If non-null, that means the build is already tagged. * If multiple tags are created, those are whitespace-separated. */ private volatile String tagName; public TagAction(AbstractBuild build) { super(build); } public String getIconFileName() { if(tagName==null && !Hudson.isAdmin()) return null; return "save.gif"; } public String getDisplayName() { if(tagName==null) return "Tag this build"; if(tagName.indexOf(' ')>=0) return "CVS tags"; else return "CVS tag"; } public String[] getTagNames() { if(tagName==null) return new String[0]; return tagName.split(" "); } /** * Checks if the value is a valid CVS tag name. */ public synchronized void doCheckTag(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req,rsp,false) { protected void check() throws IOException, ServletException { String tag = fixNull(request.getParameter("value")).trim(); if(tag.length()==0) {// nothing entered yet ok(); return; } error(isInvalidTag(tag)); } }.check(); } /** * Invoked to actually tag the workspace. */ public synchronized void doSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if(!Hudson.adminCheck(req,rsp)) return; Map<AbstractBuild,String> tagSet = new HashMap<AbstractBuild,String>(); String name = fixNull(req.getParameter("name")).trim(); String reason = isInvalidTag(name); if(reason!=null) { sendError(reason,req,rsp); return; } tagSet.put(build,name); if(req.getParameter("upstream")!=null) { // tag all upstream builds Enumeration e = req.getParameterNames(); Map<AbstractProject, Integer> upstreams = build.getUpstreamBuilds(); // TODO: define them at AbstractBuild level while(e.hasMoreElements()) { String upName = (String) e.nextElement(); if(!upName.startsWith("upstream.")) continue; String tag = fixNull(req.getParameter(upName)).trim(); reason = isInvalidTag(tag); if(reason!=null) { sendError("No valid tag name given for "+upName+" : "+reason,req,rsp); return; } upName = upName.substring(9); // trim off 'upstream.' Job p = Hudson.getInstance().getItemByFullName(upName,Job.class); Run build = p.getBuildByNumber(upstreams.get(p)); tagSet.put((AbstractBuild) build,tag); } } new TagWorkerThread(tagSet).start(); doIndex(req,rsp); } /** * Checks if the given value is a valid CVS tag. * * If it's invalid, this method gives you the reason as string. */ private String isInvalidTag(String name) { // source code from CVS rcs.c //void //RCS_check_tag (tag) // const char *tag; //{ // char *invalid = "$,.:;@"; /* invalid RCS tag characters */ // const char *cp; // // /* // * The first character must be an alphabetic letter. The remaining // * characters cannot be non-visible graphic characters, and must not be // * in the set of "invalid" RCS identifier characters. // */ // if (isalpha ((unsigned char) *tag)) // { // for (cp = tag; *cp; cp++) // { // if (!isgraph ((unsigned char) *cp)) // error (1, 0, "tag `%s' has non-visible graphic characters", // tag); // if (strchr (invalid, *cp)) // error (1, 0, "tag `%s' must not contain the characters `%s'", // tag, invalid); // } // } // else // error (1, 0, "tag `%s' must start with a letter", tag); //} if(name==null || name.length()==0) return "Tag is empty"; char ch = name.charAt(0); if(!(('A'<=ch && ch<='Z') || ('a'<=ch && ch<='z'))) return "Tag needs to start with alphabet"; for( char invalid : "$,.:;@".toCharArray() ) { if(name.indexOf(invalid)>=0) return "Tag contains illegal '"+invalid+"' character"; } return null; } /** * Performs tagging. */ public void perform(String tagName, TaskListener listener) { File destdir = null; try { destdir = Util.createTempDir(); // unzip the archive listener.getLogger().println("expanding the workspace archive into "+destdir); Expand e = new Expand(); e.setProject(new org.apache.tools.ant.Project()); e.setDest(destdir); e.setSrc(getArchiveFile(build)); e.setTaskType("unzip"); e.execute(); // run cvs tag command listener.getLogger().println("tagging the workspace"); StringTokenizer tokens = new StringTokenizer(CVSSCM.this.module); while(tokens.hasMoreTokens()) { String m = tokens.nextToken(); FilePath path = new FilePath(destdir).child(m); boolean isDir = path.isDirectory(); ArgumentListBuilder cmd = new ArgumentListBuilder(); cmd.add(getDescriptor().getCvsExe(),"tag"); if(isDir) { cmd.add("-R"); } cmd.add(tagName); if(!isDir) { cmd.add(path.getName()); path = path.getParent(); } if(!CVSSCM.this.run(new Launcher.LocalLauncher(listener),cmd,listener, path)) { listener.getLogger().println("tagging failed"); return; } } // completed successfully onTagCompleted(tagName); build.save(); } catch (Throwable e) { e.printStackTrace(listener.fatalError(e.getMessage())); } finally { try { if(destdir!=null) { listener.getLogger().println("cleaning up "+destdir); Util.deleteRecursive(destdir); } } catch (IOException e) { e.printStackTrace(listener.fatalError(e.getMessage())); } } } /** * Atomically set the tag name and then be done with {@link TagWorkerThread}. */ private synchronized void onTagCompleted(String tagName) { if(this.tagName!=null) this.tagName += ' '+tagName; else this.tagName = tagName; this.workerThread = null; } } public static final class TagWorkerThread extends AbstractTagWorkerThread { private final Map<AbstractBuild,String> tagSet; public TagWorkerThread(Map<AbstractBuild,String> tagSet) { this.tagSet = tagSet; } public synchronized void start() { for (Entry<AbstractBuild, String> e : tagSet.entrySet()) { TagAction ta = e.getKey().getAction(TagAction.class); if(ta!=null) { ta.workerThread = this; ta.log = new WeakReference<LargeText>(text); } } super.start(); } protected void perform(TaskListener listener) { for (Entry<AbstractBuild, String> e : tagSet.entrySet()) { TagAction ta = e.getKey().getAction(TagAction.class); if(ta==null) { listener.error(e.getKey()+" doesn't have CVS tag associated with it. Skipping"); continue; } listener.getLogger().println("Tagging "+e.getKey()+" to "+e.getValue()); try { e.getKey().keepLog(); } catch (IOException x) { x.printStackTrace(listener.error("Failed to mark "+e.getKey()+" for keep")); } ta.perform(e.getValue(), listener); listener.getLogger().println(); } } } /** * Temporary hack for assisting trouble-shooting. * * <p> * Setting this property to true would cause <tt>cvs log</tt> to dump a lot of messages. */ public static boolean debugLogging = false; private static final long serialVersionUID = 1L; }
improved the error message. git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@3810 71c3de6d-444a-0410-be80-ed276b4c234a
core/src/main/java/hudson/scm/CVSSCM.java
improved the error message.
Java
mit
5047c4e828bc4a2976727194a77c66e3d3ccef4d
0
bcoe/enronsearch,sarwarbhuiyan/enronsearch,bcoe/enronsearch,sarwarbhuiyan/enronsearch,sarwarbhuiyan/enronsearch,bcoe/enronsearch
package com.bcoe.enronsearch; import java.io.IOException; import org.elasticsearch.client.Client; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.action.admin.indices.create.*; import org.elasticsearch.action.admin.indices.delete.*; import org.elasticsearch.action.admin.indices.flush.*; import org.elasticsearch.action.admin.cluster.health.*; import org.elasticsearch.common.settings.*; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.index.query.FilterBuilders.*; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.client.transport.*; import org.elasticsearch.common.transport.InetSocketTransportAddress; /* Wrapper for ElasticSearch, performs searching and indexing tasks. */ public class ElasticSearch { private static String indexName = "enron-messages"; private static String mappingName = "message"; private Client client; public ElasticSearch() { client = new TransportClient() .addTransportAddress(new InetSocketTransportAddress( System.getenv("ES_HOST"), Integer.parseInt( System.getenv("ES_PORT") ) )); } public void index() { deleteIndex(); createIndex(); putMapping(); } private void deleteIndex() { try { client.admin() .indices() .delete(new DeleteIndexRequest(indexName)) .actionGet(); } catch (Exception e) { System.out.println(e); } } private void createIndex() { Settings indexSettings = ImmutableSettings.settingsBuilder() .put("number_of_shards", 1) .put("number_of_replicas", 0) .put("analysis.analyzer.default.tokenizer", "uax_url_email") .build(); CreateIndexRequestBuilder createIndexBuilder = client.admin() .indices() .prepareCreate(indexName); createIndexBuilder.setSettings(indexSettings); CreateIndexResponse createIndexResponse = createIndexBuilder .execute() .actionGet(); waitForYellow(); } private void waitForYellow() { ClusterHealthRequestBuilder healthRequest = client.admin() .cluster() .prepareHealth(); healthRequest.setIndices(indexName); healthRequest.setWaitForYellowStatus(); ClusterHealthResponse healthResponse = healthRequest.execute() .actionGet(); } private void putMapping() { try { XContentBuilder mapping = XContentFactory.jsonBuilder() .startObject() .startObject("message") .startObject("properties") .startObject("to") .field("type", "string") .field("store", "yes") .endObject() .startObject("from") .field("type", "string") .field("store", "yes") .endObject() .startObject("subject") .field("type", "string") .field("store", "yes") .endObject() .startObject("body") .field("type", "string") .field("store", "yes") .endObject() .endObject() .endObject() .endObject(); client.admin() .indices() .preparePutMapping(indexName) .setType(mappingName) .setSource(mapping) .execute() .actionGet(); flush(); } catch (IOException e) { System.out.println("Failed to put mapping: " + e); } } private void flush() { client.admin() .indices() .flush(new FlushRequest(indexName)) .actionGet(); } public void indexMessage(Message message) { try { XContentBuilder document = XContentFactory.jsonBuilder() .startObject() .field("to", message.getTo()) .field("from", message.getFrom()) .field("subject", message.getSubject()) .field("body", message.getBody()) .endObject(); client.prepareIndex(indexName, mappingName, message.getId()) .setSource(document) .execute() .actionGet(); } catch (IOException e) { System.out.println(e); } } public SearchResponse search(String query) { return client.prepareSearch(indexName) .setTypes(mappingName) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery( QueryBuilders.queryString(query) .field("_all") ) .setFrom(0).setSize(10) .addHighlightedField("to", 0, 0) .addHighlightedField("from", 0, 0) .execute() .actionGet(); } public void cleanup() { client.close(); } }
src/main/java/com/bcoe/enronsearch/ElasticSearch.java
package com.bcoe.enronsearch; import java.io.IOException; import org.elasticsearch.client.Client; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.action.admin.indices.create.*; import org.elasticsearch.action.admin.indices.delete.*; import org.elasticsearch.action.admin.indices.flush.*; import org.elasticsearch.action.admin.cluster.health.*; import org.elasticsearch.common.settings.*; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.index.query.FilterBuilders.*; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.client.transport.*; import org.elasticsearch.common.transport.InetSocketTransportAddress; /* Wrapper for ElasticSearch, performs searching and indexing tasks. */ public class ElasticSearch { private static String indexName = "enron-messages"; private static String mappingName = "message"; private Client client; public ElasticSearch() { client = new TransportClient() .addTransportAddress(new InetSocketTransportAddress( System.getenv("ES_HOST"), Integer.parseInt( System.getenv("ES_PORT") ) )); } public void index() { deleteIndex(); createIndex(); putMapping(); } private void deleteIndex() { try { client.admin() .indices() .delete(new DeleteIndexRequest(indexName)) .actionGet(); } catch (Exception e) { System.out.println(e); } } private void createIndex() { Settings indexSettings = ImmutableSettings.settingsBuilder() .put("number_of_shards", 1) .put("number_of_replicas", 0) .put("analysis.analyzer.default.tokenizer", "uax_url_email") .build(); CreateIndexRequestBuilder createIndexBuilder = client.admin() .indices() .prepareCreate(indexName); createIndexBuilder.setSettings(indexSettings); CreateIndexResponse createIndexResponse = createIndexBuilder .execute() .actionGet(); waitForYellow(); } private void waitForYellow() { ClusterHealthRequestBuilder healthRequest = client.admin() .cluster() .prepareHealth(); healthRequest.setIndices(indexName); healthRequest.setWaitForYellowStatus(); ClusterHealthResponse healthResponse = healthRequest.execute() .actionGet(); } private void putMapping() { try { XContentBuilder mapping = XContentFactory.jsonBuilder() .startObject() .startObject("message") .startObject("properties") .startObject("to") .field("type", "string") .field("store", "yes") .endObject() .startObject("from") .field("type", "string") .field("store", "yes") .endObject() .startObject("subject") .field("type", "string") .field("store", "yes") .endObject() .startObject("body") .field("type", "string") .field("store", "yes") .endObject() .endObject() .endObject() .endObject(); client.admin() .indices() .preparePutMapping(indexName) .setType(mappingName) .setSource(mapping) .execute() .actionGet(); flush(); } catch (IOException e) { System.out.println("Failed to put mapping: " + e); } } private void flush() { client.admin() .indices() .flush(new FlushRequest(indexName)) .actionGet(); } public void indexMessage(Message message) { try { XContentBuilder document = XContentFactory.jsonBuilder() .startObject() .field("to", message.getTo()) .field("from", message.getFrom()) .field("subject", message.getSubject()) .field("body", message.getBody()) .endObject(); client.prepareIndex(indexName, mappingName, message.getId()) .setSource(document) .execute() .actionGet(); } catch (IOException e) { System.out.println(e); } } public SearchResponse search(String query) { return client.prepareSearch(indexName) .setTypes(mappingName) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery( QueryBuilders.queryString(query) .field("_all") ) .setFrom(0).setSize(30) .addHighlightedField("to", 0, 0) .addHighlightedField("from", 0, 0) .execute() .actionGet(); } public void cleanup() { client.close(); } }
reduced result set size.
src/main/java/com/bcoe/enronsearch/ElasticSearch.java
reduced result set size.
Java
mit
28099b243cbd93301a54b5726c250c9526af64f7
0
arnaudricaud/HPP_Project
package HPP_PROJECT; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class ReaderPost { private static BufferedReader br; public ReaderPost(String fichier) { try{ br = new BufferedReader(new FileReader(fichier)); }catch(Exception e){ e.printStackTrace(); } } public static Post ReadPost(){ String line = ""; try { line = br.readLine(); }catch(Exception e){ e.printStackTrace(); } return split(line); } public static Post split(String line) { String[] list = line.split("\\|"); DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); DateTime dt = formatter.parseDateTime(list[0]); return new Post(dt, Integer.parseInt(list[1]), Integer.parseInt(list[2]), list[4]); } }
src/main/java/HPP_PROJECT/ReaderPost.java
package HPP_PROJECT; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class ReaderPost { public static Post ReadPost(String fichier){ String line = ""; BufferedReader br; try { br = new BufferedReader(new FileReader(fichier)); line = br.readLine(); }catch(Exception e){ e.printStackTrace(); } return split(line); } public static Post split(String line) { String[] list = line.split("\\|"); DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); DateTime dt = formatter.parseDateTime(list[0]); return new Post(dt, Integer.parseInt(list[1]), Integer.parseInt(list[2]), list[4]); } }
Amelioration readpost Amelioration constructeur + attribut static
src/main/java/HPP_PROJECT/ReaderPost.java
Amelioration readpost
Java
mit
3a1c025652f9cba2de2e06822d88d7d1a1267f4d
0
JOML-CI/JOML,JOML-CI/JOML,JOML-CI/JOML
/* * (C) Copyright 2015-2016 Richard Greenlees Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.joml; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.text.DecimalFormat; import java.text.NumberFormat; /** * Contains the definition of a 4x4 Matrix of floats, and associated functions to transform * it. The matrix is column-major to match OpenGL's interpretation, and it looks like this: * <p> * m00 m10 m20 m30<br> * m01 m11 m21 m31<br> * m02 m12 m22 m32<br> * m03 m13 m23 m33<br> * * @author Richard Greenlees * @author Kai Burjack */ public class Matrix4f implements Externalizable { private static final long serialVersionUID = 1L; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>x=-1</tt> when using the identity matrix. */ public static final int PLANE_NX = 0; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>x=1</tt> when using the identity matrix. */ public static final int PLANE_PX = 1; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>y=-1</tt> when using the identity matrix. */ public static final int PLANE_NY= 2; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>y=1</tt> when using the identity matrix. */ public static final int PLANE_PY = 3; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>z=-1</tt> when using the identity matrix. */ public static final int PLANE_NZ = 4; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>z=1</tt> when using the identity matrix. */ public static final int PLANE_PZ = 5; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, -1, -1)</tt> when using the identity matrix. */ public static final int CORNER_NXNYNZ = 0; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, -1, -1)</tt> when using the identity matrix. */ public static final int CORNER_PXNYNZ = 1; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, 1, -1)</tt> when using the identity matrix. */ public static final int CORNER_PXPYNZ = 2; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, 1, -1)</tt> when using the identity matrix. */ public static final int CORNER_NXPYNZ = 3; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, -1, 1)</tt> when using the identity matrix. */ public static final int CORNER_PXNYPZ = 4; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, -1, 1)</tt> when using the identity matrix. */ public static final int CORNER_NXNYPZ = 5; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, 1, 1)</tt> when using the identity matrix. */ public static final int CORNER_NXPYPZ = 6; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, 1, 1)</tt> when using the identity matrix. */ public static final int CORNER_PXPYPZ = 7; public float m00, m10, m20, m30; public float m01, m11, m21, m31; public float m02, m12, m22, m32; public float m03, m13, m23, m33; /** * Create a new {@link Matrix4f} and set it to {@link #identity() identity}. */ public Matrix4f() { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; } /** * Create a new {@link Matrix4f} by setting its uppper left 3x3 submatrix to the values of the given {@link Matrix3f} * and the rest to identity. * * @param mat * the {@link Matrix3f} */ public Matrix4f(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m33 = 1.0f; } /** * Create a new {@link Matrix4f} and make it a copy of the given matrix. * * @param mat * the {@link Matrix4f} to copy the values from */ public Matrix4f(Matrix4f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = mat.m03; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = mat.m13; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = mat.m23; m30 = mat.m30; m31 = mat.m31; m32 = mat.m32; m33 = mat.m33; } /** * Create a new {@link Matrix4f} and make it a copy of the given matrix. * <p> * Note that due to the given {@link Matrix4d} storing values in double-precision and the constructed {@link Matrix4f} storing them * in single-precision, there is the possibility of losing precision. * * @param mat * the {@link Matrix4d} to copy the values from */ public Matrix4f(Matrix4d mat) { m00 = (float) mat.m00; m01 = (float) mat.m01; m02 = (float) mat.m02; m03 = (float) mat.m03; m10 = (float) mat.m10; m11 = (float) mat.m11; m12 = (float) mat.m12; m13 = (float) mat.m13; m20 = (float) mat.m20; m21 = (float) mat.m21; m22 = (float) mat.m22; m23 = (float) mat.m23; m30 = (float) mat.m30; m31 = (float) mat.m31; m32 = (float) mat.m32; m33 = (float) mat.m33; } /** * Create a new 4x4 matrix using the supplied float values. * * @param m00 * the value of m00 * @param m01 * the value of m01 * @param m02 * the value of m02 * @param m03 * the value of m03 * @param m10 * the value of m10 * @param m11 * the value of m11 * @param m12 * the value of m12 * @param m13 * the value of m13 * @param m20 * the value of m20 * @param m21 * the value of m21 * @param m22 * the value of m22 * @param m23 * the value of m23 * @param m30 * the value of m30 * @param m31 * the value of m31 * @param m32 * the value of m32 * @param m33 * the value of m33 */ public Matrix4f(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; } /** * Create a new {@link Matrix4f} by reading its 16 float components from the given {@link FloatBuffer} * at the buffer's current position. * <p> * That FloatBuffer is expected to hold the values in column-major order. * <p> * The buffer's position will not be changed by this method. * * @param buffer * the {@link FloatBuffer} to read the matrix values from */ public Matrix4f(FloatBuffer buffer) { MemUtil.INSTANCE.get(this, buffer.position(), buffer); } /** * Return the value of the matrix element at column 0 and row 0. * * @return the value of the matrix element */ public float m00() { return m00; } /** * Return the value of the matrix element at column 0 and row 1. * * @return the value of the matrix element */ public float m01() { return m01; } /** * Return the value of the matrix element at column 0 and row 2. * * @return the value of the matrix element */ public float m02() { return m02; } /** * Return the value of the matrix element at column 0 and row 3. * * @return the value of the matrix element */ public float m03() { return m03; } /** * Return the value of the matrix element at column 1 and row 0. * * @return the value of the matrix element */ public float m10() { return m10; } /** * Return the value of the matrix element at column 1 and row 1. * * @return the value of the matrix element */ public float m11() { return m11; } /** * Return the value of the matrix element at column 1 and row 2. * * @return the value of the matrix element */ public float m12() { return m12; } /** * Return the value of the matrix element at column 1 and row 3. * * @return the value of the matrix element */ public float m13() { return m13; } /** * Return the value of the matrix element at column 2 and row 0. * * @return the value of the matrix element */ public float m20() { return m20; } /** * Return the value of the matrix element at column 2 and row 1. * * @return the value of the matrix element */ public float m21() { return m21; } /** * Return the value of the matrix element at column 2 and row 2. * * @return the value of the matrix element */ public float m22() { return m22; } /** * Return the value of the matrix element at column 2 and row 3. * * @return the value of the matrix element */ public float m23() { return m23; } /** * Return the value of the matrix element at column 3 and row 0. * * @return the value of the matrix element */ public float m30() { return m30; } /** * Return the value of the matrix element at column 3 and row 1. * * @return the value of the matrix element */ public float m31() { return m31; } /** * Return the value of the matrix element at column 3 and row 2. * * @return the value of the matrix element */ public float m32() { return m32; } /** * Return the value of the matrix element at column 3 and row 3. * * @return the value of the matrix element */ public float m33() { return m33; } /** * Set the value of the matrix element at column 0 and row 0 * * @param m00 * the new value * @return the value of the matrix element */ public Matrix4f m00(float m00) { this.m00 = m00; return this; } /** * Set the value of the matrix element at column 0 and row 1 * * @param m01 * the new value * @return the value of the matrix element */ public Matrix4f m01(float m01) { this.m01 = m01; return this; } /** * Set the value of the matrix element at column 0 and row 2 * * @param m02 * the new value * @return the value of the matrix element */ public Matrix4f m02(float m02) { this.m02 = m02; return this; } /** * Set the value of the matrix element at column 0 and row 3 * * @param m03 * the new value * @return the value of the matrix element */ public Matrix4f m03(float m03) { this.m03 = m03; return this; } /** * Set the value of the matrix element at column 1 and row 0 * * @param m10 * the new value * @return the value of the matrix element */ public Matrix4f m10(float m10) { this.m10 = m10; return this; } /** * Set the value of the matrix element at column 1 and row 1 * * @param m11 * the new value * @return the value of the matrix element */ public Matrix4f m11(float m11) { this.m11 = m11; return this; } /** * Set the value of the matrix element at column 1 and row 2 * * @param m12 * the new value * @return the value of the matrix element */ public Matrix4f m12(float m12) { this.m12 = m12; return this; } /** * Set the value of the matrix element at column 1 and row 3 * * @param m13 * the new value * @return the value of the matrix element */ public Matrix4f m13(float m13) { this.m13 = m13; return this; } /** * Set the value of the matrix element at column 2 and row 0 * * @param m20 * the new value * @return the value of the matrix element */ public Matrix4f m20(float m20) { this.m20 = m20; return this; } /** * Set the value of the matrix element at column 2 and row 1 * * @param m21 * the new value * @return the value of the matrix element */ public Matrix4f m21(float m21) { this.m21 = m21; return this; } /** * Set the value of the matrix element at column 2 and row 2 * * @param m22 * the new value * @return the value of the matrix element */ public Matrix4f m22(float m22) { this.m22 = m22; return this; } /** * Set the value of the matrix element at column 2 and row 3 * * @param m23 * the new value * @return the value of the matrix element */ public Matrix4f m23(float m23) { this.m23 = m23; return this; } /** * Set the value of the matrix element at column 3 and row 0 * * @param m30 * the new value * @return the value of the matrix element */ public Matrix4f m30(float m30) { this.m30 = m30; return this; } /** * Set the value of the matrix element at column 3 and row 1 * * @param m31 * the new value * @return the value of the matrix element */ public Matrix4f m31(float m31) { this.m31 = m31; return this; } /** * Set the value of the matrix element at column 3 and row 2 * * @param m32 * the new value * @return the value of the matrix element */ public Matrix4f m32(float m32) { this.m32 = m32; return this; } /** * Set the value of the matrix element at column 3 and row 3 * * @param m33 * the new value * @return this */ public Matrix4f m33(float m33) { this.m33 = m33; return this; } /** * Reset this matrix to the identity. * <p> * Please note that if a call to {@link #identity()} is immediately followed by a call to: * {@link #translate(float, float, float) translate}, * {@link #rotate(float, float, float, float) rotate}, * {@link #scale(float, float, float) scale}, * {@link #perspective(float, float, float, float) perspective}, * {@link #frustum(float, float, float, float, float, float) frustum}, * {@link #ortho(float, float, float, float, float, float) ortho}, * {@link #ortho2D(float, float, float, float) ortho2D}, * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt}, * {@link #lookAlong(float, float, float, float, float, float) lookAlong}, * or any of their overloads, then the call to {@link #identity()} can be omitted and the subsequent call replaced with: * {@link #translation(float, float, float) translation}, * {@link #rotation(float, float, float, float) rotation}, * {@link #scaling(float, float, float) scaling}, * {@link #setPerspective(float, float, float, float) setPerspective}, * {@link #setFrustum(float, float, float, float, float, float) setFrustum}, * {@link #setOrtho(float, float, float, float, float, float) setOrtho}, * {@link #setOrtho2D(float, float, float, float) setOrtho2D}, * {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt}, * {@link #setLookAlong(float, float, float, float, float, float) setLookAlong}, * or any of their overloads. * * @return this */ public Matrix4f identity() { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Store the values of the given matrix <code>m</code> into <code>this</code> matrix. * * @see #Matrix4f(Matrix4f) * @see #get(Matrix4f) * * @param m * the matrix to copy the values from * @return this */ public Matrix4f set(Matrix4f m) { m00 = m.m00; m01 = m.m01; m02 = m.m02; m03 = m.m03; m10 = m.m10; m11 = m.m11; m12 = m.m12; m13 = m.m13; m20 = m.m20; m21 = m.m21; m22 = m.m22; m23 = m.m23; m30 = m.m30; m31 = m.m31; m32 = m.m32; m33 = m.m33; return this; } /** * Store the values of the given matrix <code>m</code> into <code>this</code> matrix. * <p> * Note that due to the given matrix <code>m</code> storing values in double-precision and <code>this</code> matrix storing * them in single-precision, there is the possibility to lose precision. * * @see #Matrix4f(Matrix4d) * @see #get(Matrix4d) * * @param m * the matrix to copy the values from * @return this */ public Matrix4f set(Matrix4d m) { m00 = (float) m.m00; m01 = (float) m.m01; m02 = (float) m.m02; m03 = (float) m.m03; m10 = (float) m.m10; m11 = (float) m.m11; m12 = (float) m.m12; m13 = (float) m.m13; m20 = (float) m.m20; m21 = (float) m.m21; m22 = (float) m.m22; m23 = (float) m.m23; m30 = (float) m.m30; m31 = (float) m.m31; m32 = (float) m.m32; m33 = (float) m.m33; return this; } /** * Set the upper left 3x3 submatrix of this {@link Matrix4f} to the given {@link Matrix3f} * and the rest to identity. * * @see #Matrix4f(Matrix3f) * * @param mat * the {@link Matrix3f} * @return this */ public Matrix4f set(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = 0.0f; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = 0.0f; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link AxisAngle4f}. * * @param axisAngle * the {@link AxisAngle4f} * @return this */ public Matrix4f set(AxisAngle4f axisAngle) { float x = axisAngle.x; float y = axisAngle.y; float z = axisAngle.z; double angle = axisAngle.angle; double n = Math.sqrt(x*x + y*y + z*z); n = 1/n; x *= n; y *= n; z *= n; double c = Math.cos(angle); double s = Math.sin(angle); double omc = 1.0 - c; m00 = (float)(c + x*x*omc); m11 = (float)(c + y*y*omc); m22 = (float)(c + z*z*omc); double tmp1 = x*y*omc; double tmp2 = z*s; m10 = (float)(tmp1 - tmp2); m01 = (float)(tmp1 + tmp2); tmp1 = x*z*omc; tmp2 = y*s; m20 = (float)(tmp1 + tmp2); m02 = (float)(tmp1 - tmp2); tmp1 = y*z*omc; tmp2 = x*s; m21 = (float)(tmp1 - tmp2); m12 = (float)(tmp1 + tmp2); m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link AxisAngle4d}. * * @param axisAngle * the {@link AxisAngle4d} * @return this */ public Matrix4f set(AxisAngle4d axisAngle) { double x = axisAngle.x; double y = axisAngle.y; double z = axisAngle.z; double angle = axisAngle.angle; double n = Math.sqrt(x*x + y*y + z*z); n = 1/n; x *= n; y *= n; z *= n; double c = Math.cos(angle); double s = Math.sin(angle); double omc = 1.0 - c; m00 = (float)(c + x*x*omc); m11 = (float)(c + y*y*omc); m22 = (float)(c + z*z*omc); double tmp1 = x*y*omc; double tmp2 = z*s; m10 = (float)(tmp1 - tmp2); m01 = (float)(tmp1 + tmp2); tmp1 = x*z*omc; tmp2 = y*s; m20 = (float)(tmp1 + tmp2); m02 = (float)(tmp1 - tmp2); tmp1 = y*z*omc; tmp2 = x*s; m21 = (float)(tmp1 - tmp2); m12 = (float)(tmp1 + tmp2); m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link Quaternionf}. * * @see Quaternionf#get(Matrix4f) * * @param q * the {@link Quaternionf} * @return this */ public Matrix4f set(Quaternionf q) { q.get(this); return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link Quaterniond}. * * @see Quaterniond#get(Matrix4f) * * @param q * the {@link Quaterniond} * @return this */ public Matrix4f set(Quaterniond q) { q.get(this); return this; } /** * Set the upper left 3x3 submatrix of this {@link Matrix4f} to that of the given {@link Matrix4f} * and don't change the other elements. * * @param mat * the {@link Matrix4f} * @return this */ public Matrix4f set3x3(Matrix4f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; return this; } /** * Multiply this matrix by the supplied <code>right</code> matrix and store the result in <code>this</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication * @return this */ public Matrix4f mul(Matrix4f right) { return mul(right, this); } /** * Multiply this matrix by the supplied <code>right</code> matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mul(Matrix4f right, Matrix4f dest) { float nm00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02 + m30 * right.m03; float nm01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02 + m31 * right.m03; float nm02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02 + m32 * right.m03; float nm03 = m03 * right.m00 + m13 * right.m01 + m23 * right.m02 + m33 * right.m03; float nm10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12 + m30 * right.m13; float nm11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12 + m31 * right.m13; float nm12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12 + m32 * right.m13; float nm13 = m03 * right.m10 + m13 * right.m11 + m23 * right.m12 + m33 * right.m13; float nm20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22 + m30 * right.m23; float nm21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22 + m31 * right.m23; float nm22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22 + m32 * right.m23; float nm23 = m03 * right.m20 + m13 * right.m21 + m23 * right.m22 + m33 * right.m23; float nm30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30 * right.m33; float nm31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31 * right.m33; float nm32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32 * right.m33; float nm33 = m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33 * right.m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Multiply <code>this</code> symmetric perspective projection matrix by the supplied {@link #isAffine() affine} <code>view</code> matrix. * <p> * If <code>P</code> is <code>this</code> matrix and <code>V</code> the <code>view</code> matrix, * then the new matrix will be <code>P * V</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>P * V * v</code>, the * transformation of the <code>view</code> matrix will be applied first! * * @param view * the {@link #isAffine() affine} matrix to multiply <code>this</code> symmetric perspective projection matrix by * @return dest */ public Matrix4f mulPerspectiveAffine(Matrix4f view) { return mulPerspectiveAffine(view, this); } /** * Multiply <code>this</code> symmetric perspective projection matrix by the supplied {@link #isAffine() affine} <code>view</code> matrix and store the result in <code>dest</code>. * <p> * If <code>P</code> is <code>this</code> matrix and <code>V</code> the <code>view</code> matrix, * then the new matrix will be <code>P * V</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>P * V * v</code>, the * transformation of the <code>view</code> matrix will be applied first! * * @param view * the {@link #isAffine() affine} matrix to multiply <code>this</code> symmetric perspective projection matrix by * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mulPerspectiveAffine(Matrix4f view, Matrix4f dest) { float nm00 = m00 * view.m00; float nm01 = m11 * view.m01; float nm02 = m22 * view.m02; float nm03 = m23 * view.m02; float nm10 = m00 * view.m10; float nm11 = m11 * view.m11; float nm12 = m22 * view.m12; float nm13 = m23 * view.m12; float nm20 = m00 * view.m20; float nm21 = m11 * view.m21; float nm22 = m22 * view.m22; float nm23 = m23 * view.m22; float nm30 = m00 * view.m30; float nm31 = m11 * view.m31; float nm32 = m22 * view.m32 + m32; float nm33 = m23 * view.m32; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Multiply this matrix by the supplied <code>right</code> matrix, which is assumed to be {@link #isAffine() affine}, and store the result in <code>this</code>. * <p> * This method assumes that the given <code>right</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @return this */ public Matrix4f mulAffineR(Matrix4f right) { return mulAffineR(right, this); } /** * Multiply this matrix by the supplied <code>right</code> matrix, which is assumed to be {@link #isAffine() affine}, and store the result in <code>dest</code>. * <p> * This method assumes that the given <code>right</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mulAffineR(Matrix4f right, Matrix4f dest) { float nm00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02; float nm01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02; float nm02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02; float nm03 = m03 * right.m00 + m13 * right.m01 + m23 * right.m02; float nm10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12; float nm11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12; float nm12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12; float nm13 = m03 * right.m10 + m13 * right.m11 + m23 * right.m12; float nm20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22; float nm21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22; float nm22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22; float nm23 = m03 * right.m20 + m13 * right.m21 + m23 * right.m22; float nm30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30; float nm31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31; float nm32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32; float nm33 = m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Multiply this matrix by the supplied <code>right</code> matrix, both of which are assumed to be {@link #isAffine() affine}, and store the result in <code>this</code>. * <p> * This method assumes that <code>this</code> matrix and the given <code>right</code> matrix both represent an {@link #isAffine() affine} transformation * (i.e. their last rows are equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrices only represent affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * This method will not modify either the last row of <code>this</code> or the last row of <code>right</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @return this */ public Matrix4f mulAffine(Matrix4f right) { return mulAffine(right, this); } /** * Multiply this matrix by the supplied <code>right</code> matrix, both of which are assumed to be {@link #isAffine() affine}, and store the result in <code>dest</code>. * <p> * This method assumes that <code>this</code> matrix and the given <code>right</code> matrix both represent an {@link #isAffine() affine} transformation * (i.e. their last rows are equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrices only represent affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * This method will not modify either the last row of <code>this</code> or the last row of <code>right</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mulAffine(Matrix4f right, Matrix4f dest) { float nm00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02; float nm01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02; float nm02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02; float nm03 = m03; float nm10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12; float nm11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12; float nm12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12; float nm13 = m13; float nm20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22; float nm21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22; float nm22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22; float nm23 = m23; float nm30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30; float nm31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31; float nm32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32; float nm33 = m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Multiply <code>this</code> orthographic projection matrix by the supplied {@link #isAffine() affine} <code>view</code> matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>V</code> the <code>view</code> matrix, * then the new matrix will be <code>M * V</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * V * v</code>, the * transformation of the <code>view</code> matrix will be applied first! * * @param view * the affine matrix which to multiply <code>this</code> with * @return dest */ public Matrix4f mulOrthoAffine(Matrix4f view) { return mulOrthoAffine(view, this); } /** * Multiply <code>this</code> orthographic projection matrix by the supplied {@link #isAffine() affine} <code>view</code> matrix * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>V</code> the <code>view</code> matrix, * then the new matrix will be <code>M * V</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * V * v</code>, the * transformation of the <code>view</code> matrix will be applied first! * * @param view * the affine matrix which to multiply <code>this</code> with * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mulOrthoAffine(Matrix4f view, Matrix4f dest) { float nm00 = m00 * view.m00; float nm01 = m11 * view.m01; float nm02 = m22 * view.m02; float nm03 = 0.0f; float nm10 = m00 * view.m10; float nm11 = m11 * view.m11; float nm12 = m22 * view.m12; float nm13 = 0.0f; float nm20 = m00 * view.m20; float nm21 = m11 * view.m21; float nm22 = m22 * view.m22; float nm23 = 0.0f; float nm30 = m00 * view.m30 + m30; float nm31 = m11 * view.m31 + m31; float nm32 = m22 * view.m32 + m32; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Component-wise add the upper 4x3 submatrices of <code>this</code> and <code>other</code> * by first multiplying each component of <code>other</code>'s 4x3 submatrix by <code>otherFactor</code> and * adding that result to <code>this</code>. * <p> * The matrix <code>other</code> will not be changed. * * @param other * the other matrix * @param otherFactor * the factor to multiply each of the other matrix's 4x3 components * @return this */ public Matrix4f fma4x3(Matrix4f other, float otherFactor) { return fma4x3(other, otherFactor, this); } /** * Component-wise add the upper 4x3 submatrices of <code>this</code> and <code>other</code> * by first multiplying each component of <code>other</code>'s 4x3 submatrix by <code>otherFactor</code>, * adding that to <code>this</code> and storing the final result in <code>dest</code>. * <p> * The other components of <code>dest</code> will be set to the ones of <code>this</code>. * <p> * The matrices <code>this</code> and <code>other</code> will not be changed. * * @param other * the other matrix * @param otherFactor * the factor to multiply each of the other matrix's 4x3 components * @param dest * will hold the result * @return dest */ public Matrix4f fma4x3(Matrix4f other, float otherFactor, Matrix4f dest) { dest.m00 = m00 + other.m00 * otherFactor; dest.m01 = m01 + other.m01 * otherFactor; dest.m02 = m02 + other.m02 * otherFactor; dest.m03 = m03; dest.m10 = m10 + other.m10 * otherFactor; dest.m11 = m11 + other.m11 * otherFactor; dest.m12 = m12 + other.m12 * otherFactor; dest.m13 = m13; dest.m20 = m20 + other.m20 * otherFactor; dest.m21 = m21 + other.m21 * otherFactor; dest.m22 = m22 + other.m22 * otherFactor; dest.m23 = m23; dest.m30 = m30 + other.m30 * otherFactor; dest.m31 = m31 + other.m31 * otherFactor; dest.m32 = m32 + other.m32 * otherFactor; dest.m33 = m33; return dest; } /** * Component-wise add <code>this</code> and <code>other</code>. * * @param other * the other addend * @return this */ public Matrix4f add(Matrix4f other) { return add(other, this); } /** * Component-wise add <code>this</code> and <code>other</code> and store the result in <code>dest</code>. * * @param other * the other addend * @param dest * will hold the result * @return dest */ public Matrix4f add(Matrix4f other, Matrix4f dest) { dest.m00 = m00 + other.m00; dest.m01 = m01 + other.m01; dest.m02 = m02 + other.m02; dest.m03 = m03 + other.m03; dest.m10 = m10 + other.m10; dest.m11 = m11 + other.m11; dest.m12 = m12 + other.m12; dest.m13 = m13 + other.m13; dest.m20 = m20 + other.m20; dest.m21 = m21 + other.m21; dest.m22 = m22 + other.m22; dest.m23 = m23 + other.m23; dest.m30 = m30 + other.m30; dest.m31 = m31 + other.m31; dest.m32 = m32 + other.m32; dest.m33 = m33 + other.m33; return dest; } /** * Component-wise subtract <code>subtrahend</code> from <code>this</code>. * * @param subtrahend * the subtrahend * @return this */ public Matrix4f sub(Matrix4f subtrahend) { return sub(subtrahend, this); } /** * Component-wise subtract <code>subtrahend</code> from <code>this</code> and store the result in <code>dest</code>. * * @param subtrahend * the subtrahend * @param dest * will hold the result * @return dest */ public Matrix4f sub(Matrix4f subtrahend, Matrix4f dest) { dest.m00 = m00 - subtrahend.m00; dest.m01 = m01 - subtrahend.m01; dest.m02 = m02 - subtrahend.m02; dest.m03 = m03 - subtrahend.m03; dest.m10 = m10 - subtrahend.m10; dest.m11 = m11 - subtrahend.m11; dest.m12 = m12 - subtrahend.m12; dest.m13 = m13 - subtrahend.m13; dest.m20 = m20 - subtrahend.m20; dest.m21 = m21 - subtrahend.m21; dest.m22 = m22 - subtrahend.m22; dest.m23 = m23 - subtrahend.m23; dest.m30 = m30 - subtrahend.m30; dest.m31 = m31 - subtrahend.m31; dest.m32 = m32 - subtrahend.m32; dest.m33 = m33 - subtrahend.m33; return dest; } /** * Component-wise multiply <code>this</code> by <code>other</code>. * * @param other * the other matrix * @return this */ public Matrix4f mulComponentWise(Matrix4f other) { return mulComponentWise(other, this); } /** * Component-wise multiply <code>this</code> by <code>other</code> and store the result in <code>dest</code>. * * @param other * the other matrix * @param dest * will hold the result * @return dest */ public Matrix4f mulComponentWise(Matrix4f other, Matrix4f dest) { dest.m00 = m00 * other.m00; dest.m01 = m01 * other.m01; dest.m02 = m02 * other.m02; dest.m03 = m03 * other.m03; dest.m10 = m10 * other.m10; dest.m11 = m11 * other.m11; dest.m12 = m12 * other.m12; dest.m13 = m13 * other.m13; dest.m20 = m20 * other.m20; dest.m21 = m21 * other.m21; dest.m22 = m22 * other.m22; dest.m23 = m23 * other.m23; dest.m30 = m30 * other.m30; dest.m31 = m31 * other.m31; dest.m32 = m32 * other.m32; dest.m33 = m33 * other.m33; return dest; } /** * Component-wise add the upper 4x3 submatrices of <code>this</code> and <code>other</code>. * * @param other * the other addend * @return this */ public Matrix4f add4x3(Matrix4f other) { return add4x3(other, this); } /** * Component-wise add the upper 4x3 submatrices of <code>this</code> and <code>other</code> * and store the result in <code>dest</code>. * <p> * The other components of <code>dest</code> will be set to the ones of <code>this</code>. * * @param other * the other addend * @param dest * will hold the result * @return dest */ public Matrix4f add4x3(Matrix4f other, Matrix4f dest) { dest.m00 = m00 + other.m00; dest.m01 = m01 + other.m01; dest.m02 = m02 + other.m02; dest.m03 = m03; dest.m10 = m10 + other.m10; dest.m11 = m11 + other.m11; dest.m12 = m12 + other.m12; dest.m13 = m13; dest.m20 = m20 + other.m20; dest.m21 = m21 + other.m21; dest.m22 = m22 + other.m22; dest.m23 = m23; dest.m30 = m30 + other.m30; dest.m31 = m31 + other.m31; dest.m32 = m32 + other.m32; dest.m33 = m33; return dest; } /** * Component-wise subtract the upper 4x3 submatrices of <code>subtrahend</code> from <code>this</code>. * * @param subtrahend * the subtrahend * @return this */ public Matrix4f sub4x3(Matrix4f subtrahend) { return sub4x3(subtrahend, this); } /** * Component-wise subtract the upper 4x3 submatrices of <code>subtrahend</code> from <code>this</code> * and store the result in <code>dest</code>. * <p> * The other components of <code>dest</code> will be set to the ones of <code>this</code>. * * @param subtrahend * the subtrahend * @param dest * will hold the result * @return dest */ public Matrix4f sub4x3(Matrix4f subtrahend, Matrix4f dest) { dest.m00 = m00 - subtrahend.m00; dest.m01 = m01 - subtrahend.m01; dest.m02 = m02 - subtrahend.m02; dest.m03 = m03; dest.m10 = m10 - subtrahend.m10; dest.m11 = m11 - subtrahend.m11; dest.m12 = m12 - subtrahend.m12; dest.m13 = m13; dest.m20 = m20 - subtrahend.m20; dest.m21 = m21 - subtrahend.m21; dest.m22 = m22 - subtrahend.m22; dest.m23 = m23; dest.m30 = m30 - subtrahend.m30; dest.m31 = m31 - subtrahend.m31; dest.m32 = m32 - subtrahend.m32; dest.m33 = m33; return dest; } /** * Component-wise multiply the upper 4x3 submatrices of <code>this</code> by <code>other</code>. * * @param other * the other matrix * @return this */ public Matrix4f mul4x3ComponentWise(Matrix4f other) { return mul4x3ComponentWise(other, this); } /** * Component-wise multiply the upper 4x3 submatrices of <code>this</code> by <code>other</code> * and store the result in <code>dest</code>. * <p> * The other components of <code>dest</code> will be set to the ones of <code>this</code>. * * @param other * the other matrix * @param dest * will hold the result * @return dest */ public Matrix4f mul4x3ComponentWise(Matrix4f other, Matrix4f dest) { dest.m00 = m00 * other.m00; dest.m01 = m01 * other.m01; dest.m02 = m02 * other.m02; dest.m03 = m03; dest.m10 = m10 * other.m10; dest.m11 = m11 * other.m11; dest.m12 = m12 * other.m12; dest.m13 = m13; dest.m20 = m20 * other.m20; dest.m21 = m21 * other.m21; dest.m22 = m22 * other.m22; dest.m23 = m23; dest.m30 = m30 * other.m30; dest.m31 = m31 * other.m31; dest.m32 = m32 * other.m32; dest.m33 = m33; return dest; } /** * Set the values within this matrix to the supplied float values. The matrix will look like this:<br><br> * * m00, m10, m20, m30<br> * m01, m11, m21, m31<br> * m02, m12, m22, m32<br> * m03, m13, m23, m33 * * @param m00 * the new value of m00 * @param m01 * the new value of m01 * @param m02 * the new value of m02 * @param m03 * the new value of m03 * @param m10 * the new value of m10 * @param m11 * the new value of m11 * @param m12 * the new value of m12 * @param m13 * the new value of m13 * @param m20 * the new value of m20 * @param m21 * the new value of m21 * @param m22 * the new value of m22 * @param m23 * the new value of m23 * @param m30 * the new value of m30 * @param m31 * the new value of m31 * @param m32 * the new value of m32 * @param m33 * the new value of m33 * @return this */ public Matrix4f set(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; return this; } /** * Set the values in the matrix using a float array that contains the matrix elements in column-major order. * <p> * The results will look like this:<br><br> * * 0, 4, 8, 12<br> * 1, 5, 9, 13<br> * 2, 6, 10, 14<br> * 3, 7, 11, 15<br> * * @see #set(float[]) * * @param m * the array to read the matrix values from * @param off * the offset into the array * @return this */ public Matrix4f set(float m[], int off) { m00 = m[off+0]; m01 = m[off+1]; m02 = m[off+2]; m03 = m[off+3]; m10 = m[off+4]; m11 = m[off+5]; m12 = m[off+6]; m13 = m[off+7]; m20 = m[off+8]; m21 = m[off+9]; m22 = m[off+10]; m23 = m[off+11]; m30 = m[off+12]; m31 = m[off+13]; m32 = m[off+14]; m33 = m[off+15]; return this; } /** * Set the values in the matrix using a float array that contains the matrix elements in column-major order. * <p> * The results will look like this:<br><br> * * 0, 4, 8, 12<br> * 1, 5, 9, 13<br> * 2, 6, 10, 14<br> * 3, 7, 11, 15<br> * * @see #set(float[], int) * * @param m * the array to read the matrix values from * @return this */ public Matrix4f set(float m[]) { return set(m, 0); } /** * Set the values of this matrix by reading 16 float values from the given {@link FloatBuffer} in column-major order, * starting at its current position. * <p> * The FloatBuffer is expected to contain the values in column-major order. * <p> * The position of the FloatBuffer will not be changed by this method. * * @param buffer * the FloatBuffer to read the matrix values from in column-major order * @return this */ public Matrix4f set(FloatBuffer buffer) { MemUtil.INSTANCE.get(this, buffer.position(), buffer); return this; } /** * Set the values of this matrix by reading 16 float values from the given {@link ByteBuffer} in column-major order, * starting at its current position. * <p> * The ByteBuffer is expected to contain the values in column-major order. * <p> * The position of the ByteBuffer will not be changed by this method. * * @param buffer * the ByteBuffer to read the matrix values from in column-major order * @return this */ public Matrix4f set(ByteBuffer buffer) { MemUtil.INSTANCE.get(this, buffer.position(), buffer); return this; } /** * Return the determinant of this matrix. * <p> * If <code>this</code> matrix represents an {@link #isAffine() affine} transformation, such as translation, rotation, scaling and shearing, * and thus its last row is equal to <tt>(0, 0, 0, 1)</tt>, then {@link #determinantAffine()} can be used instead of this method. * * @see #determinantAffine() * * @return the determinant */ public float determinant() { return (m00 * m11 - m01 * m10) * (m22 * m33 - m23 * m32) + (m02 * m10 - m00 * m12) * (m21 * m33 - m23 * m31) + (m00 * m13 - m03 * m10) * (m21 * m32 - m22 * m31) + (m01 * m12 - m02 * m11) * (m20 * m33 - m23 * m30) + (m03 * m11 - m01 * m13) * (m20 * m32 - m22 * m30) + (m02 * m13 - m03 * m12) * (m20 * m31 - m21 * m30); } /** * Return the determinant of the upper left 3x3 submatrix of this matrix. * * @return the determinant */ public float determinant3x3() { return (m00 * m11 - m01 * m10) * m22 + (m02 * m10 - m00 * m12) * m21 + (m01 * m12 - m02 * m11) * m20; } /** * Return the determinant of this matrix by assuming that it represents an {@link #isAffine() affine} transformation and thus * its last row is equal to <tt>(0, 0, 0, 1)</tt>. * * @return the determinant */ public float determinantAffine() { return (m00 * m11 - m01 * m10) * m22 + (m02 * m10 - m00 * m12) * m21 + (m01 * m12 - m02 * m11) * m20; } /** * Invert this matrix and write the result into <code>dest</code>. * <p> * If <code>this</code> matrix represents an {@link #isAffine() affine} transformation, such as translation, rotation, scaling and shearing, * and thus its last row is equal to <tt>(0, 0, 0, 1)</tt>, then {@link #invertAffine(Matrix4f)} can be used instead of this method. * * @see #invertAffine(Matrix4f) * * @param dest * will hold the result * @return dest */ public Matrix4f invert(Matrix4f dest) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float c = m00 * m13 - m03 * m10; float d = m01 * m12 - m02 * m11; float e = m01 * m13 - m03 * m11; float f = m02 * m13 - m03 * m12; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float i = m20 * m33 - m23 * m30; float j = m21 * m32 - m22 * m31; float k = m21 * m33 - m23 * m31; float l = m22 * m33 - m23 * m32; float det = a * l - b * k + c * j + d * i - e * h + f * g; det = 1.0f / det; float nm00 = ( m11 * l - m12 * k + m13 * j) * det; float nm01 = (-m01 * l + m02 * k - m03 * j) * det; float nm02 = ( m31 * f - m32 * e + m33 * d) * det; float nm03 = (-m21 * f + m22 * e - m23 * d) * det; float nm10 = (-m10 * l + m12 * i - m13 * h) * det; float nm11 = ( m00 * l - m02 * i + m03 * h) * det; float nm12 = (-m30 * f + m32 * c - m33 * b) * det; float nm13 = ( m20 * f - m22 * c + m23 * b) * det; float nm20 = ( m10 * k - m11 * i + m13 * g) * det; float nm21 = (-m00 * k + m01 * i - m03 * g) * det; float nm22 = ( m30 * e - m31 * c + m33 * a) * det; float nm23 = (-m20 * e + m21 * c - m23 * a) * det; float nm30 = (-m10 * j + m11 * h - m12 * g) * det; float nm31 = ( m00 * j - m01 * h + m02 * g) * det; float nm32 = (-m30 * d + m31 * b - m32 * a) * det; float nm33 = ( m20 * d - m21 * b + m22 * a) * det; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Invert this matrix. * <p> * If <code>this</code> matrix represents an {@link #isAffine() affine} transformation, such as translation, rotation, scaling and shearing, * and thus its last row is equal to <tt>(0, 0, 0, 1)</tt>, then {@link #invertAffine()} can be used instead of this method. * * @see #invertAffine() * * @return this */ public Matrix4f invert() { return invert(this); } /** * If <code>this</code> is a perspective projection matrix obtained via one of the {@link #perspective(float, float, float, float) perspective()} methods * or via {@link #setPerspective(float, float, float, float) setPerspective()}, that is, if <code>this</code> is a symmetrical perspective frustum transformation, * then this method builds the inverse of <code>this</code> and stores it into the given <code>dest</code>. * <p> * This method can be used to quickly obtain the inverse of a perspective projection matrix when being obtained via {@link #perspective(float, float, float, float) perspective()}. * * @see #perspective(float, float, float, float) * * @param dest * will hold the inverse of <code>this</code> * @return dest */ public Matrix4f invertPerspective(Matrix4f dest) { float a = 1.0f / (m00 * m11); float l = -1.0f / (m23 * m32); dest.set(m11 * a, 0, 0, 0, 0, m00 * a, 0, 0, 0, 0, 0, -m23 * l, 0, 0, -m32 * l, m22 * l); return dest; } /** * If <code>this</code> is a perspective projection matrix obtained via one of the {@link #perspective(float, float, float, float) perspective()} methods * or via {@link #setPerspective(float, float, float, float) setPerspective()}, that is, if <code>this</code> is a symmetrical perspective frustum transformation, * then this method builds the inverse of <code>this</code>. * <p> * This method can be used to quickly obtain the inverse of a perspective projection matrix when being obtained via {@link #perspective(float, float, float, float) perspective()}. * * @see #perspective(float, float, float, float) * * @return this */ public Matrix4f invertPerspective() { return invertPerspective(this); } /** * If <code>this</code> is an arbitrary perspective projection matrix obtained via one of the {@link #frustum(float, float, float, float, float, float) frustum()} methods * or via {@link #setFrustum(float, float, float, float, float, float) setFrustum()}, * then this method builds the inverse of <code>this</code> and stores it into the given <code>dest</code>. * <p> * This method can be used to quickly obtain the inverse of a perspective projection matrix. * <p> * If this matrix represents a symmetric perspective frustum transformation, as obtained via {@link #perspective(float, float, float, float) perspective()}, then * {@link #invertPerspective(Matrix4f)} should be used instead. * * @see #frustum(float, float, float, float, float, float) * @see #invertPerspective(Matrix4f) * * @param dest * will hold the inverse of <code>this</code> * @return dest */ public Matrix4f invertFrustum(Matrix4f dest) { float invM00 = 1.0f / m00; float invM11 = 1.0f / m11; float invM23 = 1.0f / m23; float invM32 = 1.0f / m32; dest.set(invM00, 0, 0, 0, 0, invM11, 0, 0, 0, 0, 0, invM32, -m20 * invM00 * invM23, -m21 * invM11 * invM23, invM23, -m22 * invM23 * invM32); return dest; } /** * If <code>this</code> is an arbitrary perspective projection matrix obtained via one of the {@link #frustum(float, float, float, float, float, float) frustum()} methods * or via {@link #setFrustum(float, float, float, float, float, float) setFrustum()}, * then this method builds the inverse of <code>this</code>. * <p> * This method can be used to quickly obtain the inverse of a perspective projection matrix. * <p> * If this matrix represents a symmetric perspective frustum transformation, as obtained via {@link #perspective(float, float, float, float) perspective()}, then * {@link #invertPerspective()} should be used instead. * * @see #frustum(float, float, float, float, float, float) * @see #invertPerspective() * * @return this */ public Matrix4f invertFrustum() { return invertFrustum(this); } /** * Invert <code>this</code> orthographic projection matrix and store the result into the given <code>dest</code>. * <p> * This method can be used to quickly obtain the inverse of an orthographic projection matrix. * * @param dest * will hold the inverse of <code>this</code> * @return dest */ public Matrix4f invertOrtho(Matrix4f dest) { float invM00 = 1.0f / m00; float invM11 = 1.0f / m11; float invM22 = 1.0f / m22; dest.set(invM00, 0, 0, 0, 0, invM11, 0, 0, 0, 0, invM22, 0, -m30 * invM00, -m31 * invM11, -m32 * invM22, 1); return dest; } /** * Invert <code>this</code> orthographic projection matrix. * <p> * This method can be used to quickly obtain the inverse of an orthographic projection matrix. * * @return this */ public Matrix4f invertOrtho() { return invertOrtho(this); } /** * If <code>this</code> is a perspective projection matrix obtained via one of the {@link #perspective(float, float, float, float) perspective()} methods * or via {@link #setPerspective(float, float, float, float) setPerspective()}, that is, if <code>this</code> is a symmetrical perspective frustum transformation * and the given <code>view</code> matrix is {@link #isAffine() affine} and has unit scaling (for example by being obtained via {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()}), * then this method builds the inverse of <tt>this * view</tt> and stores it into the given <code>dest</code>. * <p> * This method can be used to quickly obtain the inverse of the combination of the view and projection matrices, when both were obtained * via the common methods {@link #perspective(float, float, float, float) perspective()} and {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} or * other methods, that build affine matrices, such as {@link #translate(float, float, float) translate} and {@link #rotate(float, float, float, float)}, except for {@link #scale(float, float, float) scale()}. * <p> * For the special cases of the matrices <code>this</code> and <code>view</code> mentioned above this method, this method is equivalent to the following code: * <pre> * dest.set(this).mul(view).invert(); * </pre> * * @param view * the view transformation (must be {@link #isAffine() affine} and have unit scaling) * @param dest * will hold the inverse of <tt>this * view</tt> * @return dest */ public Matrix4f invertPerspectiveView(Matrix4f view, Matrix4f dest) { float a = 1.0f / (m00 * m11); float l = -1.0f / (m23 * m32); float pm00 = m11 * a; float pm11 = m00 * a; float pm23 = -m23 * l; float pm32 = -m32 * l; float pm33 = m22 * l; float vm30 = -view.m00 * view.m30 - view.m01 * view.m31 - view.m02 * view.m32; float vm31 = -view.m10 * view.m30 - view.m11 * view.m31 - view.m12 * view.m32; float vm32 = -view.m20 * view.m30 - view.m21 * view.m31 - view.m22 * view.m32; dest.set(view.m00 * pm00, view.m10 * pm00, view.m20 * pm00, 0.0f, view.m01 * pm11, view.m11 * pm11, view.m21 * pm11, 0.0f, vm30 * pm23, vm31 * pm23, vm32 * pm23, pm23, view.m02 * pm32 + vm30 * pm33, view.m12 * pm32 + vm31 * pm33, view.m22 * pm32 + vm32 * pm33, pm33); return dest; } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and write the result into <code>dest</code>. * <p> * Note that if <code>this</code> matrix also has unit scaling, then the method {@link #invertAffineUnitScale(Matrix4f)} should be used instead. * * @see #invertAffineUnitScale(Matrix4f) * * @param dest * will hold the result * @return dest */ public Matrix4f invertAffine(Matrix4f dest) { float s = determinantAffine(); s = 1.0f / s; float m10m22 = m10 * m22; float m10m21 = m10 * m21; float m10m02 = m10 * m02; float m10m01 = m10 * m01; float m11m22 = m11 * m22; float m11m20 = m11 * m20; float m11m02 = m11 * m02; float m11m00 = m11 * m00; float m12m21 = m12 * m21; float m12m20 = m12 * m20; float m12m01 = m12 * m01; float m12m00 = m12 * m00; float m20m02 = m20 * m02; float m20m01 = m20 * m01; float m21m02 = m21 * m02; float m21m00 = m21 * m00; float m22m01 = m22 * m01; float m22m00 = m22 * m00; float nm00 = (m11m22 - m12m21) * s; float nm01 = (m21m02 - m22m01) * s; float nm02 = (m12m01 - m11m02) * s; float nm03 = 0.0f; float nm10 = (m12m20 - m10m22) * s; float nm11 = (m22m00 - m20m02) * s; float nm12 = (m10m02 - m12m00) * s; float nm13 = 0.0f; float nm20 = (m10m21 - m11m20) * s; float nm21 = (m20m01 - m21m00) * s; float nm22 = (m11m00 - m10m01) * s; float nm23 = 0.0f; float nm30 = (m10m22 * m31 - m10m21 * m32 + m11m20 * m32 - m11m22 * m30 + m12m21 * m30 - m12m20 * m31) * s; float nm31 = (m20m02 * m31 - m20m01 * m32 + m21m00 * m32 - m21m02 * m30 + m22m01 * m30 - m22m00 * m31) * s; float nm32 = (m11m02 * m30 - m12m01 * m30 + m12m00 * m31 - m10m02 * m31 + m10m01 * m32 - m11m00 * m32) * s; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>). * <p> * Note that if <code>this</code> matrix also has unit scaling, then the method {@link #invertAffineUnitScale()} should be used instead. * * @see #invertAffineUnitScale() * * @return this */ public Matrix4f invertAffine() { return invertAffine(this); } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and has unit scaling (i.e. {@link #transformDirection(Vector3f) transformDirection} does not change the {@link Vector3f#length() length} of the vector) * and write the result into <code>dest</code>. * <p> * Reference: <a href="http://www.gamedev.net/topic/425118-inverse--matrix/">http://www.gamedev.net/</a> * * @param dest * will hold the result * @return dest */ public Matrix4f invertAffineUnitScale(Matrix4f dest) { dest.set(m00, m10, m20, 0.0f, m01, m11, m21, 0.0f, m02, m12, m22, 0.0f, -m00 * m30 - m01 * m31 - m02 * m32, -m10 * m30 - m11 * m31 - m12 * m32, -m20 * m30 - m21 * m31 - m22 * m32, 1.0f); return dest; } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and has unit scaling (i.e. {@link #transformDirection(Vector3f) transformDirection} does not change the {@link Vector3f#length() length} of the vector). * <p> * Reference: <a href="http://www.gamedev.net/topic/425118-inverse--matrix/">http://www.gamedev.net/</a> * * @return this */ public Matrix4f invertAffineUnitScale() { return invertAffineUnitScale(this); } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and has unit scaling (i.e. {@link #transformDirection(Vector3f) transformDirection} does not change the {@link Vector3f#length() length} of the vector), * as is the case for matrices built via {@link #lookAt(Vector3f, Vector3f, Vector3f)} and their overloads, and write the result into <code>dest</code>. * <p> * This method is equivalent to calling {@link #invertAffineUnitScale(Matrix4f)} * <p> * Reference: <a href="http://www.gamedev.net/topic/425118-inverse--matrix/">http://www.gamedev.net/</a> * * @see #invertAffineUnitScale(Matrix4f) * * @param dest * will hold the result * @return dest */ public Matrix4f invertLookAt(Matrix4f dest) { return invertAffineUnitScale(dest); } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and has unit scaling (i.e. {@link #transformDirection(Vector3f) transformDirection} does not change the {@link Vector3f#length() length} of the vector), * as is the case for matrices built via {@link #lookAt(Vector3f, Vector3f, Vector3f)} and their overloads. * <p> * This method is equivalent to calling {@link #invertAffineUnitScale()} * <p> * Reference: <a href="http://www.gamedev.net/topic/425118-inverse--matrix/">http://www.gamedev.net/</a> * * @see #invertAffineUnitScale() * * @return this */ public Matrix4f invertLookAt() { return invertAffineUnitScale(this); } /** * Transpose this matrix and store the result in <code>dest</code>. * * @param dest * will hold the result * @return dest */ public Matrix4f transpose(Matrix4f dest) { float nm00 = m00; float nm01 = m10; float nm02 = m20; float nm03 = m30; float nm10 = m01; float nm11 = m11; float nm12 = m21; float nm13 = m31; float nm20 = m02; float nm21 = m12; float nm22 = m22; float nm23 = m32; float nm30 = m03; float nm31 = m13; float nm32 = m23; float nm33 = m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Transpose only the upper left 3x3 submatrix of this matrix and set the rest of the matrix elements to identity. * * @return this */ public Matrix4f transpose3x3() { return transpose3x3(this); } /** * Transpose only the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * All other matrix elements of <code>dest</code> will be set to identity. * * @param dest * will hold the result * @return dest */ public Matrix4f transpose3x3(Matrix4f dest) { float nm00 = m00; float nm01 = m10; float nm02 = m20; float nm03 = 0.0f; float nm10 = m01; float nm11 = m11; float nm12 = m21; float nm13 = 0.0f; float nm20 = m02; float nm21 = m12; float nm22 = m22; float nm23 = 0.0f; float nm30 = 0.0f; float nm31 = 0.0f; float nm32 = 0.0f; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Transpose only the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * * @param dest * will hold the result * @return dest */ public Matrix3f transpose3x3(Matrix3f dest) { dest.m00 = m00; dest.m01 = m10; dest.m02 = m20; dest.m10 = m01; dest.m11 = m11; dest.m12 = m21; dest.m20 = m02; dest.m21 = m12; dest.m22 = m22; return dest; } /** * Transpose this matrix. * * @return this */ public Matrix4f transpose() { return transpose(this); } /** * Set this matrix to be a simple translation matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional translation. * <p> * In order to post-multiply a translation transformation directly to a * matrix, use {@link #translate(float, float, float) translate()} instead. * * @see #translate(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translation(float x, float y, float z) { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = x; m31 = y; m32 = z; m33 = 1.0f; return this; } /** * Set this matrix to be a simple translation matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional translation. * <p> * In order to post-multiply a translation transformation directly to a * matrix, use {@link #translate(Vector3f) translate()} instead. * * @see #translate(float, float, float) * * @param offset * the offsets in x, y and z to translate * @return this */ public Matrix4f translation(Vector3f offset) { return translation(offset.x, offset.y, offset.z); } /** * Set only the translation components <tt>(m30, m31, m32)</tt> of this matrix to the given values <tt>(x, y, z)</tt>. * <p> * Note that this will only work properly for orthogonal matrices (without any perspective). * <p> * To build a translation matrix instead, use {@link #translation(float, float, float)}. * To apply a translation to another matrix, use {@link #translate(float, float, float)}. * * @see #translation(float, float, float) * @see #translate(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f setTranslation(float x, float y, float z) { m30 = x; m31 = y; m32 = z; return this; } /** * Set only the translation components <tt>(m30, m31, m32)</tt> of this matrix to the values <tt>(xyz.x, xyz.y, xyz.z)</tt>. * <p> * Note that this will only work properly for orthogonal matrices (without any perspective). * <p> * To build a translation matrix instead, use {@link #translation(Vector3f)}. * To apply a translation to another matrix, use {@link #translate(Vector3f)}. * * @see #translation(Vector3f) * @see #translate(Vector3f) * * @param xyz * the units to translate in <tt>(x, y, z)</tt> * @return this */ public Matrix4f setTranslation(Vector3f xyz) { m30 = xyz.x; m31 = xyz.y; m32 = xyz.z; return this; } /** * Get only the translation components <tt>(m30, m31, m32)</tt> of this matrix and store them in the given vector <code>xyz</code>. * * @param dest * will hold the translation components of this matrix * @return dest */ public Vector3f getTranslation(Vector3f dest) { dest.x = m30; dest.y = m31; dest.z = m32; return dest; } /** * Get the scaling factors of <code>this</code> matrix for the three base axes. * * @param dest * will hold the scaling factors for <tt>x</tt>, <tt>y</tt> and <tt>z</tt> * @return dest */ public Vector3f getScale(Vector3f dest) { dest.x = (float) Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); dest.y = (float) Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12); dest.z = (float) Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22); return dest; } /** * Return a string representation of this matrix. * <p> * This method creates a new {@link DecimalFormat} on every invocation with the format string "<tt> 0.000E0; -</tt>". * * @return the string representation */ public String toString() { DecimalFormat formatter = new DecimalFormat(" 0.000E0; -"); //$NON-NLS-1$ return toString(formatter).replaceAll("E(\\d+)", "E+$1"); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Return a string representation of this matrix by formatting the matrix elements with the given {@link NumberFormat}. * * @param formatter * the {@link NumberFormat} used to format the matrix values with * @return the string representation */ public String toString(NumberFormat formatter) { return formatter.format(m00) + formatter.format(m10) + formatter.format(m20) + formatter.format(m30) + "\n" //$NON-NLS-1$ + formatter.format(m01) + formatter.format(m11) + formatter.format(m21) + formatter.format(m31) + "\n" //$NON-NLS-1$ + formatter.format(m02) + formatter.format(m12) + formatter.format(m22) + formatter.format(m32) + "\n" //$NON-NLS-1$ + formatter.format(m03) + formatter.format(m13) + formatter.format(m23) + formatter.format(m33) + "\n"; //$NON-NLS-1$ } /** * Get the current values of <code>this</code> matrix and store them into * <code>dest</code>. * <p> * This is the reverse method of {@link #set(Matrix4f)} and allows to obtain * intermediate calculation results when chaining multiple transformations. * * @see #set(Matrix4f) * * @param dest * the destination matrix * @return the passed in destination */ public Matrix4f get(Matrix4f dest) { return dest.set(this); } /** * Get the current values of <code>this</code> matrix and store them into * <code>dest</code>. * <p> * This is the reverse method of {@link #set(Matrix4d)} and allows to obtain * intermediate calculation results when chaining multiple transformations. * * @see #set(Matrix4d) * * @param dest * the destination matrix * @return the passed in destination */ public Matrix4d get(Matrix4d dest) { return dest.set(this); } /** * Get the current values of the upper left 3x3 submatrix of <code>this</code> matrix and store them into * <code>dest</code>. * * @param dest * the destination matrix * @return the passed in destination */ public Matrix3f get3x3(Matrix3f dest) { return dest.set(this); } /** * Get the current values of the upper left 3x3 submatrix of <code>this</code> matrix and store them into * <code>dest</code>. * * @param dest * the destination matrix * @return the passed in destination */ public Matrix3d get3x3(Matrix3d dest) { return dest.set(this); } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link AxisAngle4f}. * * @see AxisAngle4f#set(Matrix4f) * * @param dest * the destination {@link AxisAngle4f} * @return the passed in destination */ public AxisAngle4f getRotation(AxisAngle4f dest) { return dest.set(this); } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link AxisAngle4d}. * * @see AxisAngle4f#set(Matrix4f) * * @param dest * the destination {@link AxisAngle4d} * @return the passed in destination */ public AxisAngle4d getRotation(AxisAngle4d dest) { return dest.set(this); } /** * Get the current values of <code>this</code> matrix and store the represented rotation * into the given {@link Quaternionf}. * <p> * This method assumes that the first three column vectors of the upper left 3x3 submatrix are not normalized and * thus allows to ignore any additional scaling factor that is applied to the matrix. * * @see Quaternionf#setFromUnnormalized(Matrix4f) * * @param dest * the destination {@link Quaternionf} * @return the passed in destination */ public Quaternionf getUnnormalizedRotation(Quaternionf dest) { return dest.setFromUnnormalized(this); } /** * Get the current values of <code>this</code> matrix and store the represented rotation * into the given {@link Quaternionf}. * <p> * This method assumes that the first three column vectors of the upper left 3x3 submatrix are normalized. * * @see Quaternionf#setFromNormalized(Matrix4f) * * @param dest * the destination {@link Quaternionf} * @return the passed in destination */ public Quaternionf getNormalizedRotation(Quaternionf dest) { return dest.setFromNormalized(this); } /** * Get the current values of <code>this</code> matrix and store the represented rotation * into the given {@link Quaterniond}. * <p> * This method assumes that the first three column vectors of the upper left 3x3 submatrix are not normalized and * thus allows to ignore any additional scaling factor that is applied to the matrix. * * @see Quaterniond#setFromUnnormalized(Matrix4f) * * @param dest * the destination {@link Quaterniond} * @return the passed in destination */ public Quaterniond getUnnormalizedRotation(Quaterniond dest) { return dest.setFromUnnormalized(this); } /** * Get the current values of <code>this</code> matrix and store the represented rotation * into the given {@link Quaterniond}. * <p> * This method assumes that the first three column vectors of the upper left 3x3 submatrix are normalized. * * @see Quaterniond#setFromNormalized(Matrix4f) * * @param dest * the destination {@link Quaterniond} * @return the passed in destination */ public Quaterniond getNormalizedRotation(Quaterniond dest) { return dest.setFromNormalized(this); } /** * Store this matrix in column-major order into the supplied {@link FloatBuffer} at the current * buffer {@link FloatBuffer#position() position}. * <p> * This method will not increment the position of the given FloatBuffer. * <p> * In order to specify the offset into the FloatBuffer at which * the matrix is stored, use {@link #get(int, FloatBuffer)}, taking * the absolute position as parameter. * * @see #get(int, FloatBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return the passed in buffer */ public FloatBuffer get(FloatBuffer buffer) { return get(buffer.position(), buffer); } /** * Store this matrix in column-major order into the supplied {@link FloatBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given FloatBuffer. * * @param index * the absolute position into the FloatBuffer * @param buffer * will receive the values of this matrix in column-major order * @return the passed in buffer */ public FloatBuffer get(int index, FloatBuffer buffer) { MemUtil.INSTANCE.put(this, index, buffer); return buffer; } /** * Store this matrix in column-major order into the supplied {@link ByteBuffer} at the current * buffer {@link ByteBuffer#position() position}. * <p> * This method will not increment the position of the given ByteBuffer. * <p> * In order to specify the offset into the ByteBuffer at which * the matrix is stored, use {@link #get(int, ByteBuffer)}, taking * the absolute position as parameter. * * @see #get(int, ByteBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return the passed in buffer */ public ByteBuffer get(ByteBuffer buffer) { return get(buffer.position(), buffer); } /** * Store this matrix in column-major order into the supplied {@link ByteBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given ByteBuffer. * * @param index * the absolute position into the ByteBuffer * @param buffer * will receive the values of this matrix in column-major order * @return the passed in buffer */ public ByteBuffer get(int index, ByteBuffer buffer) { MemUtil.INSTANCE.put(this, index, buffer); return buffer; } /** * Store the transpose of this matrix in column-major order into the supplied {@link FloatBuffer} at the current * buffer {@link FloatBuffer#position() position}. * <p> * This method will not increment the position of the given FloatBuffer. * <p> * In order to specify the offset into the FloatBuffer at which * the matrix is stored, use {@link #getTransposed(int, FloatBuffer)}, taking * the absolute position as parameter. * * @see #getTransposed(int, FloatBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return the passed in buffer */ public FloatBuffer getTransposed(FloatBuffer buffer) { return getTransposed(buffer.position(), buffer); } /** * Store the transpose of this matrix in column-major order into the supplied {@link FloatBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given FloatBuffer. * * @param index * the absolute position into the FloatBuffer * @param buffer * will receive the values of this matrix in column-major order * @return the passed in buffer */ public FloatBuffer getTransposed(int index, FloatBuffer buffer) { MemUtil.INSTANCE.putTransposed(this, index, buffer); return buffer; } /** * Store the transpose of this matrix in column-major order into the supplied {@link ByteBuffer} at the current * buffer {@link ByteBuffer#position() position}. * <p> * This method will not increment the position of the given ByteBuffer. * <p> * In order to specify the offset into the ByteBuffer at which * the matrix is stored, use {@link #getTransposed(int, ByteBuffer)}, taking * the absolute position as parameter. * * @see #getTransposed(int, ByteBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return the passed in buffer */ public ByteBuffer getTransposed(ByteBuffer buffer) { return getTransposed(buffer.position(), buffer); } /** * Store the transpose of this matrix in column-major order into the supplied {@link ByteBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given ByteBuffer. * * @param index * the absolute position into the ByteBuffer * @param buffer * will receive the values of this matrix in column-major order * @return the passed in buffer */ public ByteBuffer getTransposed(int index, ByteBuffer buffer) { MemUtil.INSTANCE.putTransposed(this, index, buffer); return buffer; } /** * Store this matrix into the supplied float array in column-major order at the given offset. * * @param arr * the array to write the matrix values into * @param offset * the offset into the array * @return the passed in array */ public float[] get(float[] arr, int offset) { arr[offset+0] = m00; arr[offset+1] = m01; arr[offset+2] = m02; arr[offset+3] = m03; arr[offset+4] = m10; arr[offset+5] = m11; arr[offset+6] = m12; arr[offset+7] = m13; arr[offset+8] = m20; arr[offset+9] = m21; arr[offset+10] = m22; arr[offset+11] = m23; arr[offset+12] = m30; arr[offset+13] = m31; arr[offset+14] = m32; arr[offset+15] = m33; return arr; } /** * Store this matrix into the supplied float array in column-major order. * <p> * In order to specify an explicit offset into the array, use the method {@link #get(float[], int)}. * * @see #get(float[], int) * * @param arr * the array to write the matrix values into * @return the passed in array */ public float[] get(float[] arr) { return get(arr, 0); } /** * Set all the values within this matrix to <code>0</code>. * * @return this */ public Matrix4f zero() { m00 = 0.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 0.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 0.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be a simple scale matrix, which scales all axes uniformly by the given factor. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * In order to post-multiply a scaling transformation directly to a * matrix, use {@link #scale(float) scale()} instead. * * @see #scale(float) * * @param factor * the scale factor in x, y and z * @return this */ public Matrix4f scaling(float factor) { m00 = factor; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = factor; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = factor; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a simple scale matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * In order to post-multiply a scaling transformation directly to a * matrix, use {@link #scale(float, float, float) scale()} instead. * * @see #scale(float, float, float) * * @param x * the scale in x * @param y * the scale in y * @param z * the scale in z * @return this */ public Matrix4f scaling(float x, float y, float z) { m00 = x; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = y; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = z; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a simple scale matrix which scales the base axes by <tt>xyz.x</tt>, <tt>xyz.y</tt> and <tt>xyz.z</tt> respectively. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * In order to post-multiply a scaling transformation directly to a * matrix use {@link #scale(Vector3f) scale()} instead. * * @see #scale(Vector3f) * * @param xyz * the scale in x, y and z respectively * @return this */ public Matrix4f scaling(Vector3f xyz) { return scaling(xyz.x, xyz.y, xyz.z); } /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to post-multiply a rotation transformation directly to a * matrix, use {@link #rotate(float, Vector3f) rotate()} instead. * * @see #rotate(float, Vector3f) * * @param angle * the angle in radians * @param axis * the axis to rotate about (needs to be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f rotation(float angle, Vector3f axis) { return rotation(angle, axis.x, axis.y, axis.z); } /** * Set this matrix to a rotation transformation using the given {@link AxisAngle4f}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(AxisAngle4f) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @return this */ public Matrix4f rotation(AxisAngle4f axisAngle) { return rotation(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); } /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(float, float, float, float) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * * @param angle * the angle in radians * @param x * the x-component of the rotation axis * @param y * the y-component of the rotation axis * @param z * the z-component of the rotation axis * @return this */ public Matrix4f rotation(float angle, float x, float y, float z) { float cos = (float) Math.cos(angle); float sin = (float) Math.sin(angle); float C = 1.0f - cos; float xy = x * y, xz = x * z, yz = y * z; m00 = cos + x * x * C; m10 = xy * C - z * sin; m20 = xz * C + y * sin; m30 = 0.0f; m01 = xy * C + z * sin; m11 = cos + y * y * C; m21 = yz * C - x * sin; m31 = 0.0f; m02 = xz * C - y * sin; m12 = yz * C + x * sin; m22 = cos + z * z * C; m32 = 0.0f; m03 = 0.0f; m13 = 0.0f; m23 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationX(float ang) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = cos; m12 = sin; m13 = 0.0f; m20 = 0.0f; m21 = -sin; m22 = cos; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the Y axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationY(float ang) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } m00 = cos; m01 = 0.0f; m02 = -sin; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = sin; m21 = 0.0f; m22 = cos; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationZ(float ang) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } m00 = cos; m01 = sin; m02 = 0.0f; m03 = 0.0f; m10 = -sin; m11 = cos; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation of <code>angleX</code> radians about the X axis, followed by a rotation * of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>rotationX(angleX).rotateY(angleY).rotateZ(angleZ)</tt> * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotationXYZ(float angleX, float angleY, float angleZ) { float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm11 = cosX; float nm12 = sinX; float nm21 = m_sinX; float nm22 = cosX; // rotateY float nm00 = cosY; float nm01 = nm21 * m_sinY; float nm02 = nm22 * m_sinY; m20 = sinY; m21 = nm21 * cosY; m22 = nm22 * cosY; m23 = 0.0f; // rotateZ m00 = nm00 * cosZ; m01 = nm01 * cosZ + nm11 * sinZ; m02 = nm02 * cosZ + nm12 * sinZ; m03 = 0.0f; m10 = nm00 * m_sinZ; m11 = nm01 * m_sinZ + nm11 * cosZ; m12 = nm02 * m_sinZ + nm12 * cosZ; m13 = 0.0f; // set last column to identity m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation * of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleX</code> radians about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>rotationZ(angleZ).rotateY(angleY).rotateX(angleX)</tt> * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @return this */ public Matrix4f rotationZYX(float angleZ, float angleY, float angleX) { float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = cosZ; float nm01 = sinZ; float nm10 = m_sinZ; float nm11 = cosZ; // rotateY float nm20 = nm00 * sinY; float nm21 = nm01 * sinY; float nm22 = cosY; m00 = nm00 * cosY; m01 = nm01 * cosY; m02 = m_sinY; m03 = 0.0f; // rotateX m10 = nm10 * cosX + nm20 * sinX; m11 = nm11 * cosX + nm21 * sinX; m12 = nm22 * sinX; m13 = 0.0f; m20 = nm10 * m_sinX + nm20 * cosX; m21 = nm11 * m_sinX + nm21 * cosX; m22 = nm22 * cosX; m23 = 0.0f; // set last column to identity m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation of <code>angleY</code> radians about the Y axis, followed by a rotation * of <code>angleX</code> radians about the X axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>rotationY(angleY).rotateX(angleX).rotateZ(angleZ)</tt> * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotationYXZ(float angleY, float angleX, float angleZ) { float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinY = -sinY; float m_sinX = -sinX; float m_sinZ = -sinZ; // rotateY float nm00 = cosY; float nm02 = m_sinY; float nm20 = sinY; float nm22 = cosY; // rotateX float nm10 = nm20 * sinX; float nm11 = cosX; float nm12 = nm22 * sinX; m20 = nm20 * cosX; m21 = m_sinX; m22 = nm22 * cosX; m23 = 0.0f; // rotateZ m00 = nm00 * cosZ + nm10 * sinZ; m01 = nm11 * sinZ; m02 = nm02 * cosZ + nm12 * sinZ; m03 = 0.0f; m10 = nm00 * m_sinZ + nm10 * cosZ; m11 = nm11 * cosZ; m12 = nm02 * m_sinZ + nm12 * cosZ; m13 = 0.0f; // set last column to identity m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set only the upper left 3x3 submatrix of this matrix to a rotation of <code>angleX</code> radians about the X axis, followed by a rotation * of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f setRotationXYZ(float angleX, float angleY, float angleZ) { float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm11 = cosX; float nm12 = sinX; float nm21 = m_sinX; float nm22 = cosX; // rotateY float nm00 = cosY; float nm01 = nm21 * m_sinY; float nm02 = nm22 * m_sinY; m20 = sinY; m21 = nm21 * cosY; m22 = nm22 * cosY; // rotateZ m00 = nm00 * cosZ; m01 = nm01 * cosZ + nm11 * sinZ; m02 = nm02 * cosZ + nm12 * sinZ; m10 = nm00 * m_sinZ; m11 = nm01 * m_sinZ + nm11 * cosZ; m12 = nm02 * m_sinZ + nm12 * cosZ; return this; } /** * Set only the upper left 3x3 submatrix of this matrix to a rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation * of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleX</code> radians about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @return this */ public Matrix4f setRotationZYX(float angleZ, float angleY, float angleX) { float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = cosZ; float nm01 = sinZ; float nm10 = m_sinZ; float nm11 = cosZ; // rotateY float nm20 = nm00 * sinY; float nm21 = nm01 * sinY; float nm22 = cosY; m00 = nm00 * cosY; m01 = nm01 * cosY; m02 = m_sinY; // rotateX m10 = nm10 * cosX + nm20 * sinX; m11 = nm11 * cosX + nm21 * sinX; m12 = nm22 * sinX; m20 = nm10 * m_sinX + nm20 * cosX; m21 = nm11 * m_sinX + nm21 * cosX; m22 = nm22 * cosX; return this; } /** * Set only the upper left 3x3 submatrix of this matrix to a rotation of <code>angleY</code> radians about the Y axis, followed by a rotation * of <code>angleX</code> radians about the X axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f setRotationYXZ(float angleY, float angleX, float angleZ) { float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinY = -sinY; float m_sinX = -sinX; float m_sinZ = -sinZ; // rotateY float nm00 = cosY; float nm02 = m_sinY; float nm20 = sinY; float nm22 = cosY; // rotateX float nm10 = nm20 * sinX; float nm11 = cosX; float nm12 = nm22 * sinX; m20 = nm20 * cosX; m21 = m_sinX; m22 = nm22 * cosX; // rotateZ m00 = nm00 * cosZ + nm10 * sinZ; m01 = nm11 * sinZ; m02 = nm02 * cosZ + nm12 * sinZ; m10 = nm00 * m_sinZ + nm10 * cosZ; m11 = nm11 * cosZ; m12 = nm02 * m_sinZ + nm12 * cosZ; return this; } /** * Set this matrix to the rotation transformation of the given {@link Quaternionf}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(Quaternionf) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotate(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotation(Quaternionf quat) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; m00 = 1.0f - q11 - q22; m01 = q01 + q23; m02 = q02 - q13; m03 = 0.0f; m10 = q01 - q23; m11 = 1.0f - q22 - q00; m12 = q12 + q03; m13 = 0.0f; m20 = q02 + q13; m21 = q12 - q03; m22 = 1.0f - q11 - q00; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt>, * <tt>R</tt> is a rotation transformation specified by the quaternion <tt>(qx, qy, qz, qw)</tt>, and <tt>S</tt> is a scaling transformation * which scales the three axes x, y and z by <tt>(sx, sy, sz)</tt>. * <p> * When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and * at last the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat).scale(sx, sy, sz)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * @see #scale(float, float, float) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param qx * the x-coordinate of the vector part of the quaternion * @param qy * the y-coordinate of the vector part of the quaternion * @param qz * the z-coordinate of the vector part of the quaternion * @param qw * the scalar part of the quaternion * @param sx * the scaling factor for the x-axis * @param sy * the scaling factor for the y-axis * @param sz * the scaling factor for the z-axis * @return this */ public Matrix4f translationRotateScale(float tx, float ty, float tz, float qx, float qy, float qz, float qw, float sx, float sy, float sz) { float dqx = qx + qx; float dqy = qy + qy; float dqz = qz + qz; float q00 = dqx * qx; float q11 = dqy * qy; float q22 = dqz * qz; float q01 = dqx * qy; float q02 = dqx * qz; float q03 = dqx * qw; float q12 = dqy * qz; float q13 = dqy * qw; float q23 = dqz * qw; m00 = sx - (q11 + q22) * sx; m01 = (q01 + q23) * sx; m02 = (q02 - q13) * sx; m03 = 0.0f; m10 = (q01 - q23) * sy; m11 = sy - (q22 + q00) * sy; m12 = (q12 + q03) * sy; m13 = 0.0f; m20 = (q02 + q13) * sz; m21 = (q12 - q03) * sz; m22 = sz - (q11 + q00) * sz; m23 = 0.0f; m30 = tx; m31 = ty; m32 = tz; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S</tt>, where <tt>T</tt> is the given <code>translation</code>, * <tt>R</tt> is a rotation transformation specified by the given quaternion, and <tt>S</tt> is a scaling transformation * which scales the axes by <code>scale</code>. * <p> * When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and * at last the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(translation).rotate(quat).scale(scale)</tt> * * @see #translation(Vector3f) * @see #rotate(Quaternionf) * * @param translation * the translation * @param quat * the quaternion representing a rotation * @param scale * the scaling factors * @return this */ public Matrix4f translationRotateScale(Vector3f translation, Quaternionf quat, Vector3f scale) { return translationRotateScale(translation.x, translation.y, translation.z, quat.x, quat.y, quat.z, quat.w, scale.x, scale.y, scale.z); } /** * Set <code>this</code> matrix to <tt>T * R * S * M</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt>, * <tt>R</tt> is a rotation transformation specified by the quaternion <tt>(qx, qy, qz, qw)</tt>, <tt>S</tt> is a scaling transformation * which scales the three axes x, y and z by <tt>(sx, sy, sz)</tt> and <code>M</code> is an {@link #isAffine() affine} matrix. * <p> * When transforming a vector by the resulting matrix the transformation described by <code>M</code> will be applied first, then the scaling, then rotation and * at last the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat).scale(sx, sy, sz).mulAffine(m)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * @see #scale(float, float, float) * @see #mulAffine(Matrix4f) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param qx * the x-coordinate of the vector part of the quaternion * @param qy * the y-coordinate of the vector part of the quaternion * @param qz * the z-coordinate of the vector part of the quaternion * @param qw * the scalar part of the quaternion * @param sx * the scaling factor for the x-axis * @param sy * the scaling factor for the y-axis * @param sz * the scaling factor for the z-axis * @param m * the {@link #isAffine() affine} matrix to multiply by * @return this */ public Matrix4f translationRotateScaleMulAffine(float tx, float ty, float tz, float qx, float qy, float qz, float qw, float sx, float sy, float sz, Matrix4f m) { float dqx = qx + qx; float dqy = qy + qy; float dqz = qz + qz; float q00 = dqx * qx; float q11 = dqy * qy; float q22 = dqz * qz; float q01 = dqx * qy; float q02 = dqx * qz; float q03 = dqx * qw; float q12 = dqy * qz; float q13 = dqy * qw; float q23 = dqz * qw; float nm00 = sx - (q11 + q22) * sx; float nm01 = (q01 + q23) * sx; float nm02 = (q02 - q13) * sx; float nm10 = (q01 - q23) * sy; float nm11 = sy - (q22 + q00) * sy; float nm12 = (q12 + q03) * sy; float nm20 = (q02 + q13) * sz; float nm21 = (q12 - q03) * sz; float nm22 = sz - (q11 + q00) * sz; float m00 = nm00 * m.m00 + nm10 * m.m01 + nm20 * m.m02; float m01 = nm01 * m.m00 + nm11 * m.m01 + nm21 * m.m02; m02 = nm02 * m.m00 + nm12 * m.m01 + nm22 * m.m02; this.m00 = m00; this.m01 = m01; m03 = 0.0f; float m10 = nm00 * m.m10 + nm10 * m.m11 + nm20 * m.m12; float m11 = nm01 * m.m10 + nm11 * m.m11 + nm21 * m.m12; m12 = nm02 * m.m10 + nm12 * m.m11 + nm22 * m.m12; this.m10 = m10; this.m11 = m11; m13 = 0.0f; float m20 = nm00 * m.m20 + nm10 * m.m21 + nm20 * m.m22; float m21 = nm01 * m.m20 + nm11 * m.m21 + nm21 * m.m22; m22 = nm02 * m.m20 + nm12 * m.m21 + nm22 * m.m22; this.m20 = m20; this.m21 = m21; m23 = 0.0f; float m30 = nm00 * m.m30 + nm10 * m.m31 + nm20 * m.m32 + tx; float m31 = nm01 * m.m30 + nm11 * m.m31 + nm21 * m.m32 + ty; m32 = nm02 * m.m30 + nm12 * m.m31 + nm22 * m.m32 + tz; this.m30 = m30; this.m31 = m31; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S * M</tt>, where <tt>T</tt> is the given <code>translation</code>, * <tt>R</tt> is a rotation transformation specified by the given quaternion, <tt>S</tt> is a scaling transformation * which scales the axes by <code>scale</code> and <code>M</code> is an {@link #isAffine() affine} matrix. * <p> * When transforming a vector by the resulting matrix the transformation described by <code>M</code> will be applied first, then the scaling, then rotation and * at last the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(translation).rotate(quat).scale(scale).mulAffine(m)</tt> * * @see #translation(Vector3f) * @see #rotate(Quaternionf) * @see #mulAffine(Matrix4f) * * @param translation * the translation * @param quat * the quaternion representing a rotation * @param scale * the scaling factors * @param m * the {@link #isAffine() affine} matrix to multiply by * @return this */ public Matrix4f translationRotateScaleMulAffine(Vector3f translation, Quaternionf quat, Vector3f scale, Matrix4f m) { return translationRotateScaleMulAffine(translation.x, translation.y, translation.z, quat.x, quat.y, quat.z, quat.w, scale.x, scale.y, scale.z, m); } /** * Set <code>this</code> matrix to <tt>T * R</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt> and * <tt>R</tt> is a rotation transformation specified by the given quaternion. * <p> * When transforming a vector by the resulting matrix the rotation transformation will be applied first and then the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param quat * the quaternion representing a rotation * @return this */ public Matrix4f translationRotate(float tx, float ty, float tz, Quaternionf quat) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; m00 = 1.0f - (q11 + q22); m01 = q01 + q23; m02 = q02 - q13; m03 = 0.0f; m10 = q01 - q23; m11 = 1.0f - (q22 + q00); m12 = q12 + q03; m13 = 0.0f; m20 = q02 + q13; m21 = q12 - q03; m22 = 1.0f - (q11 + q00); m23 = 0.0f; m30 = tx; m31 = ty; m32 = tz; m33 = 1.0f; return this; } /** * Set the upper left 3x3 submatrix of this {@link Matrix4f} to the given {@link Matrix3f} and don't change the other elements.. * * @param mat * the 3x3 matrix * @return this */ public Matrix4f set3x3(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; return this; } /** * Transform/multiply the given vector by this matrix and store the result in that vector. * * @see Vector4f#mul(Matrix4f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector4f transform(Vector4f v) { return v.mul(this); } /** * Transform/multiply the given vector by this matrix and store the result in <code>dest</code>. * * @see Vector4f#mul(Matrix4f, Vector4f) * * @param v * the vector to transform * @param dest * will contain the result * @return dest */ public Vector4f transform(Vector4f v, Vector4f dest) { return v.mul(this, dest); } /** * Transform/multiply the given vector by this matrix, perform perspective divide and store the result in that vector. * * @see Vector4f#mulProject(Matrix4f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector4f transformProject(Vector4f v) { return v.mulProject(this); } /** * Transform/multiply the given vector by this matrix, perform perspective divide and store the result in <code>dest</code>. * * @see Vector4f#mulProject(Matrix4f, Vector4f) * * @param v * the vector to transform * @param dest * will contain the result * @return dest */ public Vector4f transformProject(Vector4f v, Vector4f dest) { return v.mulProject(this, dest); } /** * Transform/multiply the given vector by this matrix, perform perspective divide and store the result in that vector. * <p> * This method uses <tt>w=1.0</tt> as the fourth vector component. * * @see Vector3f#mulProject(Matrix4f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector3f transformProject(Vector3f v) { return v.mulProject(this); } /** * Transform/multiply the given vector by this matrix, perform perspective divide and store the result in <code>dest</code>. * <p> * This method uses <tt>w=1.0</tt> as the fourth vector component. * * @see Vector3f#mulProject(Matrix4f, Vector3f) * * @param v * the vector to transform * @param dest * will contain the result * @return dest */ public Vector3f transformProject(Vector3f v, Vector3f dest) { return v.mulProject(this, dest); } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=1, by * this matrix and store the result in that vector. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being 1.0, so it * will represent a position/location in 3D-space rather than a direction. This method is therefore * not suited for perspective projection transformations as it will not save the * <tt>w</tt> component of the transformed vector. * For perspective projection use {@link #transform(Vector4f)} or {@link #transformProject(Vector3f)} * when perspective divide should be applied, too. * <p> * In order to store the result in another vector, use {@link #transformPosition(Vector3f, Vector3f)}. * * @see #transformPosition(Vector3f, Vector3f) * @see #transform(Vector4f) * @see #transformProject(Vector3f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector3f transformPosition(Vector3f v) { v.set(m00 * v.x + m10 * v.y + m20 * v.z + m30, m01 * v.x + m11 * v.y + m21 * v.z + m31, m02 * v.x + m12 * v.y + m22 * v.z + m32); return v; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=1, by * this matrix and store the result in <code>dest</code>. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being 1.0, so it * will represent a position/location in 3D-space rather than a direction. This method is therefore * not suited for perspective projection transformations as it will not save the * <tt>w</tt> component of the transformed vector. * For perspective projection use {@link #transform(Vector4f, Vector4f)} or * {@link #transformProject(Vector3f, Vector3f)} when perspective divide should be applied, too. * <p> * In order to store the result in the same vector, use {@link #transformPosition(Vector3f)}. * * @see #transformPosition(Vector3f) * @see #transform(Vector4f, Vector4f) * @see #transformProject(Vector3f, Vector3f) * * @param v * the vector to transform * @param dest * will hold the result * @return dest */ public Vector3f transformPosition(Vector3f v, Vector3f dest) { dest.set(m00 * v.x + m10 * v.y + m20 * v.z + m30, m01 * v.x + m11 * v.y + m21 * v.z + m31, m02 * v.x + m12 * v.y + m22 * v.z + m32); return dest; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=0, by * this matrix and store the result in that vector. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being <tt>0.0</tt>, so it * will represent a direction in 3D-space rather than a position. This method will therefore * not take the translation part of the matrix into account. * <p> * In order to store the result in another vector, use {@link #transformDirection(Vector3f, Vector3f)}. * * @see #transformDirection(Vector3f, Vector3f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector3f transformDirection(Vector3f v) { v.set(m00 * v.x + m10 * v.y + m20 * v.z, m01 * v.x + m11 * v.y + m21 * v.z, m02 * v.x + m12 * v.y + m22 * v.z); return v; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=0, by * this matrix and store the result in <code>dest</code>. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being <tt>0.0</tt>, so it * will represent a direction in 3D-space rather than a position. This method will therefore * not take the translation part of the matrix into account. * <p> * In order to store the result in the same vector, use {@link #transformDirection(Vector3f)}. * * @see #transformDirection(Vector3f) * * @param v * the vector to transform and to hold the final result * @param dest * will hold the result * @return dest */ public Vector3f transformDirection(Vector3f v, Vector3f dest) { dest.set(m00 * v.x + m10 * v.y + m20 * v.z, m01 * v.x + m11 * v.y + m21 * v.z, m02 * v.x + m12 * v.y + m22 * v.z); return dest; } /** * Transform/multiply the given 4D-vector by assuming that <code>this</code> matrix represents an {@link #isAffine() affine} transformation * (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>). * <p> * In order to store the result in another vector, use {@link #transformAffine(Vector4f, Vector4f)}. * * @see #transformAffine(Vector4f, Vector4f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector4f transformAffine(Vector4f v) { v.set(m00 * v.x + m10 * v.y + m20 * v.z + m30 * v.w, m01 * v.x + m11 * v.y + m21 * v.z + m31 * v.w, m02 * v.x + m12 * v.y + m22 * v.z + m32 * v.w, v.w); return v; } /** * Transform/multiply the given 4D-vector by assuming that <code>this</code> matrix represents an {@link #isAffine() affine} transformation * (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) and store the result in <code>dest</code>. * <p> * In order to store the result in the same vector, use {@link #transformAffine(Vector4f)}. * * @see #transformAffine(Vector4f) * * @param v * the vector to transform and to hold the final result * @param dest * will hold the result * @return dest */ public Vector4f transformAffine(Vector4f v, Vector4f dest) { dest.set(m00 * v.x + m10 * v.y + m20 * v.z + m30 * v.w, m01 * v.x + m11 * v.y + m21 * v.z + m31 * v.w, m02 * v.x + m12 * v.y + m22 * v.z + m32 * v.w, v.w); return dest; } /** * Apply scaling to the this matrix by scaling the base axes by the given <tt>xyz.x</tt>, * <tt>xyz.y</tt> and <tt>xyz.z</tt> factors, respectively and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code> * , the scaling will be applied first! * * @param xyz * the factors of the x, y and z component, respectively * @param dest * will hold the result * @return dest */ public Matrix4f scale(Vector3f xyz, Matrix4f dest) { return scale(xyz.x, xyz.y, xyz.z, dest); } /** * Apply scaling to this matrix by scaling the base axes by the given <tt>xyz.x</tt>, * <tt>xyz.y</tt> and <tt>xyz.z</tt> factors, respectively. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * * @param xyz * the factors of the x, y and z component, respectively * @return this */ public Matrix4f scale(Vector3f xyz) { return scale(xyz.x, xyz.y, xyz.z, this); } /** * Apply scaling to this matrix by uniformly scaling all base axes by the given <code>xyz</code> factor * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * <p> * Individual scaling of all three axes can be applied using {@link #scale(float, float, float, Matrix4f)}. * * @see #scale(float, float, float, Matrix4f) * * @param xyz * the factor for all components * @param dest * will hold the result * @return dest */ public Matrix4f scale(float xyz, Matrix4f dest) { return scale(xyz, xyz, xyz, dest); } /** * Apply scaling to this matrix by uniformly scaling all base axes by the given <code>xyz</code> factor. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * <p> * Individual scaling of all three axes can be applied using {@link #scale(float, float, float)}. * * @see #scale(float, float, float) * * @param xyz * the factor for all components * @return this */ public Matrix4f scale(float xyz) { return scale(xyz, xyz, xyz); } /** * Apply scaling to the this matrix by scaling the base axes by the given x, * y and z factors and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code> * , the scaling will be applied first! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @param dest * will hold the result * @return dest */ public Matrix4f scale(float x, float y, float z, Matrix4f dest) { // scale matrix elements: // m00 = x, m11 = y, m22 = z // m33 = 1 // all others = 0 dest.m00 = m00 * x; dest.m01 = m01 * x; dest.m02 = m02 * x; dest.m03 = m03 * x; dest.m10 = m10 * y; dest.m11 = m11 * y; dest.m12 = m12 * y; dest.m13 = m13 * y; dest.m20 = m20 * z; dest.m21 = m21 * z; dest.m22 = m22 * z; dest.m23 = m23 * z; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply scaling to this matrix by scaling the base axes by the given x, * y and z factors. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @return this */ public Matrix4f scale(float x, float y, float z) { return scale(x, y, z, this); } /** * Pre-multiply scaling to the this matrix by scaling the base axes by the given x, * y and z factors and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>S * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>S * M * v</code> * , the scaling will be applied last! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @param dest * will hold the result * @return dest */ public Matrix4f scaleLocal(float x, float y, float z, Matrix4f dest) { float nm00 = x * m00; float nm01 = y * m01; float nm02 = z * m02; float nm03 = m03; float nm10 = x * m10; float nm11 = y * m11; float nm12 = z * m12; float nm13 = m13; float nm20 = x * m20; float nm21 = y * m21; float nm22 = z * m22; float nm23 = m23; float nm30 = x * m30; float nm31 = y * m31; float nm32 = z * m32; float nm33 = m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Pre-multiply scaling to this matrix by scaling the base axes by the given x, * y and z factors. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>S * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>S * M * v</code>, the * scaling will be applied last! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @return this */ public Matrix4f scaleLocal(float x, float y, float z) { return scaleLocal(x, y, z, this); } /** * Apply rotation about the X axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return dest */ public Matrix4f rotateX(float ang, Matrix4f dest) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } float rm11 = cos; float rm12 = sin; float rm21 = -sin; float rm22 = cos; // add temporaries for dependent values float nm10 = m10 * rm11 + m20 * rm12; float nm11 = m11 * rm11 + m21 * rm12; float nm12 = m12 * rm11 + m22 * rm12; float nm13 = m13 * rm11 + m23 * rm12; // set non-dependent values directly dest.m20 = m10 * rm21 + m20 * rm22; dest.m21 = m11 * rm21 + m21 * rm22; dest.m22 = m12 * rm21 + m22 * rm22; dest.m23 = m13 * rm21 + m23 * rm22; // set other values dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation about the X axis to this matrix by rotating the given amount of radians. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateX(float ang) { return rotateX(ang, this); } /** * Apply rotation about the Y axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return dest */ public Matrix4f rotateY(float ang, Matrix4f dest) { float cos, sin; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } float rm00 = cos; float rm02 = -sin; float rm20 = sin; float rm22 = cos; // add temporaries for dependent values float nm00 = m00 * rm00 + m20 * rm02; float nm01 = m01 * rm00 + m21 * rm02; float nm02 = m02 * rm00 + m22 * rm02; float nm03 = m03 * rm00 + m23 * rm02; // set non-dependent values directly dest.m20 = m00 * rm20 + m20 * rm22; dest.m21 = m01 * rm20 + m21 * rm22; dest.m22 = m02 * rm20 + m22 * rm22; dest.m23 = m03 * rm20 + m23 * rm22; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = m13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation about the Y axis to this matrix by rotating the given amount of radians. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateY(float ang) { return rotateY(ang, this); } /** * Apply rotation about the Z axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return dest */ public Matrix4f rotateZ(float ang, Matrix4f dest) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } float rm00 = cos; float rm01 = sin; float rm10 = -sin; float rm11 = cos; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01; float nm01 = m01 * rm00 + m11 * rm01; float nm02 = m02 * rm00 + m12 * rm01; float nm03 = m03 * rm00 + m13 * rm01; // set non-dependent values directly dest.m10 = m00 * rm10 + m10 * rm11; dest.m11 = m01 * rm10 + m11 * rm11; dest.m12 = m02 * rm10 + m12 * rm11; dest.m13 = m03 * rm10 + m13 * rm11; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = m23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation about the Z axis to this matrix by rotating the given amount of radians. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateZ(float ang) { return rotateZ(ang, this); } /** * Apply rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateX(angleX).rotateY(angleY).rotateZ(angleZ)</tt> * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotateXYZ(float angleX, float angleY, float angleZ) { return rotateXYZ(angleX, angleY, angleZ, this); } /** * Apply rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateX(angleX, dest).rotateY(angleY).rotateZ(angleZ)</tt> * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @param dest * will hold the result * @return dest */ public Matrix4f rotateXYZ(float angleX, float angleY, float angleZ, Matrix4f dest) { float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm10 = m10 * cosX + m20 * sinX; float nm11 = m11 * cosX + m21 * sinX; float nm12 = m12 * cosX + m22 * sinX; float nm13 = m13 * cosX + m23 * sinX; float nm20 = m10 * m_sinX + m20 * cosX; float nm21 = m11 * m_sinX + m21 * cosX; float nm22 = m12 * m_sinX + m22 * cosX; float nm23 = m13 * m_sinX + m23 * cosX; // rotateY float nm00 = m00 * cosY + nm20 * m_sinY; float nm01 = m01 * cosY + nm21 * m_sinY; float nm02 = m02 * cosY + nm22 * m_sinY; float nm03 = m03 * cosY + nm23 * m_sinY; dest.m20 = m00 * sinY + nm20 * cosY; dest.m21 = m01 * sinY + nm21 * cosY; dest.m22 = m02 * sinY + nm22 * cosY; dest.m23 = m03 * sinY + nm23 * cosY; // rotateZ dest.m00 = nm00 * cosZ + nm10 * sinZ; dest.m01 = nm01 * cosZ + nm11 * sinZ; dest.m02 = nm02 * cosZ + nm12 * sinZ; dest.m03 = nm03 * cosZ + nm13 * sinZ; dest.m10 = nm00 * m_sinZ + nm10 * cosZ; dest.m11 = nm01 * m_sinZ + nm11 * cosZ; dest.m12 = nm02 * m_sinZ + nm12 * cosZ; dest.m13 = nm03 * m_sinZ + nm13 * cosZ; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateX(angleX).rotateY(angleY).rotateZ(angleZ)</tt> * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotateAffineXYZ(float angleX, float angleY, float angleZ) { return rotateAffineXYZ(angleX, angleY, angleZ, this); } /** * Apply rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineXYZ(float angleX, float angleY, float angleZ, Matrix4f dest) { float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm10 = m10 * cosX + m20 * sinX; float nm11 = m11 * cosX + m21 * sinX; float nm12 = m12 * cosX + m22 * sinX; float nm20 = m10 * m_sinX + m20 * cosX; float nm21 = m11 * m_sinX + m21 * cosX; float nm22 = m12 * m_sinX + m22 * cosX; // rotateY float nm00 = m00 * cosY + nm20 * m_sinY; float nm01 = m01 * cosY + nm21 * m_sinY; float nm02 = m02 * cosY + nm22 * m_sinY; dest.m20 = m00 * sinY + nm20 * cosY; dest.m21 = m01 * sinY + nm21 * cosY; dest.m22 = m02 * sinY + nm22 * cosY; dest.m23 = 0.0f; // rotateZ dest.m00 = nm00 * cosZ + nm10 * sinZ; dest.m01 = nm01 * cosZ + nm11 * sinZ; dest.m02 = nm02 * cosZ + nm12 * sinZ; dest.m03 = 0.0f; dest.m10 = nm00 * m_sinZ + nm10 * cosZ; dest.m11 = nm01 * m_sinZ + nm11 * cosZ; dest.m12 = nm02 * m_sinZ + nm12 * cosZ; dest.m13 = 0.0f; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleX</code> radians about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateZ(angleZ).rotateY(angleY).rotateX(angleX)</tt> * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @return this */ public Matrix4f rotateZYX(float angleZ, float angleY, float angleX) { return rotateZYX(angleZ, angleY, angleX, this); } /** * Apply rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleX</code> radians about the X axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateZ(angleZ, dest).rotateY(angleY).rotateX(angleX)</tt> * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param dest * will hold the result * @return dest */ public Matrix4f rotateZYX(float angleZ, float angleY, float angleX, Matrix4f dest) { float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = m00 * cosZ + m10 * sinZ; float nm01 = m01 * cosZ + m11 * sinZ; float nm02 = m02 * cosZ + m12 * sinZ; float nm03 = m03 * cosZ + m13 * sinZ; float nm10 = m00 * m_sinZ + m10 * cosZ; float nm11 = m01 * m_sinZ + m11 * cosZ; float nm12 = m02 * m_sinZ + m12 * cosZ; float nm13 = m03 * m_sinZ + m13 * cosZ; // rotateY float nm20 = nm00 * sinY + m20 * cosY; float nm21 = nm01 * sinY + m21 * cosY; float nm22 = nm02 * sinY + m22 * cosY; float nm23 = nm03 * sinY + m23 * cosY; dest.m00 = nm00 * cosY + m20 * m_sinY; dest.m01 = nm01 * cosY + m21 * m_sinY; dest.m02 = nm02 * cosY + m22 * m_sinY; dest.m03 = nm03 * cosY + m23 * m_sinY; // rotateX dest.m10 = nm10 * cosX + nm20 * sinX; dest.m11 = nm11 * cosX + nm21 * sinX; dest.m12 = nm12 * cosX + nm22 * sinX; dest.m13 = nm13 * cosX + nm23 * sinX; dest.m20 = nm10 * m_sinX + nm20 * cosX; dest.m21 = nm11 * m_sinX + nm21 * cosX; dest.m22 = nm12 * m_sinX + nm22 * cosX; dest.m23 = nm13 * m_sinX + nm23 * cosX; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleX</code> radians about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @return this */ public Matrix4f rotateAffineZYX(float angleZ, float angleY, float angleX) { return rotateAffineZYX(angleZ, angleY, angleX, this); } /** * Apply rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleX</code> radians about the X axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineZYX(float angleZ, float angleY, float angleX, Matrix4f dest) { float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = m00 * cosZ + m10 * sinZ; float nm01 = m01 * cosZ + m11 * sinZ; float nm02 = m02 * cosZ + m12 * sinZ; float nm10 = m00 * m_sinZ + m10 * cosZ; float nm11 = m01 * m_sinZ + m11 * cosZ; float nm12 = m02 * m_sinZ + m12 * cosZ; // rotateY float nm20 = nm00 * sinY + m20 * cosY; float nm21 = nm01 * sinY + m21 * cosY; float nm22 = nm02 * sinY + m22 * cosY; dest.m00 = nm00 * cosY + m20 * m_sinY; dest.m01 = nm01 * cosY + m21 * m_sinY; dest.m02 = nm02 * cosY + m22 * m_sinY; dest.m03 = 0.0f; // rotateX dest.m10 = nm10 * cosX + nm20 * sinX; dest.m11 = nm11 * cosX + nm21 * sinX; dest.m12 = nm12 * cosX + nm22 * sinX; dest.m13 = 0.0f; dest.m20 = nm10 * m_sinX + nm20 * cosX; dest.m21 = nm11 * m_sinX + nm21 * cosX; dest.m22 = nm12 * m_sinX + nm22 * cosX; dest.m23 = 0.0f; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateY(angleY).rotateX(angleX).rotateZ(angleZ)</tt> * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotateYXZ(float angleY, float angleX, float angleZ) { return rotateYXZ(angleY, angleX, angleZ, this); } /** * Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateY(angleY, dest).rotateX(angleX).rotateZ(angleZ)</tt> * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @param dest * will hold the result * @return dest */ public Matrix4f rotateYXZ(float angleY, float angleX, float angleZ, Matrix4f dest) { float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinY = -sinY; float m_sinX = -sinX; float m_sinZ = -sinZ; // rotateY float nm20 = m00 * sinY + m20 * cosY; float nm21 = m01 * sinY + m21 * cosY; float nm22 = m02 * sinY + m22 * cosY; float nm23 = m03 * sinY + m23 * cosY; float nm00 = m00 * cosY + m20 * m_sinY; float nm01 = m01 * cosY + m21 * m_sinY; float nm02 = m02 * cosY + m22 * m_sinY; float nm03 = m03 * cosY + m23 * m_sinY; // rotateX float nm10 = m10 * cosX + nm20 * sinX; float nm11 = m11 * cosX + nm21 * sinX; float nm12 = m12 * cosX + nm22 * sinX; float nm13 = m13 * cosX + nm23 * sinX; dest.m20 = m10 * m_sinX + nm20 * cosX; dest.m21 = m11 * m_sinX + nm21 * cosX; dest.m22 = m12 * m_sinX + nm22 * cosX; dest.m23 = m13 * m_sinX + nm23 * cosX; // rotateZ dest.m00 = nm00 * cosZ + nm10 * sinZ; dest.m01 = nm01 * cosZ + nm11 * sinZ; dest.m02 = nm02 * cosZ + nm12 * sinZ; dest.m03 = nm03 * cosZ + nm13 * sinZ; dest.m10 = nm00 * m_sinZ + nm10 * cosZ; dest.m11 = nm01 * m_sinZ + nm11 * cosZ; dest.m12 = nm02 * m_sinZ + nm12 * cosZ; dest.m13 = nm03 * m_sinZ + nm13 * cosZ; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotateAffineYXZ(float angleY, float angleX, float angleZ) { return rotateAffineYXZ(angleY, angleX, angleZ, this); } /** * Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineYXZ(float angleY, float angleX, float angleZ, Matrix4f dest) { float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinY = -sinY; float m_sinX = -sinX; float m_sinZ = -sinZ; // rotateY float nm20 = m00 * sinY + m20 * cosY; float nm21 = m01 * sinY + m21 * cosY; float nm22 = m02 * sinY + m22 * cosY; float nm00 = m00 * cosY + m20 * m_sinY; float nm01 = m01 * cosY + m21 * m_sinY; float nm02 = m02 * cosY + m22 * m_sinY; // rotateX float nm10 = m10 * cosX + nm20 * sinX; float nm11 = m11 * cosX + nm21 * sinX; float nm12 = m12 * cosX + nm22 * sinX; dest.m20 = m10 * m_sinX + nm20 * cosX; dest.m21 = m11 * m_sinX + nm21 * cosX; dest.m22 = m12 * m_sinX + nm22 * cosX; dest.m23 = 0.0f; // rotateZ dest.m00 = nm00 * cosZ + nm10 * sinZ; dest.m01 = nm01 * cosZ + nm11 * sinZ; dest.m02 = nm02 * cosZ + nm12 * sinZ; dest.m03 = 0.0f; dest.m10 = nm00 * m_sinZ + nm10 * cosZ; dest.m11 = nm01 * m_sinZ + nm11 * cosZ; dest.m12 = nm02 * m_sinZ + nm12 * cosZ; dest.m13 = 0.0f; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation to this matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis and store the result in <code>dest</code>. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @param dest * will hold the result * @return dest */ public Matrix4f rotate(float ang, float x, float y, float z, Matrix4f dest) { float s = (float) Math.sin(ang); float c = (float) Math.cos(ang); float C = 1.0f - c; // rotation matrix elements: // m30, m31, m32, m03, m13, m23 = 0 // m33 = 1 float xx = x * x, xy = x * y, xz = x * z; float yy = y * y, yz = y * z; float zz = z * z; float rm00 = xx * C + c; float rm01 = xy * C + z * s; float rm02 = xz * C - y * s; float rm10 = xy * C - z * s; float rm11 = yy * C + c; float rm12 = yz * C + x * s; float rm20 = xz * C + y * s; float rm21 = yz * C - x * s; float rm22 = zz * C + c; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; // set non-dependent values directly dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation to this matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @return this */ public Matrix4f rotate(float ang, float x, float y, float z) { return rotate(ang, x, y, z, this); } /** * Apply rotation to this {@link #isAffine() affine} matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis and store the result in <code>dest</code>. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffine(float ang, float x, float y, float z, Matrix4f dest) { float s = (float) Math.sin(ang); float c = (float) Math.cos(ang); float C = 1.0f - c; float xx = x * x, xy = x * y, xz = x * z; float yy = y * y, yz = y * z; float zz = z * z; float rm00 = xx * C + c; float rm01 = xy * C + z * s; float rm02 = xz * C - y * s; float rm10 = xy * C - z * s; float rm11 = yy * C + c; float rm12 = yz * C + x * s; float rm20 = xz * C + y * s; float rm21 = yz * C - x * s; float rm22 = zz * C + c; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; // set non-dependent values directly dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = 0.0f; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = 0.0f; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = 0.0f; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation to this {@link #isAffine() affine} matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @return this */ public Matrix4f rotateAffine(float ang, float x, float y, float z) { return rotateAffine(ang, x, y, z, this); } /** * Pre-multiply a rotation to this {@link #isAffine() affine} matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis and store the result in <code>dest</code>. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>R * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the * rotation will be applied last! * <p> * In order to set the matrix to a rotation matrix without pre-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineLocal(float ang, float x, float y, float z, Matrix4f dest) { float s = (float) Math.sin(ang); float c = (float) Math.cos(ang); float C = 1.0f - c; float xx = x * x, xy = x * y, xz = x * z; float yy = y * y, yz = y * z; float zz = z * z; float lm00 = xx * C + c; float lm01 = xy * C + z * s; float lm02 = xz * C - y * s; float lm10 = xy * C - z * s; float lm11 = yy * C + c; float lm12 = yz * C + x * s; float lm20 = xz * C + y * s; float lm21 = yz * C - x * s; float lm22 = zz * C + c; float nm00 = lm00 * m00 + lm10 * m01 + lm20 * m02; float nm01 = lm01 * m00 + lm11 * m01 + lm21 * m02; float nm02 = lm02 * m00 + lm12 * m01 + lm22 * m02; float nm03 = 0.0f; float nm10 = lm00 * m10 + lm10 * m11 + lm20 * m12; float nm11 = lm01 * m10 + lm11 * m11 + lm21 * m12; float nm12 = lm02 * m10 + lm12 * m11 + lm22 * m12; float nm13 = 0.0f; float nm20 = lm00 * m20 + lm10 * m21 + lm20 * m22; float nm21 = lm01 * m20 + lm11 * m21 + lm21 * m22; float nm22 = lm02 * m20 + lm12 * m21 + lm22 * m22; float nm23 = 0.0f; float nm30 = lm00 * m30 + lm10 * m31 + lm20 * m32; float nm31 = lm01 * m30 + lm11 * m31 + lm21 * m32; float nm32 = lm02 * m30 + lm12 * m31 + lm22 * m32; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Pre-multiply a rotation to this {@link #isAffine() affine} matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>R * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the * rotation will be applied last! * <p> * In order to set the matrix to a rotation matrix without pre-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @return this */ public Matrix4f rotateAffineLocal(float ang, float x, float y, float z) { return rotateAffineLocal(ang, x, y, z, this); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @return this */ public Matrix4f translate(Vector3f offset) { return translate(offset.x, offset.y, offset.z); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @param dest * will hold the result * @return dest */ public Matrix4f translate(Vector3f offset, Matrix4f dest) { return translate(offset.x, offset.y, offset.z, dest); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @param dest * will hold the result * @return dest */ public Matrix4f translate(float x, float y, float z, Matrix4f dest) { // translation matrix elements: // m00, m11, m22, m33 = 1 // m30 = x, m31 = y, m32 = z // all others = 0 dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = m13; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = m23; dest.m30 = m00 * x + m10 * y + m20 * z + m30; dest.m31 = m01 * x + m11 * y + m21 * z + m31; dest.m32 = m02 * x + m12 * y + m22 * z + m32; dest.m33 = m03 * x + m13 * y + m23 * z + m33; return dest; } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translate(float x, float y, float z) { Matrix4f c = this; // translation matrix elements: // m00, m11, m22, m33 = 1 // m30 = x, m31 = y, m32 = z // all others = 0 c.m30 = c.m00 * x + c.m10 * y + c.m20 * z + c.m30; c.m31 = c.m01 * x + c.m11 * y + c.m21 * z + c.m31; c.m32 = c.m02 * x + c.m12 * y + c.m22 * z + c.m32; c.m33 = c.m03 * x + c.m13 * y + c.m23 * z + c.m33; return this; } /** * Pre-multiply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>T * M</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>T * M * v</code>, the translation will be applied last! * <p> * In order to set the matrix to a translation transformation without pre-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @return this */ public Matrix4f translateLocal(Vector3f offset) { return translateLocal(offset.x, offset.y, offset.z); } /** * Pre-multiply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>T * M</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>T * M * v</code>, the translation will be applied last! * <p> * In order to set the matrix to a translation transformation without pre-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @param dest * will hold the result * @return dest */ public Matrix4f translateLocal(Vector3f offset, Matrix4f dest) { return translateLocal(offset.x, offset.y, offset.z, dest); } /** * Pre-multiply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>T * M</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>T * M * v</code>, the translation will be applied last! * <p> * In order to set the matrix to a translation transformation without pre-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @param dest * will hold the result * @return dest */ public Matrix4f translateLocal(float x, float y, float z, Matrix4f dest) { float nm00 = m00 + x * m03; float nm01 = m01 + y * m03; float nm02 = m02 + z * m03; float nm03 = m03; float nm10 = m10 + x * m13; float nm11 = m11 + y * m13; float nm12 = m12 + z * m13; float nm13 = m13; float nm20 = m20 + x * m23; float nm21 = m21 + y * m23; float nm22 = m22 + z * m23; float nm23 = m23; float nm30 = m30 + x * m33; float nm31 = m31 + y * m33; float nm32 = m32 + z * m33; float nm33 = m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Pre-multiply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>T * M</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>T * M * v</code>, the translation will be applied last! * <p> * In order to set the matrix to a translation transformation without pre-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translateLocal(float x, float y, float z) { return translateLocal(x, y, z, this); } public void writeExternal(ObjectOutput out) throws IOException { out.writeFloat(m00); out.writeFloat(m01); out.writeFloat(m02); out.writeFloat(m03); out.writeFloat(m10); out.writeFloat(m11); out.writeFloat(m12); out.writeFloat(m13); out.writeFloat(m20); out.writeFloat(m21); out.writeFloat(m22); out.writeFloat(m23); out.writeFloat(m30); out.writeFloat(m31); out.writeFloat(m32); out.writeFloat(m33); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { m00 = in.readFloat(); m01 = in.readFloat(); m02 = in.readFloat(); m03 = in.readFloat(); m10 = in.readFloat(); m11 = in.readFloat(); m12 = in.readFloat(); m13 = in.readFloat(); m20 = in.readFloat(); m21 = in.readFloat(); m22 = in.readFloat(); m23 = in.readFloat(); m30 = in.readFloat(); m31 = in.readFloat(); m32 = in.readFloat(); m33 = in.readFloat(); } /** * Apply an orthographic projection transformation using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float, boolean) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float, boolean) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @param dest * will hold the result * @return dest */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / (right - left); float rm11 = 2.0f / (top - bottom); float rm22 = (zZeroToOne ? 1.0f : 2.0f) / (zNear - zFar); float rm30 = (left + right) / (left - right); float rm31 = (top + bottom) / (bottom - top); float rm32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); // perform optimized multiplication // compute the last column first, because other columns do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = m20 * rm22; dest.m21 = m21 * rm22; dest.m22 = m22 * rm22; dest.m23 = m23 * rm22; return dest; } /** * Apply an orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return dest */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { return ortho(left, right, bottom, top, zNear, zFar, false, dest); } /** * Apply an orthographic projection transformation using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float, boolean) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float, boolean) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { return ortho(left, right, bottom, top, zNear, zFar, zZeroToOne, this); } /** * Apply an orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar) { return ortho(left, right, bottom, top, zNear, zFar, false); } /** * Set this matrix to be an orthographic projection transformation using the given NDC z range. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho(float, float, float, float, float, float, boolean) ortho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float, boolean) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setOrtho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { m00 = 2.0f / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = (zZeroToOne ? 1.0f : 2.0f) / (zNear - zFar); m23 = 0.0f; m30 = (right + left) / (left - right); m31 = (top + bottom) / (bottom - top); m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); m33 = 1.0f; return this; } /** * Set this matrix to be an orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho(float, float, float, float, float, float) ortho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setOrtho(float left, float right, float bottom, float top, float zNear, float zFar) { return setOrtho(left, right, bottom, top, zNear, zFar, false); } /** * Apply a symmetric orthographic projection transformation using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, boolean, Matrix4f) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float, boolean) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float, boolean) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return dest */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / width; float rm11 = 2.0f / height; float rm22 = (zZeroToOne ? 1.0f : 2.0f) / (zNear - zFar); float rm32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); // perform optimized multiplication // compute the last column first, because other columns do not depend on it dest.m30 = m20 * rm32 + m30; dest.m31 = m21 * rm32 + m31; dest.m32 = m22 * rm32 + m32; dest.m33 = m23 * rm32 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = m20 * rm22; dest.m21 = m21 * rm22; dest.m22 = m22 * rm22; dest.m23 = m23 * rm22; return dest; } /** * Apply a symmetric orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, Matrix4f) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return dest */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, Matrix4f dest) { return orthoSymmetric(width, height, zNear, zFar, false, dest); } /** * Apply a symmetric orthographic projection transformation using the given NDC z range to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, boolean) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float, boolean) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float, boolean) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, boolean zZeroToOne) { return orthoSymmetric(width, height, zNear, zFar, zZeroToOne, this); } /** * Apply a symmetric orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar) { return orthoSymmetric(width, height, zNear, zFar, false, this); } /** * Set this matrix to be a symmetric orthographic projection transformation using the given NDC z range. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float, boolean) setOrtho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * In order to apply the symmetric orthographic projection to an already existing transformation, * use {@link #orthoSymmetric(float, float, float, float, boolean) orthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #orthoSymmetric(float, float, float, float, boolean) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setOrthoSymmetric(float width, float height, float zNear, float zFar, boolean zZeroToOne) { m00 = 2.0f / width; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / height; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = (zZeroToOne ? 1.0f : 2.0f) / (zNear - zFar); m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); m33 = 1.0f; return this; } /** * Set this matrix to be a symmetric orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * In order to apply the symmetric orthographic projection to an already existing transformation, * use {@link #orthoSymmetric(float, float, float, float) orthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #orthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setOrthoSymmetric(float width, float height, float zNear, float zFar) { return setOrthoSymmetric(width, height, zNear, zFar, false); } /** * Apply an orthographic projection transformation to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, Matrix4f) ortho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho2D(float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float, Matrix4f) * @see #setOrtho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param dest * will hold the result * @return dest */ public Matrix4f ortho2D(float left, float right, float bottom, float top, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / (right - left); float rm11 = 2.0f / (top - bottom); float rm30 = -(right + left) / (right - left); float rm31 = -(top + bottom) / (top - bottom); // perform optimized multiplication // compute the last column first, because other columns do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = -m20; dest.m21 = -m21; dest.m22 = -m22; dest.m23 = -m23; return dest; } /** * Apply an orthographic projection transformation to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float) ortho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho2D(float, float, float, float) setOrtho2D()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float) * @see #setOrtho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @return this */ public Matrix4f ortho2D(float left, float right, float bottom, float top) { return ortho2D(left, right, bottom, top, this); } /** * Set this matrix to be an orthographic projection transformation. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho2D(float, float, float, float) ortho2D()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * @see #ortho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @return this */ public Matrix4f setOrtho2D(float left, float right, float bottom, float top) { m00 = 2.0f / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -1.0f; m23 = 0.0f; m30 = -(right + left) / (right - left); m31 = -(top + bottom) / (top - bottom); m32 = 0.0f; m33 = 1.0f; return this; } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(Vector3f, Vector3f) setLookAlong()}. * * @see #lookAlong(float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @return this */ public Matrix4f lookAlong(Vector3f dir, Vector3f up) { return lookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z, this); } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code> * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(Vector3f, Vector3f) setLookAlong()}. * * @see #lookAlong(float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @param dest * will hold the result * @return dest */ public Matrix4f lookAlong(Vector3f dir, Vector3f up, Matrix4f dest) { return lookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z, dest); } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code> * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()} * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return dest */ public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ, Matrix4f dest) { // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float dirnX = dirX * invDirLength; float dirnY = dirY * invDirLength; float dirnZ = dirZ * invDirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirnY * upZ - dirnZ * upY; rightY = dirnZ * upX - dirnX * upZ; rightZ = dirnX * upY - dirnY * upX; // normalize right float invRightLength = 1.0f / (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX *= invRightLength; rightY *= invRightLength; rightZ *= invRightLength; // up = right x direction float upnX = rightY * dirnZ - rightZ * dirnY; float upnY = rightZ * dirnX - rightX * dirnZ; float upnZ = rightX * dirnY - rightY * dirnX; // calculate right matrix elements float rm00 = rightX; float rm01 = upnX; float rm02 = -dirnX; float rm10 = rightY; float rm11 = upnY; float rm12 = -dirnY; float rm20 = rightZ; float rm21 = upnZ; float rm22 = -dirnZ; // perform optimized matrix multiplication // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()} * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this); } /** * Set this matrix to a rotation transformation to make <code>-z</code> * point along <code>dir</code>. * <p> * This is equivalent to calling * {@link #setLookAt(Vector3f, Vector3f, Vector3f) setLookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to apply the lookalong transformation to any previous existing transformation, * use {@link #lookAlong(Vector3f, Vector3f)}. * * @see #setLookAlong(Vector3f, Vector3f) * @see #lookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAlong(Vector3f dir, Vector3f up) { return setLookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z); } /** * Set this matrix to a rotation transformation to make <code>-z</code> * point along <code>dir</code>. * <p> * This is equivalent to calling * {@link #setLookAt(float, float, float, float, float, float, float, float, float) * setLookAt()} with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to apply the lookalong transformation to any previous existing transformation, * use {@link #lookAlong(float, float, float, float, float, float) lookAlong()} * * @see #setLookAlong(float, float, float, float, float, float) * @see #lookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float dirnX = dirX * invDirLength; float dirnY = dirY * invDirLength; float dirnZ = dirZ * invDirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirnY * upZ - dirnZ * upY; rightY = dirnZ * upX - dirnX * upZ; rightZ = dirnX * upY - dirnY * upX; // normalize right float invRightLength = 1.0f / (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX *= invRightLength; rightY *= invRightLength; rightZ *= invRightLength; // up = right x direction float upnX = rightY * dirnZ - rightZ * dirnY; float upnY = rightZ * dirnX - rightX * dirnZ; float upnZ = rightX * dirnY - rightY * dirnX; m00 = rightX; m01 = upnX; m02 = -dirnX; m03 = 0.0f; m10 = rightY; m11 = upnY; m12 = -dirnY; m13 = 0.0f; m20 = rightZ; m21 = upnZ; m22 = -dirnZ; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a "lookat" transformation for a right-handed coordinate system, that aligns * <code>-z</code> with <code>center - eye</code>. * <p> * In order to not make use of vectors to specify <code>eye</code>, <code>center</code> and <code>up</code> but use primitives, * like in the GLU function, use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()} * instead. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt()}. * * @see #setLookAt(float, float, float, float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAt(Vector3f eye, Vector3f center, Vector3f up) { return setLookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z); } /** * Set this matrix to be a "lookat" transformation for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt}. * * @see #setLookAt(Vector3f, Vector3f, Vector3f) * @see #lookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = eyeX - centerX; dirY = eyeY - centerY; dirZ = eyeZ - centerZ; // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLength; dirY *= invDirLength; dirZ *= invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * dirZ - upZ * dirY; leftY = upZ * dirX - upX * dirZ; leftZ = upX * dirY - upY * dirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = dirY * leftZ - dirZ * leftY; float upnY = dirZ * leftX - dirX * leftZ; float upnZ = dirX * leftY - dirY * leftX; m00 = leftX; m01 = upnX; m02 = dirX; m03 = 0.0f; m10 = leftY; m11 = upnY; m12 = dirY; m13 = 0.0f; m20 = leftZ; m21 = upnZ; m22 = dirZ; m23 = 0.0f; m30 = -(leftX * eyeX + leftY * eyeY + leftZ * eyeZ); m31 = -(upnX * eyeX + upnY * eyeY + upnZ * eyeZ); m32 = -(dirX * eyeX + dirY * eyeY + dirZ * eyeZ); m33 = 1.0f; return this; } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(Vector3f, Vector3f, Vector3f)}. * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @param dest * will hold the result * @return dest */ public Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up, Matrix4f dest) { return lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, dest); } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(Vector3f, Vector3f, Vector3f)}. * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up) { return lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, this); } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()}. * * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return dest */ public Matrix4f lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = eyeX - centerX; dirY = eyeY - centerY; dirZ = eyeZ - centerZ; // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLength; dirY *= invDirLength; dirZ *= invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * dirZ - upZ * dirY; leftY = upZ * dirX - upX * dirZ; leftZ = upX * dirY - upY * dirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = dirY * leftZ - dirZ * leftY; float upnY = dirZ * leftX - dirX * leftZ; float upnZ = dirX * leftY - dirY * leftX; // calculate right matrix elements float rm00 = leftX; float rm01 = upnX; float rm02 = dirX; float rm10 = leftY; float rm11 = upnY; float rm12 = dirY; float rm20 = leftZ; float rm21 = upnZ; float rm22 = dirZ; float rm30 = -(leftX * eyeX + leftY * eyeY + leftZ * eyeZ); float rm31 = -(upnX * eyeX + upnY * eyeY + upnZ * eyeZ); float rm32 = -(dirX * eyeX + dirY * eyeY + dirZ * eyeZ); // perform optimized matrix multiplication // compute last column first, because others do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return dest; } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()}. * * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { return lookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, this); } /** * Set this matrix to be a "lookat" transformation for a left-handed coordinate system, that aligns * <code>+z</code> with <code>center - eye</code>. * <p> * In order to not make use of vectors to specify <code>eye</code>, <code>center</code> and <code>up</code> but use primitives, * like in the GLU function, use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()} * instead. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAtLH(Vector3f, Vector3f, Vector3f) lookAt()}. * * @see #setLookAtLH(float, float, float, float, float, float, float, float, float) * @see #lookAtLH(Vector3f, Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAtLH(Vector3f eye, Vector3f center, Vector3f up) { return setLookAtLH(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z); } /** * Set this matrix to be a "lookat" transformation for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code>. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAtLH(float, float, float, float, float, float, float, float, float) lookAtLH}. * * @see #setLookAtLH(Vector3f, Vector3f, Vector3f) * @see #lookAtLH(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = centerX - eyeX; dirY = centerY - eyeY; dirZ = centerZ - eyeZ; // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLength; dirY *= invDirLength; dirZ *= invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * dirZ - upZ * dirY; leftY = upZ * dirX - upX * dirZ; leftZ = upX * dirY - upY * dirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = dirY * leftZ - dirZ * leftY; float upnY = dirZ * leftX - dirX * leftZ; float upnZ = dirX * leftY - dirY * leftX; m00 = leftX; m01 = upnX; m02 = dirX; m03 = 0.0f; m10 = leftY; m11 = upnY; m12 = dirY; m13 = 0.0f; m20 = leftZ; m21 = upnZ; m22 = dirZ; m23 = 0.0f; m30 = -(leftX * eyeX + leftY * eyeY + leftZ * eyeZ); m31 = -(upnX * eyeX + upnY * eyeY + upnZ * eyeZ); m32 = -(dirX * eyeX + dirY * eyeY + dirZ * eyeZ); m33 = 1.0f; return this; } /** * Apply a "lookat" transformation to this matrix for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAtLH(Vector3f, Vector3f, Vector3f)}. * * @see #lookAtLH(float, float, float, float, float, float, float, float, float) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @param dest * will hold the result * @return dest */ public Matrix4f lookAtLH(Vector3f eye, Vector3f center, Vector3f up, Matrix4f dest) { return lookAtLH(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, dest); } /** * Apply a "lookat" transformation to this matrix for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAtLH(Vector3f, Vector3f, Vector3f)}. * * @see #lookAtLH(float, float, float, float, float, float, float, float, float) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f lookAtLH(Vector3f eye, Vector3f center, Vector3f up) { return lookAtLH(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, this); } /** * Apply a "lookat" transformation to this matrix for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. * * @see #lookAtLH(Vector3f, Vector3f, Vector3f) * @see #setLookAtLH(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return dest */ public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = centerX - eyeX; dirY = centerY - eyeY; dirZ = centerZ - eyeZ; // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLength; dirY *= invDirLength; dirZ *= invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * dirZ - upZ * dirY; leftY = upZ * dirX - upX * dirZ; leftZ = upX * dirY - upY * dirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = dirY * leftZ - dirZ * leftY; float upnY = dirZ * leftX - dirX * leftZ; float upnZ = dirX * leftY - dirY * leftX; // calculate right matrix elements float rm00 = leftX; float rm01 = upnX; float rm02 = dirX; float rm10 = leftY; float rm11 = upnY; float rm12 = dirY; float rm20 = leftZ; float rm21 = upnZ; float rm22 = dirZ; float rm30 = -(leftX * eyeX + leftY * eyeY + leftZ * eyeZ); float rm31 = -(upnX * eyeX + upnY * eyeY + upnZ * eyeZ); float rm32 = -(dirX * eyeX + dirY * eyeY + dirZ * eyeZ); // perform optimized matrix multiplication // compute last column first, because others do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return dest; } /** * Apply a "lookat" transformation to this matrix for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. * * @see #lookAtLH(Vector3f, Vector3f, Vector3f) * @see #setLookAtLH(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { return lookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, this); } /** * Apply a symmetric perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float, boolean) setPerspective}. * * @see #setPerspective(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return dest */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { float h = (float) Math.tan(fovy * 0.5f); // calculate right matrix elements float rm00 = 1.0f / (h * aspect); float rm11 = 1.0f / h; float rm22; float rm32; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; rm22 = e - 1.0f; rm32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; rm22 = (zZeroToOne ? 0.0f : 1.0f) - e; rm32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { rm22 = (zZeroToOne ? zFar : zFar + zNear) / (zNear - zFar); rm32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } // perform optimized matrix multiplication float nm20 = m20 * rm22 - m30; float nm21 = m21 * rm22 - m31; float nm22 = m22 * rm22 - m32; float nm23 = m23 * rm22 - m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return dest; } /** * Apply a symmetric perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float) setPerspective}. * * @see #setPerspective(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @return dest */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, Matrix4f dest) { return perspective(fovy, aspect, zNear, zFar, false, dest); } /** * Apply a symmetric perspective projection frustum transformation using for a right-handed coordinate system * the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float, boolean) setPerspective}. * * @see #setPerspective(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { return perspective(fovy, aspect, zNear, zFar, zZeroToOne, this); } /** * Apply a symmetric perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float) setPerspective}. * * @see #setPerspective(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar) { return perspective(fovy, aspect, zNear, zFar, this); } /** * Set this matrix to be a symmetric perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspective(float, float, float, float, boolean) perspective()}. * * @see #perspective(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { float h = (float) Math.tan(fovy * 0.5f); m00 = 1.0f / (h * aspect); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f / h; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; m22 = e - 1.0f; m32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; m22 = (zZeroToOne ? 0.0f : 1.0f) - e; m32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { m22 = (zZeroToOne ? zFar : zFar + zNear) / (zNear - zFar); m32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } m23 = -1.0f; m30 = 0.0f; m31 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be a symmetric perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspective(float, float, float, float) perspective()}. * * @see #perspective(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar) { return setPerspective(fovy, aspect, zNear, zFar, false); } /** * Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspectiveLH(float, float, float, float, boolean) setPerspectiveLH}. * * @see #setPerspectiveLH(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @param dest * will hold the result * @return dest */ public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { float h = (float) Math.tan(fovy * 0.5f); // calculate right matrix elements float rm00 = 1.0f / (h * aspect); float rm11 = 1.0f / h; float rm22; float rm32; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; rm22 = 1.0f - e; rm32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; rm22 = (zZeroToOne ? 0.0f : 1.0f) - e; rm32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { rm22 = (zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear); rm32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } // perform optimized matrix multiplication float nm20 = m20 * rm22 + m30; float nm21 = m21 * rm22 + m31; float nm22 = m22 * rm22 + m32; float nm23 = m23 * rm22 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return dest; } /** * Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspectiveLH(float, float, float, float, boolean) setPerspectiveLH}. * * @see #setPerspectiveLH(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { return perspectiveLH(fovy, aspect, zNear, zFar, zZeroToOne, this); } /** * Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspectiveLH(float, float, float, float) setPerspectiveLH}. * * @see #setPerspectiveLH(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @return dest */ public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar, Matrix4f dest) { return perspectiveLH(fovy, aspect, zNear, zFar, false, dest); } /** * Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspectiveLH(float, float, float, float) setPerspectiveLH}. * * @see #setPerspectiveLH(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar) { return perspectiveLH(fovy, aspect, zNear, zFar, this); } /** * Set this matrix to be a symmetric perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspectiveLH(float, float, float, float, boolean) perspectiveLH()}. * * @see #perspectiveLH(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setPerspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { float h = (float) Math.tan(fovy * 0.5f); m00 = 1.0f / (h * aspect); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f / h; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; m22 = 1.0f - e; m32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; m22 = (zZeroToOne ? 0.0f : 1.0f) - e; m32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { m22 = (zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear); m32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } m23 = 1.0f; m30 = 0.0f; m31 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be a symmetric perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspectiveLH(float, float, float, float) perspectiveLH()}. * * @see #perspectiveLH(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f setPerspectiveLH(float fovy, float aspect, float zNear, float zFar) { return setPerspectiveLH(fovy, aspect, zNear, zFar, false); } /** * Apply an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float, boolean) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @param dest * will hold the result * @return dest */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { // calculate right matrix elements float rm00 = (zNear + zNear) / (right - left); float rm11 = (zNear + zNear) / (top - bottom); float rm20 = (right + left) / (right - left); float rm21 = (top + bottom) / (top - bottom); float rm22; float rm32; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; rm22 = e - 1.0f; rm32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; rm22 = (zZeroToOne ? 0.0f : 1.0f) - e; rm32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { rm22 = (zZeroToOne ? zFar : zFar + zNear) / (zNear - zFar); rm32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } // perform optimized matrix multiplication float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 - m30; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 - m31; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 - m32; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 - m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @return dest */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { return frustum(left, right, bottom, top, zNear, zFar, false, dest); } /** * Apply an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float, boolean) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { return frustum(left, right, bottom, top, zNear, zFar, zZeroToOne, this); } /** * Apply an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar) { return frustum(left, right, bottom, top, zNear, zFar, this); } /** * Set this matrix to be an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustum(float, float, float, float, float, float, boolean) frustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustum(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setFrustum(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { m00 = (zNear + zNear) / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = (zNear + zNear) / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = (right + left) / (right - left); m21 = (top + bottom) / (top - bottom); boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; m22 = e - 1.0f; m32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; m22 = (zZeroToOne ? 0.0f : 1.0f) - e; m32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { m22 = (zZeroToOne ? zFar : zFar + zNear) / (zNear - zFar); m32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } m23 = -1.0f; m30 = 0.0f; m31 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f setFrustum(float left, float right, float bottom, float top, float zNear, float zFar) { return setFrustum(left, right, bottom, top, zNear, zFar, false); } /** * Apply an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustumLH(float, float, float, float, float, float, boolean) setFrustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustumLH(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @param dest * will hold the result * @return dest */ public Matrix4f frustumLH(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { // calculate right matrix elements float rm00 = (zNear + zNear) / (right - left); float rm11 = (zNear + zNear) / (top - bottom); float rm20 = (right + left) / (right - left); float rm21 = (top + bottom) / (top - bottom); float rm22; float rm32; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; rm22 = 1.0f - e; rm32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; rm22 = (zZeroToOne ? 0.0f : 1.0f) - e; rm32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { rm22 = (zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear); rm32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } // perform optimized matrix multiplication float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 + m30; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 + m31; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 + m32; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustumLH(float, float, float, float, float, float, boolean) setFrustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustumLH(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f frustumLH(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { return frustumLH(left, right, bottom, top, zNear, zFar, zZeroToOne, this); } /** * Apply an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustumLH(float, float, float, float, float, float) setFrustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustumLH(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @return dest */ public Matrix4f frustumLH(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { return frustumLH(left, right, bottom, top, zNear, zFar, false, dest); } /** * Apply an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustumLH(float, float, float, float, float, float) setFrustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustumLH(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f frustumLH(float left, float right, float bottom, float top, float zNear, float zFar) { return frustumLH(left, right, bottom, top, zNear, zFar, this); } /** * Set this matrix to be an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustumLH(float, float, float, float, float, float, boolean) frustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustumLH(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setFrustumLH(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { m00 = (zNear + zNear) / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = (zNear + zNear) / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = (right + left) / (right - left); m21 = (top + bottom) / (top - bottom); boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; m22 = 1.0f - e; m32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; m22 = (zZeroToOne ? 0.0f : 1.0f) - e; m32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { m22 = (zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear); m32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } m23 = 1.0f; m30 = 0.0f; m31 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustumLH(float, float, float, float, float, float) frustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustumLH(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f setFrustumLH(float left, float right, float bottom, float top, float zNear, float zFar) { return setFrustumLH(left, right, bottom, top, zNear, zFar, false); } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix and store * the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @param dest * will hold the result * @return dest */ public Matrix4f rotate(Quaternionf quat, Matrix4f dest) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; float rm00 = 1.0f - q11 - q22; float rm01 = q01 + q23; float rm02 = q02 - q13; float rm10 = q01 - q23; float rm11 = 1.0f - q22 - q00; float rm12 = q12 + q03; float rm20 = q02 + q13; float rm21 = q12 - q03; float rm22 = 1.0f - q11 - q00; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotate(Quaternionf quat) { return rotate(quat, this); } /** * Apply the rotation transformation of the given {@link Quaternionf} to this {@link #isAffine() affine} matrix and store * the result in <code>dest</code>. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffine(Quaternionf quat, Matrix4f dest) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; float rm00 = 1.0f - q11 - q22; float rm01 = q01 + q23; float rm02 = q02 - q13; float rm10 = q01 - q23; float rm11 = 1.0f - q22 - q00; float rm12 = q12 + q03; float rm20 = q02 + q13; float rm21 = q12 - q03; float rm22 = 1.0f - q11 - q00; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = 0.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = 0.0f; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = 0.0f; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotateAffine(Quaternionf quat) { return rotateAffine(quat, this); } /** * Pre-multiply the rotation transformation of the given {@link Quaternionf} to this {@link #isAffine() affine} matrix and store * the result in <code>dest</code>. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>Q * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>Q * M * v</code>, * the quaternion rotation will be applied last! * <p> * In order to set the matrix to a rotation transformation without pre-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineLocal(Quaternionf quat, Matrix4f dest) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; float lm00 = 1.0f - q11 - q22; float lm01 = q01 + q23; float lm02 = q02 - q13; float lm10 = q01 - q23; float lm11 = 1.0f - q22 - q00; float lm12 = q12 + q03; float lm20 = q02 + q13; float lm21 = q12 - q03; float lm22 = 1.0f - q11 - q00; float nm00 = lm00 * m00 + lm10 * m01 + lm20 * m02; float nm01 = lm01 * m00 + lm11 * m01 + lm21 * m02; float nm02 = lm02 * m00 + lm12 * m01 + lm22 * m02; float nm03 = 0.0f; float nm10 = lm00 * m10 + lm10 * m11 + lm20 * m12; float nm11 = lm01 * m10 + lm11 * m11 + lm21 * m12; float nm12 = lm02 * m10 + lm12 * m11 + lm22 * m12; float nm13 = 0.0f; float nm20 = lm00 * m20 + lm10 * m21 + lm20 * m22; float nm21 = lm01 * m20 + lm11 * m21 + lm21 * m22; float nm22 = lm02 * m20 + lm12 * m21 + lm22 * m22; float nm23 = 0.0f; float nm30 = lm00 * m30 + lm10 * m31 + lm20 * m32; float nm31 = lm01 * m30 + lm11 * m31 + lm21 * m32; float nm32 = lm02 * m30 + lm12 * m31 + lm22 * m32; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Pre-multiply the rotation transformation of the given {@link Quaternionf} to this matrix. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>Q * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>Q * M * v</code>, * the quaternion rotation will be applied last! * <p> * In order to set the matrix to a rotation transformation without pre-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotateAffineLocal(Quaternionf quat) { return rotateAffineLocal(quat, this); } /** * Apply a rotation transformation, rotating about the given {@link AxisAngle4f}, to this matrix. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given {@link AxisAngle4f}, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the {@link AxisAngle4f} rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(AxisAngle4f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @return this */ public Matrix4f rotate(AxisAngle4f axisAngle) { return rotate(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); } /** * Apply a rotation transformation, rotating about the given {@link AxisAngle4f} and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given {@link AxisAngle4f}, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the {@link AxisAngle4f} rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(AxisAngle4f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @param dest * will hold the result * @return dest */ public Matrix4f rotate(AxisAngle4f axisAngle, Matrix4f dest) { return rotate(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z, dest); } /** * Apply a rotation transformation, rotating the given radians about the specified axis, to this matrix. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given axis-angle, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the axis-angle rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(float, Vector3f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(float, Vector3f) * * @param angle * the angle in radians * @param axis * the rotation axis (needs to be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f rotate(float angle, Vector3f axis) { return rotate(angle, axis.x, axis.y, axis.z); } /** * Apply a rotation transformation, rotating the given radians about the specified axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given axis-angle, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the axis-angle rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(float, Vector3f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(float, Vector3f) * * @param angle * the angle in radians * @param axis * the rotation axis (needs to be {@link Vector3f#normalize() normalized}) * @param dest * will hold the result * @return dest */ public Matrix4f rotate(float angle, Vector3f axis, Matrix4f dest) { return rotate(angle, axis.x, axis.y, axis.z, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix. * In order to avoid computing the matrix inverse with every invocation, the inverse of <code>this</code> matrix can be built * once outside using {@link #invert(Matrix4f)} and then the method {@link #unprojectInv(float, float, float, int[], Vector4f) unprojectInv()} can be invoked on it. * * @see #unprojectInv(float, float, float, int[], Vector4f) * @see #invert(Matrix4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector4f unproject(float winX, float winY, float winZ, int[] viewport, Vector4f dest) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float c = m00 * m13 - m03 * m10; float d = m01 * m12 - m02 * m11; float e = m01 * m13 - m03 * m11; float f = m02 * m13 - m03 * m12; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float i = m20 * m33 - m23 * m30; float j = m21 * m32 - m22 * m31; float k = m21 * m33 - m23 * m31; float l = m22 * m33 - m23 * m32; float det = a * l - b * k + c * j + d * i - e * h + f * g; det = 1.0f / det; float im00 = ( m11 * l - m12 * k + m13 * j) * det; float im01 = (-m01 * l + m02 * k - m03 * j) * det; float im02 = ( m31 * f - m32 * e + m33 * d) * det; float im03 = (-m21 * f + m22 * e - m23 * d) * det; float im10 = (-m10 * l + m12 * i - m13 * h) * det; float im11 = ( m00 * l - m02 * i + m03 * h) * det; float im12 = (-m30 * f + m32 * c - m33 * b) * det; float im13 = ( m20 * f - m22 * c + m23 * b) * det; float im20 = ( m10 * k - m11 * i + m13 * g) * det; float im21 = (-m00 * k + m01 * i - m03 * g) * det; float im22 = ( m30 * e - m31 * c + m33 * a) * det; float im23 = (-m20 * e + m21 * c - m23 * a) * det; float im30 = (-m10 * j + m11 * h - m12 * g) * det; float im31 = ( m00 * j - m01 * h + m02 * g) * det; float im32 = (-m30 * d + m31 * b - m32 * a) * det; float im33 = ( m20 * d - m21 * b + m22 * a) * det; float ndcX = (winX-viewport[0])/viewport[2]*2.0f-1.0f; float ndcY = (winY-viewport[1])/viewport[3]*2.0f-1.0f; float ndcZ = winZ+winZ-1.0f; dest.x = im00 * ndcX + im10 * ndcY + im20 * ndcZ + im30; dest.y = im01 * ndcX + im11 * ndcY + im21 * ndcZ + im31; dest.z = im02 * ndcX + im12 * ndcY + im22 * ndcZ + im32; dest.w = im03 * ndcX + im13 * ndcY + im23 * ndcZ + im33; dest.div(dest.w); return dest; } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix. * In order to avoid computing the matrix inverse with every invocation, the inverse of <code>this</code> matrix can be built * once outside using {@link #invert(Matrix4f)} and then the method {@link #unprojectInv(float, float, float, int[], Vector4f) unprojectInv()} can be invoked on it. * * @see #unprojectInv(float, float, float, int[], Vector3f) * @see #invert(Matrix4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector3f unproject(float winX, float winY, float winZ, int[] viewport, Vector3f dest) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float c = m00 * m13 - m03 * m10; float d = m01 * m12 - m02 * m11; float e = m01 * m13 - m03 * m11; float f = m02 * m13 - m03 * m12; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float i = m20 * m33 - m23 * m30; float j = m21 * m32 - m22 * m31; float k = m21 * m33 - m23 * m31; float l = m22 * m33 - m23 * m32; float det = a * l - b * k + c * j + d * i - e * h + f * g; det = 1.0f / det; float im00 = ( m11 * l - m12 * k + m13 * j) * det; float im01 = (-m01 * l + m02 * k - m03 * j) * det; float im02 = ( m31 * f - m32 * e + m33 * d) * det; float im03 = (-m21 * f + m22 * e - m23 * d) * det; float im10 = (-m10 * l + m12 * i - m13 * h) * det; float im11 = ( m00 * l - m02 * i + m03 * h) * det; float im12 = (-m30 * f + m32 * c - m33 * b) * det; float im13 = ( m20 * f - m22 * c + m23 * b) * det; float im20 = ( m10 * k - m11 * i + m13 * g) * det; float im21 = (-m00 * k + m01 * i - m03 * g) * det; float im22 = ( m30 * e - m31 * c + m33 * a) * det; float im23 = (-m20 * e + m21 * c - m23 * a) * det; float im30 = (-m10 * j + m11 * h - m12 * g) * det; float im31 = ( m00 * j - m01 * h + m02 * g) * det; float im32 = (-m30 * d + m31 * b - m32 * a) * det; float im33 = ( m20 * d - m21 * b + m22 * a) * det; float ndcX = (winX-viewport[0])/viewport[2]*2.0f-1.0f; float ndcY = (winY-viewport[1])/viewport[3]*2.0f-1.0f; float ndcZ = winZ+winZ-1.0f; dest.x = im00 * ndcX + im10 * ndcY + im20 * ndcZ + im30; dest.y = im01 * ndcX + im11 * ndcY + im21 * ndcZ + im31; dest.z = im02 * ndcX + im12 * ndcY + im22 * ndcZ + im32; float w = im03 * ndcX + im13 * ndcY + im23 * ndcZ + im33; dest.div(w); return dest; } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix. * In order to avoid computing the matrix inverse with every invocation, the inverse of <code>this</code> matrix can be built * once outside using {@link #invert(Matrix4f)} and then the method {@link #unprojectInv(float, float, float, int[], Vector4f) unprojectInv()} can be invoked on it. * * @see #unprojectInv(float, float, float, int[], Vector4f) * @see #unproject(float, float, float, int[], Vector4f) * @see #invert(Matrix4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector4f unproject(Vector3f winCoords, int[] viewport, Vector4f dest) { return unproject(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix. * In order to avoid computing the matrix inverse with every invocation, the inverse of <code>this</code> matrix can be built * once outside using {@link #invert(Matrix4f)} and then the method {@link #unprojectInv(float, float, float, int[], Vector3f) unprojectInv()} can be invoked on it. * * @see #unprojectInv(float, float, float, int[], Vector3f) * @see #unproject(float, float, float, int[], Vector3f) * @see #invert(Matrix4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector3f unproject(Vector3f winCoords, int[] viewport, Vector3f dest) { return unproject(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(Vector3f, int[], Vector4f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current int[]'s {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(Vector3f, int[], Vector4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector4f unprojectInv(Vector3f winCoords, int[] viewport, Vector4f dest) { return unprojectInv(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(float, float, float, int[], Vector4f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #unproject(float, float, float, int[], Vector4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector4f unprojectInv(float winX, float winY, float winZ, int[] viewport, Vector4f dest) { float ndcX = (winX-viewport[0])/viewport[2]*2.0f-1.0f; float ndcY = (winY-viewport[1])/viewport[3]*2.0f-1.0f; float ndcZ = winZ+winZ-1.0f; dest.x = m00 * ndcX + m10 * ndcY + m20 * ndcZ + m30; dest.y = m01 * ndcX + m11 * ndcY + m21 * ndcZ + m31; dest.z = m02 * ndcX + m12 * ndcY + m22 * ndcZ + m32; dest.w = m03 * ndcX + m13 * ndcY + m23 * ndcZ + m33; dest.div(dest.w); return dest; } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(Vector3f, int[], Vector3f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #unproject(Vector3f, int[], Vector3f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector3f unprojectInv(Vector3f winCoords, int[] viewport, Vector3f dest) { return unprojectInv(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(float, float, float, int[], Vector3f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #unproject(float, float, float, int[], Vector3f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector3f unprojectInv(float winX, float winY, float winZ, int[] viewport, Vector3f dest) { float ndcX = (winX-viewport[0])/viewport[2]*2.0f-1.0f; float ndcY = (winY-viewport[1])/viewport[3]*2.0f-1.0f; float ndcZ = winZ+winZ-1.0f; dest.x = m00 * ndcX + m10 * ndcY + m20 * ndcZ + m30; dest.y = m01 * ndcX + m11 * ndcY + m21 * ndcZ + m31; dest.z = m02 * ndcX + m12 * ndcY + m22 * ndcZ + m32; float w = m03 * ndcX + m13 * ndcY + m23 * ndcZ + m33; dest.div(w); return dest; } /** * Project the given <tt>(x, y, z)</tt> position via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return winCoordsDest */ public Vector4f project(float x, float y, float z, int[] viewport, Vector4f winCoordsDest) { winCoordsDest.x = m00 * x + m10 * y + m20 * z + m30; winCoordsDest.y = m01 * x + m11 * y + m21 * z + m31; winCoordsDest.z = m02 * x + m12 * y + m22 * z + m32; winCoordsDest.w = m03 * x + m13 * y + m23 * z + m33; winCoordsDest.div(winCoordsDest.w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport[2] + viewport[0]; winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport[3] + viewport[1]; winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; return winCoordsDest; } /** * Project the given <tt>(x, y, z)</tt> position via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return winCoordsDest */ public Vector3f project(float x, float y, float z, int[] viewport, Vector3f winCoordsDest) { winCoordsDest.x = m00 * x + m10 * y + m20 * z + m30; winCoordsDest.y = m01 * x + m11 * y + m21 * z + m31; winCoordsDest.z = m02 * x + m12 * y + m22 * z + m32; float w = m03 * x + m13 * y + m23 * z + m33; winCoordsDest.div(w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport[2] + viewport[0]; winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport[3] + viewport[1]; winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; return winCoordsDest; } /** * Project the given <code>position</code> via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, int[], Vector4f) * * @param position * the position to project into window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return winCoordsDest */ public Vector4f project(Vector3f position, int[] viewport, Vector4f winCoordsDest) { return project(position.x, position.y, position.z, viewport, winCoordsDest); } /** * Project the given <code>position</code> via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, int[], Vector4f) * * @param position * the position to project into window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return winCoordsDest */ public Vector3f project(Vector3f position, int[] viewport, Vector3f winCoordsDest) { return project(position.x, position.y, position.z, viewport, winCoordsDest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt> and store the result in <code>dest</code>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return dest */ public Matrix4f reflect(float a, float b, float c, float d, Matrix4f dest) { float da = a + a, db = b + b, dc = c + c, dd = d + d; float rm00 = 1.0f - da * a; float rm01 = -da * b; float rm02 = -da * c; float rm10 = -db * a; float rm11 = 1.0f - db * b; float rm12 = -db * c; float rm20 = -dc * a; float rm21 = -dc * b; float rm22 = 1.0f - dc * c; float rm30 = -dd * a; float rm31 = -dd * b; float rm32 = -dd * c; // matrix multiplication dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return dest; } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f reflect(float a, float b, float c, float d) { return reflect(a, b, c, d, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @return this */ public Matrix4f reflect(float nx, float ny, float nz, float px, float py, float pz) { return reflect(nx, ny, nz, px, py, pz, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane, and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @param dest * will hold the result * @return dest */ public Matrix4f reflect(float nx, float ny, float nz, float px, float py, float pz, Matrix4f dest) { float invLength = 1.0f / (float) Math.sqrt(nx * nx + ny * ny + nz * nz); float nnx = nx * invLength; float nny = ny * invLength; float nnz = nz * invLength; /* See: http://mathworld.wolfram.com/Plane.html */ return reflect(nnx, nny, nnz, -nnx * px - nny * py - nnz * pz, dest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param normal * the plane normal * @param point * a point on the plane * @return this */ public Matrix4f reflect(Vector3f normal, Vector3f point) { return reflect(normal.x, normal.y, normal.z, point.x, point.y, point.z); } /** * Apply a mirror/reflection transformation to this matrix that reflects about a plane * specified via the plane orientation and a point on the plane. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param orientation * the plane orientation * @param point * a point on the plane * @return this */ public Matrix4f reflect(Quaternionf orientation, Vector3f point) { return reflect(orientation, point, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about a plane * specified via the plane orientation and a point on the plane, and store the result in <code>dest</code>. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param orientation * the plane orientation relative to an implied normal vector of <tt>(0, 0, 1)</tt> * @param point * a point on the plane * @param dest * will hold the result * @return dest */ public Matrix4f reflect(Quaternionf orientation, Vector3f point, Matrix4f dest) { double num1 = orientation.x + orientation.x; double num2 = orientation.y + orientation.y; double num3 = orientation.z + orientation.z; float normalX = (float) (orientation.x * num3 + orientation.w * num2); float normalY = (float) (orientation.y * num3 - orientation.w * num1); float normalZ = (float) (1.0 - (orientation.x * num1 + orientation.y * num2)); return reflect(normalX, normalY, normalZ, point.x, point.y, point.z, dest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane, and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param normal * the plane normal * @param point * a point on the plane * @param dest * will hold the result * @return dest */ public Matrix4f reflect(Vector3f normal, Vector3f point, Matrix4f dest) { return reflect(normal.x, normal.y, normal.z, point.x, point.y, point.z, dest); } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f reflection(float a, float b, float c, float d) { float da = a + a, db = b + b, dc = c + c, dd = d + d; m00 = 1.0f - da * a; m01 = -da * b; m02 = -da * c; m03 = 0.0f; m10 = -db * a; m11 = 1.0f - db * b; m12 = -db * c; m13 = 0.0f; m20 = -dc * a; m21 = -dc * b; m22 = 1.0f - dc * c; m23 = 0.0f; m30 = -dd * a; m31 = -dd * b; m32 = -dd * c; m33 = 1.0f; return this; } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the plane normal and a point on the plane. * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @return this */ public Matrix4f reflection(float nx, float ny, float nz, float px, float py, float pz) { float invLength = 1.0f / (float) Math.sqrt(nx * nx + ny * ny + nz * nz); float nnx = nx * invLength; float nny = ny * invLength; float nnz = nz * invLength; /* See: http://mathworld.wolfram.com/Plane.html */ return reflection(nnx, nny, nnz, -nnx * px - nny * py - nnz * pz); } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the plane normal and a point on the plane. * * @param normal * the plane normal * @param point * a point on the plane * @return this */ public Matrix4f reflection(Vector3f normal, Vector3f point) { return reflection(normal.x, normal.y, normal.z, point.x, point.y, point.z); } /** * Set this matrix to a mirror/reflection transformation that reflects about a plane * specified via the plane orientation and a point on the plane. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * * @param orientation * the plane orientation * @param point * a point on the plane * @return this */ public Matrix4f reflection(Quaternionf orientation, Vector3f point) { double num1 = orientation.x + orientation.x; double num2 = orientation.y + orientation.y; double num3 = orientation.z + orientation.z; float normalX = (float) (orientation.x * num3 + orientation.w * num2); float normalY = (float) (orientation.y * num3 - orientation.w * num1); float normalZ = (float) (1.0 - (orientation.x * num1 + orientation.y * num2)); return reflection(normalX, normalY, normalZ, point.x, point.y, point.z); } /** * Get the row at the given <code>row</code> index, starting with <code>0</code>. * * @param row * the row index in <tt>[0..3]</tt> * @param dest * will hold the row components * @return the passed in destination * @throws IndexOutOfBoundsException if <code>row</code> is not in <tt>[0..3]</tt> */ public Vector4f getRow(int row, Vector4f dest) throws IndexOutOfBoundsException { switch (row) { case 0: dest.x = m00; dest.y = m10; dest.z = m20; dest.w = m30; break; case 1: dest.x = m01; dest.y = m11; dest.z = m21; dest.w = m31; break; case 2: dest.x = m02; dest.y = m12; dest.z = m22; dest.w = m32; break; case 3: dest.x = m03; dest.y = m13; dest.z = m23; dest.w = m33; break; default: throw new IndexOutOfBoundsException(); } return dest; } /** * Get the column at the given <code>column</code> index, starting with <code>0</code>. * * @param column * the column index in <tt>[0..3]</tt> * @param dest * will hold the column components * @return the passed in destination * @throws IndexOutOfBoundsException if <code>column</code> is not in <tt>[0..3]</tt> */ public Vector4f getColumn(int column, Vector4f dest) throws IndexOutOfBoundsException { switch (column) { case 0: dest.x = m00; dest.y = m01; dest.z = m02; dest.w = m03; break; case 1: dest.x = m10; dest.y = m11; dest.z = m12; dest.w = m13; break; case 2: dest.x = m20; dest.y = m21; dest.z = m22; dest.w = m23; break; case 3: dest.x = m30; dest.y = m31; dest.z = m32; dest.w = m32; break; default: throw new IndexOutOfBoundsException(); } return dest; } /** * Compute a normal matrix from the upper left 3x3 submatrix of <code>this</code> * and store it into the upper left 3x3 submatrix of <code>this</code>. * All other values of <code>this</code> will be set to {@link #identity() identity}. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * <p> * Please note that, if <code>this</code> is an orthogonal matrix or a matrix whose columns are orthogonal vectors, * then this method <i>need not</i> be invoked, since in that case <code>this</code> itself is its normal matrix. * In that case, use {@link #set3x3(Matrix4f)} to set a given Matrix4f to only the upper left 3x3 submatrix * of this matrix. * * @see #set3x3(Matrix4f) * * @return this */ public Matrix4f normal() { return normal(this); } /** * Compute a normal matrix from the upper left 3x3 submatrix of <code>this</code> * and store it into the upper left 3x3 submatrix of <code>dest</code>. * All other values of <code>dest</code> will be set to {@link #identity() identity}. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * <p> * Please note that, if <code>this</code> is an orthogonal matrix or a matrix whose columns are orthogonal vectors, * then this method <i>need not</i> be invoked, since in that case <code>this</code> itself is its normal matrix. * In that case, use {@link #set3x3(Matrix4f)} to set a given Matrix4f to only the upper left 3x3 submatrix * of this matrix. * * @see #set3x3(Matrix4f) * * @param dest * will hold the result * @return dest */ public Matrix4f normal(Matrix4f dest) { float det = determinant3x3(); float s = 1.0f / det; /* Invert and transpose in one go */ float nm00 = (m11 * m22 - m21 * m12) * s; float nm01 = (m20 * m12 - m10 * m22) * s; float nm02 = (m10 * m21 - m20 * m11) * s; float nm03 = 0.0f; float nm10 = (m21 * m02 - m01 * m22) * s; float nm11 = (m00 * m22 - m20 * m02) * s; float nm12 = (m20 * m01 - m00 * m21) * s; float nm13 = 0.0f; float nm20 = (m01 * m12 - m11 * m02) * s; float nm21 = (m10 * m02 - m00 * m12) * s; float nm22 = (m00 * m11 - m10 * m01) * s; float nm23 = 0.0f; float nm30 = 0.0f; float nm31 = 0.0f; float nm32 = 0.0f; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Compute a normal matrix from the upper left 3x3 submatrix of <code>this</code> * and store it into <code>dest</code>. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * <p> * Please note that, if <code>this</code> is an orthogonal matrix or a matrix whose columns are orthogonal vectors, * then this method <i>need not</i> be invoked, since in that case <code>this</code> itself is its normal matrix. * In that case, use {@link Matrix3f#set(Matrix4f)} to set a given Matrix3f to only the upper left 3x3 submatrix * of this matrix. * * @see Matrix3f#set(Matrix4f) * @see #get3x3(Matrix3f) * * @param dest * will hold the result * @return dest */ public Matrix3f normal(Matrix3f dest) { float det = determinant3x3(); float s = 1.0f / det; /* Invert and transpose in one go */ dest.m00 = (m11 * m22 - m21 * m12) * s; dest.m01 = (m20 * m12 - m10 * m22) * s; dest.m02 = (m10 * m21 - m20 * m11) * s; dest.m10 = (m21 * m02 - m01 * m22) * s; dest.m11 = (m00 * m22 - m20 * m02) * s; dest.m12 = (m20 * m01 - m00 * m21) * s; dest.m20 = (m01 * m12 - m11 * m02) * s; dest.m21 = (m10 * m02 - m00 * m12) * s; dest.m22 = (m00 * m11 - m10 * m01) * s; return dest; } /** * Normalize the upper left 3x3 submatrix of this matrix. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @return this */ public Matrix4f normalize3x3() { return normalize3x3(this); } /** * Normalize the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @param dest * will hold the result * @return dest */ public Matrix4f normalize3x3(Matrix4f dest) { float invXlen = (float) (1.0 / Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02)); float invYlen = (float) (1.0 / Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12)); float invZlen = (float) (1.0 / Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22)); dest.m00 = m00 * invXlen; dest.m01 = m01 * invXlen; dest.m02 = m02 * invXlen; dest.m10 = m10 * invYlen; dest.m11 = m11 * invYlen; dest.m12 = m12 * invYlen; dest.m20 = m20 * invZlen; dest.m21 = m21 * invZlen; dest.m22 = m22 * invZlen; return dest; } /** * Normalize the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @param dest * will hold the result * @return dest */ public Matrix3f normalize3x3(Matrix3f dest) { float invXlen = (float) (1.0 / Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02)); float invYlen = (float) (1.0 / Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12)); float invZlen = (float) (1.0 / Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22)); dest.m00 = m00 * invXlen; dest.m01 = m01 * invXlen; dest.m02 = m02 * invXlen; dest.m10 = m10 * invYlen; dest.m11 = m11 * invYlen; dest.m12 = m12 * invYlen; dest.m20 = m20 * invZlen; dest.m21 = m21 * invZlen; dest.m22 = m22 * invZlen; return dest; } /** * Calculate a frustum plane of <code>this</code> matrix, which * can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>planeEquation</code>. * <p> * Generally, this method computes the frustum plane in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The frustum plane will be given in the form of a general plane equation: * <tt>a*x + b*y + c*z + d = 0</tt>, where the given {@link Vector4f} components will * hold the <tt>(a, b, c, d)</tt> values of the equation. * <p> * The plane normal, which is <tt>(a, b, c)</tt>, is directed "inwards" of the frustum. * Any plane/point test using <tt>a*x + b*y + c*z + d</tt> therefore will yield a result greater than zero * if the point is within the frustum (i.e. at the <i>positive</i> side of the frustum plane). * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param plane * one of the six possible planes, given as numeric constants * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} * @param planeEquation * will hold the computed plane equation. * The plane equation will be normalized, meaning that <tt>(a, b, c)</tt> will be a unit vector * @return planeEquation */ public Vector4f frustumPlane(int plane, Vector4f planeEquation) { switch (plane) { case PLANE_NX: planeEquation.set(m03 + m00, m13 + m10, m23 + m20, m33 + m30).normalize3(); break; case PLANE_PX: planeEquation.set(m03 - m00, m13 - m10, m23 - m20, m33 - m30).normalize3(); break; case PLANE_NY: planeEquation.set(m03 + m01, m13 + m11, m23 + m21, m33 + m31).normalize3(); break; case PLANE_PY: planeEquation.set(m03 - m01, m13 - m11, m23 - m21, m33 - m31).normalize3(); break; case PLANE_NZ: planeEquation.set(m03 + m02, m13 + m12, m23 + m22, m33 + m32).normalize3(); break; case PLANE_PZ: planeEquation.set(m03 - m02, m13 - m12, m23 - m22, m33 - m32).normalize3(); break; default: throw new IllegalArgumentException("plane"); //$NON-NLS-1$ } return planeEquation; } /** * Compute the corner coordinates of the frustum defined by <code>this</code> matrix, which * can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>point</code>. * <p> * Generally, this method computes the frustum corners in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * Reference: <a href="http://geomalgorithms.com/a05-_intersect-1.html">http://geomalgorithms.com</a> * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param corner * one of the eight possible corners, given as numeric constants * {@link #CORNER_NXNYNZ}, {@link #CORNER_PXNYNZ}, {@link #CORNER_PXPYNZ}, {@link #CORNER_NXPYNZ}, * {@link #CORNER_PXNYPZ}, {@link #CORNER_NXNYPZ}, {@link #CORNER_NXPYPZ}, {@link #CORNER_PXPYPZ} * @param point * will hold the resulting corner point coordinates * @return point */ public Vector3f frustumCorner(int corner, Vector3f point) { float d1, d2, d3; float n1x, n1y, n1z, n2x, n2y, n2z, n3x, n3y, n3z; switch (corner) { case CORNER_NXNYNZ: // left, bottom, near n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXNYNZ: // right, bottom, near n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXPYNZ: // right, top, near n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_NXPYNZ: // left, top, near n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXNYPZ: // right, bottom, far n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_NXNYPZ: // left, bottom, far n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_NXPYPZ: // left, top, far n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_PXPYPZ: // right, top, far n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; default: throw new IllegalArgumentException("corner"); //$NON-NLS-1$ } float c23x, c23y, c23z; c23x = n2y * n3z - n2z * n3y; c23y = n2z * n3x - n2x * n3z; c23z = n2x * n3y - n2y * n3x; float c31x, c31y, c31z; c31x = n3y * n1z - n3z * n1y; c31y = n3z * n1x - n3x * n1z; c31z = n3x * n1y - n3y * n1x; float c12x, c12y, c12z; c12x = n1y * n2z - n1z * n2y; c12y = n1z * n2x - n1x * n2z; c12z = n1x * n2y - n1y * n2x; float invDot = 1.0f / (n1x * c23x + n1y * c23y + n1z * c23z); point.x = (-c23x * d1 - c31x * d2 - c12x * d3) * invDot; point.y = (-c23y * d1 - c31y * d2 - c12y * d3) * invDot; point.z = (-c23z * d1 - c31z * d2 - c12z * d3) * invDot; return point; } /** * Compute the eye/origin of the perspective frustum transformation defined by <code>this</code> matrix, * which can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>origin</code>. * <p> * Note that this method will only work using perspective projections obtained via one of the * perspective methods, such as {@link #perspective(float, float, float, float) perspective()} * or {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * Generally, this method computes the origin in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * Reference: <a href="http://geomalgorithms.com/a05-_intersect-1.html">http://geomalgorithms.com</a> * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param origin * will hold the origin of the coordinate system before applying <code>this</code> * perspective projection transformation * @return origin */ public Vector3f perspectiveOrigin(Vector3f origin) { /* * Simply compute the intersection point of the left, right and top frustum plane. */ float d1, d2, d3; float n1x, n1y, n1z, n2x, n2y, n2z, n3x, n3y, n3z; n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m00; n2y = m13 - m10; n2z = m23 - m20; d2 = m33 - m30; // right n3x = m03 - m01; n3y = m13 - m11; n3z = m23 - m21; d3 = m33 - m31; // top float c23x, c23y, c23z; c23x = n2y * n3z - n2z * n3y; c23y = n2z * n3x - n2x * n3z; c23z = n2x * n3y - n2y * n3x; float c31x, c31y, c31z; c31x = n3y * n1z - n3z * n1y; c31y = n3z * n1x - n3x * n1z; c31z = n3x * n1y - n3y * n1x; float c12x, c12y, c12z; c12x = n1y * n2z - n1z * n2y; c12y = n1z * n2x - n1x * n2z; c12z = n1x * n2y - n1y * n2x; float invDot = 1.0f / (n1x * c23x + n1y * c23y + n1z * c23z); origin.x = (-c23x * d1 - c31x * d2 - c12x * d3) * invDot; origin.y = (-c23y * d1 - c31y * d2 - c12y * d3) * invDot; origin.z = (-c23z * d1 - c31z * d2 - c12z * d3) * invDot; return origin; } /** * Return the vertical field-of-view angle in radians of this perspective transformation matrix. * <p> * Note that this method will only work using perspective projections obtained via one of the * perspective methods, such as {@link #perspective(float, float, float, float) perspective()} * or {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * For orthogonal transformations this method will return <tt>0.0</tt>. * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @return the vertical field-of-view angle in radians */ public float perspectiveFov() { /* * Compute the angle between the bottom and top frustum plane normals. */ float n1x, n1y, n1z, n2x, n2y, n2z; n1x = m03 + m01; n1y = m13 + m11; n1z = m23 + m21; // bottom n2x = m01 - m03; n2y = m11 - m13; n2z = m21 - m23; // top float n1len = (float) Math.sqrt(n1x * n1x + n1y * n1y + n1z * n1z); float n2len = (float) Math.sqrt(n2x * n2x + n2y * n2y + n2z * n2z); return (float) Math.acos((n1x * n2x + n1y * n2y + n1z * n2z) / (n1len * n2len)); } /** * Extract the near clip plane distance from <code>this</code> perspective projection matrix. * <p> * This method only works if <code>this</code> is a perspective projection matrix, for example obtained via {@link #perspective(float, float, float, float)}. * * @return the near clip plane distance */ public float perspectiveNear() { return m32 / (m23 + m22); } /** * Extract the far clip plane distance from <code>this</code> perspective projection matrix. * <p> * This method only works if <code>this</code> is a perspective projection matrix, for example obtained via {@link #perspective(float, float, float, float)}. * * @return the far clip plane distance */ public float perspectiveFar() { return m32 / (m22 - m23); } /** * Obtain the direction of a ray starting at the center of the coordinate system and going * through the near frustum plane. * <p> * This method computes the <code>dir</code> vector in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The parameters <code>x</code> and <code>y</code> are used to interpolate the generated ray direction * from the bottom-left to the top-right frustum corners. * <p> * For optimal efficiency when building many ray directions over the whole frustum, * it is recommended to use this method only in order to compute the four corner rays at * <tt>(0, 0)</tt>, <tt>(1, 0)</tt>, <tt>(0, 1)</tt> and <tt>(1, 1)</tt> * and then bilinearly interpolating between them; or to use the {@link FrustumRayBuilder}. * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param x * the interpolation factor along the left-to-right frustum planes, within <tt>[0..1]</tt> * @param y * the interpolation factor along the bottom-to-top frustum planes, within <tt>[0..1]</tt> * @param dir * will hold the normalized ray direction in the local frame of the coordinate system before * transforming to homogeneous clipping space using <code>this</code> matrix * @return dir */ public Vector3f frustumRayDir(float x, float y, Vector3f dir) { /* * This method works by first obtaining the frustum plane normals, * then building the cross product to obtain the corner rays, * and finally bilinearly interpolating to obtain the desired direction. * The code below uses a condense form of doing all this making use * of some mathematical identities to simplify the overall expression. */ float a = m10 * m23, b = m13 * m21, c = m10 * m21, d = m11 * m23, e = m13 * m20, f = m11 * m20; float g = m03 * m20, h = m01 * m23, i = m01 * m20, j = m03 * m21, k = m00 * m23, l = m00 * m21; float m = m00 * m13, n = m03 * m11, o = m00 * m11, p = m01 * m13, q = m03 * m10, r = m01 * m10; float m1x, m1y, m1z; m1x = (d + e + f - a - b - c) * (1.0f - y) + (a - b - c + d - e + f) * y; m1y = (j + k + l - g - h - i) * (1.0f - y) + (g - h - i + j - k + l) * y; m1z = (p + q + r - m - n - o) * (1.0f - y) + (m - n - o + p - q + r) * y; float m2x, m2y, m2z; m2x = (b - c - d + e + f - a) * (1.0f - y) + (a + b - c - d - e + f) * y; m2y = (h - i - j + k + l - g) * (1.0f - y) + (g + h - i - j - k + l) * y; m2z = (n - o - p + q + r - m) * (1.0f - y) + (m + n - o - p - q + r) * y; dir.x = m1x + (m2x - m1x) * x; dir.y = m1y + (m2y - m1y) * x; dir.z = m1z + (m2z - m1z) * x; dir.normalize(); return dir; } /** * Obtain the direction of <tt>+Z</tt> before the transformation represented by <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Z</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invert(); * inv.transformDirection(dir.set(0, 0, 1)).normalize(); * </pre> * If <code>this</code> is already an orthogonal matrix, then consider using {@link #normalizedPositiveZ(Vector3f)} instead. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Z</tt> * @return dir */ public Vector3f positiveZ(Vector3f dir) { dir.x = m10 * m21 - m11 * m20; dir.y = m20 * m01 - m21 * m00; dir.z = m00 * m11 - m01 * m10; dir.normalize(); return dir; } /** * Obtain the direction of <tt>+Z</tt> before the transformation represented by <code>this</code> <i>orthogonal</i> matrix is applied. * This method only produces correct results if <code>this</code> is an <i>orthogonal</i> matrix. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Z</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).transpose(); * inv.transformDirection(dir.set(0, 0, 1)).normalize(); * </pre> * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Z</tt> * @return dir */ public Vector3f normalizedPositiveZ(Vector3f dir) { dir.x = m02; dir.y = m12; dir.z = m22; return dir; } /** * Obtain the direction of <tt>+X</tt> before the transformation represented by <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+X</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invert(); * inv.transformDirection(dir.set(1, 0, 0)).normalize(); * </pre> * If <code>this</code> is already an orthogonal matrix, then consider using {@link #normalizedPositiveX(Vector3f)} instead. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+X</tt> * @return dir */ public Vector3f positiveX(Vector3f dir) { dir.x = m11 * m22 - m12 * m21; dir.y = m02 * m21 - m01 * m22; dir.z = m01 * m12 - m02 * m11; dir.normalize(); return dir; } /** * Obtain the direction of <tt>+X</tt> before the transformation represented by <code>this</code> <i>orthogonal</i> matrix is applied. * This method only produces correct results if <code>this</code> is an <i>orthogonal</i> matrix. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+X</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).transpose(); * inv.transformDirection(dir.set(1, 0, 0)).normalize(); * </pre> * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+X</tt> * @return dir */ public Vector3f normalizedPositiveX(Vector3f dir) { dir.x = m00; dir.y = m10; dir.z = m20; return dir; } /** * Obtain the direction of <tt>+Y</tt> before the transformation represented by <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Y</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invert(); * inv.transformDirection(dir.set(0, 1, 0)).normalize(); * </pre> * If <code>this</code> is already an orthogonal matrix, then consider using {@link #normalizedPositiveY(Vector3f)} instead. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Y</tt> * @return dir */ public Vector3f positiveY(Vector3f dir) { dir.x = m12 * m20 - m10 * m22; dir.y = m00 * m22 - m02 * m20; dir.z = m02 * m10 - m00 * m12; dir.normalize(); return dir; } /** * Obtain the direction of <tt>+Y</tt> before the transformation represented by <code>this</code> <i>orthogonal</i> matrix is applied. * This method only produces correct results if <code>this</code> is an <i>orthogonal</i> matrix. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Y</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).transpose(); * inv.transformDirection(dir.set(0, 1, 0)).normalize(); * </pre> * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Y</tt> * @return dir */ public Vector3f normalizedPositiveY(Vector3f dir) { dir.x = m01; dir.y = m11; dir.z = m21; return dir; } /** * Obtain the position that gets transformed to the origin by <code>this</code> {@link #isAffine() affine} matrix. * This can be used to get the position of the "camera" from a given <i>view</i> transformation matrix. * <p> * This method only works with {@link #isAffine() affine} matrices. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invertAffine(); * inv.transformPosition(origin.set(0, 0, 0)); * </pre> * * @param origin * will hold the position transformed to the origin * @return origin */ public Vector3f originAffine(Vector3f origin) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float d = m01 * m12 - m02 * m11; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float j = m21 * m32 - m22 * m31; origin.x = -m10 * j + m11 * h - m12 * g; origin.y = m00 * j - m01 * h + m02 * g; origin.z = -m30 * d + m31 * b - m32 * a; return origin; } /** * Obtain the position that gets transformed to the origin by <code>this</code> matrix. * This can be used to get the position of the "camera" from a given <i>view/projection</i> transformation matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invert(); * inv.transformPosition(origin.set(0, 0, 0)); * </pre> * * @param origin * will hold the position transformed to the origin * @return origin */ public Vector3f origin(Vector3f origin) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float c = m00 * m13 - m03 * m10; float d = m01 * m12 - m02 * m11; float e = m01 * m13 - m03 * m11; float f = m02 * m13 - m03 * m12; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float i = m20 * m33 - m23 * m30; float j = m21 * m32 - m22 * m31; float k = m21 * m33 - m23 * m31; float l = m22 * m33 - m23 * m32; float det = a * l - b * k + c * j + d * i - e * h + f * g; float invDet = 1.0f / det; float nm30 = (-m10 * j + m11 * h - m12 * g) * invDet; float nm31 = ( m00 * j - m01 * h + m02 * g) * invDet; float nm32 = (-m30 * d + m31 * b - m32 * a) * invDet; float nm33 = det / ( m20 * d - m21 * b + m22 * a); float x = nm30 * nm33; float y = nm31 * nm33; float z = nm32 * nm33; return origin.set(x, y, z); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <code>light</code>. * <p> * If <tt>light.w</tt> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param light * the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f shadow(Vector4f light, float a, float b, float c, float d) { return shadow(light.x, light.y, light.z, light.w, a, b, c, d, this); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <code>light</code> * and store the result in <code>dest</code>. * <p> * If <tt>light.w</tt> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param light * the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return dest */ public Matrix4f shadow(Vector4f light, float a, float b, float c, float d, Matrix4f dest) { return shadow(light.x, light.y, light.z, light.w, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param lightX * the x-component of the light's vector * @param lightY * the y-component of the light's vector * @param lightZ * the z-component of the light's vector * @param lightW * the w-component of the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d) { return shadow(lightX, lightY, lightZ, lightW, a, b, c, d, this); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt> * and store the result in <code>dest</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param lightX * the x-component of the light's vector * @param lightY * the y-component of the light's vector * @param lightZ * the z-component of the light's vector * @param lightW * the w-component of the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return dest */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d, Matrix4f dest) { // normalize plane float invPlaneLen = (float) (1.0 / Math.sqrt(a*a + b*b + c*c)); float an = a * invPlaneLen; float bn = b * invPlaneLen; float cn = c * invPlaneLen; float dn = d * invPlaneLen; float dot = an * lightX + bn * lightY + cn * lightZ + dn * lightW; // compute right matrix elements float rm00 = dot - an * lightX; float rm01 = -an * lightY; float rm02 = -an * lightZ; float rm03 = -an * lightW; float rm10 = -bn * lightX; float rm11 = dot - bn * lightY; float rm12 = -bn * lightZ; float rm13 = -bn * lightW; float rm20 = -cn * lightX; float rm21 = -cn * lightY; float rm22 = dot - cn * lightZ; float rm23 = -cn * lightW; float rm30 = -dn * lightX; float rm31 = -dn * lightY; float rm32 = -dn * lightZ; float rm33 = dot - dn * lightW; // matrix multiplication float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02 + m30 * rm03; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02 + m31 * rm03; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02 + m32 * rm03; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02 + m33 * rm03; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12 + m30 * rm13; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12 + m31 * rm13; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12 + m32 * rm13; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12 + m33 * rm13; float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 + m30 * rm23; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 + m31 * rm23; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 + m32 * rm23; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 + m33 * rm23; dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30 * rm33; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31 * rm33; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32 * rm33; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33 * rm33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return dest; } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <code>light</code> * and store the result in <code>dest</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <tt>light.w</tt> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param light * the light's vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @param dest * will hold the result * @return dest */ public Matrix4f shadow(Vector4f light, Matrix4f planeTransform, Matrix4f dest) { // compute plane equation by transforming (y = 0) float a = planeTransform.m10; float b = planeTransform.m11; float c = planeTransform.m12; float d = -a * planeTransform.m30 - b * planeTransform.m31 - c * planeTransform.m32; return shadow(light.x, light.y, light.z, light.w, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <code>light</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <tt>light.w</tt> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param light * the light's vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @return this */ public Matrix4f shadow(Vector4f light, Matrix4f planeTransform) { return shadow(light, planeTransform, this); } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt> * and store the result in <code>dest</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param lightX * the x-component of the light vector * @param lightY * the y-component of the light vector * @param lightZ * the z-component of the light vector * @param lightW * the w-component of the light vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @param dest * will hold the result * @return dest */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, Matrix4f planeTransform, Matrix4f dest) { // compute plane equation by transforming (y = 0) float a = planeTransform.m10; float b = planeTransform.m11; float c = planeTransform.m12; float d = -a * planeTransform.m30 - b * planeTransform.m31 - c * planeTransform.m32; return shadow(lightX, lightY, lightZ, lightW, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param lightX * the x-component of the light vector * @param lightY * the y-component of the light vector * @param lightZ * the z-component of the light vector * @param lightW * the w-component of the light vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @return this */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, Matrix4f planeTransform) { return shadow(lightX, lightY, lightZ, lightW, planeTransform, this); } /** * Set this matrix to a cylindrical billboard transformation that rotates the local +Z axis of a given object with position <code>objPos</code> towards * a target position at <code>targetPos</code> while constraining a cylindrical rotation around the given <code>up</code> vector. * <p> * This method can be used to create the complete model transformation for a given object, including the translation of the object to * its position <code>objPos</code>. * * @param objPos * the position of the object to rotate towards <code>targetPos</code> * @param targetPos * the position of the target (for example the camera) towards which to rotate the object * @param up * the rotation axis (must be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f billboardCylindrical(Vector3f objPos, Vector3f targetPos, Vector3f up) { float dirX = targetPos.x - objPos.x; float dirY = targetPos.y - objPos.y; float dirZ = targetPos.z - objPos.z; // left = up x dir float leftX = up.y * dirZ - up.z * dirY; float leftY = up.z * dirX - up.x * dirZ; float leftZ = up.x * dirY - up.y * dirX; // normalize left float invLeftLen = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLen; leftY *= invLeftLen; leftZ *= invLeftLen; // recompute dir by constraining rotation around 'up' // dir = left x up dirX = leftY * up.z - leftZ * up.y; dirY = leftZ * up.x - leftX * up.z; dirZ = leftX * up.y - leftY * up.x; // normalize dir float invDirLen = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLen; dirY *= invDirLen; dirZ *= invDirLen; // set matrix elements m00 = leftX; m01 = leftY; m02 = leftZ; m03 = 0.0f; m10 = up.x; m11 = up.y; m12 = up.z; m13 = 0.0f; m20 = dirX; m21 = dirY; m22 = dirZ; m23 = 0.0f; m30 = objPos.x; m31 = objPos.y; m32 = objPos.z; m33 = 1.0f; return this; } /** * Set this matrix to a spherical billboard transformation that rotates the local +Z axis of a given object with position <code>objPos</code> towards * a target position at <code>targetPos</code>. * <p> * This method can be used to create the complete model transformation for a given object, including the translation of the object to * its position <code>objPos</code>. * <p> * If preserving an <i>up</i> vector is not necessary when rotating the +Z axis, then a shortest arc rotation can be obtained * using {@link #billboardSpherical(Vector3f, Vector3f)}. * * @see #billboardSpherical(Vector3f, Vector3f) * * @param objPos * the position of the object to rotate towards <code>targetPos</code> * @param targetPos * the position of the target (for example the camera) towards which to rotate the object * @param up * the up axis used to orient the object * @return this */ public Matrix4f billboardSpherical(Vector3f objPos, Vector3f targetPos, Vector3f up) { float dirX = targetPos.x - objPos.x; float dirY = targetPos.y - objPos.y; float dirZ = targetPos.z - objPos.z; // normalize dir float invDirLen = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLen; dirY *= invDirLen; dirZ *= invDirLen; // left = up x dir float leftX = up.y * dirZ - up.z * dirY; float leftY = up.z * dirX - up.x * dirZ; float leftZ = up.x * dirY - up.y * dirX; // normalize left float invLeftLen = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLen; leftY *= invLeftLen; leftZ *= invLeftLen; // up = dir x left float upX = dirY * leftZ - dirZ * leftY; float upY = dirZ * leftX - dirX * leftZ; float upZ = dirX * leftY - dirY * leftX; // set matrix elements m00 = leftX; m01 = leftY; m02 = leftZ; m03 = 0.0f; m10 = upX; m11 = upY; m12 = upZ; m13 = 0.0f; m20 = dirX; m21 = dirY; m22 = dirZ; m23 = 0.0f; m30 = objPos.x; m31 = objPos.y; m32 = objPos.z; m33 = 1.0f; return this; } /** * Set this matrix to a spherical billboard transformation that rotates the local +Z axis of a given object with position <code>objPos</code> towards * a target position at <code>targetPos</code> using a shortest arc rotation by not preserving any <i>up</i> vector of the object. * <p> * This method can be used to create the complete model transformation for a given object, including the translation of the object to * its position <code>objPos</code>. * <p> * In order to specify an <i>up</i> vector which needs to be maintained when rotating the +Z axis of the object, * use {@link #billboardSpherical(Vector3f, Vector3f, Vector3f)}. * * @see #billboardSpherical(Vector3f, Vector3f, Vector3f) * * @param objPos * the position of the object to rotate towards <code>targetPos</code> * @param targetPos * the position of the target (for example the camera) towards which to rotate the object * @return this */ public Matrix4f billboardSpherical(Vector3f objPos, Vector3f targetPos) { float toDirX = targetPos.x - objPos.x; float toDirY = targetPos.y - objPos.y; float toDirZ = targetPos.z - objPos.z; float x = -toDirY; float y = toDirX; float w = (float) Math.sqrt(toDirX * toDirX + toDirY * toDirY + toDirZ * toDirZ) + toDirZ; float invNorm = (float) (1.0 / Math.sqrt(x * x + y * y + w * w)); x *= invNorm; y *= invNorm; w *= invNorm; float q00 = (x + x) * x; float q11 = (y + y) * y; float q01 = (x + x) * y; float q03 = (x + x) * w; float q13 = (y + y) * w; m00 = 1.0f - q11; m01 = q01; m02 = -q13; m03 = 0.0f; m10 = q01; m11 = 1.0f - q00; m12 = q03; m13 = 0.0f; m20 = q13; m21 = -q03; m22 = 1.0f - q11 - q00; m23 = 0.0f; m30 = objPos.x; m31 = objPos.y; m32 = objPos.z; m33 = 1.0f; return this; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Float.floatToIntBits(m00); result = prime * result + Float.floatToIntBits(m01); result = prime * result + Float.floatToIntBits(m02); result = prime * result + Float.floatToIntBits(m03); result = prime * result + Float.floatToIntBits(m10); result = prime * result + Float.floatToIntBits(m11); result = prime * result + Float.floatToIntBits(m12); result = prime * result + Float.floatToIntBits(m13); result = prime * result + Float.floatToIntBits(m20); result = prime * result + Float.floatToIntBits(m21); result = prime * result + Float.floatToIntBits(m22); result = prime * result + Float.floatToIntBits(m23); result = prime * result + Float.floatToIntBits(m30); result = prime * result + Float.floatToIntBits(m31); result = prime * result + Float.floatToIntBits(m32); result = prime * result + Float.floatToIntBits(m33); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Matrix4f)) return false; Matrix4f other = (Matrix4f) obj; if (Float.floatToIntBits(m00) != Float.floatToIntBits(other.m00)) return false; if (Float.floatToIntBits(m01) != Float.floatToIntBits(other.m01)) return false; if (Float.floatToIntBits(m02) != Float.floatToIntBits(other.m02)) return false; if (Float.floatToIntBits(m03) != Float.floatToIntBits(other.m03)) return false; if (Float.floatToIntBits(m10) != Float.floatToIntBits(other.m10)) return false; if (Float.floatToIntBits(m11) != Float.floatToIntBits(other.m11)) return false; if (Float.floatToIntBits(m12) != Float.floatToIntBits(other.m12)) return false; if (Float.floatToIntBits(m13) != Float.floatToIntBits(other.m13)) return false; if (Float.floatToIntBits(m20) != Float.floatToIntBits(other.m20)) return false; if (Float.floatToIntBits(m21) != Float.floatToIntBits(other.m21)) return false; if (Float.floatToIntBits(m22) != Float.floatToIntBits(other.m22)) return false; if (Float.floatToIntBits(m23) != Float.floatToIntBits(other.m23)) return false; if (Float.floatToIntBits(m30) != Float.floatToIntBits(other.m30)) return false; if (Float.floatToIntBits(m31) != Float.floatToIntBits(other.m31)) return false; if (Float.floatToIntBits(m32) != Float.floatToIntBits(other.m32)) return false; if (Float.floatToIntBits(m33) != Float.floatToIntBits(other.m33)) return false; return true; } /** * Apply a picking transformation to this matrix using the given window coordinates <tt>(x, y)</tt> as the pick center * and the given <tt>(width, height)</tt> as the size of the picking region in window coordinates, and store the result * in <code>dest</code>. * * @param x * the x coordinate of the picking region center in window coordinates * @param y * the y coordinate of the picking region center in window coordinates * @param width * the width of the picking region in window coordinates * @param height * the height of the picking region in window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f pick(float x, float y, float width, float height, int[] viewport, Matrix4f dest) { float sx = viewport[2] / width; float sy = viewport[3] / height; float tx = (viewport[2] + 2.0f * (viewport[0] - x)) / width; float ty = (viewport[3] + 2.0f * (viewport[1] - y)) / height; dest.m30 = m00 * tx + m10 * ty + m30; dest.m31 = m01 * tx + m11 * ty + m31; dest.m32 = m02 * tx + m12 * ty + m32; dest.m33 = m03 * tx + m13 * ty + m33; dest.m00 = m00 * sx; dest.m01 = m01 * sx; dest.m02 = m02 * sx; dest.m03 = m03 * sx; dest.m10 = m10 * sy; dest.m11 = m11 * sy; dest.m12 = m12 * sy; dest.m13 = m13 * sy; return dest; } /** * Apply a picking transformation to this matrix using the given window coordinates <tt>(x, y)</tt> as the pick center * and the given <tt>(width, height)</tt> as the size of the picking region in window coordinates. * * @param x * the x coordinate of the picking region center in window coordinates * @param y * the y coordinate of the picking region center in window coordinates * @param width * the width of the picking region in window coordinates * @param height * the height of the picking region in window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @return this */ public Matrix4f pick(float x, float y, float width, float height, int[] viewport) { return pick(x, y, width, height, viewport, this); } /** * Determine whether this matrix describes an affine transformation. This is the case iff its last row is equal to <tt>(0, 0, 0, 1)</tt>. * * @return <code>true</code> iff this matrix is affine; <code>false</code> otherwise */ public boolean isAffine() { return m03 == 0.0f && m13 == 0.0f && m23 == 0.0f && m33 == 1.0f; } /** * Exchange the values of <code>this</code> matrix with the given <code>other</code> matrix. * * @param other * the other matrix to exchange the values with * @return this */ public Matrix4f swap(Matrix4f other) { float tmp; tmp = m00; m00 = other.m00; other.m00 = tmp; tmp = m01; m01 = other.m01; other.m01 = tmp; tmp = m02; m02 = other.m02; other.m02 = tmp; tmp = m03; m03 = other.m03; other.m03 = tmp; tmp = m10; m10 = other.m10; other.m10 = tmp; tmp = m11; m11 = other.m11; other.m11 = tmp; tmp = m12; m12 = other.m12; other.m12 = tmp; tmp = m13; m13 = other.m13; other.m13 = tmp; tmp = m20; m20 = other.m20; other.m20 = tmp; tmp = m21; m21 = other.m21; other.m21 = tmp; tmp = m22; m22 = other.m22; other.m22 = tmp; tmp = m23; m23 = other.m23; other.m23 = tmp; tmp = m30; m30 = other.m30; other.m30 = tmp; tmp = m31; m31 = other.m31; other.m31 = tmp; tmp = m32; m32 = other.m32; other.m32 = tmp; tmp = m33; m33 = other.m33; other.m33 = tmp; return this; } /** * Apply an arcball view transformation to this matrix with the given <code>radius</code> and center <tt>(centerX, centerY, centerZ)</tt> * position of the arcball and the specified X and Y rotation angles, and store the result in <code>dest</code>. * <p> * This method is equivalent to calling: <tt>translate(0, 0, -radius).rotateX(angleX).rotateY(angleY).translate(-centerX, -centerY, -centerZ)</tt> * * @param radius * the arcball radius * @param centerX * the x coordinate of the center position of the arcball * @param centerY * the y coordinate of the center position of the arcball * @param centerZ * the z coordinate of the center position of the arcball * @param angleX * the rotation angle around the X axis in radians * @param angleY * the rotation angle around the Y axis in radians * @param dest * will hold the result * @return dest */ public Matrix4f arcball(float radius, float centerX, float centerY, float centerZ, float angleX, float angleY, Matrix4f dest) { float m30 = m20 * -radius + this.m30; float m31 = m21 * -radius + this.m31; float m32 = m22 * -radius + this.m32; float m33 = m23 * -radius + this.m33; float cos = (float) Math.cos(angleX); float sin = (float) Math.sin(angleX); float nm10 = m10 * cos + m20 * sin; float nm11 = m11 * cos + m21 * sin; float nm12 = m12 * cos + m22 * sin; float nm13 = m13 * cos + m23 * sin; float m20 = this.m20 * cos - m10 * sin; float m21 = this.m21 * cos - m11 * sin; float m22 = this.m22 * cos - m12 * sin; float m23 = this.m23 * cos - m13 * sin; cos = (float) Math.cos(angleY); sin = (float) Math.sin(angleY); float nm00 = m00 * cos - m20 * sin; float nm01 = m01 * cos - m21 * sin; float nm02 = m02 * cos - m22 * sin; float nm03 = m03 * cos - m23 * sin; float nm20 = m00 * sin + m20 * cos; float nm21 = m01 * sin + m21 * cos; float nm22 = m02 * sin + m22 * cos; float nm23 = m03 * sin + m23 * cos; dest.m30 = -nm00 * centerX - nm10 * centerY - nm20 * centerZ + m30; dest.m31 = -nm01 * centerX - nm11 * centerY - nm21 * centerZ + m31; dest.m32 = -nm02 * centerX - nm12 * centerY - nm22 * centerZ + m32; dest.m33 = -nm03 * centerX - nm13 * centerY - nm23 * centerZ + m33; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; return dest; } /** * Apply an arcball view transformation to this matrix with the given <code>radius</code> and <code>center</code> * position of the arcball and the specified X and Y rotation angles, and store the result in <code>dest</code>. * <p> * This method is equivalent to calling: <tt>translate(0, 0, -radius).rotateX(angleX).rotateY(angleY).translate(-center.x, -center.y, -center.z)</tt> * * @param radius * the arcball radius * @param center * the center position of the arcball * @param angleX * the rotation angle around the X axis in radians * @param angleY * the rotation angle around the Y axis in radians * @param dest * will hold the result * @return dest */ public Matrix4f arcball(float radius, Vector3f center, float angleX, float angleY, Matrix4f dest) { return arcball(radius, center.x, center.y, center.z, angleX, angleY, dest); } /** * Apply an arcball view transformation to this matrix with the given <code>radius</code> and center <tt>(centerX, centerY, centerZ)</tt> * position of the arcball and the specified X and Y rotation angles. * <p> * This method is equivalent to calling: <tt>translate(0, 0, -radius).rotateX(angleX).rotateY(angleY).translate(-centerX, -centerY, -centerZ)</tt> * * @param radius * the arcball radius * @param centerX * the x coordinate of the center position of the arcball * @param centerY * the y coordinate of the center position of the arcball * @param centerZ * the z coordinate of the center position of the arcball * @param angleX * the rotation angle around the X axis in radians * @param angleY * the rotation angle around the Y axis in radians * @return dest */ public Matrix4f arcball(float radius, float centerX, float centerY, float centerZ, float angleX, float angleY) { return arcball(radius, centerX, centerY, centerZ, angleX, angleY, this); } /** * Apply an arcball view transformation to this matrix with the given <code>radius</code> and <code>center</code> * position of the arcball and the specified X and Y rotation angles. * <p> * This method is equivalent to calling: <tt>translate(0, 0, -radius).rotateX(angleX).rotateY(angleY).translate(-center.x, -center.y, -center.z)</tt> * * @param radius * the arcball radius * @param center * the center position of the arcball * @param angleX * the rotation angle around the X axis in radians * @param angleY * the rotation angle around the Y axis in radians * @return this */ public Matrix4f arcball(float radius, Vector3f center, float angleX, float angleY) { return arcball(radius, center.x, center.y, center.z, angleX, angleY, this); } /** * Compute the axis-aligned bounding box of the frustum described by <code>this</code> matrix and store the minimum corner * coordinates in the given <code>min</code> and the maximum corner coordinates in the given <code>max</code> vector. * <p> * The matrix <code>this</code> is assumed to be the {@link #invert() inverse} of the origial view-projection matrix * for which to compute the axis-aligned bounding box in world-space. * <p> * The axis-aligned bounding box of the unit frustum is <tt>(-1, -1, -1)</tt>, <tt>(1, 1, 1)</tt>. * * @param min * will hold the minimum corner coordinates of the axis-aligned bounding box * @param max * will hold the maximum corner coordinates of the axis-aligned bounding box * @return this */ public Matrix4f frustumAabb(Vector3f min, Vector3f max) { float minX = Float.MAX_VALUE; float minY = Float.MAX_VALUE; float minZ = Float.MAX_VALUE; float maxX = -Float.MAX_VALUE; float maxY = -Float.MAX_VALUE; float maxZ = -Float.MAX_VALUE; for (int t = 0; t < 8; t++) { float x = ((t & 1) << 1) - 1.0f; float y = (((t >>> 1) & 1) << 1) - 1.0f; float z = (((t >>> 2) & 1) << 1) - 1.0f; float invW = 1.0f / (m03 * x + m13 * y + m23 * z + m33); float nx = (m00 * x + m10 * y + m20 * z + m30) * invW; float ny = (m01 * x + m11 * y + m21 * z + m31) * invW; float nz = (m02 * x + m12 * y + m22 * z + m32) * invW; minX = minX < nx ? minX : nx; minY = minY < ny ? minY : ny; minZ = minZ < nz ? minZ : nz; maxX = maxX > nx ? maxX : nx; maxY = maxY > ny ? maxY : ny; maxZ = maxZ > nz ? maxZ : nz; } min.x = minX; min.y = minY; min.z = minZ; max.x = maxX; max.y = maxY; max.z = maxZ; return this; } /** * Compute the <i>range matrix</i> for the Projected Grid transformation as described in chapter "2.4.2 Creating the range conversion matrix" * of the paper <a href="http://fileadmin.cs.lth.se/graphics/theses/projects/projgrid/projgrid-lq.pdf">Real-time water rendering - Introducing the projected grid concept</a> * based on the <i>inverse</i> of the view-projection matrix which is assumed to be <code>this</code>, and store that range matrix into <code>dest</code>. * <p> * If the projected grid will not be visible then this method returns <code>null</code>. * <p> * This method uses the <tt>y = 0</tt> plane for the projection. * * @param projector * the projector view-projection transformation * @param sLower * the lower (smallest) Y-coordinate which any transformed vertex might have while still being visible on the projected grid * @param sUpper * the upper (highest) Y-coordinate which any transformed vertex might have while still being visible on the projected grid * @param dest * will hold the resulting range matrix * @return the computed range matrix; or <code>null</code> if the projected grid will not be visible */ public Matrix4f projectedGridRange(Matrix4f projector, float sLower, float sUpper, Matrix4f dest) { // Compute intersection with frustum edges and plane float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE; float maxX = -Float.MAX_VALUE, maxY = -Float.MAX_VALUE; boolean intersection = false; for (int t = 0; t < 3 * 4; t++) { float c0X, c0Y, c0Z; float c1X, c1Y, c1Z; if (t < 4) { // all x edges c0X = -1; c1X = +1; c0Y = c1Y = ((t & 1) << 1) - 1.0f; c0Z = c1Z = (((t >>> 1) & 1) << 1) - 1.0f; } else if (t < 8) { // all y edges c0Y = -1; c1Y = +1; c0X = c1X = ((t & 1) << 1) - 1.0f; c0Z = c1Z = (((t >>> 1) & 1) << 1) - 1.0f; } else { // all z edges c0Z = -1; c1Z = +1; c0X = c1X = ((t & 1) << 1) - 1.0f; c0Y = c1Y = (((t >>> 1) & 1) << 1) - 1.0f; } // unproject corners float invW = 1.0f / (m03 * c0X + m13 * c0Y + m23 * c0Z + m33); float p0x = (m00 * c0X + m10 * c0Y + m20 * c0Z + m30) * invW; float p0y = (m01 * c0X + m11 * c0Y + m21 * c0Z + m31) * invW; float p0z = (m02 * c0X + m12 * c0Y + m22 * c0Z + m32) * invW; invW = 1.0f / (m03 * c1X + m13 * c1Y + m23 * c1Z + m33); float p1x = (m00 * c1X + m10 * c1Y + m20 * c1Z + m30) * invW; float p1y = (m01 * c1X + m11 * c1Y + m21 * c1Z + m31) * invW; float p1z = (m02 * c1X + m12 * c1Y + m22 * c1Z + m32) * invW; float dirX = p1x - p0x; float dirY = p1y - p0y; float dirZ = p1z - p0z; float invDenom = 1.0f / dirY; // test for intersection for (int s = 0; s < 2; s++) { float isectT = -(p0y + (s == 0 ? sLower : sUpper)) * invDenom; if (isectT >= 0.0f && isectT <= 1.0f) { intersection = true; // project with projector matrix float ix = p0x + isectT * dirX; float iz = p0z + isectT * dirZ; invW = 1.0f / (projector.m03 * ix + projector.m23 * iz + projector.m33); float px = (projector.m00 * ix + projector.m20 * iz + projector.m30) * invW; float py = (projector.m01 * ix + projector.m21 * iz + projector.m31) * invW; minX = minX < px ? minX : px; minY = minY < py ? minY : py; maxX = maxX > px ? maxX : px; maxY = maxY > py ? maxY : py; } } } if (!intersection) return null; // <- projected grid is not visible return dest.set(maxX - minX, 0, 0, 0, 0, maxY - minY, 0, 0, 0, 0, 1, 0, minX, minY, 0, 1); } /** * Change the near and far clip plane distances of <code>this</code> perspective frustum transformation matrix * and store the result in <code>dest</code>. * <p> * This method only works if <code>this</code> is a perspective projection frustum transformation, for example obtained * via {@link #perspective(float, float, float, float) perspective()} or {@link #frustum(float, float, float, float, float, float) frustum()}. * * @see #perspective(float, float, float, float) * @see #frustum(float, float, float, float, float, float) * * @param near * the new near clip plane distance * @param far * the new far clip plane distance * @param dest * will hold the resulting matrix * @return dest */ public Matrix4f perspectiveFrustumSlice(float near, float far, Matrix4f dest) { float invOldNear = (m23 + m22) / m32; float invNearFar = 1.0f / (near - far); dest.m00 = m00 * invOldNear * near; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m10 = m10; dest.m11 = m11 * invOldNear * near; dest.m12 = m12; dest.m13 = m13; dest.m20 = m20; dest.m21 = m21; dest.m22 = (far + near) * invNearFar; dest.m23 = m23; dest.m30 = m30; dest.m31 = m31; dest.m32 = (far + far) * near * invNearFar; dest.m33 = m33; return dest; } /** * Build an ortographic projection transformation that fits the view-projection transformation represented by <code>this</code> * into the given affine <code>view</code> transformation. * <p> * The transformation represented by <code>this</code> must be given as the {@link #invert() inverse} of a typical combined camera view-projection * transformation, whose projection can be either orthographic or perspective. * <p> * The <code>view</code> must be an {@link #isAffine() affine} transformation which in the application of Cascaded Shadow Maps is usually the light view transformation. * It be obtained via any affine transformation or for example via {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()}. * <p> * Reference: <a href="http://developer.download.nvidia.com/SDK/10.5/opengl/screenshots/samples/cascaded_shadow_maps.html">OpenGL SDK - Cascaded Shadow Maps</a> * * @param view * the view transformation to build a corresponding orthographic projection to fit the frustum of <code>this</code> * @param dest * will hold the crop projection transformation * @return dest */ public Matrix4f orthoCrop(Matrix4f view, Matrix4f dest) { // determine min/max world z and min/max orthographically view-projected x/y float minX = Float.MAX_VALUE, maxX = -Float.MAX_VALUE; float minY = Float.MAX_VALUE, maxY = -Float.MAX_VALUE; float minZ = Float.MAX_VALUE, maxZ = -Float.MAX_VALUE; for (int t = 0; t < 8; t++) { float x = ((t & 1) << 1) - 1.0f; float y = (((t >>> 1) & 1) << 1) - 1.0f; float z = (((t >>> 2) & 1) << 1) - 1.0f; float invW = 1.0f / (m03 * x + m13 * y + m23 * z + m33); float wx = (m00 * x + m10 * y + m20 * z + m30) * invW; float wy = (m01 * x + m11 * y + m21 * z + m31) * invW; float wz = (m02 * x + m12 * y + m22 * z + m32) * invW; invW = 1.0f / (view.m03 * wx + view.m13 * wy + view.m23 * wz + view.m33); float vx = view.m00 * wx + view.m10 * wy + view.m20 * wz + view.m30; float vy = view.m01 * wx + view.m11 * wy + view.m21 * wz + view.m31; float vz = (view.m02 * wx + view.m12 * wy + view.m22 * wz + view.m32) * invW; minX = minX < vx ? minX : vx; maxX = maxX > vx ? maxX : vx; minY = minY < vy ? minY : vy; maxY = maxY > vy ? maxY : vy; minZ = minZ < vz ? minZ : vz; maxZ = maxZ > vz ? maxZ : vz; } // build crop projection matrix to fit 'this' frustum into view return dest.setOrtho(minX, maxX, minY, maxY, -maxZ, -minZ); } /** * Set <code>this</code> matrix to a perspective transformation that maps the trapezoid spanned by the four corner coordinates * <code>(p0x, p0y)</code>, <code>(p1x, p1y)</code>, <code>(p2x, p2y)</code> and <code>(p3x, p3y)</code> to the unit square <tt>[(-1, -1)..(+1, +1)]</tt>. * <p> * The corner coordinates are given in counter-clockwise order starting from the <i>left</i> corner on the smaller parallel side of the trapezoid * seen when looking at the trapezoid oriented with its shorter parallel edge at the bottom and its longer parallel edge at the top. * <p> * Reference: <a href="https://kenai.com/downloads/wpbdc/Documents/tsm.pdf">Notes On Implementation Of Trapezoidal Shadow Maps</a> * * @param p0x * the x coordinate of the left corner at the shorter edge of the trapezoid * @param p0y * the y coordinate of the left corner at the shorter edge of the trapezoid * @param p1x * the x coordinate of the right corner at the shorter edge of the trapezoid * @param p1y * the y coordinate of the right corner at the shorter edge of the trapezoid * @param p2x * the x coordinate of the right corner at the longer edge of the trapezoid * @param p2y * the y coordinate of the right corner at the longer edge of the trapezoid * @param p3x * the x coordinate of the left corner at the longer edge of the trapezoid * @param p3y * the y coordinate of the left corner at the longer edge of the trapezoid * @return this */ public Matrix4f trapezoidCrop(float p0x, float p0y, float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { float aX = p1y - p0y, aY = p0x - p1x; float m00 = aY; float m10 = -aX; float m30 = aX * p0y - aY * p0x; float m01 = aX; float m11 = aY; float m31 = -(aX * p0x + aY * p0y); float c3x = m00 * p3x + m10 * p3y + m30; float c3y = m01 * p3x + m11 * p3y + m31; float s = -c3x / c3y; m00 += s * m01; m10 += s * m11; m30 += s * m31; float d1x = m00 * p1x + m10 * p1y + m30; float d2x = m00 * p2x + m10 * p2y + m30; float d = d1x * c3y / (d2x - d1x); m31 += d; float sx = 2.0f / d2x; float sy = 1.0f / (c3y + d); float u = (sy + sy) * d / (1.0f - sy * d); float m03 = m01 * sy; float m13 = m11 * sy; float m33 = m31 * sy; m01 = (u + 1.0f) * m03; m11 = (u + 1.0f) * m13; m31 = (u + 1.0f) * m33 - u; m00 = sx * m00 - m03; m10 = sx * m10 - m13; m30 = sx * m30 - m33; return set(m00, m01, 0, m03, m10, m11, 0, m13, 0, 0, 1, 0, m30, m31, 0, m33); } /** * Transform the axis-aligned box given as the minimum corner <tt>(minX, minY, minZ)</tt> and maximum corner <tt>(maxX, maxY, maxZ)</tt> * by <code>this</code> {@link #isAffine() affine} matrix and compute the axis-aligned box of the result whose minimum corner is stored in <code>outMin</code> * and maximum corner stored in <code>outMax</code>. * <p> * Reference: <a href="http://dev.theomader.com/transform-bounding-boxes/">http://dev.theomader.com</a> * * @param minX * the x coordinate of the minimum corner of the axis-aligned box * @param minY * the y coordinate of the minimum corner of the axis-aligned box * @param minZ * the z coordinate of the minimum corner of the axis-aligned box * @param maxX * the x coordinate of the maximum corner of the axis-aligned box * @param maxY * the y coordinate of the maximum corner of the axis-aligned box * @param maxZ * the y coordinate of the maximum corner of the axis-aligned box * @param outMin * will hold the minimum corner of the resulting axis-aligned box * @param outMax * will hold the maximum corner of the resulting axis-aligned box * @return this */ public Matrix4f transformAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, Vector3f outMin, Vector3f outMax) { float xax = m00 * minX, xay = m01 * minX, xaz = m02 * minX; float xbx = m00 * maxX, xby = m01 * maxX, xbz = m02 * maxX; float yax = m10 * minY, yay = m11 * minY, yaz = m12 * minY; float ybx = m10 * maxY, yby = m11 * maxY, ybz = m12 * maxY; float zax = m20 * minZ, zay = m21 * minZ, zaz = m22 * minZ; float zbx = m20 * maxZ, zby = m21 * maxZ, zbz = m22 * maxZ; float xminx, xminy, xminz, yminx, yminy, yminz, zminx, zminy, zminz; float xmaxx, xmaxy, xmaxz, ymaxx, ymaxy, ymaxz, zmaxx, zmaxy, zmaxz; if (xax < xbx) { xminx = xax; xmaxx = xbx; } else { xminx = xbx; xmaxx = xax; } if (xay < xby) { xminy = xay; xmaxy = xby; } else { xminy = xby; xmaxy = xay; } if (xaz < xbz) { xminz = xaz; xmaxz = xbz; } else { xminz = xbz; xmaxz = xaz; } if (yax < ybx) { yminx = yax; ymaxx = ybx; } else { yminx = ybx; ymaxx = yax; } if (yay < yby) { yminy = yay; ymaxy = yby; } else { yminy = yby; ymaxy = yay; } if (yaz < ybz) { yminz = yaz; ymaxz = ybz; } else { yminz = ybz; ymaxz = yaz; } if (zax < zbx) { zminx = zax; zmaxx = zbx; } else { zminx = zbx; zmaxx = zax; } if (zay < zby) { zminy = zay; zmaxy = zby; } else { zminy = zby; zmaxy = zay; } if (zaz < zbz) { zminz = zaz; zmaxz = zbz; } else { zminz = zbz; zmaxz = zaz; } outMin.x = xminx + yminx + zminx + m30; outMin.y = xminy + yminy + zminy + m31; outMin.z = xminz + yminz + zminz + m32; outMax.x = xmaxx + ymaxx + zmaxx + m30; outMax.y = xmaxy + ymaxy + zmaxy + m31; outMax.z = xmaxz + ymaxz + zmaxz + m32; return this; } /** * Transform the axis-aligned box given as the minimum corner <code>min</code> and maximum corner <code>max</code> * by <code>this</code> {@link #isAffine() affine} matrix and compute the axis-aligned box of the result whose minimum corner is stored in <code>outMin</code> * and maximum corner stored in <code>outMax</code>. * * @param min * the minimum corner of the axis-aligned box * @param max * the maximum corner of the axis-aligned box * @param outMin * will hold the minimum corner of the resulting axis-aligned box * @param outMax * will hold the maximum corner of the resulting axis-aligned box * @return this */ public Matrix4f transformAab(Vector3f min, Vector3f max, Vector3f outMin, Vector3f outMax) { return transformAab(min.x, min.y, min.z, max.x, max.y, max.z, outMin, outMax); } }
src/org/joml/Matrix4f.java
/* * (C) Copyright 2015-2016 Richard Greenlees Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.joml; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.text.DecimalFormat; import java.text.NumberFormat; /** * Contains the definition of a 4x4 Matrix of floats, and associated functions to transform * it. The matrix is column-major to match OpenGL's interpretation, and it looks like this: * <p> * m00 m10 m20 m30<br> * m01 m11 m21 m31<br> * m02 m12 m22 m32<br> * m03 m13 m23 m33<br> * * @author Richard Greenlees * @author Kai Burjack */ public class Matrix4f implements Externalizable { private static final long serialVersionUID = 1L; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>x=-1</tt> when using the identity matrix. */ public static final int PLANE_NX = 0; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>x=1</tt> when using the identity matrix. */ public static final int PLANE_PX = 1; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>y=-1</tt> when using the identity matrix. */ public static final int PLANE_NY= 2; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>y=1</tt> when using the identity matrix. */ public static final int PLANE_PY = 3; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>z=-1</tt> when using the identity matrix. */ public static final int PLANE_NZ = 4; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} * identifying the plane with equation <tt>z=1</tt> when using the identity matrix. */ public static final int PLANE_PZ = 5; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, -1, -1)</tt> when using the identity matrix. */ public static final int CORNER_NXNYNZ = 0; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, -1, -1)</tt> when using the identity matrix. */ public static final int CORNER_PXNYNZ = 1; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, 1, -1)</tt> when using the identity matrix. */ public static final int CORNER_PXPYNZ = 2; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, 1, -1)</tt> when using the identity matrix. */ public static final int CORNER_NXPYNZ = 3; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, -1, 1)</tt> when using the identity matrix. */ public static final int CORNER_PXNYPZ = 4; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, -1, 1)</tt> when using the identity matrix. */ public static final int CORNER_NXNYPZ = 5; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, 1, 1)</tt> when using the identity matrix. */ public static final int CORNER_NXPYPZ = 6; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, 1, 1)</tt> when using the identity matrix. */ public static final int CORNER_PXPYPZ = 7; public float m00, m10, m20, m30; public float m01, m11, m21, m31; public float m02, m12, m22, m32; public float m03, m13, m23, m33; /** * Create a new {@link Matrix4f} and set it to {@link #identity() identity}. */ public Matrix4f() { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; } /** * Create a new {@link Matrix4f} by setting its uppper left 3x3 submatrix to the values of the given {@link Matrix3f} * and the rest to identity. * * @param mat * the {@link Matrix3f} */ public Matrix4f(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m33 = 1.0f; } /** * Create a new {@link Matrix4f} and make it a copy of the given matrix. * * @param mat * the {@link Matrix4f} to copy the values from */ public Matrix4f(Matrix4f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = mat.m03; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = mat.m13; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = mat.m23; m30 = mat.m30; m31 = mat.m31; m32 = mat.m32; m33 = mat.m33; } /** * Create a new {@link Matrix4f} and make it a copy of the given matrix. * <p> * Note that due to the given {@link Matrix4d} storing values in double-precision and the constructed {@link Matrix4f} storing them * in single-precision, there is the possibility of losing precision. * * @param mat * the {@link Matrix4d} to copy the values from */ public Matrix4f(Matrix4d mat) { m00 = (float) mat.m00; m01 = (float) mat.m01; m02 = (float) mat.m02; m03 = (float) mat.m03; m10 = (float) mat.m10; m11 = (float) mat.m11; m12 = (float) mat.m12; m13 = (float) mat.m13; m20 = (float) mat.m20; m21 = (float) mat.m21; m22 = (float) mat.m22; m23 = (float) mat.m23; m30 = (float) mat.m30; m31 = (float) mat.m31; m32 = (float) mat.m32; m33 = (float) mat.m33; } /** * Create a new 4x4 matrix using the supplied float values. * * @param m00 * the value of m00 * @param m01 * the value of m01 * @param m02 * the value of m02 * @param m03 * the value of m03 * @param m10 * the value of m10 * @param m11 * the value of m11 * @param m12 * the value of m12 * @param m13 * the value of m13 * @param m20 * the value of m20 * @param m21 * the value of m21 * @param m22 * the value of m22 * @param m23 * the value of m23 * @param m30 * the value of m30 * @param m31 * the value of m31 * @param m32 * the value of m32 * @param m33 * the value of m33 */ public Matrix4f(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; } /** * Create a new {@link Matrix4f} by reading its 16 float components from the given {@link FloatBuffer} * at the buffer's current position. * <p> * That FloatBuffer is expected to hold the values in column-major order. * <p> * The buffer's position will not be changed by this method. * * @param buffer * the {@link FloatBuffer} to read the matrix values from */ public Matrix4f(FloatBuffer buffer) { MemUtil.INSTANCE.get(this, buffer.position(), buffer); } /** * Return the value of the matrix element at column 0 and row 0. * * @return the value of the matrix element */ public float m00() { return m00; } /** * Return the value of the matrix element at column 0 and row 1. * * @return the value of the matrix element */ public float m01() { return m01; } /** * Return the value of the matrix element at column 0 and row 2. * * @return the value of the matrix element */ public float m02() { return m02; } /** * Return the value of the matrix element at column 0 and row 3. * * @return the value of the matrix element */ public float m03() { return m03; } /** * Return the value of the matrix element at column 1 and row 0. * * @return the value of the matrix element */ public float m10() { return m10; } /** * Return the value of the matrix element at column 1 and row 1. * * @return the value of the matrix element */ public float m11() { return m11; } /** * Return the value of the matrix element at column 1 and row 2. * * @return the value of the matrix element */ public float m12() { return m12; } /** * Return the value of the matrix element at column 1 and row 3. * * @return the value of the matrix element */ public float m13() { return m13; } /** * Return the value of the matrix element at column 2 and row 0. * * @return the value of the matrix element */ public float m20() { return m20; } /** * Return the value of the matrix element at column 2 and row 1. * * @return the value of the matrix element */ public float m21() { return m21; } /** * Return the value of the matrix element at column 2 and row 2. * * @return the value of the matrix element */ public float m22() { return m22; } /** * Return the value of the matrix element at column 2 and row 3. * * @return the value of the matrix element */ public float m23() { return m23; } /** * Return the value of the matrix element at column 3 and row 0. * * @return the value of the matrix element */ public float m30() { return m30; } /** * Return the value of the matrix element at column 3 and row 1. * * @return the value of the matrix element */ public float m31() { return m31; } /** * Return the value of the matrix element at column 3 and row 2. * * @return the value of the matrix element */ public float m32() { return m32; } /** * Return the value of the matrix element at column 3 and row 3. * * @return the value of the matrix element */ public float m33() { return m33; } /** * Set the value of the matrix element at column 0 and row 0 * * @param m00 * the new value * @return the value of the matrix element */ public Matrix4f m00(float m00) { this.m00 = m00; return this; } /** * Set the value of the matrix element at column 0 and row 1 * * @param m01 * the new value * @return the value of the matrix element */ public Matrix4f m01(float m01) { this.m01 = m01; return this; } /** * Set the value of the matrix element at column 0 and row 2 * * @param m02 * the new value * @return the value of the matrix element */ public Matrix4f m02(float m02) { this.m02 = m02; return this; } /** * Set the value of the matrix element at column 0 and row 3 * * @param m03 * the new value * @return the value of the matrix element */ public Matrix4f m03(float m03) { this.m03 = m03; return this; } /** * Set the value of the matrix element at column 1 and row 0 * * @param m10 * the new value * @return the value of the matrix element */ public Matrix4f m10(float m10) { this.m10 = m10; return this; } /** * Set the value of the matrix element at column 1 and row 1 * * @param m11 * the new value * @return the value of the matrix element */ public Matrix4f m11(float m11) { this.m11 = m11; return this; } /** * Set the value of the matrix element at column 1 and row 2 * * @param m12 * the new value * @return the value of the matrix element */ public Matrix4f m12(float m12) { this.m12 = m12; return this; } /** * Set the value of the matrix element at column 1 and row 3 * * @param m13 * the new value * @return the value of the matrix element */ public Matrix4f m13(float m13) { this.m13 = m13; return this; } /** * Set the value of the matrix element at column 2 and row 0 * * @param m20 * the new value * @return the value of the matrix element */ public Matrix4f m20(float m20) { this.m20 = m20; return this; } /** * Set the value of the matrix element at column 2 and row 1 * * @param m21 * the new value * @return the value of the matrix element */ public Matrix4f m21(float m21) { this.m21 = m21; return this; } /** * Set the value of the matrix element at column 2 and row 2 * * @param m22 * the new value * @return the value of the matrix element */ public Matrix4f m22(float m22) { this.m22 = m22; return this; } /** * Set the value of the matrix element at column 2 and row 3 * * @param m23 * the new value * @return the value of the matrix element */ public Matrix4f m23(float m23) { this.m23 = m23; return this; } /** * Set the value of the matrix element at column 3 and row 0 * * @param m30 * the new value * @return the value of the matrix element */ public Matrix4f m30(float m30) { this.m30 = m30; return this; } /** * Set the value of the matrix element at column 3 and row 1 * * @param m31 * the new value * @return the value of the matrix element */ public Matrix4f m31(float m31) { this.m31 = m31; return this; } /** * Set the value of the matrix element at column 3 and row 2 * * @param m32 * the new value * @return the value of the matrix element */ public Matrix4f m32(float m32) { this.m32 = m32; return this; } /** * Set the value of the matrix element at column 3 and row 3 * * @param m33 * the new value * @return this */ public Matrix4f m33(float m33) { this.m33 = m33; return this; } /** * Reset this matrix to the identity. * <p> * Please note that if a call to {@link #identity()} is immediately followed by a call to: * {@link #translate(float, float, float) translate}, * {@link #rotate(float, float, float, float) rotate}, * {@link #scale(float, float, float) scale}, * {@link #perspective(float, float, float, float) perspective}, * {@link #frustum(float, float, float, float, float, float) frustum}, * {@link #ortho(float, float, float, float, float, float) ortho}, * {@link #ortho2D(float, float, float, float) ortho2D}, * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt}, * {@link #lookAlong(float, float, float, float, float, float) lookAlong}, * or any of their overloads, then the call to {@link #identity()} can be omitted and the subsequent call replaced with: * {@link #translation(float, float, float) translation}, * {@link #rotation(float, float, float, float) rotation}, * {@link #scaling(float, float, float) scaling}, * {@link #setPerspective(float, float, float, float) setPerspective}, * {@link #setFrustum(float, float, float, float, float, float) setFrustum}, * {@link #setOrtho(float, float, float, float, float, float) setOrtho}, * {@link #setOrtho2D(float, float, float, float) setOrtho2D}, * {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt}, * {@link #setLookAlong(float, float, float, float, float, float) setLookAlong}, * or any of their overloads. * * @return this */ public Matrix4f identity() { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Store the values of the given matrix <code>m</code> into <code>this</code> matrix. * * @see #Matrix4f(Matrix4f) * @see #get(Matrix4f) * * @param m * the matrix to copy the values from * @return this */ public Matrix4f set(Matrix4f m) { m00 = m.m00; m01 = m.m01; m02 = m.m02; m03 = m.m03; m10 = m.m10; m11 = m.m11; m12 = m.m12; m13 = m.m13; m20 = m.m20; m21 = m.m21; m22 = m.m22; m23 = m.m23; m30 = m.m30; m31 = m.m31; m32 = m.m32; m33 = m.m33; return this; } /** * Store the values of the given matrix <code>m</code> into <code>this</code> matrix. * <p> * Note that due to the given matrix <code>m</code> storing values in double-precision and <code>this</code> matrix storing * them in single-precision, there is the possibility to lose precision. * * @see #Matrix4f(Matrix4d) * @see #get(Matrix4d) * * @param m * the matrix to copy the values from * @return this */ public Matrix4f set(Matrix4d m) { m00 = (float) m.m00; m01 = (float) m.m01; m02 = (float) m.m02; m03 = (float) m.m03; m10 = (float) m.m10; m11 = (float) m.m11; m12 = (float) m.m12; m13 = (float) m.m13; m20 = (float) m.m20; m21 = (float) m.m21; m22 = (float) m.m22; m23 = (float) m.m23; m30 = (float) m.m30; m31 = (float) m.m31; m32 = (float) m.m32; m33 = (float) m.m33; return this; } /** * Set the upper left 3x3 submatrix of this {@link Matrix4f} to the given {@link Matrix3f} * and the rest to identity. * * @see #Matrix4f(Matrix3f) * * @param mat * the {@link Matrix3f} * @return this */ public Matrix4f set(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = 0.0f; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = 0.0f; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link AxisAngle4f}. * * @param axisAngle * the {@link AxisAngle4f} * @return this */ public Matrix4f set(AxisAngle4f axisAngle) { float x = axisAngle.x; float y = axisAngle.y; float z = axisAngle.z; double angle = axisAngle.angle; double n = Math.sqrt(x*x + y*y + z*z); n = 1/n; x *= n; y *= n; z *= n; double c = Math.cos(angle); double s = Math.sin(angle); double omc = 1.0 - c; m00 = (float)(c + x*x*omc); m11 = (float)(c + y*y*omc); m22 = (float)(c + z*z*omc); double tmp1 = x*y*omc; double tmp2 = z*s; m10 = (float)(tmp1 - tmp2); m01 = (float)(tmp1 + tmp2); tmp1 = x*z*omc; tmp2 = y*s; m20 = (float)(tmp1 + tmp2); m02 = (float)(tmp1 - tmp2); tmp1 = y*z*omc; tmp2 = x*s; m21 = (float)(tmp1 - tmp2); m12 = (float)(tmp1 + tmp2); m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link AxisAngle4d}. * * @param axisAngle * the {@link AxisAngle4d} * @return this */ public Matrix4f set(AxisAngle4d axisAngle) { double x = axisAngle.x; double y = axisAngle.y; double z = axisAngle.z; double angle = axisAngle.angle; double n = Math.sqrt(x*x + y*y + z*z); n = 1/n; x *= n; y *= n; z *= n; double c = Math.cos(angle); double s = Math.sin(angle); double omc = 1.0 - c; m00 = (float)(c + x*x*omc); m11 = (float)(c + y*y*omc); m22 = (float)(c + z*z*omc); double tmp1 = x*y*omc; double tmp2 = z*s; m10 = (float)(tmp1 - tmp2); m01 = (float)(tmp1 + tmp2); tmp1 = x*z*omc; tmp2 = y*s; m20 = (float)(tmp1 + tmp2); m02 = (float)(tmp1 - tmp2); tmp1 = y*z*omc; tmp2 = x*s; m21 = (float)(tmp1 - tmp2); m12 = (float)(tmp1 + tmp2); m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link Quaternionf}. * * @see Quaternionf#get(Matrix4f) * * @param q * the {@link Quaternionf} * @return this */ public Matrix4f set(Quaternionf q) { q.get(this); return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link Quaterniond}. * * @see Quaterniond#get(Matrix4f) * * @param q * the {@link Quaterniond} * @return this */ public Matrix4f set(Quaterniond q) { q.get(this); return this; } /** * Set the upper left 3x3 submatrix of this {@link Matrix4f} to that of the given {@link Matrix4f} * and don't change the other elements. * * @param mat * the {@link Matrix4f} * @return this */ public Matrix4f set3x3(Matrix4f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; return this; } /** * Multiply this matrix by the supplied <code>right</code> matrix and store the result in <code>this</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication * @return this */ public Matrix4f mul(Matrix4f right) { return mul(right, this); } /** * Multiply this matrix by the supplied <code>right</code> matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mul(Matrix4f right, Matrix4f dest) { float nm00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02 + m30 * right.m03; float nm01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02 + m31 * right.m03; float nm02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02 + m32 * right.m03; float nm03 = m03 * right.m00 + m13 * right.m01 + m23 * right.m02 + m33 * right.m03; float nm10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12 + m30 * right.m13; float nm11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12 + m31 * right.m13; float nm12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12 + m32 * right.m13; float nm13 = m03 * right.m10 + m13 * right.m11 + m23 * right.m12 + m33 * right.m13; float nm20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22 + m30 * right.m23; float nm21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22 + m31 * right.m23; float nm22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22 + m32 * right.m23; float nm23 = m03 * right.m20 + m13 * right.m21 + m23 * right.m22 + m33 * right.m23; float nm30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30 * right.m33; float nm31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31 * right.m33; float nm32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32 * right.m33; float nm33 = m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33 * right.m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Multiply <code>this</code> symmetric perspective projection matrix by the supplied {@link #isAffine() affine} <code>view</code> matrix. * <p> * If <code>P</code> is <code>this</code> matrix and <code>V</code> the <code>view</code> matrix, * then the new matrix will be <code>P * V</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>P * V * v</code>, the * transformation of the <code>view</code> matrix will be applied first! * * @param view * the {@link #isAffine() affine} matrix to multiply <code>this</code> symmetric perspective projection matrix by * @return dest */ public Matrix4f mulPerspectiveAffine(Matrix4f view) { return mulPerspectiveAffine(view, this); } /** * Multiply <code>this</code> symmetric perspective projection matrix by the supplied {@link #isAffine() affine} <code>view</code> matrix and store the result in <code>dest</code>. * <p> * If <code>P</code> is <code>this</code> matrix and <code>V</code> the <code>view</code> matrix, * then the new matrix will be <code>P * V</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>P * V * v</code>, the * transformation of the <code>view</code> matrix will be applied first! * * @param view * the {@link #isAffine() affine} matrix to multiply <code>this</code> symmetric perspective projection matrix by * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mulPerspectiveAffine(Matrix4f view, Matrix4f dest) { float nm00 = m00 * view.m00; float nm01 = m11 * view.m01; float nm02 = m22 * view.m02; float nm03 = m23 * view.m02; float nm10 = m00 * view.m10; float nm11 = m11 * view.m11; float nm12 = m22 * view.m12; float nm13 = m23 * view.m12; float nm20 = m00 * view.m20; float nm21 = m11 * view.m21; float nm22 = m22 * view.m22; float nm23 = m23 * view.m22; float nm30 = m00 * view.m30; float nm31 = m11 * view.m31; float nm32 = m22 * view.m32 + m32; float nm33 = m23 * view.m32; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Multiply this matrix by the supplied <code>right</code> matrix, which is assumed to be {@link #isAffine() affine}, and store the result in <code>this</code>. * <p> * This method assumes that the given <code>right</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @return this */ public Matrix4f mulAffineR(Matrix4f right) { return mulAffineR(right, this); } /** * Multiply this matrix by the supplied <code>right</code> matrix, which is assumed to be {@link #isAffine() affine}, and store the result in <code>dest</code>. * <p> * This method assumes that the given <code>right</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mulAffineR(Matrix4f right, Matrix4f dest) { float nm00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02; float nm01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02; float nm02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02; float nm03 = m03 * right.m00 + m13 * right.m01 + m23 * right.m02; float nm10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12; float nm11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12; float nm12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12; float nm13 = m03 * right.m10 + m13 * right.m11 + m23 * right.m12; float nm20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22; float nm21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22; float nm22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22; float nm23 = m03 * right.m20 + m13 * right.m21 + m23 * right.m22; float nm30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30; float nm31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31; float nm32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32; float nm33 = m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Multiply this matrix by the supplied <code>right</code> matrix, both of which are assumed to be {@link #isAffine() affine}, and store the result in <code>this</code>. * <p> * This method assumes that <code>this</code> matrix and the given <code>right</code> matrix both represent an {@link #isAffine() affine} transformation * (i.e. their last rows are equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrices only represent affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * This method will not modify either the last row of <code>this</code> or the last row of <code>right</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @return this */ public Matrix4f mulAffine(Matrix4f right) { return mulAffine(right, this); } /** * Multiply this matrix by the supplied <code>right</code> matrix, both of which are assumed to be {@link #isAffine() affine}, and store the result in <code>dest</code>. * <p> * This method assumes that <code>this</code> matrix and the given <code>right</code> matrix both represent an {@link #isAffine() affine} transformation * (i.e. their last rows are equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrices only represent affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * This method will not modify either the last row of <code>this</code> or the last row of <code>right</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mulAffine(Matrix4f right, Matrix4f dest) { float nm00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02; float nm01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02; float nm02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02; float nm03 = m03; float nm10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12; float nm11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12; float nm12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12; float nm13 = m13; float nm20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22; float nm21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22; float nm22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22; float nm23 = m23; float nm30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30; float nm31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31; float nm32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32; float nm33 = m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Multiply <code>this</code> orthographic projection matrix by the supplied {@link #isAffine() affine} <code>view</code> matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>V</code> the <code>view</code> matrix, * then the new matrix will be <code>M * V</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * V * v</code>, the * transformation of the <code>view</code> matrix will be applied first! * * @param view * the affine matrix which to multiply <code>this</code> with * @return dest */ public Matrix4f mulOrthoAffine(Matrix4f view) { return mulOrthoAffine(view, this); } /** * Multiply <code>this</code> orthographic projection matrix by the supplied {@link #isAffine() affine} <code>view</code> matrix * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>V</code> the <code>view</code> matrix, * then the new matrix will be <code>M * V</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * V * v</code>, the * transformation of the <code>view</code> matrix will be applied first! * * @param view * the affine matrix which to multiply <code>this</code> with * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f mulOrthoAffine(Matrix4f view, Matrix4f dest) { float nm00 = m00 * view.m00; float nm01 = m11 * view.m01; float nm02 = m22 * view.m02; float nm03 = 0.0f; float nm10 = m00 * view.m10; float nm11 = m11 * view.m11; float nm12 = m22 * view.m12; float nm13 = 0.0f; float nm20 = m00 * view.m20; float nm21 = m11 * view.m21; float nm22 = m22 * view.m22; float nm23 = 0.0f; float nm30 = m00 * view.m30 + m30; float nm31 = m11 * view.m31 + m31; float nm32 = m22 * view.m32 + m32; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Component-wise add the upper 4x3 submatrices of <code>this</code> and <code>other</code> * by first multiplying each component of <code>other</code>'s 4x3 submatrix by <code>otherFactor</code> and * adding that result to <code>this</code>. * <p> * The matrix <code>other</code> will not be changed. * * @param other * the other matrix * @param otherFactor * the factor to multiply each of the other matrix's 4x3 components * @return this */ public Matrix4f fma4x3(Matrix4f other, float otherFactor) { return fma4x3(other, otherFactor, this); } /** * Component-wise add the upper 4x3 submatrices of <code>this</code> and <code>other</code> * by first multiplying each component of <code>other</code>'s 4x3 submatrix by <code>otherFactor</code>, * adding that to <code>this</code> and storing the final result in <code>dest</code>. * <p> * The other components of <code>dest</code> will be set to the ones of <code>this</code>. * <p> * The matrices <code>this</code> and <code>other</code> will not be changed. * * @param other * the other matrix * @param otherFactor * the factor to multiply each of the other matrix's 4x3 components * @param dest * will hold the result * @return dest */ public Matrix4f fma4x3(Matrix4f other, float otherFactor, Matrix4f dest) { dest.m00 = m00 + other.m00 * otherFactor; dest.m01 = m01 + other.m01 * otherFactor; dest.m02 = m02 + other.m02 * otherFactor; dest.m03 = m03; dest.m10 = m10 + other.m10 * otherFactor; dest.m11 = m11 + other.m11 * otherFactor; dest.m12 = m12 + other.m12 * otherFactor; dest.m13 = m13; dest.m20 = m20 + other.m20 * otherFactor; dest.m21 = m21 + other.m21 * otherFactor; dest.m22 = m22 + other.m22 * otherFactor; dest.m23 = m23; dest.m30 = m30 + other.m30 * otherFactor; dest.m31 = m31 + other.m31 * otherFactor; dest.m32 = m32 + other.m32 * otherFactor; dest.m33 = m33; return dest; } /** * Component-wise add <code>this</code> and <code>other</code>. * * @param other * the other addend * @return this */ public Matrix4f add(Matrix4f other) { return add(other, this); } /** * Component-wise add <code>this</code> and <code>other</code> and store the result in <code>dest</code>. * * @param other * the other addend * @param dest * will hold the result * @return dest */ public Matrix4f add(Matrix4f other, Matrix4f dest) { dest.m00 = m00 + other.m00; dest.m01 = m01 + other.m01; dest.m02 = m02 + other.m02; dest.m03 = m03 + other.m03; dest.m10 = m10 + other.m10; dest.m11 = m11 + other.m11; dest.m12 = m12 + other.m12; dest.m13 = m13 + other.m13; dest.m20 = m20 + other.m20; dest.m21 = m21 + other.m21; dest.m22 = m22 + other.m22; dest.m23 = m23 + other.m23; dest.m30 = m30 + other.m30; dest.m31 = m31 + other.m31; dest.m32 = m32 + other.m32; dest.m33 = m33 + other.m33; return dest; } /** * Component-wise subtract <code>subtrahend</code> from <code>this</code>. * * @param subtrahend * the subtrahend * @return this */ public Matrix4f sub(Matrix4f subtrahend) { return sub(subtrahend, this); } /** * Component-wise subtract <code>subtrahend</code> from <code>this</code> and store the result in <code>dest</code>. * * @param subtrahend * the subtrahend * @param dest * will hold the result * @return dest */ public Matrix4f sub(Matrix4f subtrahend, Matrix4f dest) { dest.m00 = m00 - subtrahend.m00; dest.m01 = m01 - subtrahend.m01; dest.m02 = m02 - subtrahend.m02; dest.m03 = m03 - subtrahend.m03; dest.m10 = m10 - subtrahend.m10; dest.m11 = m11 - subtrahend.m11; dest.m12 = m12 - subtrahend.m12; dest.m13 = m13 - subtrahend.m13; dest.m20 = m20 - subtrahend.m20; dest.m21 = m21 - subtrahend.m21; dest.m22 = m22 - subtrahend.m22; dest.m23 = m23 - subtrahend.m23; dest.m30 = m30 - subtrahend.m30; dest.m31 = m31 - subtrahend.m31; dest.m32 = m32 - subtrahend.m32; dest.m33 = m33 - subtrahend.m33; return dest; } /** * Component-wise multiply <code>this</code> by <code>other</code>. * * @param other * the other matrix * @return this */ public Matrix4f mulComponentWise(Matrix4f other) { return mulComponentWise(other, this); } /** * Component-wise multiply <code>this</code> by <code>other</code> and store the result in <code>dest</code>. * * @param other * the other matrix * @param dest * will hold the result * @return dest */ public Matrix4f mulComponentWise(Matrix4f other, Matrix4f dest) { dest.m00 = m00 * other.m00; dest.m01 = m01 * other.m01; dest.m02 = m02 * other.m02; dest.m03 = m03 * other.m03; dest.m10 = m10 * other.m10; dest.m11 = m11 * other.m11; dest.m12 = m12 * other.m12; dest.m13 = m13 * other.m13; dest.m20 = m20 * other.m20; dest.m21 = m21 * other.m21; dest.m22 = m22 * other.m22; dest.m23 = m23 * other.m23; dest.m30 = m30 * other.m30; dest.m31 = m31 * other.m31; dest.m32 = m32 * other.m32; dest.m33 = m33 * other.m33; return dest; } /** * Component-wise add the upper 4x3 submatrices of <code>this</code> and <code>other</code>. * * @param other * the other addend * @return this */ public Matrix4f add4x3(Matrix4f other) { return add4x3(other, this); } /** * Component-wise add the upper 4x3 submatrices of <code>this</code> and <code>other</code> * and store the result in <code>dest</code>. * <p> * The other components of <code>dest</code> will be set to the ones of <code>this</code>. * * @param other * the other addend * @param dest * will hold the result * @return dest */ public Matrix4f add4x3(Matrix4f other, Matrix4f dest) { dest.m00 = m00 + other.m00; dest.m01 = m01 + other.m01; dest.m02 = m02 + other.m02; dest.m03 = m03; dest.m10 = m10 + other.m10; dest.m11 = m11 + other.m11; dest.m12 = m12 + other.m12; dest.m13 = m13; dest.m20 = m20 + other.m20; dest.m21 = m21 + other.m21; dest.m22 = m22 + other.m22; dest.m23 = m23; dest.m30 = m30 + other.m30; dest.m31 = m31 + other.m31; dest.m32 = m32 + other.m32; dest.m33 = m33; return dest; } /** * Component-wise subtract the upper 4x3 submatrices of <code>subtrahend</code> from <code>this</code>. * * @param subtrahend * the subtrahend * @return this */ public Matrix4f sub4x3(Matrix4f subtrahend) { return sub4x3(subtrahend, this); } /** * Component-wise subtract the upper 4x3 submatrices of <code>subtrahend</code> from <code>this</code> * and store the result in <code>dest</code>. * <p> * The other components of <code>dest</code> will be set to the ones of <code>this</code>. * * @param subtrahend * the subtrahend * @param dest * will hold the result * @return dest */ public Matrix4f sub4x3(Matrix4f subtrahend, Matrix4f dest) { dest.m00 = m00 - subtrahend.m00; dest.m01 = m01 - subtrahend.m01; dest.m02 = m02 - subtrahend.m02; dest.m03 = m03; dest.m10 = m10 - subtrahend.m10; dest.m11 = m11 - subtrahend.m11; dest.m12 = m12 - subtrahend.m12; dest.m13 = m13; dest.m20 = m20 - subtrahend.m20; dest.m21 = m21 - subtrahend.m21; dest.m22 = m22 - subtrahend.m22; dest.m23 = m23; dest.m30 = m30 - subtrahend.m30; dest.m31 = m31 - subtrahend.m31; dest.m32 = m32 - subtrahend.m32; dest.m33 = m33; return dest; } /** * Component-wise multiply the upper 4x3 submatrices of <code>this</code> by <code>other</code>. * * @param other * the other matrix * @return this */ public Matrix4f mul4x3ComponentWise(Matrix4f other) { return mul4x3ComponentWise(other, this); } /** * Component-wise multiply the upper 4x3 submatrices of <code>this</code> by <code>other</code> * and store the result in <code>dest</code>. * <p> * The other components of <code>dest</code> will be set to the ones of <code>this</code>. * * @param other * the other matrix * @param dest * will hold the result * @return dest */ public Matrix4f mul4x3ComponentWise(Matrix4f other, Matrix4f dest) { dest.m00 = m00 * other.m00; dest.m01 = m01 * other.m01; dest.m02 = m02 * other.m02; dest.m03 = m03; dest.m10 = m10 * other.m10; dest.m11 = m11 * other.m11; dest.m12 = m12 * other.m12; dest.m13 = m13; dest.m20 = m20 * other.m20; dest.m21 = m21 * other.m21; dest.m22 = m22 * other.m22; dest.m23 = m23; dest.m30 = m30 * other.m30; dest.m31 = m31 * other.m31; dest.m32 = m32 * other.m32; dest.m33 = m33; return dest; } /** * Set the values within this matrix to the supplied float values. The matrix will look like this:<br><br> * * m00, m10, m20, m30<br> * m01, m11, m21, m31<br> * m02, m12, m22, m32<br> * m03, m13, m23, m33 * * @param m00 * the new value of m00 * @param m01 * the new value of m01 * @param m02 * the new value of m02 * @param m03 * the new value of m03 * @param m10 * the new value of m10 * @param m11 * the new value of m11 * @param m12 * the new value of m12 * @param m13 * the new value of m13 * @param m20 * the new value of m20 * @param m21 * the new value of m21 * @param m22 * the new value of m22 * @param m23 * the new value of m23 * @param m30 * the new value of m30 * @param m31 * the new value of m31 * @param m32 * the new value of m32 * @param m33 * the new value of m33 * @return this */ public Matrix4f set(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; return this; } /** * Set the values in the matrix using a float array that contains the matrix elements in column-major order. * <p> * The results will look like this:<br><br> * * 0, 4, 8, 12<br> * 1, 5, 9, 13<br> * 2, 6, 10, 14<br> * 3, 7, 11, 15<br> * * @see #set(float[]) * * @param m * the array to read the matrix values from * @param off * the offset into the array * @return this */ public Matrix4f set(float m[], int off) { m00 = m[off+0]; m01 = m[off+1]; m02 = m[off+2]; m03 = m[off+3]; m10 = m[off+4]; m11 = m[off+5]; m12 = m[off+6]; m13 = m[off+7]; m20 = m[off+8]; m21 = m[off+9]; m22 = m[off+10]; m23 = m[off+11]; m30 = m[off+12]; m31 = m[off+13]; m32 = m[off+14]; m33 = m[off+15]; return this; } /** * Set the values in the matrix using a float array that contains the matrix elements in column-major order. * <p> * The results will look like this:<br><br> * * 0, 4, 8, 12<br> * 1, 5, 9, 13<br> * 2, 6, 10, 14<br> * 3, 7, 11, 15<br> * * @see #set(float[], int) * * @param m * the array to read the matrix values from * @return this */ public Matrix4f set(float m[]) { return set(m, 0); } /** * Set the values of this matrix by reading 16 float values from the given {@link FloatBuffer} in column-major order, * starting at its current position. * <p> * The FloatBuffer is expected to contain the values in column-major order. * <p> * The position of the FloatBuffer will not be changed by this method. * * @param buffer * the FloatBuffer to read the matrix values from in column-major order * @return this */ public Matrix4f set(FloatBuffer buffer) { MemUtil.INSTANCE.get(this, buffer.position(), buffer); return this; } /** * Set the values of this matrix by reading 16 float values from the given {@link ByteBuffer} in column-major order, * starting at its current position. * <p> * The ByteBuffer is expected to contain the values in column-major order. * <p> * The position of the ByteBuffer will not be changed by this method. * * @param buffer * the ByteBuffer to read the matrix values from in column-major order * @return this */ public Matrix4f set(ByteBuffer buffer) { MemUtil.INSTANCE.get(this, buffer.position(), buffer); return this; } /** * Return the determinant of this matrix. * <p> * If <code>this</code> matrix represents an {@link #isAffine() affine} transformation, such as translation, rotation, scaling and shearing, * and thus its last row is equal to <tt>(0, 0, 0, 1)</tt>, then {@link #determinantAffine()} can be used instead of this method. * * @see #determinantAffine() * * @return the determinant */ public float determinant() { return (m00 * m11 - m01 * m10) * (m22 * m33 - m23 * m32) + (m02 * m10 - m00 * m12) * (m21 * m33 - m23 * m31) + (m00 * m13 - m03 * m10) * (m21 * m32 - m22 * m31) + (m01 * m12 - m02 * m11) * (m20 * m33 - m23 * m30) + (m03 * m11 - m01 * m13) * (m20 * m32 - m22 * m30) + (m02 * m13 - m03 * m12) * (m20 * m31 - m21 * m30); } /** * Return the determinant of the upper left 3x3 submatrix of this matrix. * * @return the determinant */ public float determinant3x3() { return (m00 * m11 - m01 * m10) * m22 + (m02 * m10 - m00 * m12) * m21 + (m01 * m12 - m02 * m11) * m20; } /** * Return the determinant of this matrix by assuming that it represents an {@link #isAffine() affine} transformation and thus * its last row is equal to <tt>(0, 0, 0, 1)</tt>. * * @return the determinant */ public float determinantAffine() { return (m00 * m11 - m01 * m10) * m22 + (m02 * m10 - m00 * m12) * m21 + (m01 * m12 - m02 * m11) * m20; } /** * Invert this matrix and write the result into <code>dest</code>. * <p> * If <code>this</code> matrix represents an {@link #isAffine() affine} transformation, such as translation, rotation, scaling and shearing, * and thus its last row is equal to <tt>(0, 0, 0, 1)</tt>, then {@link #invertAffine(Matrix4f)} can be used instead of this method. * * @see #invertAffine(Matrix4f) * * @param dest * will hold the result * @return dest */ public Matrix4f invert(Matrix4f dest) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float c = m00 * m13 - m03 * m10; float d = m01 * m12 - m02 * m11; float e = m01 * m13 - m03 * m11; float f = m02 * m13 - m03 * m12; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float i = m20 * m33 - m23 * m30; float j = m21 * m32 - m22 * m31; float k = m21 * m33 - m23 * m31; float l = m22 * m33 - m23 * m32; float det = a * l - b * k + c * j + d * i - e * h + f * g; det = 1.0f / det; float nm00 = ( m11 * l - m12 * k + m13 * j) * det; float nm01 = (-m01 * l + m02 * k - m03 * j) * det; float nm02 = ( m31 * f - m32 * e + m33 * d) * det; float nm03 = (-m21 * f + m22 * e - m23 * d) * det; float nm10 = (-m10 * l + m12 * i - m13 * h) * det; float nm11 = ( m00 * l - m02 * i + m03 * h) * det; float nm12 = (-m30 * f + m32 * c - m33 * b) * det; float nm13 = ( m20 * f - m22 * c + m23 * b) * det; float nm20 = ( m10 * k - m11 * i + m13 * g) * det; float nm21 = (-m00 * k + m01 * i - m03 * g) * det; float nm22 = ( m30 * e - m31 * c + m33 * a) * det; float nm23 = (-m20 * e + m21 * c - m23 * a) * det; float nm30 = (-m10 * j + m11 * h - m12 * g) * det; float nm31 = ( m00 * j - m01 * h + m02 * g) * det; float nm32 = (-m30 * d + m31 * b - m32 * a) * det; float nm33 = ( m20 * d - m21 * b + m22 * a) * det; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Invert this matrix. * <p> * If <code>this</code> matrix represents an {@link #isAffine() affine} transformation, such as translation, rotation, scaling and shearing, * and thus its last row is equal to <tt>(0, 0, 0, 1)</tt>, then {@link #invertAffine()} can be used instead of this method. * * @see #invertAffine() * * @return this */ public Matrix4f invert() { return invert(this); } /** * If <code>this</code> is a perspective projection matrix obtained via one of the {@link #perspective(float, float, float, float) perspective()} methods * or via {@link #setPerspective(float, float, float, float) setPerspective()}, that is, if <code>this</code> is a symmetrical perspective frustum transformation, * then this method builds the inverse of <code>this</code> and stores it into the given <code>dest</code>. * <p> * This method can be used to quickly obtain the inverse of a perspective projection matrix when being obtained via {@link #perspective(float, float, float, float) perspective()}. * * @see #perspective(float, float, float, float) * * @param dest * will hold the inverse of <code>this</code> * @return dest */ public Matrix4f invertPerspective(Matrix4f dest) { float a = 1.0f / (m00 * m11); float l = -1.0f / (m23 * m32); dest.set(m11 * a, 0, 0, 0, 0, m00 * a, 0, 0, 0, 0, 0, -m23 * l, 0, 0, -m32 * l, m22 * l); return dest; } /** * If <code>this</code> is a perspective projection matrix obtained via one of the {@link #perspective(float, float, float, float) perspective()} methods * or via {@link #setPerspective(float, float, float, float) setPerspective()}, that is, if <code>this</code> is a symmetrical perspective frustum transformation, * then this method builds the inverse of <code>this</code>. * <p> * This method can be used to quickly obtain the inverse of a perspective projection matrix when being obtained via {@link #perspective(float, float, float, float) perspective()}. * * @see #perspective(float, float, float, float) * * @return this */ public Matrix4f invertPerspective() { return invertPerspective(this); } /** * If <code>this</code> is an arbitrary perspective projection matrix obtained via one of the {@link #frustum(float, float, float, float, float, float) frustum()} methods * or via {@link #setFrustum(float, float, float, float, float, float) setFrustum()}, * then this method builds the inverse of <code>this</code> and stores it into the given <code>dest</code>. * <p> * This method can be used to quickly obtain the inverse of a perspective projection matrix. * <p> * If this matrix represents a symmetric perspective frustum transformation, as obtained via {@link #perspective(float, float, float, float) perspective()}, then * {@link #invertPerspective(Matrix4f)} should be used instead. * * @see #frustum(float, float, float, float, float, float) * @see #invertPerspective(Matrix4f) * * @param dest * will hold the inverse of <code>this</code> * @return dest */ public Matrix4f invertFrustum(Matrix4f dest) { float invM00 = 1.0f / m00; float invM11 = 1.0f / m11; float invM23 = 1.0f / m23; float invM32 = 1.0f / m32; dest.set(invM00, 0, 0, 0, 0, invM11, 0, 0, 0, 0, 0, invM32, -m20 * invM00 * invM23, -m21 * invM11 * invM23, invM23, -m22 * invM23 * invM32); return dest; } /** * If <code>this</code> is an arbitrary perspective projection matrix obtained via one of the {@link #frustum(float, float, float, float, float, float) frustum()} methods * or via {@link #setFrustum(float, float, float, float, float, float) setFrustum()}, * then this method builds the inverse of <code>this</code>. * <p> * This method can be used to quickly obtain the inverse of a perspective projection matrix. * <p> * If this matrix represents a symmetric perspective frustum transformation, as obtained via {@link #perspective(float, float, float, float) perspective()}, then * {@link #invertPerspective()} should be used instead. * * @see #frustum(float, float, float, float, float, float) * @see #invertPerspective() * * @return this */ public Matrix4f invertFrustum() { return invertFrustum(this); } /** * Invert <code>this</code> orthographic projection matrix and store the result into the given <code>dest</code>. * <p> * This method can be used to quickly obtain the inverse of an orthographic projection matrix. * * @param dest * will hold the inverse of <code>this</code> * @return dest */ public Matrix4f invertOrtho(Matrix4f dest) { float invM00 = 1.0f / m00; float invM11 = 1.0f / m11; float invM22 = 1.0f / m22; dest.set(invM00, 0, 0, 0, 0, invM11, 0, 0, 0, 0, invM22, 0, -m30 * invM00, -m31 * invM11, -m32 * invM22, 1); return dest; } /** * Invert <code>this</code> orthographic projection matrix. * <p> * This method can be used to quickly obtain the inverse of an orthographic projection matrix. * * @return this */ public Matrix4f invertOrtho() { return invertOrtho(this); } /** * If <code>this</code> is a perspective projection matrix obtained via one of the {@link #perspective(float, float, float, float) perspective()} methods * or via {@link #setPerspective(float, float, float, float) setPerspective()}, that is, if <code>this</code> is a symmetrical perspective frustum transformation * and the given <code>view</code> matrix is {@link #isAffine() affine} and has unit scaling (for example by being obtained via {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()}), * then this method builds the inverse of <tt>this * view</tt> and stores it into the given <code>dest</code>. * <p> * This method can be used to quickly obtain the inverse of the combination of the view and projection matrices, when both were obtained * via the common methods {@link #perspective(float, float, float, float) perspective()} and {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} or * other methods, that build affine matrices, such as {@link #translate(float, float, float) translate} and {@link #rotate(float, float, float, float)}, except for {@link #scale(float, float, float) scale()}. * <p> * For the special cases of the matrices <code>this</code> and <code>view</code> mentioned above this method, this method is equivalent to the following code: * <pre> * dest.set(this).mul(view).invert(); * </pre> * * @param view * the view transformation (must be {@link #isAffine() affine} and have unit scaling) * @param dest * will hold the inverse of <tt>this * view</tt> * @return dest */ public Matrix4f invertPerspectiveView(Matrix4f view, Matrix4f dest) { float a = 1.0f / (m00 * m11); float l = -1.0f / (m23 * m32); float pm00 = m11 * a; float pm11 = m00 * a; float pm23 = -m23 * l; float pm32 = -m32 * l; float pm33 = m22 * l; float vm30 = -view.m00 * view.m30 - view.m01 * view.m31 - view.m02 * view.m32; float vm31 = -view.m10 * view.m30 - view.m11 * view.m31 - view.m12 * view.m32; float vm32 = -view.m20 * view.m30 - view.m21 * view.m31 - view.m22 * view.m32; dest.set(view.m00 * pm00, view.m10 * pm00, view.m20 * pm00, 0.0f, view.m01 * pm11, view.m11 * pm11, view.m21 * pm11, 0.0f, vm30 * pm23, vm31 * pm23, vm32 * pm23, pm23, view.m02 * pm32 + vm30 * pm33, view.m12 * pm32 + vm31 * pm33, view.m22 * pm32 + vm32 * pm33, pm33); return dest; } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and write the result into <code>dest</code>. * <p> * Note that if <code>this</code> matrix also has unit scaling, then the method {@link #invertAffineUnitScale(Matrix4f)} should be used instead. * * @see #invertAffineUnitScale(Matrix4f) * * @param dest * will hold the result * @return dest */ public Matrix4f invertAffine(Matrix4f dest) { float s = determinantAffine(); s = 1.0f / s; float m10m22 = m10 * m22; float m10m21 = m10 * m21; float m10m02 = m10 * m02; float m10m01 = m10 * m01; float m11m22 = m11 * m22; float m11m20 = m11 * m20; float m11m02 = m11 * m02; float m11m00 = m11 * m00; float m12m21 = m12 * m21; float m12m20 = m12 * m20; float m12m01 = m12 * m01; float m12m00 = m12 * m00; float m20m02 = m20 * m02; float m20m01 = m20 * m01; float m21m02 = m21 * m02; float m21m00 = m21 * m00; float m22m01 = m22 * m01; float m22m00 = m22 * m00; float nm00 = (m11m22 - m12m21) * s; float nm01 = (m21m02 - m22m01) * s; float nm02 = (m12m01 - m11m02) * s; float nm03 = 0.0f; float nm10 = (m12m20 - m10m22) * s; float nm11 = (m22m00 - m20m02) * s; float nm12 = (m10m02 - m12m00) * s; float nm13 = 0.0f; float nm20 = (m10m21 - m11m20) * s; float nm21 = (m20m01 - m21m00) * s; float nm22 = (m11m00 - m10m01) * s; float nm23 = 0.0f; float nm30 = (m10m22 * m31 - m10m21 * m32 + m11m20 * m32 - m11m22 * m30 + m12m21 * m30 - m12m20 * m31) * s; float nm31 = (m20m02 * m31 - m20m01 * m32 + m21m00 * m32 - m21m02 * m30 + m22m01 * m30 - m22m00 * m31) * s; float nm32 = (m11m02 * m30 - m12m01 * m30 + m12m00 * m31 - m10m02 * m31 + m10m01 * m32 - m11m00 * m32) * s; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>). * <p> * Note that if <code>this</code> matrix also has unit scaling, then the method {@link #invertAffineUnitScale()} should be used instead. * * @see #invertAffineUnitScale() * * @return this */ public Matrix4f invertAffine() { return invertAffine(this); } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and has unit scaling (i.e. {@link #transformDirection(Vector3f) transformDirection} does not change the {@link Vector3f#length() length} of the vector) * and write the result into <code>dest</code>. * <p> * Reference: <a href="http://www.gamedev.net/topic/425118-inverse--matrix/">http://www.gamedev.net/</a> * * @param dest * will hold the result * @return dest */ public Matrix4f invertAffineUnitScale(Matrix4f dest) { dest.set(m00, m10, m20, 0.0f, m01, m11, m21, 0.0f, m02, m12, m22, 0.0f, -m00 * m30 - m01 * m31 - m02 * m32, -m10 * m30 - m11 * m31 - m12 * m32, -m20 * m30 - m21 * m31 - m22 * m32, 1.0f); return dest; } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and has unit scaling (i.e. {@link #transformDirection(Vector3f) transformDirection} does not change the {@link Vector3f#length() length} of the vector). * <p> * Reference: <a href="http://www.gamedev.net/topic/425118-inverse--matrix/">http://www.gamedev.net/</a> * * @return this */ public Matrix4f invertAffineUnitScale() { return invertAffineUnitScale(this); } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and has unit scaling (i.e. {@link #transformDirection(Vector3f) transformDirection} does not change the {@link Vector3f#length() length} of the vector), * as is the case for matrices built via {@link #lookAt(Vector3f, Vector3f, Vector3f)} and their overloads, and write the result into <code>dest</code>. * <p> * This method is equivalent to calling {@link #invertAffineUnitScale(Matrix4f)} * <p> * Reference: <a href="http://www.gamedev.net/topic/425118-inverse--matrix/">http://www.gamedev.net/</a> * * @see #invertAffineUnitScale(Matrix4f) * * @param dest * will hold the result * @return dest */ public Matrix4f invertLookAt(Matrix4f dest) { return invertAffineUnitScale(dest); } /** * Invert this matrix by assuming that it is an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and has unit scaling (i.e. {@link #transformDirection(Vector3f) transformDirection} does not change the {@link Vector3f#length() length} of the vector), * as is the case for matrices built via {@link #lookAt(Vector3f, Vector3f, Vector3f)} and their overloads. * <p> * This method is equivalent to calling {@link #invertAffineUnitScale()} * <p> * Reference: <a href="http://www.gamedev.net/topic/425118-inverse--matrix/">http://www.gamedev.net/</a> * * @see #invertAffineUnitScale() * * @return this */ public Matrix4f invertLookAt() { return invertAffineUnitScale(this); } /** * Transpose this matrix and store the result in <code>dest</code>. * * @param dest * will hold the result * @return dest */ public Matrix4f transpose(Matrix4f dest) { float nm00 = m00; float nm01 = m10; float nm02 = m20; float nm03 = m30; float nm10 = m01; float nm11 = m11; float nm12 = m21; float nm13 = m31; float nm20 = m02; float nm21 = m12; float nm22 = m22; float nm23 = m32; float nm30 = m03; float nm31 = m13; float nm32 = m23; float nm33 = m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Transpose only the upper left 3x3 submatrix of this matrix and set the rest of the matrix elements to identity. * * @return this */ public Matrix4f transpose3x3() { return transpose3x3(this); } /** * Transpose only the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * All other matrix elements of <code>dest</code> will be set to identity. * * @param dest * will hold the result * @return dest */ public Matrix4f transpose3x3(Matrix4f dest) { float nm00 = m00; float nm01 = m10; float nm02 = m20; float nm03 = 0.0f; float nm10 = m01; float nm11 = m11; float nm12 = m21; float nm13 = 0.0f; float nm20 = m02; float nm21 = m12; float nm22 = m22; float nm23 = 0.0f; float nm30 = 0.0f; float nm31 = 0.0f; float nm32 = 0.0f; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Transpose only the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * * @param dest * will hold the result * @return dest */ public Matrix3f transpose3x3(Matrix3f dest) { dest.m00 = m00; dest.m01 = m10; dest.m02 = m20; dest.m10 = m01; dest.m11 = m11; dest.m12 = m21; dest.m20 = m02; dest.m21 = m12; dest.m22 = m22; return dest; } /** * Transpose this matrix. * * @return this */ public Matrix4f transpose() { return transpose(this); } /** * Set this matrix to be a simple translation matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional translation. * <p> * In order to post-multiply a translation transformation directly to a * matrix, use {@link #translate(float, float, float) translate()} instead. * * @see #translate(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translation(float x, float y, float z) { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = x; m31 = y; m32 = z; m33 = 1.0f; return this; } /** * Set this matrix to be a simple translation matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional translation. * <p> * In order to post-multiply a translation transformation directly to a * matrix, use {@link #translate(Vector3f) translate()} instead. * * @see #translate(float, float, float) * * @param offset * the offsets in x, y and z to translate * @return this */ public Matrix4f translation(Vector3f offset) { return translation(offset.x, offset.y, offset.z); } /** * Set only the translation components <tt>(m30, m31, m32)</tt> of this matrix to the given values <tt>(x, y, z)</tt>. * <p> * Note that this will only work properly for orthogonal matrices (without any perspective). * <p> * To build a translation matrix instead, use {@link #translation(float, float, float)}. * To apply a translation to another matrix, use {@link #translate(float, float, float)}. * * @see #translation(float, float, float) * @see #translate(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f setTranslation(float x, float y, float z) { m30 = x; m31 = y; m32 = z; return this; } /** * Set only the translation components <tt>(m30, m31, m32)</tt> of this matrix to the values <tt>(xyz.x, xyz.y, xyz.z)</tt>. * <p> * Note that this will only work properly for orthogonal matrices (without any perspective). * <p> * To build a translation matrix instead, use {@link #translation(Vector3f)}. * To apply a translation to another matrix, use {@link #translate(Vector3f)}. * * @see #translation(Vector3f) * @see #translate(Vector3f) * * @param xyz * the units to translate in <tt>(x, y, z)</tt> * @return this */ public Matrix4f setTranslation(Vector3f xyz) { m30 = xyz.x; m31 = xyz.y; m32 = xyz.z; return this; } /** * Get only the translation components <tt>(m30, m31, m32)</tt> of this matrix and store them in the given vector <code>xyz</code>. * * @param dest * will hold the translation components of this matrix * @return dest */ public Vector3f getTranslation(Vector3f dest) { dest.x = m30; dest.y = m31; dest.z = m32; return dest; } /** * Get the scaling factors of <code>this</code> matrix for the three base axes. * * @param dest * will hold the scaling factors for <tt>x</tt>, <tt>y</tt> and <tt>z</tt> * @return dest */ public Vector3f getScale(Vector3f dest) { dest.x = (float) Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); dest.y = (float) Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12); dest.z = (float) Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22); return dest; } /** * Return a string representation of this matrix. * <p> * This method creates a new {@link DecimalFormat} on every invocation with the format string "<tt> 0.000E0; -</tt>". * * @return the string representation */ public String toString() { DecimalFormat formatter = new DecimalFormat(" 0.000E0; -"); //$NON-NLS-1$ return toString(formatter).replaceAll("E(\\d+)", "E+$1"); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Return a string representation of this matrix by formatting the matrix elements with the given {@link NumberFormat}. * * @param formatter * the {@link NumberFormat} used to format the matrix values with * @return the string representation */ public String toString(NumberFormat formatter) { return formatter.format(m00) + formatter.format(m10) + formatter.format(m20) + formatter.format(m30) + "\n" //$NON-NLS-1$ + formatter.format(m01) + formatter.format(m11) + formatter.format(m21) + formatter.format(m31) + "\n" //$NON-NLS-1$ + formatter.format(m02) + formatter.format(m12) + formatter.format(m22) + formatter.format(m32) + "\n" //$NON-NLS-1$ + formatter.format(m03) + formatter.format(m13) + formatter.format(m23) + formatter.format(m33) + "\n"; //$NON-NLS-1$ } /** * Get the current values of <code>this</code> matrix and store them into * <code>dest</code>. * <p> * This is the reverse method of {@link #set(Matrix4f)} and allows to obtain * intermediate calculation results when chaining multiple transformations. * * @see #set(Matrix4f) * * @param dest * the destination matrix * @return the passed in destination */ public Matrix4f get(Matrix4f dest) { return dest.set(this); } /** * Get the current values of <code>this</code> matrix and store them into * <code>dest</code>. * <p> * This is the reverse method of {@link #set(Matrix4d)} and allows to obtain * intermediate calculation results when chaining multiple transformations. * * @see #set(Matrix4d) * * @param dest * the destination matrix * @return the passed in destination */ public Matrix4d get(Matrix4d dest) { return dest.set(this); } /** * Get the current values of the upper left 3x3 submatrix of <code>this</code> matrix and store them into * <code>dest</code>. * * @param dest * the destination matrix * @return the passed in destination */ public Matrix3f get3x3(Matrix3f dest) { return dest.set(this); } /** * Get the current values of the upper left 3x3 submatrix of <code>this</code> matrix and store them into * <code>dest</code>. * * @param dest * the destination matrix * @return the passed in destination */ public Matrix3d get3x3(Matrix3d dest) { return dest.set(this); } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link AxisAngle4f}. * * @see AxisAngle4f#set(Matrix4f) * * @param dest * the destination {@link AxisAngle4f} * @return the passed in destination */ public AxisAngle4f getRotation(AxisAngle4f dest) { return dest.set(this); } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link AxisAngle4d}. * * @see AxisAngle4f#set(Matrix4f) * * @param dest * the destination {@link AxisAngle4d} * @return the passed in destination */ public AxisAngle4d getRotation(AxisAngle4d dest) { return dest.set(this); } /** * Get the current values of <code>this</code> matrix and store the represented rotation * into the given {@link Quaternionf}. * <p> * This method assumes that the first three column vectors of the upper left 3x3 submatrix are not normalized and * thus allows to ignore any additional scaling factor that is applied to the matrix. * * @see Quaternionf#setFromUnnormalized(Matrix4f) * * @param dest * the destination {@link Quaternionf} * @return the passed in destination */ public Quaternionf getUnnormalizedRotation(Quaternionf dest) { return dest.setFromUnnormalized(this); } /** * Get the current values of <code>this</code> matrix and store the represented rotation * into the given {@link Quaternionf}. * <p> * This method assumes that the first three column vectors of the upper left 3x3 submatrix are normalized. * * @see Quaternionf#setFromNormalized(Matrix4f) * * @param dest * the destination {@link Quaternionf} * @return the passed in destination */ public Quaternionf getNormalizedRotation(Quaternionf dest) { return dest.setFromNormalized(this); } /** * Get the current values of <code>this</code> matrix and store the represented rotation * into the given {@link Quaterniond}. * <p> * This method assumes that the first three column vectors of the upper left 3x3 submatrix are not normalized and * thus allows to ignore any additional scaling factor that is applied to the matrix. * * @see Quaterniond#setFromUnnormalized(Matrix4f) * * @param dest * the destination {@link Quaterniond} * @return the passed in destination */ public Quaterniond getUnnormalizedRotation(Quaterniond dest) { return dest.setFromUnnormalized(this); } /** * Get the current values of <code>this</code> matrix and store the represented rotation * into the given {@link Quaterniond}. * <p> * This method assumes that the first three column vectors of the upper left 3x3 submatrix are normalized. * * @see Quaterniond#setFromNormalized(Matrix4f) * * @param dest * the destination {@link Quaterniond} * @return the passed in destination */ public Quaterniond getNormalizedRotation(Quaterniond dest) { return dest.setFromNormalized(this); } /** * Store this matrix in column-major order into the supplied {@link FloatBuffer} at the current * buffer {@link FloatBuffer#position() position}. * <p> * This method will not increment the position of the given FloatBuffer. * <p> * In order to specify the offset into the FloatBuffer at which * the matrix is stored, use {@link #get(int, FloatBuffer)}, taking * the absolute position as parameter. * * @see #get(int, FloatBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return the passed in buffer */ public FloatBuffer get(FloatBuffer buffer) { return get(buffer.position(), buffer); } /** * Store this matrix in column-major order into the supplied {@link FloatBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given FloatBuffer. * * @param index * the absolute position into the FloatBuffer * @param buffer * will receive the values of this matrix in column-major order * @return the passed in buffer */ public FloatBuffer get(int index, FloatBuffer buffer) { MemUtil.INSTANCE.put(this, index, buffer); return buffer; } /** * Store this matrix in column-major order into the supplied {@link ByteBuffer} at the current * buffer {@link ByteBuffer#position() position}. * <p> * This method will not increment the position of the given ByteBuffer. * <p> * In order to specify the offset into the ByteBuffer at which * the matrix is stored, use {@link #get(int, ByteBuffer)}, taking * the absolute position as parameter. * * @see #get(int, ByteBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return the passed in buffer */ public ByteBuffer get(ByteBuffer buffer) { return get(buffer.position(), buffer); } /** * Store this matrix in column-major order into the supplied {@link ByteBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given ByteBuffer. * * @param index * the absolute position into the ByteBuffer * @param buffer * will receive the values of this matrix in column-major order * @return the passed in buffer */ public ByteBuffer get(int index, ByteBuffer buffer) { MemUtil.INSTANCE.put(this, index, buffer); return buffer; } /** * Store the transpose of this matrix in column-major order into the supplied {@link FloatBuffer} at the current * buffer {@link FloatBuffer#position() position}. * <p> * This method will not increment the position of the given FloatBuffer. * <p> * In order to specify the offset into the FloatBuffer at which * the matrix is stored, use {@link #getTransposed(int, FloatBuffer)}, taking * the absolute position as parameter. * * @see #getTransposed(int, FloatBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return the passed in buffer */ public FloatBuffer getTransposed(FloatBuffer buffer) { return getTransposed(buffer.position(), buffer); } /** * Store the transpose of this matrix in column-major order into the supplied {@link FloatBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given FloatBuffer. * * @param index * the absolute position into the FloatBuffer * @param buffer * will receive the values of this matrix in column-major order * @return the passed in buffer */ public FloatBuffer getTransposed(int index, FloatBuffer buffer) { MemUtil.INSTANCE.putTransposed(this, index, buffer); return buffer; } /** * Store the transpose of this matrix in column-major order into the supplied {@link ByteBuffer} at the current * buffer {@link ByteBuffer#position() position}. * <p> * This method will not increment the position of the given ByteBuffer. * <p> * In order to specify the offset into the ByteBuffer at which * the matrix is stored, use {@link #getTransposed(int, ByteBuffer)}, taking * the absolute position as parameter. * * @see #getTransposed(int, ByteBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return the passed in buffer */ public ByteBuffer getTransposed(ByteBuffer buffer) { return getTransposed(buffer.position(), buffer); } /** * Store the transpose of this matrix in column-major order into the supplied {@link ByteBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given ByteBuffer. * * @param index * the absolute position into the ByteBuffer * @param buffer * will receive the values of this matrix in column-major order * @return the passed in buffer */ public ByteBuffer getTransposed(int index, ByteBuffer buffer) { MemUtil.INSTANCE.putTransposed(this, index, buffer); return buffer; } /** * Store this matrix into the supplied float array in column-major order at the given offset. * * @param arr * the array to write the matrix values into * @param offset * the offset into the array * @return the passed in array */ public float[] get(float[] arr, int offset) { arr[offset+0] = m00; arr[offset+1] = m01; arr[offset+2] = m02; arr[offset+3] = m03; arr[offset+4] = m10; arr[offset+5] = m11; arr[offset+6] = m12; arr[offset+7] = m13; arr[offset+8] = m20; arr[offset+9] = m21; arr[offset+10] = m22; arr[offset+11] = m23; arr[offset+12] = m30; arr[offset+13] = m31; arr[offset+14] = m32; arr[offset+15] = m33; return arr; } /** * Store this matrix into the supplied float array in column-major order. * <p> * In order to specify an explicit offset into the array, use the method {@link #get(float[], int)}. * * @see #get(float[], int) * * @param arr * the array to write the matrix values into * @return the passed in array */ public float[] get(float[] arr) { return get(arr, 0); } /** * Set all the values within this matrix to <code>0</code>. * * @return this */ public Matrix4f zero() { m00 = 0.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 0.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 0.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be a simple scale matrix, which scales all axes uniformly by the given factor. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * In order to post-multiply a scaling transformation directly to a * matrix, use {@link #scale(float) scale()} instead. * * @see #scale(float) * * @param factor * the scale factor in x, y and z * @return this */ public Matrix4f scaling(float factor) { m00 = factor; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = factor; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = factor; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a simple scale matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * In order to post-multiply a scaling transformation directly to a * matrix, use {@link #scale(float, float, float) scale()} instead. * * @see #scale(float, float, float) * * @param x * the scale in x * @param y * the scale in y * @param z * the scale in z * @return this */ public Matrix4f scaling(float x, float y, float z) { m00 = x; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = y; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = z; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a simple scale matrix which scales the base axes by <tt>xyz.x</tt>, <tt>xyz.y</tt> and <tt>xyz.z</tt> respectively. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * In order to post-multiply a scaling transformation directly to a * matrix use {@link #scale(Vector3f) scale()} instead. * * @see #scale(Vector3f) * * @param xyz * the scale in x, y and z respectively * @return this */ public Matrix4f scaling(Vector3f xyz) { return scaling(xyz.x, xyz.y, xyz.z); } /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to post-multiply a rotation transformation directly to a * matrix, use {@link #rotate(float, Vector3f) rotate()} instead. * * @see #rotate(float, Vector3f) * * @param angle * the angle in radians * @param axis * the axis to rotate about (needs to be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f rotation(float angle, Vector3f axis) { return rotation(angle, axis.x, axis.y, axis.z); } /** * Set this matrix to a rotation transformation using the given {@link AxisAngle4f}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(AxisAngle4f) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @return this */ public Matrix4f rotation(AxisAngle4f axisAngle) { return rotation(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); } /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(float, float, float, float) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * * @param angle * the angle in radians * @param x * the x-component of the rotation axis * @param y * the y-component of the rotation axis * @param z * the z-component of the rotation axis * @return this */ public Matrix4f rotation(float angle, float x, float y, float z) { float cos = (float) Math.cos(angle); float sin = (float) Math.sin(angle); float C = 1.0f - cos; float xy = x * y, xz = x * z, yz = y * z; m00 = cos + x * x * C; m10 = xy * C - z * sin; m20 = xz * C + y * sin; m30 = 0.0f; m01 = xy * C + z * sin; m11 = cos + y * y * C; m21 = yz * C - x * sin; m31 = 0.0f; m02 = xz * C - y * sin; m12 = yz * C + x * sin; m22 = cos + z * z * C; m32 = 0.0f; m03 = 0.0f; m13 = 0.0f; m23 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationX(float ang) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = cos; m12 = sin; m13 = 0.0f; m20 = 0.0f; m21 = -sin; m22 = cos; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the Y axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationY(float ang) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } m00 = cos; m01 = 0.0f; m02 = -sin; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = sin; m21 = 0.0f; m22 = cos; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationZ(float ang) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } m00 = cos; m01 = sin; m02 = 0.0f; m03 = 0.0f; m10 = -sin; m11 = cos; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation of <code>angleX</code> radians about the X axis, followed by a rotation * of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>rotationX(angleX).rotateY(angleY).rotateZ(angleZ)</tt> * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotationXYZ(float angleX, float angleY, float angleZ) { float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm11 = cosX; float nm12 = sinX; float nm21 = m_sinX; float nm22 = cosX; // rotateY float nm00 = cosY; float nm01 = nm21 * m_sinY; float nm02 = nm22 * m_sinY; m20 = sinY; m21 = nm21 * cosY; m22 = nm22 * cosY; m23 = 0.0f; // rotateZ m00 = nm00 * cosZ; m01 = nm01 * cosZ + nm11 * sinZ; m02 = nm02 * cosZ + nm12 * sinZ; m03 = 0.0f; m10 = nm00 * m_sinZ; m11 = nm01 * m_sinZ + nm11 * cosZ; m12 = nm02 * m_sinZ + nm12 * cosZ; m13 = 0.0f; // set last column to identity m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation * of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleX</code> radians about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>rotationZ(angleZ).rotateY(angleY).rotateX(angleX)</tt> * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @return this */ public Matrix4f rotationZYX(float angleZ, float angleY, float angleX) { float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = cosZ; float nm01 = sinZ; float nm10 = m_sinZ; float nm11 = cosZ; // rotateY float nm20 = nm00 * sinY; float nm21 = nm01 * sinY; float nm22 = cosY; m00 = nm00 * cosY; m01 = nm01 * cosY; m02 = m_sinY; m03 = 0.0f; // rotateX m10 = nm10 * cosX + nm20 * sinX; m11 = nm11 * cosX + nm21 * sinX; m12 = nm22 * sinX; m13 = 0.0f; m20 = nm10 * m_sinX + nm20 * cosX; m21 = nm11 * m_sinX + nm21 * cosX; m22 = nm22 * cosX; m23 = 0.0f; // set last column to identity m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation of <code>angleY</code> radians about the Y axis, followed by a rotation * of <code>angleX</code> radians about the X axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>rotationY(angleY).rotateX(angleX).rotateZ(angleZ)</tt> * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotationYXZ(float angleY, float angleX, float angleZ) { float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinY = -sinY; float m_sinX = -sinX; float m_sinZ = -sinZ; // rotateY float nm00 = cosY; float nm02 = m_sinY; float nm20 = sinY; float nm22 = cosY; // rotateX float nm10 = nm20 * sinX; float nm11 = cosX; float nm12 = nm22 * sinX; m20 = nm20 * cosX; m21 = m_sinX; m22 = nm22 * cosX; m23 = 0.0f; // rotateZ m00 = nm00 * cosZ + nm10 * sinZ; m01 = nm11 * sinZ; m02 = nm02 * cosZ + nm12 * sinZ; m03 = 0.0f; m10 = nm00 * m_sinZ + nm10 * cosZ; m11 = nm11 * cosZ; m12 = nm02 * m_sinZ + nm12 * cosZ; m13 = 0.0f; // set last column to identity m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set only the upper left 3x3 submatrix of this matrix to a rotation of <code>angleX</code> radians about the X axis, followed by a rotation * of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f setRotationXYZ(float angleX, float angleY, float angleZ) { float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm11 = cosX; float nm12 = sinX; float nm21 = m_sinX; float nm22 = cosX; // rotateY float nm00 = cosY; float nm01 = nm21 * m_sinY; float nm02 = nm22 * m_sinY; m20 = sinY; m21 = nm21 * cosY; m22 = nm22 * cosY; // rotateZ m00 = nm00 * cosZ; m01 = nm01 * cosZ + nm11 * sinZ; m02 = nm02 * cosZ + nm12 * sinZ; m10 = nm00 * m_sinZ; m11 = nm01 * m_sinZ + nm11 * cosZ; m12 = nm02 * m_sinZ + nm12 * cosZ; return this; } /** * Set only the upper left 3x3 submatrix of this matrix to a rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation * of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleX</code> radians about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @return this */ public Matrix4f setRotationZYX(float angleZ, float angleY, float angleX) { float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = cosZ; float nm01 = sinZ; float nm10 = m_sinZ; float nm11 = cosZ; // rotateY float nm20 = nm00 * sinY; float nm21 = nm01 * sinY; float nm22 = cosY; m00 = nm00 * cosY; m01 = nm01 * cosY; m02 = m_sinY; // rotateX m10 = nm10 * cosX + nm20 * sinX; m11 = nm11 * cosX + nm21 * sinX; m12 = nm22 * sinX; m20 = nm10 * m_sinX + nm20 * cosX; m21 = nm11 * m_sinX + nm21 * cosX; m22 = nm22 * cosX; return this; } /** * Set only the upper left 3x3 submatrix of this matrix to a rotation of <code>angleY</code> radians about the Y axis, followed by a rotation * of <code>angleX</code> radians about the X axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f setRotationYXZ(float angleY, float angleX, float angleZ) { float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinY = -sinY; float m_sinX = -sinX; float m_sinZ = -sinZ; // rotateY float nm00 = cosY; float nm02 = m_sinY; float nm20 = sinY; float nm22 = cosY; // rotateX float nm10 = nm20 * sinX; float nm11 = cosX; float nm12 = nm22 * sinX; m20 = nm20 * cosX; m21 = m_sinX; m22 = nm22 * cosX; // rotateZ m00 = nm00 * cosZ + nm10 * sinZ; m01 = nm11 * sinZ; m02 = nm02 * cosZ + nm12 * sinZ; m10 = nm00 * m_sinZ + nm10 * cosZ; m11 = nm11 * cosZ; m12 = nm02 * m_sinZ + nm12 * cosZ; return this; } /** * Set this matrix to the rotation transformation of the given {@link Quaternionf}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(Quaternionf) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotate(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotation(Quaternionf quat) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; m00 = 1.0f - q11 - q22; m01 = q01 + q23; m02 = q02 - q13; m03 = 0.0f; m10 = q01 - q23; m11 = 1.0f - q22 - q00; m12 = q12 + q03; m13 = 0.0f; m20 = q02 + q13; m21 = q12 - q03; m22 = 1.0f - q11 - q00; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt>, * <tt>R</tt> is a rotation transformation specified by the quaternion <tt>(qx, qy, qz, qw)</tt>, and <tt>S</tt> is a scaling transformation * which scales the three axes x, y and z by <tt>(sx, sy, sz)</tt>. * <p> * When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and * at last the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat).scale(sx, sy, sz)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * @see #scale(float, float, float) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param qx * the x-coordinate of the vector part of the quaternion * @param qy * the y-coordinate of the vector part of the quaternion * @param qz * the z-coordinate of the vector part of the quaternion * @param qw * the scalar part of the quaternion * @param sx * the scaling factor for the x-axis * @param sy * the scaling factor for the y-axis * @param sz * the scaling factor for the z-axis * @return this */ public Matrix4f translationRotateScale(float tx, float ty, float tz, float qx, float qy, float qz, float qw, float sx, float sy, float sz) { float dqx = qx + qx; float dqy = qy + qy; float dqz = qz + qz; float q00 = dqx * qx; float q11 = dqy * qy; float q22 = dqz * qz; float q01 = dqx * qy; float q02 = dqx * qz; float q03 = dqx * qw; float q12 = dqy * qz; float q13 = dqy * qw; float q23 = dqz * qw; m00 = sx - (q11 + q22) * sx; m01 = (q01 + q23) * sx; m02 = (q02 - q13) * sx; m03 = 0.0f; m10 = (q01 - q23) * sy; m11 = sy - (q22 + q00) * sy; m12 = (q12 + q03) * sy; m13 = 0.0f; m20 = (q02 + q13) * sz; m21 = (q12 - q03) * sz; m22 = sz - (q11 + q00) * sz; m23 = 0.0f; m30 = tx; m31 = ty; m32 = tz; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S</tt>, where <tt>T</tt> is the given <code>translation</code>, * <tt>R</tt> is a rotation transformation specified by the given quaternion, and <tt>S</tt> is a scaling transformation * which scales the axes by <code>scale</code>. * <p> * When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and * at last the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(translation).rotate(quat).scale(scale)</tt> * * @see #translation(Vector3f) * @see #rotate(Quaternionf) * * @param translation * the translation * @param quat * the quaternion representing a rotation * @param scale * the scaling factors * @return this */ public Matrix4f translationRotateScale(Vector3f translation, Quaternionf quat, Vector3f scale) { return translationRotateScale(translation.x, translation.y, translation.z, quat.x, quat.y, quat.z, quat.w, scale.x, scale.y, scale.z); } /** * Set <code>this</code> matrix to <tt>T * R * S * M</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt>, * <tt>R</tt> is a rotation transformation specified by the quaternion <tt>(qx, qy, qz, qw)</tt>, <tt>S</tt> is a scaling transformation * which scales the three axes x, y and z by <tt>(sx, sy, sz)</tt> and <code>M</code> is an {@link #isAffine() affine} matrix. * <p> * When transforming a vector by the resulting matrix the transformation described by <code>M</code> will be applied first, then the scaling, then rotation and * at last the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat).scale(sx, sy, sz).mulAffine(m)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * @see #scale(float, float, float) * @see #mulAffine(Matrix4f) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param qx * the x-coordinate of the vector part of the quaternion * @param qy * the y-coordinate of the vector part of the quaternion * @param qz * the z-coordinate of the vector part of the quaternion * @param qw * the scalar part of the quaternion * @param sx * the scaling factor for the x-axis * @param sy * the scaling factor for the y-axis * @param sz * the scaling factor for the z-axis * @param m * the {@link #isAffine() affine} matrix to multiply by * @return this */ public Matrix4f translationRotateScaleMulAffine(float tx, float ty, float tz, float qx, float qy, float qz, float qw, float sx, float sy, float sz, Matrix4f m) { float dqx = qx + qx; float dqy = qy + qy; float dqz = qz + qz; float q00 = dqx * qx; float q11 = dqy * qy; float q22 = dqz * qz; float q01 = dqx * qy; float q02 = dqx * qz; float q03 = dqx * qw; float q12 = dqy * qz; float q13 = dqy * qw; float q23 = dqz * qw; float nm00 = sx - (q11 + q22) * sx; float nm01 = (q01 + q23) * sx; float nm02 = (q02 - q13) * sx; float nm10 = (q01 - q23) * sy; float nm11 = sy - (q22 + q00) * sy; float nm12 = (q12 + q03) * sy; float nm20 = (q02 + q13) * sz; float nm21 = (q12 - q03) * sz; float nm22 = sz - (q11 + q00) * sz; float m00 = nm00 * m.m00 + nm10 * m.m01 + nm20 * m.m02; float m01 = nm01 * m.m00 + nm11 * m.m01 + nm21 * m.m02; m02 = nm02 * m.m00 + nm12 * m.m01 + nm22 * m.m02; this.m00 = m00; this.m01 = m01; m03 = 0.0f; float m10 = nm00 * m.m10 + nm10 * m.m11 + nm20 * m.m12; float m11 = nm01 * m.m10 + nm11 * m.m11 + nm21 * m.m12; m12 = nm02 * m.m10 + nm12 * m.m11 + nm22 * m.m12; this.m10 = m10; this.m11 = m11; m13 = 0.0f; float m20 = nm00 * m.m20 + nm10 * m.m21 + nm20 * m.m22; float m21 = nm01 * m.m20 + nm11 * m.m21 + nm21 * m.m22; m22 = nm02 * m.m20 + nm12 * m.m21 + nm22 * m.m22; this.m20 = m20; this.m21 = m21; m23 = 0.0f; float m30 = nm00 * m.m30 + nm10 * m.m31 + nm20 * m.m32 + tx; float m31 = nm01 * m.m30 + nm11 * m.m31 + nm21 * m.m32 + ty; m32 = nm02 * m.m30 + nm12 * m.m31 + nm22 * m.m32 + tz; this.m30 = m30; this.m31 = m31; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S * M</tt>, where <tt>T</tt> is the given <code>translation</code>, * <tt>R</tt> is a rotation transformation specified by the given quaternion, <tt>S</tt> is a scaling transformation * which scales the axes by <code>scale</code> and <code>M</code> is an {@link #isAffine() affine} matrix. * <p> * When transforming a vector by the resulting matrix the transformation described by <code>M</code> will be applied first, then the scaling, then rotation and * at last the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(translation).rotate(quat).scale(scale).mulAffine(m)</tt> * * @see #translation(Vector3f) * @see #rotate(Quaternionf) * @see #mulAffine(Matrix4f) * * @param translation * the translation * @param quat * the quaternion representing a rotation * @param scale * the scaling factors * @param m * the {@link #isAffine() affine} matrix to multiply by * @return this */ public Matrix4f translationRotateScaleMulAffine(Vector3f translation, Quaternionf quat, Vector3f scale, Matrix4f m) { return translationRotateScaleMulAffine(translation.x, translation.y, translation.z, quat.x, quat.y, quat.z, quat.w, scale.x, scale.y, scale.z, m); } /** * Set <code>this</code> matrix to <tt>T * R</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt> and * <tt>R</tt> is a rotation transformation specified by the given quaternion. * <p> * When transforming a vector by the resulting matrix the rotation transformation will be applied first and then the translation. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param quat * the quaternion representing a rotation * @return this */ public Matrix4f translationRotate(float tx, float ty, float tz, Quaternionf quat) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; m00 = 1.0f - (q11 + q22); m01 = q01 + q23; m02 = q02 - q13; m03 = 0.0f; m10 = q01 - q23; m11 = 1.0f - (q22 + q00); m12 = q12 + q03; m13 = 0.0f; m20 = q02 + q13; m21 = q12 - q03; m22 = 1.0f - (q11 + q00); m23 = 0.0f; m30 = tx; m31 = ty; m32 = tz; m33 = 1.0f; return this; } /** * Set the upper left 3x3 submatrix of this {@link Matrix4f} to the given {@link Matrix3f} and don't change the other elements.. * * @param mat * the 3x3 matrix * @return this */ public Matrix4f set3x3(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; return this; } /** * Transform/multiply the given vector by this matrix and store the result in that vector. * * @see Vector4f#mul(Matrix4f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector4f transform(Vector4f v) { return v.mul(this); } /** * Transform/multiply the given vector by this matrix and store the result in <code>dest</code>. * * @see Vector4f#mul(Matrix4f, Vector4f) * * @param v * the vector to transform * @param dest * will contain the result * @return dest */ public Vector4f transform(Vector4f v, Vector4f dest) { return v.mul(this, dest); } /** * Transform/multiply the given vector by this matrix, perform perspective divide and store the result in that vector. * * @see Vector4f#mulProject(Matrix4f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector4f transformProject(Vector4f v) { return v.mulProject(this); } /** * Transform/multiply the given vector by this matrix, perform perspective divide and store the result in <code>dest</code>. * * @see Vector4f#mulProject(Matrix4f, Vector4f) * * @param v * the vector to transform * @param dest * will contain the result * @return dest */ public Vector4f transformProject(Vector4f v, Vector4f dest) { return v.mulProject(this, dest); } /** * Transform/multiply the given vector by this matrix, perform perspective divide and store the result in that vector. * <p> * This method uses <tt>w=1.0</tt> as the fourth vector component. * * @see Vector3f#mulProject(Matrix4f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector3f transformProject(Vector3f v) { return v.mulProject(this); } /** * Transform/multiply the given vector by this matrix, perform perspective divide and store the result in <code>dest</code>. * <p> * This method uses <tt>w=1.0</tt> as the fourth vector component. * * @see Vector3f#mulProject(Matrix4f, Vector3f) * * @param v * the vector to transform * @param dest * will contain the result * @return dest */ public Vector3f transformProject(Vector3f v, Vector3f dest) { return v.mulProject(this, dest); } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=1, by * this matrix and store the result in that vector. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being 1.0, so it * will represent a position/location in 3D-space rather than a direction. This method is therefore * not suited for perspective projection transformations as it will not save the * <tt>w</tt> component of the transformed vector. * For perspective projection use {@link #transform(Vector4f)} or {@link #transformProject(Vector3f)} * when perspective divide should be applied, too. * <p> * In order to store the result in another vector, use {@link #transformPosition(Vector3f, Vector3f)}. * * @see #transformPosition(Vector3f, Vector3f) * @see #transform(Vector4f) * @see #transformProject(Vector3f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector3f transformPosition(Vector3f v) { v.set(m00 * v.x + m10 * v.y + m20 * v.z + m30, m01 * v.x + m11 * v.y + m21 * v.z + m31, m02 * v.x + m12 * v.y + m22 * v.z + m32); return v; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=1, by * this matrix and store the result in <code>dest</code>. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being 1.0, so it * will represent a position/location in 3D-space rather than a direction. This method is therefore * not suited for perspective projection transformations as it will not save the * <tt>w</tt> component of the transformed vector. * For perspective projection use {@link #transform(Vector4f, Vector4f)} or * {@link #transformProject(Vector3f, Vector3f)} when perspective divide should be applied, too. * <p> * In order to store the result in the same vector, use {@link #transformPosition(Vector3f)}. * * @see #transformPosition(Vector3f) * @see #transform(Vector4f, Vector4f) * @see #transformProject(Vector3f, Vector3f) * * @param v * the vector to transform * @param dest * will hold the result * @return dest */ public Vector3f transformPosition(Vector3f v, Vector3f dest) { dest.set(m00 * v.x + m10 * v.y + m20 * v.z + m30, m01 * v.x + m11 * v.y + m21 * v.z + m31, m02 * v.x + m12 * v.y + m22 * v.z + m32); return dest; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=0, by * this matrix and store the result in that vector. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being <tt>0.0</tt>, so it * will represent a direction in 3D-space rather than a position. This method will therefore * not take the translation part of the matrix into account. * <p> * In order to store the result in another vector, use {@link #transformDirection(Vector3f, Vector3f)}. * * @see #transformDirection(Vector3f, Vector3f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector3f transformDirection(Vector3f v) { v.set(m00 * v.x + m10 * v.y + m20 * v.z, m01 * v.x + m11 * v.y + m21 * v.z, m02 * v.x + m12 * v.y + m22 * v.z); return v; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=0, by * this matrix and store the result in <code>dest</code>. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being <tt>0.0</tt>, so it * will represent a direction in 3D-space rather than a position. This method will therefore * not take the translation part of the matrix into account. * <p> * In order to store the result in the same vector, use {@link #transformDirection(Vector3f)}. * * @see #transformDirection(Vector3f) * * @param v * the vector to transform and to hold the final result * @param dest * will hold the result * @return dest */ public Vector3f transformDirection(Vector3f v, Vector3f dest) { dest.set(m00 * v.x + m10 * v.y + m20 * v.z, m01 * v.x + m11 * v.y + m21 * v.z, m02 * v.x + m12 * v.y + m22 * v.z); return dest; } /** * Transform/multiply the given 4D-vector by assuming that <code>this</code> matrix represents an {@link #isAffine() affine} transformation * (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>). * <p> * In order to store the result in another vector, use {@link #transformAffine(Vector4f, Vector4f)}. * * @see #transformAffine(Vector4f, Vector4f) * * @param v * the vector to transform and to hold the final result * @return v */ public Vector4f transformAffine(Vector4f v) { v.set(m00 * v.x + m10 * v.y + m20 * v.z + m30 * v.w, m01 * v.x + m11 * v.y + m21 * v.z + m31 * v.w, m02 * v.x + m12 * v.y + m22 * v.z + m32 * v.w, v.w); return v; } /** * Transform/multiply the given 4D-vector by assuming that <code>this</code> matrix represents an {@link #isAffine() affine} transformation * (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) and store the result in <code>dest</code>. * <p> * In order to store the result in the same vector, use {@link #transformAffine(Vector4f)}. * * @see #transformAffine(Vector4f) * * @param v * the vector to transform and to hold the final result * @param dest * will hold the result * @return dest */ public Vector4f transformAffine(Vector4f v, Vector4f dest) { dest.set(m00 * v.x + m10 * v.y + m20 * v.z + m30 * v.w, m01 * v.x + m11 * v.y + m21 * v.z + m31 * v.w, m02 * v.x + m12 * v.y + m22 * v.z + m32 * v.w, v.w); return dest; } /** * Apply scaling to the this matrix by scaling the base axes by the given <tt>xyz.x</tt>, * <tt>xyz.y</tt> and <tt>xyz.z</tt> factors, respectively and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code> * , the scaling will be applied first! * * @param xyz * the factors of the x, y and z component, respectively * @param dest * will hold the result * @return dest */ public Matrix4f scale(Vector3f xyz, Matrix4f dest) { return scale(xyz.x, xyz.y, xyz.z, dest); } /** * Apply scaling to this matrix by scaling the base axes by the given <tt>xyz.x</tt>, * <tt>xyz.y</tt> and <tt>xyz.z</tt> factors, respectively. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * * @param xyz * the factors of the x, y and z component, respectively * @return this */ public Matrix4f scale(Vector3f xyz) { return scale(xyz.x, xyz.y, xyz.z, this); } /** * Apply scaling to this matrix by uniformly scaling all base axes by the given <code>xyz</code> factor * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * <p> * Individual scaling of all three axes can be applied using {@link #scale(float, float, float, Matrix4f)}. * * @see #scale(float, float, float, Matrix4f) * * @param xyz * the factor for all components * @param dest * will hold the result * @return dest */ public Matrix4f scale(float xyz, Matrix4f dest) { return scale(xyz, xyz, xyz, dest); } /** * Apply scaling to this matrix by uniformly scaling all base axes by the given <code>xyz</code> factor. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * <p> * Individual scaling of all three axes can be applied using {@link #scale(float, float, float)}. * * @see #scale(float, float, float) * * @param xyz * the factor for all components * @return this */ public Matrix4f scale(float xyz) { return scale(xyz, xyz, xyz); } /** * Apply scaling to the this matrix by scaling the base axes by the given x, * y and z factors and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code> * , the scaling will be applied first! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @param dest * will hold the result * @return dest */ public Matrix4f scale(float x, float y, float z, Matrix4f dest) { // scale matrix elements: // m00 = x, m11 = y, m22 = z // m33 = 1 // all others = 0 dest.m00 = m00 * x; dest.m01 = m01 * x; dest.m02 = m02 * x; dest.m03 = m03 * x; dest.m10 = m10 * y; dest.m11 = m11 * y; dest.m12 = m12 * y; dest.m13 = m13 * y; dest.m20 = m20 * z; dest.m21 = m21 * z; dest.m22 = m22 * z; dest.m23 = m23 * z; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply scaling to this matrix by scaling the base axes by the given x, * y and z factors. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @return this */ public Matrix4f scale(float x, float y, float z) { return scale(x, y, z, this); } /** * Apply rotation about the X axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return dest */ public Matrix4f rotateX(float ang, Matrix4f dest) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } float rm11 = cos; float rm12 = sin; float rm21 = -sin; float rm22 = cos; // add temporaries for dependent values float nm10 = m10 * rm11 + m20 * rm12; float nm11 = m11 * rm11 + m21 * rm12; float nm12 = m12 * rm11 + m22 * rm12; float nm13 = m13 * rm11 + m23 * rm12; // set non-dependent values directly dest.m20 = m10 * rm21 + m20 * rm22; dest.m21 = m11 * rm21 + m21 * rm22; dest.m22 = m12 * rm21 + m22 * rm22; dest.m23 = m13 * rm21 + m23 * rm22; // set other values dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation about the X axis to this matrix by rotating the given amount of radians. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateX(float ang) { return rotateX(ang, this); } /** * Apply rotation about the Y axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return dest */ public Matrix4f rotateY(float ang, Matrix4f dest) { float cos, sin; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } float rm00 = cos; float rm02 = -sin; float rm20 = sin; float rm22 = cos; // add temporaries for dependent values float nm00 = m00 * rm00 + m20 * rm02; float nm01 = m01 * rm00 + m21 * rm02; float nm02 = m02 * rm00 + m22 * rm02; float nm03 = m03 * rm00 + m23 * rm02; // set non-dependent values directly dest.m20 = m00 * rm20 + m20 * rm22; dest.m21 = m01 * rm20 + m21 * rm22; dest.m22 = m02 * rm20 + m22 * rm22; dest.m23 = m03 * rm20 + m23 * rm22; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = m13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation about the Y axis to this matrix by rotating the given amount of radians. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateY(float ang) { return rotateY(ang, this); } /** * Apply rotation about the Z axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return dest */ public Matrix4f rotateZ(float ang, Matrix4f dest) { float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { cos = (float) Math.cos(ang); sin = (float) Math.sin(ang); } float rm00 = cos; float rm01 = sin; float rm10 = -sin; float rm11 = cos; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01; float nm01 = m01 * rm00 + m11 * rm01; float nm02 = m02 * rm00 + m12 * rm01; float nm03 = m03 * rm00 + m13 * rm01; // set non-dependent values directly dest.m10 = m00 * rm10 + m10 * rm11; dest.m11 = m01 * rm10 + m11 * rm11; dest.m12 = m02 * rm10 + m12 * rm11; dest.m13 = m03 * rm10 + m13 * rm11; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = m23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation about the Z axis to this matrix by rotating the given amount of radians. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateZ(float ang) { return rotateZ(ang, this); } /** * Apply rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateX(angleX).rotateY(angleY).rotateZ(angleZ)</tt> * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotateXYZ(float angleX, float angleY, float angleZ) { return rotateXYZ(angleX, angleY, angleZ, this); } /** * Apply rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateX(angleX, dest).rotateY(angleY).rotateZ(angleZ)</tt> * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @param dest * will hold the result * @return dest */ public Matrix4f rotateXYZ(float angleX, float angleY, float angleZ, Matrix4f dest) { float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm10 = m10 * cosX + m20 * sinX; float nm11 = m11 * cosX + m21 * sinX; float nm12 = m12 * cosX + m22 * sinX; float nm13 = m13 * cosX + m23 * sinX; float nm20 = m10 * m_sinX + m20 * cosX; float nm21 = m11 * m_sinX + m21 * cosX; float nm22 = m12 * m_sinX + m22 * cosX; float nm23 = m13 * m_sinX + m23 * cosX; // rotateY float nm00 = m00 * cosY + nm20 * m_sinY; float nm01 = m01 * cosY + nm21 * m_sinY; float nm02 = m02 * cosY + nm22 * m_sinY; float nm03 = m03 * cosY + nm23 * m_sinY; dest.m20 = m00 * sinY + nm20 * cosY; dest.m21 = m01 * sinY + nm21 * cosY; dest.m22 = m02 * sinY + nm22 * cosY; dest.m23 = m03 * sinY + nm23 * cosY; // rotateZ dest.m00 = nm00 * cosZ + nm10 * sinZ; dest.m01 = nm01 * cosZ + nm11 * sinZ; dest.m02 = nm02 * cosZ + nm12 * sinZ; dest.m03 = nm03 * cosZ + nm13 * sinZ; dest.m10 = nm00 * m_sinZ + nm10 * cosZ; dest.m11 = nm01 * m_sinZ + nm11 * cosZ; dest.m12 = nm02 * m_sinZ + nm12 * cosZ; dest.m13 = nm03 * m_sinZ + nm13 * cosZ; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateX(angleX).rotateY(angleY).rotateZ(angleZ)</tt> * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotateAffineXYZ(float angleX, float angleY, float angleZ) { return rotateAffineXYZ(angleX, angleY, angleZ, this); } /** * Apply rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleX * the angle to rotate about X * @param angleY * the angle to rotate about Y * @param angleZ * the angle to rotate about Z * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineXYZ(float angleX, float angleY, float angleZ, Matrix4f dest) { float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm10 = m10 * cosX + m20 * sinX; float nm11 = m11 * cosX + m21 * sinX; float nm12 = m12 * cosX + m22 * sinX; float nm20 = m10 * m_sinX + m20 * cosX; float nm21 = m11 * m_sinX + m21 * cosX; float nm22 = m12 * m_sinX + m22 * cosX; // rotateY float nm00 = m00 * cosY + nm20 * m_sinY; float nm01 = m01 * cosY + nm21 * m_sinY; float nm02 = m02 * cosY + nm22 * m_sinY; dest.m20 = m00 * sinY + nm20 * cosY; dest.m21 = m01 * sinY + nm21 * cosY; dest.m22 = m02 * sinY + nm22 * cosY; dest.m23 = 0.0f; // rotateZ dest.m00 = nm00 * cosZ + nm10 * sinZ; dest.m01 = nm01 * cosZ + nm11 * sinZ; dest.m02 = nm02 * cosZ + nm12 * sinZ; dest.m03 = 0.0f; dest.m10 = nm00 * m_sinZ + nm10 * cosZ; dest.m11 = nm01 * m_sinZ + nm11 * cosZ; dest.m12 = nm02 * m_sinZ + nm12 * cosZ; dest.m13 = 0.0f; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleX</code> radians about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateZ(angleZ).rotateY(angleY).rotateX(angleX)</tt> * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @return this */ public Matrix4f rotateZYX(float angleZ, float angleY, float angleX) { return rotateZYX(angleZ, angleY, angleX, this); } /** * Apply rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleX</code> radians about the X axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateZ(angleZ, dest).rotateY(angleY).rotateX(angleX)</tt> * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param dest * will hold the result * @return dest */ public Matrix4f rotateZYX(float angleZ, float angleY, float angleX, Matrix4f dest) { float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = m00 * cosZ + m10 * sinZ; float nm01 = m01 * cosZ + m11 * sinZ; float nm02 = m02 * cosZ + m12 * sinZ; float nm03 = m03 * cosZ + m13 * sinZ; float nm10 = m00 * m_sinZ + m10 * cosZ; float nm11 = m01 * m_sinZ + m11 * cosZ; float nm12 = m02 * m_sinZ + m12 * cosZ; float nm13 = m03 * m_sinZ + m13 * cosZ; // rotateY float nm20 = nm00 * sinY + m20 * cosY; float nm21 = nm01 * sinY + m21 * cosY; float nm22 = nm02 * sinY + m22 * cosY; float nm23 = nm03 * sinY + m23 * cosY; dest.m00 = nm00 * cosY + m20 * m_sinY; dest.m01 = nm01 * cosY + m21 * m_sinY; dest.m02 = nm02 * cosY + m22 * m_sinY; dest.m03 = nm03 * cosY + m23 * m_sinY; // rotateX dest.m10 = nm10 * cosX + nm20 * sinX; dest.m11 = nm11 * cosX + nm21 * sinX; dest.m12 = nm12 * cosX + nm22 * sinX; dest.m13 = nm13 * cosX + nm23 * sinX; dest.m20 = nm10 * m_sinX + nm20 * cosX; dest.m21 = nm11 * m_sinX + nm21 * cosX; dest.m22 = nm12 * m_sinX + nm22 * cosX; dest.m23 = nm13 * m_sinX + nm23 * cosX; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleX</code> radians about the X axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @return this */ public Matrix4f rotateAffineZYX(float angleZ, float angleY, float angleX) { return rotateAffineZYX(angleZ, angleY, angleX, this); } /** * Apply rotation of <code>angleZ</code> radians about the Z axis, followed by a rotation of <code>angleY</code> radians about the Y axis and * followed by a rotation of <code>angleX</code> radians about the X axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleZ * the angle to rotate about Z * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineZYX(float angleZ, float angleY, float angleX, Matrix4f dest) { float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float m_sinZ = -sinZ; float m_sinY = -sinY; float m_sinX = -sinX; // rotateZ float nm00 = m00 * cosZ + m10 * sinZ; float nm01 = m01 * cosZ + m11 * sinZ; float nm02 = m02 * cosZ + m12 * sinZ; float nm10 = m00 * m_sinZ + m10 * cosZ; float nm11 = m01 * m_sinZ + m11 * cosZ; float nm12 = m02 * m_sinZ + m12 * cosZ; // rotateY float nm20 = nm00 * sinY + m20 * cosY; float nm21 = nm01 * sinY + m21 * cosY; float nm22 = nm02 * sinY + m22 * cosY; dest.m00 = nm00 * cosY + m20 * m_sinY; dest.m01 = nm01 * cosY + m21 * m_sinY; dest.m02 = nm02 * cosY + m22 * m_sinY; dest.m03 = 0.0f; // rotateX dest.m10 = nm10 * cosX + nm20 * sinX; dest.m11 = nm11 * cosX + nm21 * sinX; dest.m12 = nm12 * cosX + nm22 * sinX; dest.m13 = 0.0f; dest.m20 = nm10 * m_sinX + nm20 * cosX; dest.m21 = nm11 * m_sinX + nm21 * cosX; dest.m22 = nm12 * m_sinX + nm22 * cosX; dest.m23 = 0.0f; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateY(angleY).rotateX(angleX).rotateZ(angleZ)</tt> * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotateYXZ(float angleY, float angleX, float angleZ) { return rotateYXZ(angleY, angleX, angleZ, this); } /** * Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * This method is equivalent to calling: <tt>rotateY(angleY, dest).rotateX(angleX).rotateZ(angleZ)</tt> * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @param dest * will hold the result * @return dest */ public Matrix4f rotateYXZ(float angleY, float angleX, float angleZ, Matrix4f dest) { float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinY = -sinY; float m_sinX = -sinX; float m_sinZ = -sinZ; // rotateY float nm20 = m00 * sinY + m20 * cosY; float nm21 = m01 * sinY + m21 * cosY; float nm22 = m02 * sinY + m22 * cosY; float nm23 = m03 * sinY + m23 * cosY; float nm00 = m00 * cosY + m20 * m_sinY; float nm01 = m01 * cosY + m21 * m_sinY; float nm02 = m02 * cosY + m22 * m_sinY; float nm03 = m03 * cosY + m23 * m_sinY; // rotateX float nm10 = m10 * cosX + nm20 * sinX; float nm11 = m11 * cosX + nm21 * sinX; float nm12 = m12 * cosX + nm22 * sinX; float nm13 = m13 * cosX + nm23 * sinX; dest.m20 = m10 * m_sinX + nm20 * cosX; dest.m21 = m11 * m_sinX + nm21 * cosX; dest.m22 = m12 * m_sinX + nm22 * cosX; dest.m23 = m13 * m_sinX + nm23 * cosX; // rotateZ dest.m00 = nm00 * cosZ + nm10 * sinZ; dest.m01 = nm01 * cosZ + nm11 * sinZ; dest.m02 = nm02 * cosZ + nm12 * sinZ; dest.m03 = nm03 * cosZ + nm13 * sinZ; dest.m10 = nm00 * m_sinZ + nm10 * cosZ; dest.m11 = nm01 * m_sinZ + nm11 * cosZ; dest.m12 = nm02 * m_sinZ + nm12 * cosZ; dest.m13 = nm03 * m_sinZ + nm13 * cosZ; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @return this */ public Matrix4f rotateAffineYXZ(float angleY, float angleX, float angleZ) { return rotateAffineYXZ(angleY, angleX, angleZ, this); } /** * Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and * followed by a rotation of <code>angleZ</code> radians about the Z axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <tt>(0, 0, 0, 1)</tt>) * and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination). * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * * @param angleY * the angle to rotate about Y * @param angleX * the angle to rotate about X * @param angleZ * the angle to rotate about Z * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineYXZ(float angleY, float angleX, float angleZ, Matrix4f dest) { float cosY = (float) Math.cos(angleY); float sinY = (float) Math.sin(angleY); float cosX = (float) Math.cos(angleX); float sinX = (float) Math.sin(angleX); float cosZ = (float) Math.cos(angleZ); float sinZ = (float) Math.sin(angleZ); float m_sinY = -sinY; float m_sinX = -sinX; float m_sinZ = -sinZ; // rotateY float nm20 = m00 * sinY + m20 * cosY; float nm21 = m01 * sinY + m21 * cosY; float nm22 = m02 * sinY + m22 * cosY; float nm00 = m00 * cosY + m20 * m_sinY; float nm01 = m01 * cosY + m21 * m_sinY; float nm02 = m02 * cosY + m22 * m_sinY; // rotateX float nm10 = m10 * cosX + nm20 * sinX; float nm11 = m11 * cosX + nm21 * sinX; float nm12 = m12 * cosX + nm22 * sinX; dest.m20 = m10 * m_sinX + nm20 * cosX; dest.m21 = m11 * m_sinX + nm21 * cosX; dest.m22 = m12 * m_sinX + nm22 * cosX; dest.m23 = 0.0f; // rotateZ dest.m00 = nm00 * cosZ + nm10 * sinZ; dest.m01 = nm01 * cosZ + nm11 * sinZ; dest.m02 = nm02 * cosZ + nm12 * sinZ; dest.m03 = 0.0f; dest.m10 = nm00 * m_sinZ + nm10 * cosZ; dest.m11 = nm01 * m_sinZ + nm11 * cosZ; dest.m12 = nm02 * m_sinZ + nm12 * cosZ; dest.m13 = 0.0f; // copy last column from 'this' dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation to this matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis and store the result in <code>dest</code>. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @param dest * will hold the result * @return dest */ public Matrix4f rotate(float ang, float x, float y, float z, Matrix4f dest) { float s = (float) Math.sin(ang); float c = (float) Math.cos(ang); float C = 1.0f - c; // rotation matrix elements: // m30, m31, m32, m03, m13, m23 = 0 // m33 = 1 float xx = x * x, xy = x * y, xz = x * z; float yy = y * y, yz = y * z; float zz = z * z; float rm00 = xx * C + c; float rm01 = xy * C + z * s; float rm02 = xz * C - y * s; float rm10 = xy * C - z * s; float rm11 = yy * C + c; float rm12 = yz * C + x * s; float rm20 = xz * C + y * s; float rm21 = yz * C - x * s; float rm22 = zz * C + c; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; // set non-dependent values directly dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation to this matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @return this */ public Matrix4f rotate(float ang, float x, float y, float z) { return rotate(ang, x, y, z, this); } /** * Apply rotation to this {@link #isAffine() affine} matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis and store the result in <code>dest</code>. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffine(float ang, float x, float y, float z, Matrix4f dest) { float s = (float) Math.sin(ang); float c = (float) Math.cos(ang); float C = 1.0f - c; float xx = x * x, xy = x * y, xz = x * z; float yy = y * y, yz = y * z; float zz = z * z; float rm00 = xx * C + c; float rm01 = xy * C + z * s; float rm02 = xz * C - y * s; float rm10 = xy * C - z * s; float rm11 = yy * C + c; float rm12 = yz * C + x * s; float rm20 = xz * C + y * s; float rm21 = yz * C - x * s; float rm22 = zz * C + c; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; // set non-dependent values directly dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = 0.0f; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = 0.0f; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = 0.0f; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply rotation to this {@link #isAffine() affine} matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @return this */ public Matrix4f rotateAffine(float ang, float x, float y, float z) { return rotateAffine(ang, x, y, z, this); } /** * Pre-multiply a rotation to this {@link #isAffine() affine} matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis and store the result in <code>dest</code>. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>R * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the * rotation will be applied last! * <p> * In order to set the matrix to a rotation matrix without pre-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineLocal(float ang, float x, float y, float z, Matrix4f dest) { float s = (float) Math.sin(ang); float c = (float) Math.cos(ang); float C = 1.0f - c; float xx = x * x, xy = x * y, xz = x * z; float yy = y * y, yz = y * z; float zz = z * z; float lm00 = xx * C + c; float lm01 = xy * C + z * s; float lm02 = xz * C - y * s; float lm10 = xy * C - z * s; float lm11 = yy * C + c; float lm12 = yz * C + x * s; float lm20 = xz * C + y * s; float lm21 = yz * C - x * s; float lm22 = zz * C + c; float nm00 = lm00 * m00 + lm10 * m01 + lm20 * m02; float nm01 = lm01 * m00 + lm11 * m01 + lm21 * m02; float nm02 = lm02 * m00 + lm12 * m01 + lm22 * m02; float nm03 = 0.0f; float nm10 = lm00 * m10 + lm10 * m11 + lm20 * m12; float nm11 = lm01 * m10 + lm11 * m11 + lm21 * m12; float nm12 = lm02 * m10 + lm12 * m11 + lm22 * m12; float nm13 = 0.0f; float nm20 = lm00 * m20 + lm10 * m21 + lm20 * m22; float nm21 = lm01 * m20 + lm11 * m21 + lm21 * m22; float nm22 = lm02 * m20 + lm12 * m21 + lm22 * m22; float nm23 = 0.0f; float nm30 = lm00 * m30 + lm10 * m31 + lm20 * m32; float nm31 = lm01 * m30 + lm11 * m31 + lm21 * m32; float nm32 = lm02 * m30 + lm12 * m31 + lm22 * m32; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Pre-multiply a rotation to this {@link #isAffine() affine} matrix by rotating the given amount of radians * about the specified <tt>(x, y, z)</tt> axis. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * The axis described by the three components needs to be a unit vector. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>R * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the * rotation will be applied last! * <p> * In order to set the matrix to a rotation matrix without pre-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @return this */ public Matrix4f rotateAffineLocal(float ang, float x, float y, float z) { return rotateAffineLocal(ang, x, y, z, this); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @return this */ public Matrix4f translate(Vector3f offset) { return translate(offset.x, offset.y, offset.z); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @param dest * will hold the result * @return dest */ public Matrix4f translate(Vector3f offset, Matrix4f dest) { return translate(offset.x, offset.y, offset.z, dest); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @param dest * will hold the result * @return dest */ public Matrix4f translate(float x, float y, float z, Matrix4f dest) { // translation matrix elements: // m00, m11, m22, m33 = 1 // m30 = x, m31 = y, m32 = z // all others = 0 dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = m13; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = m23; dest.m30 = m00 * x + m10 * y + m20 * z + m30; dest.m31 = m01 * x + m11 * y + m21 * z + m31; dest.m32 = m02 * x + m12 * y + m22 * z + m32; dest.m33 = m03 * x + m13 * y + m23 * z + m33; return dest; } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translate(float x, float y, float z) { Matrix4f c = this; // translation matrix elements: // m00, m11, m22, m33 = 1 // m30 = x, m31 = y, m32 = z // all others = 0 c.m30 = c.m00 * x + c.m10 * y + c.m20 * z + c.m30; c.m31 = c.m01 * x + c.m11 * y + c.m21 * z + c.m31; c.m32 = c.m02 * x + c.m12 * y + c.m22 * z + c.m32; c.m33 = c.m03 * x + c.m13 * y + c.m23 * z + c.m33; return this; } /** * Pre-multiply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>T * M</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>T * M * v</code>, the translation will be applied last! * <p> * In order to set the matrix to a translation transformation without pre-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @return this */ public Matrix4f translateLocal(Vector3f offset) { return translateLocal(offset.x, offset.y, offset.z); } /** * Pre-multiply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>T * M</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>T * M * v</code>, the translation will be applied last! * <p> * In order to set the matrix to a translation transformation without pre-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @param dest * will hold the result * @return dest */ public Matrix4f translateLocal(Vector3f offset, Matrix4f dest) { return translateLocal(offset.x, offset.y, offset.z, dest); } /** * Pre-multiply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>T * M</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>T * M * v</code>, the translation will be applied last! * <p> * In order to set the matrix to a translation transformation without pre-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @param dest * will hold the result * @return dest */ public Matrix4f translateLocal(float x, float y, float z, Matrix4f dest) { float nm00 = m00 + x * m03; float nm01 = m01 + y * m03; float nm02 = m02 + z * m03; float nm03 = m03; float nm10 = m10 + x * m13; float nm11 = m11 + y * m13; float nm12 = m12 + z * m13; float nm13 = m13; float nm20 = m20 + x * m23; float nm21 = m21 + y * m23; float nm22 = m22 + z * m23; float nm23 = m23; float nm30 = m30 + x * m33; float nm31 = m31 + y * m33; float nm32 = m32 + z * m33; float nm33 = m33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Pre-multiply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>T * M</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>T * M * v</code>, the translation will be applied last! * <p> * In order to set the matrix to a translation transformation without pre-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translateLocal(float x, float y, float z) { return translateLocal(x, y, z, this); } public void writeExternal(ObjectOutput out) throws IOException { out.writeFloat(m00); out.writeFloat(m01); out.writeFloat(m02); out.writeFloat(m03); out.writeFloat(m10); out.writeFloat(m11); out.writeFloat(m12); out.writeFloat(m13); out.writeFloat(m20); out.writeFloat(m21); out.writeFloat(m22); out.writeFloat(m23); out.writeFloat(m30); out.writeFloat(m31); out.writeFloat(m32); out.writeFloat(m33); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { m00 = in.readFloat(); m01 = in.readFloat(); m02 = in.readFloat(); m03 = in.readFloat(); m10 = in.readFloat(); m11 = in.readFloat(); m12 = in.readFloat(); m13 = in.readFloat(); m20 = in.readFloat(); m21 = in.readFloat(); m22 = in.readFloat(); m23 = in.readFloat(); m30 = in.readFloat(); m31 = in.readFloat(); m32 = in.readFloat(); m33 = in.readFloat(); } /** * Apply an orthographic projection transformation using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float, boolean) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float, boolean) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @param dest * will hold the result * @return dest */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / (right - left); float rm11 = 2.0f / (top - bottom); float rm22 = (zZeroToOne ? 1.0f : 2.0f) / (zNear - zFar); float rm30 = (left + right) / (left - right); float rm31 = (top + bottom) / (bottom - top); float rm32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); // perform optimized multiplication // compute the last column first, because other columns do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = m20 * rm22; dest.m21 = m21 * rm22; dest.m22 = m22 * rm22; dest.m23 = m23 * rm22; return dest; } /** * Apply an orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return dest */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { return ortho(left, right, bottom, top, zNear, zFar, false, dest); } /** * Apply an orthographic projection transformation using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float, boolean) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float, boolean) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { return ortho(left, right, bottom, top, zNear, zFar, zZeroToOne, this); } /** * Apply an orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar) { return ortho(left, right, bottom, top, zNear, zFar, false); } /** * Set this matrix to be an orthographic projection transformation using the given NDC z range. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho(float, float, float, float, float, float, boolean) ortho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float, boolean) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setOrtho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { m00 = 2.0f / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = (zZeroToOne ? 1.0f : 2.0f) / (zNear - zFar); m23 = 0.0f; m30 = (right + left) / (left - right); m31 = (top + bottom) / (bottom - top); m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); m33 = 1.0f; return this; } /** * Set this matrix to be an orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho(float, float, float, float, float, float) ortho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setOrtho(float left, float right, float bottom, float top, float zNear, float zFar) { return setOrtho(left, right, bottom, top, zNear, zFar, false); } /** * Apply a symmetric orthographic projection transformation using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, boolean, Matrix4f) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float, boolean) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float, boolean) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return dest */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / width; float rm11 = 2.0f / height; float rm22 = (zZeroToOne ? 1.0f : 2.0f) / (zNear - zFar); float rm32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); // perform optimized multiplication // compute the last column first, because other columns do not depend on it dest.m30 = m20 * rm32 + m30; dest.m31 = m21 * rm32 + m31; dest.m32 = m22 * rm32 + m32; dest.m33 = m23 * rm32 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = m20 * rm22; dest.m21 = m21 * rm22; dest.m22 = m22 * rm22; dest.m23 = m23 * rm22; return dest; } /** * Apply a symmetric orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, Matrix4f) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return dest */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, Matrix4f dest) { return orthoSymmetric(width, height, zNear, zFar, false, dest); } /** * Apply a symmetric orthographic projection transformation using the given NDC z range to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, boolean) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float, boolean) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float, boolean) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, boolean zZeroToOne) { return orthoSymmetric(width, height, zNear, zFar, zZeroToOne, this); } /** * Apply a symmetric orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar) { return orthoSymmetric(width, height, zNear, zFar, false, this); } /** * Set this matrix to be a symmetric orthographic projection transformation using the given NDC z range. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float, boolean) setOrtho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * In order to apply the symmetric orthographic projection to an already existing transformation, * use {@link #orthoSymmetric(float, float, float, float, boolean) orthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #orthoSymmetric(float, float, float, float, boolean) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setOrthoSymmetric(float width, float height, float zNear, float zFar, boolean zZeroToOne) { m00 = 2.0f / width; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / height; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = (zZeroToOne ? 1.0f : 2.0f) / (zNear - zFar); m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); m33 = 1.0f; return this; } /** * Set this matrix to be a symmetric orthographic projection transformation using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * In order to apply the symmetric orthographic projection to an already existing transformation, * use {@link #orthoSymmetric(float, float, float, float) orthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #orthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setOrthoSymmetric(float width, float height, float zNear, float zFar) { return setOrthoSymmetric(width, height, zNear, zFar, false); } /** * Apply an orthographic projection transformation to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, Matrix4f) ortho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho2D(float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float, Matrix4f) * @see #setOrtho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param dest * will hold the result * @return dest */ public Matrix4f ortho2D(float left, float right, float bottom, float top, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / (right - left); float rm11 = 2.0f / (top - bottom); float rm30 = -(right + left) / (right - left); float rm31 = -(top + bottom) / (top - bottom); // perform optimized multiplication // compute the last column first, because other columns do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = -m20; dest.m21 = -m21; dest.m22 = -m22; dest.m23 = -m23; return dest; } /** * Apply an orthographic projection transformation to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float) ortho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho2D(float, float, float, float) setOrtho2D()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float) * @see #setOrtho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @return this */ public Matrix4f ortho2D(float left, float right, float bottom, float top) { return ortho2D(left, right, bottom, top, this); } /** * Set this matrix to be an orthographic projection transformation. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho2D(float, float, float, float) ortho2D()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * @see #ortho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @return this */ public Matrix4f setOrtho2D(float left, float right, float bottom, float top) { m00 = 2.0f / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -1.0f; m23 = 0.0f; m30 = -(right + left) / (right - left); m31 = -(top + bottom) / (top - bottom); m32 = 0.0f; m33 = 1.0f; return this; } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(Vector3f, Vector3f) setLookAlong()}. * * @see #lookAlong(float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @return this */ public Matrix4f lookAlong(Vector3f dir, Vector3f up) { return lookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z, this); } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code> * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(Vector3f, Vector3f) setLookAlong()}. * * @see #lookAlong(float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @param dest * will hold the result * @return dest */ public Matrix4f lookAlong(Vector3f dir, Vector3f up, Matrix4f dest) { return lookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z, dest); } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code> * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()} * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return dest */ public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ, Matrix4f dest) { // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float dirnX = dirX * invDirLength; float dirnY = dirY * invDirLength; float dirnZ = dirZ * invDirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirnY * upZ - dirnZ * upY; rightY = dirnZ * upX - dirnX * upZ; rightZ = dirnX * upY - dirnY * upX; // normalize right float invRightLength = 1.0f / (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX *= invRightLength; rightY *= invRightLength; rightZ *= invRightLength; // up = right x direction float upnX = rightY * dirnZ - rightZ * dirnY; float upnY = rightZ * dirnX - rightX * dirnZ; float upnZ = rightX * dirnY - rightY * dirnX; // calculate right matrix elements float rm00 = rightX; float rm01 = upnX; float rm02 = -dirnX; float rm10 = rightY; float rm11 = upnY; float rm12 = -dirnY; float rm20 = rightZ; float rm21 = upnZ; float rm22 = -dirnZ; // perform optimized matrix multiplication // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()} * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this); } /** * Set this matrix to a rotation transformation to make <code>-z</code> * point along <code>dir</code>. * <p> * This is equivalent to calling * {@link #setLookAt(Vector3f, Vector3f, Vector3f) setLookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to apply the lookalong transformation to any previous existing transformation, * use {@link #lookAlong(Vector3f, Vector3f)}. * * @see #setLookAlong(Vector3f, Vector3f) * @see #lookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAlong(Vector3f dir, Vector3f up) { return setLookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z); } /** * Set this matrix to a rotation transformation to make <code>-z</code> * point along <code>dir</code>. * <p> * This is equivalent to calling * {@link #setLookAt(float, float, float, float, float, float, float, float, float) * setLookAt()} with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to apply the lookalong transformation to any previous existing transformation, * use {@link #lookAlong(float, float, float, float, float, float) lookAlong()} * * @see #setLookAlong(float, float, float, float, float, float) * @see #lookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float dirnX = dirX * invDirLength; float dirnY = dirY * invDirLength; float dirnZ = dirZ * invDirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirnY * upZ - dirnZ * upY; rightY = dirnZ * upX - dirnX * upZ; rightZ = dirnX * upY - dirnY * upX; // normalize right float invRightLength = 1.0f / (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX *= invRightLength; rightY *= invRightLength; rightZ *= invRightLength; // up = right x direction float upnX = rightY * dirnZ - rightZ * dirnY; float upnY = rightZ * dirnX - rightX * dirnZ; float upnZ = rightX * dirnY - rightY * dirnX; m00 = rightX; m01 = upnX; m02 = -dirnX; m03 = 0.0f; m10 = rightY; m11 = upnY; m12 = -dirnY; m13 = 0.0f; m20 = rightZ; m21 = upnZ; m22 = -dirnZ; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a "lookat" transformation for a right-handed coordinate system, that aligns * <code>-z</code> with <code>center - eye</code>. * <p> * In order to not make use of vectors to specify <code>eye</code>, <code>center</code> and <code>up</code> but use primitives, * like in the GLU function, use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()} * instead. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt()}. * * @see #setLookAt(float, float, float, float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAt(Vector3f eye, Vector3f center, Vector3f up) { return setLookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z); } /** * Set this matrix to be a "lookat" transformation for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt}. * * @see #setLookAt(Vector3f, Vector3f, Vector3f) * @see #lookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = eyeX - centerX; dirY = eyeY - centerY; dirZ = eyeZ - centerZ; // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLength; dirY *= invDirLength; dirZ *= invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * dirZ - upZ * dirY; leftY = upZ * dirX - upX * dirZ; leftZ = upX * dirY - upY * dirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = dirY * leftZ - dirZ * leftY; float upnY = dirZ * leftX - dirX * leftZ; float upnZ = dirX * leftY - dirY * leftX; m00 = leftX; m01 = upnX; m02 = dirX; m03 = 0.0f; m10 = leftY; m11 = upnY; m12 = dirY; m13 = 0.0f; m20 = leftZ; m21 = upnZ; m22 = dirZ; m23 = 0.0f; m30 = -(leftX * eyeX + leftY * eyeY + leftZ * eyeZ); m31 = -(upnX * eyeX + upnY * eyeY + upnZ * eyeZ); m32 = -(dirX * eyeX + dirY * eyeY + dirZ * eyeZ); m33 = 1.0f; return this; } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(Vector3f, Vector3f, Vector3f)}. * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @param dest * will hold the result * @return dest */ public Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up, Matrix4f dest) { return lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, dest); } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(Vector3f, Vector3f, Vector3f)}. * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up) { return lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, this); } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()}. * * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return dest */ public Matrix4f lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = eyeX - centerX; dirY = eyeY - centerY; dirZ = eyeZ - centerZ; // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLength; dirY *= invDirLength; dirZ *= invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * dirZ - upZ * dirY; leftY = upZ * dirX - upX * dirZ; leftZ = upX * dirY - upY * dirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = dirY * leftZ - dirZ * leftY; float upnY = dirZ * leftX - dirX * leftZ; float upnZ = dirX * leftY - dirY * leftX; // calculate right matrix elements float rm00 = leftX; float rm01 = upnX; float rm02 = dirX; float rm10 = leftY; float rm11 = upnY; float rm12 = dirY; float rm20 = leftZ; float rm21 = upnZ; float rm22 = dirZ; float rm30 = -(leftX * eyeX + leftY * eyeY + leftZ * eyeZ); float rm31 = -(upnX * eyeX + upnY * eyeY + upnZ * eyeZ); float rm32 = -(dirX * eyeX + dirY * eyeY + dirZ * eyeZ); // perform optimized matrix multiplication // compute last column first, because others do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return dest; } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()}. * * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { return lookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, this); } /** * Set this matrix to be a "lookat" transformation for a left-handed coordinate system, that aligns * <code>+z</code> with <code>center - eye</code>. * <p> * In order to not make use of vectors to specify <code>eye</code>, <code>center</code> and <code>up</code> but use primitives, * like in the GLU function, use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()} * instead. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAtLH(Vector3f, Vector3f, Vector3f) lookAt()}. * * @see #setLookAtLH(float, float, float, float, float, float, float, float, float) * @see #lookAtLH(Vector3f, Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAtLH(Vector3f eye, Vector3f center, Vector3f up) { return setLookAtLH(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z); } /** * Set this matrix to be a "lookat" transformation for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code>. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAtLH(float, float, float, float, float, float, float, float, float) lookAtLH}. * * @see #setLookAtLH(Vector3f, Vector3f, Vector3f) * @see #lookAtLH(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = centerX - eyeX; dirY = centerY - eyeY; dirZ = centerZ - eyeZ; // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLength; dirY *= invDirLength; dirZ *= invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * dirZ - upZ * dirY; leftY = upZ * dirX - upX * dirZ; leftZ = upX * dirY - upY * dirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = dirY * leftZ - dirZ * leftY; float upnY = dirZ * leftX - dirX * leftZ; float upnZ = dirX * leftY - dirY * leftX; m00 = leftX; m01 = upnX; m02 = dirX; m03 = 0.0f; m10 = leftY; m11 = upnY; m12 = dirY; m13 = 0.0f; m20 = leftZ; m21 = upnZ; m22 = dirZ; m23 = 0.0f; m30 = -(leftX * eyeX + leftY * eyeY + leftZ * eyeZ); m31 = -(upnX * eyeX + upnY * eyeY + upnZ * eyeZ); m32 = -(dirX * eyeX + dirY * eyeY + dirZ * eyeZ); m33 = 1.0f; return this; } /** * Apply a "lookat" transformation to this matrix for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAtLH(Vector3f, Vector3f, Vector3f)}. * * @see #lookAtLH(float, float, float, float, float, float, float, float, float) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @param dest * will hold the result * @return dest */ public Matrix4f lookAtLH(Vector3f eye, Vector3f center, Vector3f up, Matrix4f dest) { return lookAtLH(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, dest); } /** * Apply a "lookat" transformation to this matrix for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAtLH(Vector3f, Vector3f, Vector3f)}. * * @see #lookAtLH(float, float, float, float, float, float, float, float, float) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f lookAtLH(Vector3f eye, Vector3f center, Vector3f up) { return lookAtLH(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, this); } /** * Apply a "lookat" transformation to this matrix for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. * * @see #lookAtLH(Vector3f, Vector3f, Vector3f) * @see #setLookAtLH(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return dest */ public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = centerX - eyeX; dirY = centerY - eyeY; dirZ = centerZ - eyeZ; // Normalize direction float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLength; dirY *= invDirLength; dirZ *= invDirLength; // left = up x direction float leftX, leftY, leftZ; leftX = upY * dirZ - upZ * dirY; leftY = upZ * dirX - upX * dirZ; leftZ = upX * dirY - upY * dirX; // normalize left float invLeftLength = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLength; leftY *= invLeftLength; leftZ *= invLeftLength; // up = direction x left float upnX = dirY * leftZ - dirZ * leftY; float upnY = dirZ * leftX - dirX * leftZ; float upnZ = dirX * leftY - dirY * leftX; // calculate right matrix elements float rm00 = leftX; float rm01 = upnX; float rm02 = dirX; float rm10 = leftY; float rm11 = upnY; float rm12 = dirY; float rm20 = leftZ; float rm21 = upnZ; float rm22 = dirZ; float rm30 = -(leftX * eyeX + leftY * eyeY + leftZ * eyeZ); float rm31 = -(upnX * eyeX + upnY * eyeY + upnZ * eyeZ); float rm32 = -(dirX * eyeX + dirY * eyeY + dirZ * eyeZ); // perform optimized matrix multiplication // compute last column first, because others do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return dest; } /** * Apply a "lookat" transformation to this matrix for a left-handed coordinate system, * that aligns <code>+z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. * * @see #lookAtLH(Vector3f, Vector3f, Vector3f) * @see #setLookAtLH(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { return lookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, this); } /** * Apply a symmetric perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float, boolean) setPerspective}. * * @see #setPerspective(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return dest */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { float h = (float) Math.tan(fovy * 0.5f); // calculate right matrix elements float rm00 = 1.0f / (h * aspect); float rm11 = 1.0f / h; float rm22; float rm32; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; rm22 = e - 1.0f; rm32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; rm22 = (zZeroToOne ? 0.0f : 1.0f) - e; rm32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { rm22 = (zZeroToOne ? zFar : zFar + zNear) / (zNear - zFar); rm32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } // perform optimized matrix multiplication float nm20 = m20 * rm22 - m30; float nm21 = m21 * rm22 - m31; float nm22 = m22 * rm22 - m32; float nm23 = m23 * rm22 - m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return dest; } /** * Apply a symmetric perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float) setPerspective}. * * @see #setPerspective(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @return dest */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, Matrix4f dest) { return perspective(fovy, aspect, zNear, zFar, false, dest); } /** * Apply a symmetric perspective projection frustum transformation using for a right-handed coordinate system * the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float, boolean) setPerspective}. * * @see #setPerspective(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { return perspective(fovy, aspect, zNear, zFar, zZeroToOne, this); } /** * Apply a symmetric perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float) setPerspective}. * * @see #setPerspective(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar) { return perspective(fovy, aspect, zNear, zFar, this); } /** * Set this matrix to be a symmetric perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspective(float, float, float, float, boolean) perspective()}. * * @see #perspective(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { float h = (float) Math.tan(fovy * 0.5f); m00 = 1.0f / (h * aspect); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f / h; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; m22 = e - 1.0f; m32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; m22 = (zZeroToOne ? 0.0f : 1.0f) - e; m32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { m22 = (zZeroToOne ? zFar : zFar + zNear) / (zNear - zFar); m32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } m23 = -1.0f; m30 = 0.0f; m31 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be a symmetric perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspective(float, float, float, float) perspective()}. * * @see #perspective(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar) { return setPerspective(fovy, aspect, zNear, zFar, false); } /** * Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspectiveLH(float, float, float, float, boolean) setPerspectiveLH}. * * @see #setPerspectiveLH(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @param dest * will hold the result * @return dest */ public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { float h = (float) Math.tan(fovy * 0.5f); // calculate right matrix elements float rm00 = 1.0f / (h * aspect); float rm11 = 1.0f / h; float rm22; float rm32; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; rm22 = 1.0f - e; rm32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; rm22 = (zZeroToOne ? 0.0f : 1.0f) - e; rm32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { rm22 = (zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear); rm32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } // perform optimized matrix multiplication float nm20 = m20 * rm22 + m30; float nm21 = m21 * rm22 + m31; float nm22 = m22 * rm22 + m32; float nm23 = m23 * rm22 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return dest; } /** * Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspectiveLH(float, float, float, float, boolean) setPerspectiveLH}. * * @see #setPerspectiveLH(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { return perspectiveLH(fovy, aspect, zNear, zFar, zZeroToOne, this); } /** * Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspectiveLH(float, float, float, float) setPerspectiveLH}. * * @see #setPerspectiveLH(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @return dest */ public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar, Matrix4f dest) { return perspectiveLH(fovy, aspect, zNear, zFar, false, dest); } /** * Apply a symmetric perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspectiveLH(float, float, float, float) setPerspectiveLH}. * * @see #setPerspectiveLH(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f perspectiveLH(float fovy, float aspect, float zNear, float zFar) { return perspectiveLH(fovy, aspect, zNear, zFar, this); } /** * Set this matrix to be a symmetric perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspectiveLH(float, float, float, float, boolean) perspectiveLH()}. * * @see #perspectiveLH(float, float, float, float, boolean) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setPerspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { float h = (float) Math.tan(fovy * 0.5f); m00 = 1.0f / (h * aspect); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f / h; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; m22 = 1.0f - e; m32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; m22 = (zZeroToOne ? 0.0f : 1.0f) - e; m32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { m22 = (zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear); m32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } m23 = 1.0f; m30 = 0.0f; m31 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be a symmetric perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspectiveLH(float, float, float, float) perspectiveLH()}. * * @see #perspectiveLH(float, float, float, float) * * @param fovy * the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) * @param aspect * the aspect ratio (i.e. width / height; must be greater than zero) * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f setPerspectiveLH(float fovy, float aspect, float zNear, float zFar) { return setPerspectiveLH(fovy, aspect, zNear, zFar, false); } /** * Apply an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float, boolean) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @param dest * will hold the result * @return dest */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { // calculate right matrix elements float rm00 = (zNear + zNear) / (right - left); float rm11 = (zNear + zNear) / (top - bottom); float rm20 = (right + left) / (right - left); float rm21 = (top + bottom) / (top - bottom); float rm22; float rm32; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; rm22 = e - 1.0f; rm32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; rm22 = (zZeroToOne ? 0.0f : 1.0f) - e; rm32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { rm22 = (zZeroToOne ? zFar : zFar + zNear) / (zNear - zFar); rm32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } // perform optimized matrix multiplication float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 - m30; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 - m31; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 - m32; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 - m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @return dest */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { return frustum(left, right, bottom, top, zNear, zFar, false, dest); } /** * Apply an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float, boolean) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { return frustum(left, right, bottom, top, zNear, zFar, zZeroToOne, this); } /** * Apply an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar) { return frustum(left, right, bottom, top, zNear, zFar, this); } /** * Set this matrix to be an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using the given NDC z range. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustum(float, float, float, float, float, float, boolean) frustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustum(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setFrustum(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { m00 = (zNear + zNear) / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = (zNear + zNear) / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = (right + left) / (right - left); m21 = (top + bottom) / (top - bottom); boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; m22 = e - 1.0f; m32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; m22 = (zZeroToOne ? 0.0f : 1.0f) - e; m32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { m22 = (zZeroToOne ? zFar : zFar + zNear) / (zNear - zFar); m32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } m23 = -1.0f; m30 = 0.0f; m31 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be an arbitrary perspective projection frustum transformation for a right-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f setFrustum(float left, float right, float bottom, float top, float zNear, float zFar) { return setFrustum(left, right, bottom, top, zNear, zFar, false); } /** * Apply an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustumLH(float, float, float, float, float, float, boolean) setFrustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustumLH(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @param dest * will hold the result * @return dest */ public Matrix4f frustumLH(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { // calculate right matrix elements float rm00 = (zNear + zNear) / (right - left); float rm11 = (zNear + zNear) / (top - bottom); float rm20 = (right + left) / (right - left); float rm21 = (top + bottom) / (top - bottom); float rm22; float rm32; boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; rm22 = 1.0f - e; rm32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; rm22 = (zZeroToOne ? 0.0f : 1.0f) - e; rm32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { rm22 = (zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear); rm32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } // perform optimized matrix multiplication float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 + m30; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 + m31; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 + m32; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustumLH(float, float, float, float, float, float, boolean) setFrustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustumLH(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f frustumLH(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { return frustumLH(left, right, bottom, top, zNear, zFar, zZeroToOne, this); } /** * Apply an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt> to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustumLH(float, float, float, float, float, float) setFrustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustumLH(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param dest * will hold the result * @return dest */ public Matrix4f frustumLH(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { return frustumLH(left, right, bottom, top, zNear, zFar, false, dest); } /** * Apply an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using the given NDC z range to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustumLH(float, float, float, float, float, float) setFrustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustumLH(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f frustumLH(float left, float right, float bottom, float top, float zNear, float zFar) { return frustumLH(left, right, bottom, top, zNear, zFar, this); } /** * Set this matrix to be an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustumLH(float, float, float, float, float, float, boolean) frustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustumLH(float, float, float, float, float, float, boolean) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zZeroToOne * whether to use Vulkan's and Direct3D's NDC z range of <tt>[0..+1]</tt> when <code>true</code> * or whether to use OpenGL's NDC z range of <tt>[-1..+1]</tt> when <code>false</code> * @return this */ public Matrix4f setFrustumLH(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne) { m00 = (zNear + zNear) / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = (zNear + zNear) / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = (right + left) / (right - left); m21 = (top + bottom) / (top - bottom); boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; m22 = 1.0f - e; m32 = (e - (zZeroToOne ? 1.0f : 2.0f)) * zNear; } else if (nearInf) { float e = 1E-6f; m22 = (zZeroToOne ? 0.0f : 1.0f) - e; m32 = ((zZeroToOne ? 1.0f : 2.0f) - e) * zFar; } else { m22 = (zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear); m32 = (zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar); } m23 = 1.0f; m30 = 0.0f; m31 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be an arbitrary perspective projection frustum transformation for a left-handed coordinate system * using OpenGL's NDC z range of <tt>[-1..+1]</tt>. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustumLH(float, float, float, float, float, float) frustumLH()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustumLH(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. * In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. * @param zFar * far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. * In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. * @return this */ public Matrix4f setFrustumLH(float left, float right, float bottom, float top, float zNear, float zFar) { return setFrustumLH(left, right, bottom, top, zNear, zFar, false); } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix and store * the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @param dest * will hold the result * @return dest */ public Matrix4f rotate(Quaternionf quat, Matrix4f dest) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; float rm00 = 1.0f - q11 - q22; float rm01 = q01 + q23; float rm02 = q02 - q13; float rm10 = q01 - q23; float rm11 = 1.0f - q22 - q00; float rm12 = q12 + q03; float rm20 = q02 + q13; float rm21 = q12 - q03; float rm22 = 1.0f - q11 - q00; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotate(Quaternionf quat) { return rotate(quat, this); } /** * Apply the rotation transformation of the given {@link Quaternionf} to this {@link #isAffine() affine} matrix and store * the result in <code>dest</code>. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffine(Quaternionf quat, Matrix4f dest) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; float rm00 = 1.0f - q11 - q22; float rm01 = q01 + q23; float rm02 = q02 - q13; float rm10 = q01 - q23; float rm11 = 1.0f - q22 - q00; float rm12 = q12 + q03; float rm20 = q02 + q13; float rm21 = q12 - q03; float rm22 = 1.0f - q11 - q00; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = 0.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = 0.0f; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = 0.0f; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return dest; } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotateAffine(Quaternionf quat) { return rotateAffine(quat, this); } /** * Pre-multiply the rotation transformation of the given {@link Quaternionf} to this {@link #isAffine() affine} matrix and store * the result in <code>dest</code>. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>Q * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>Q * M * v</code>, * the quaternion rotation will be applied last! * <p> * In order to set the matrix to a rotation transformation without pre-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @param dest * will hold the result * @return dest */ public Matrix4f rotateAffineLocal(Quaternionf quat, Matrix4f dest) { float dqx = quat.x + quat.x; float dqy = quat.y + quat.y; float dqz = quat.z + quat.z; float q00 = dqx * quat.x; float q11 = dqy * quat.y; float q22 = dqz * quat.z; float q01 = dqx * quat.y; float q02 = dqx * quat.z; float q03 = dqx * quat.w; float q12 = dqy * quat.z; float q13 = dqy * quat.w; float q23 = dqz * quat.w; float lm00 = 1.0f - q11 - q22; float lm01 = q01 + q23; float lm02 = q02 - q13; float lm10 = q01 - q23; float lm11 = 1.0f - q22 - q00; float lm12 = q12 + q03; float lm20 = q02 + q13; float lm21 = q12 - q03; float lm22 = 1.0f - q11 - q00; float nm00 = lm00 * m00 + lm10 * m01 + lm20 * m02; float nm01 = lm01 * m00 + lm11 * m01 + lm21 * m02; float nm02 = lm02 * m00 + lm12 * m01 + lm22 * m02; float nm03 = 0.0f; float nm10 = lm00 * m10 + lm10 * m11 + lm20 * m12; float nm11 = lm01 * m10 + lm11 * m11 + lm21 * m12; float nm12 = lm02 * m10 + lm12 * m11 + lm22 * m12; float nm13 = 0.0f; float nm20 = lm00 * m20 + lm10 * m21 + lm20 * m22; float nm21 = lm01 * m20 + lm11 * m21 + lm21 * m22; float nm22 = lm02 * m20 + lm12 * m21 + lm22 * m22; float nm23 = 0.0f; float nm30 = lm00 * m30 + lm10 * m31 + lm20 * m32; float nm31 = lm01 * m30 + lm11 * m31 + lm21 * m32; float nm32 = lm02 * m30 + lm12 * m31 + lm22 * m32; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Pre-multiply the rotation transformation of the given {@link Quaternionf} to this matrix. * <p> * This method assumes <code>this</code> to be {@link #isAffine() affine}. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>Q * M</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>Q * M * v</code>, * the quaternion rotation will be applied last! * <p> * In order to set the matrix to a rotation transformation without pre-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotateAffineLocal(Quaternionf quat) { return rotateAffineLocal(quat, this); } /** * Apply a rotation transformation, rotating about the given {@link AxisAngle4f}, to this matrix. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given {@link AxisAngle4f}, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the {@link AxisAngle4f} rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(AxisAngle4f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @return this */ public Matrix4f rotate(AxisAngle4f axisAngle) { return rotate(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); } /** * Apply a rotation transformation, rotating about the given {@link AxisAngle4f} and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given {@link AxisAngle4f}, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the {@link AxisAngle4f} rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(AxisAngle4f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @param dest * will hold the result * @return dest */ public Matrix4f rotate(AxisAngle4f axisAngle, Matrix4f dest) { return rotate(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z, dest); } /** * Apply a rotation transformation, rotating the given radians about the specified axis, to this matrix. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given axis-angle, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the axis-angle rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(float, Vector3f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(float, Vector3f) * * @param angle * the angle in radians * @param axis * the rotation axis (needs to be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f rotate(float angle, Vector3f axis) { return rotate(angle, axis.x, axis.y, axis.z); } /** * Apply a rotation transformation, rotating the given radians about the specified axis and store the result in <code>dest</code>. * <p> * When used with a right-handed coordinate system, the produced rotation will rotate vector * counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. * When used with a left-handed coordinate system, the rotation is clockwise. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given axis-angle, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the axis-angle rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(float, Vector3f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(float, Vector3f) * * @param angle * the angle in radians * @param axis * the rotation axis (needs to be {@link Vector3f#normalize() normalized}) * @param dest * will hold the result * @return dest */ public Matrix4f rotate(float angle, Vector3f axis, Matrix4f dest) { return rotate(angle, axis.x, axis.y, axis.z, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix. * In order to avoid computing the matrix inverse with every invocation, the inverse of <code>this</code> matrix can be built * once outside using {@link #invert(Matrix4f)} and then the method {@link #unprojectInv(float, float, float, int[], Vector4f) unprojectInv()} can be invoked on it. * * @see #unprojectInv(float, float, float, int[], Vector4f) * @see #invert(Matrix4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector4f unproject(float winX, float winY, float winZ, int[] viewport, Vector4f dest) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float c = m00 * m13 - m03 * m10; float d = m01 * m12 - m02 * m11; float e = m01 * m13 - m03 * m11; float f = m02 * m13 - m03 * m12; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float i = m20 * m33 - m23 * m30; float j = m21 * m32 - m22 * m31; float k = m21 * m33 - m23 * m31; float l = m22 * m33 - m23 * m32; float det = a * l - b * k + c * j + d * i - e * h + f * g; det = 1.0f / det; float im00 = ( m11 * l - m12 * k + m13 * j) * det; float im01 = (-m01 * l + m02 * k - m03 * j) * det; float im02 = ( m31 * f - m32 * e + m33 * d) * det; float im03 = (-m21 * f + m22 * e - m23 * d) * det; float im10 = (-m10 * l + m12 * i - m13 * h) * det; float im11 = ( m00 * l - m02 * i + m03 * h) * det; float im12 = (-m30 * f + m32 * c - m33 * b) * det; float im13 = ( m20 * f - m22 * c + m23 * b) * det; float im20 = ( m10 * k - m11 * i + m13 * g) * det; float im21 = (-m00 * k + m01 * i - m03 * g) * det; float im22 = ( m30 * e - m31 * c + m33 * a) * det; float im23 = (-m20 * e + m21 * c - m23 * a) * det; float im30 = (-m10 * j + m11 * h - m12 * g) * det; float im31 = ( m00 * j - m01 * h + m02 * g) * det; float im32 = (-m30 * d + m31 * b - m32 * a) * det; float im33 = ( m20 * d - m21 * b + m22 * a) * det; float ndcX = (winX-viewport[0])/viewport[2]*2.0f-1.0f; float ndcY = (winY-viewport[1])/viewport[3]*2.0f-1.0f; float ndcZ = winZ+winZ-1.0f; dest.x = im00 * ndcX + im10 * ndcY + im20 * ndcZ + im30; dest.y = im01 * ndcX + im11 * ndcY + im21 * ndcZ + im31; dest.z = im02 * ndcX + im12 * ndcY + im22 * ndcZ + im32; dest.w = im03 * ndcX + im13 * ndcY + im23 * ndcZ + im33; dest.div(dest.w); return dest; } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix. * In order to avoid computing the matrix inverse with every invocation, the inverse of <code>this</code> matrix can be built * once outside using {@link #invert(Matrix4f)} and then the method {@link #unprojectInv(float, float, float, int[], Vector4f) unprojectInv()} can be invoked on it. * * @see #unprojectInv(float, float, float, int[], Vector3f) * @see #invert(Matrix4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector3f unproject(float winX, float winY, float winZ, int[] viewport, Vector3f dest) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float c = m00 * m13 - m03 * m10; float d = m01 * m12 - m02 * m11; float e = m01 * m13 - m03 * m11; float f = m02 * m13 - m03 * m12; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float i = m20 * m33 - m23 * m30; float j = m21 * m32 - m22 * m31; float k = m21 * m33 - m23 * m31; float l = m22 * m33 - m23 * m32; float det = a * l - b * k + c * j + d * i - e * h + f * g; det = 1.0f / det; float im00 = ( m11 * l - m12 * k + m13 * j) * det; float im01 = (-m01 * l + m02 * k - m03 * j) * det; float im02 = ( m31 * f - m32 * e + m33 * d) * det; float im03 = (-m21 * f + m22 * e - m23 * d) * det; float im10 = (-m10 * l + m12 * i - m13 * h) * det; float im11 = ( m00 * l - m02 * i + m03 * h) * det; float im12 = (-m30 * f + m32 * c - m33 * b) * det; float im13 = ( m20 * f - m22 * c + m23 * b) * det; float im20 = ( m10 * k - m11 * i + m13 * g) * det; float im21 = (-m00 * k + m01 * i - m03 * g) * det; float im22 = ( m30 * e - m31 * c + m33 * a) * det; float im23 = (-m20 * e + m21 * c - m23 * a) * det; float im30 = (-m10 * j + m11 * h - m12 * g) * det; float im31 = ( m00 * j - m01 * h + m02 * g) * det; float im32 = (-m30 * d + m31 * b - m32 * a) * det; float im33 = ( m20 * d - m21 * b + m22 * a) * det; float ndcX = (winX-viewport[0])/viewport[2]*2.0f-1.0f; float ndcY = (winY-viewport[1])/viewport[3]*2.0f-1.0f; float ndcZ = winZ+winZ-1.0f; dest.x = im00 * ndcX + im10 * ndcY + im20 * ndcZ + im30; dest.y = im01 * ndcX + im11 * ndcY + im21 * ndcZ + im31; dest.z = im02 * ndcX + im12 * ndcY + im22 * ndcZ + im32; float w = im03 * ndcX + im13 * ndcY + im23 * ndcZ + im33; dest.div(w); return dest; } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix. * In order to avoid computing the matrix inverse with every invocation, the inverse of <code>this</code> matrix can be built * once outside using {@link #invert(Matrix4f)} and then the method {@link #unprojectInv(float, float, float, int[], Vector4f) unprojectInv()} can be invoked on it. * * @see #unprojectInv(float, float, float, int[], Vector4f) * @see #unproject(float, float, float, int[], Vector4f) * @see #invert(Matrix4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector4f unproject(Vector3f winCoords, int[] viewport, Vector4f dest) { return unproject(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix. * In order to avoid computing the matrix inverse with every invocation, the inverse of <code>this</code> matrix can be built * once outside using {@link #invert(Matrix4f)} and then the method {@link #unprojectInv(float, float, float, int[], Vector3f) unprojectInv()} can be invoked on it. * * @see #unprojectInv(float, float, float, int[], Vector3f) * @see #unproject(float, float, float, int[], Vector3f) * @see #invert(Matrix4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector3f unproject(Vector3f winCoords, int[] viewport, Vector3f dest) { return unproject(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(Vector3f, int[], Vector4f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current int[]'s {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(Vector3f, int[], Vector4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector4f unprojectInv(Vector3f winCoords, int[] viewport, Vector4f dest) { return unprojectInv(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(float, float, float, int[], Vector4f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #unproject(float, float, float, int[], Vector4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector4f unprojectInv(float winX, float winY, float winZ, int[] viewport, Vector4f dest) { float ndcX = (winX-viewport[0])/viewport[2]*2.0f-1.0f; float ndcY = (winY-viewport[1])/viewport[3]*2.0f-1.0f; float ndcZ = winZ+winZ-1.0f; dest.x = m00 * ndcX + m10 * ndcY + m20 * ndcZ + m30; dest.y = m01 * ndcX + m11 * ndcY + m21 * ndcZ + m31; dest.z = m02 * ndcX + m12 * ndcY + m22 * ndcZ + m32; dest.w = m03 * ndcX + m13 * ndcY + m23 * ndcZ + m33; dest.div(dest.w); return dest; } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(Vector3f, int[], Vector3f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #unproject(Vector3f, int[], Vector3f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector3f unprojectInv(Vector3f winCoords, int[] viewport, Vector3f dest) { return unprojectInv(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(float, float, float, int[], Vector3f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #unproject(float, float, float, int[], Vector3f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return dest */ public Vector3f unprojectInv(float winX, float winY, float winZ, int[] viewport, Vector3f dest) { float ndcX = (winX-viewport[0])/viewport[2]*2.0f-1.0f; float ndcY = (winY-viewport[1])/viewport[3]*2.0f-1.0f; float ndcZ = winZ+winZ-1.0f; dest.x = m00 * ndcX + m10 * ndcY + m20 * ndcZ + m30; dest.y = m01 * ndcX + m11 * ndcY + m21 * ndcZ + m31; dest.z = m02 * ndcX + m12 * ndcY + m22 * ndcZ + m32; float w = m03 * ndcX + m13 * ndcY + m23 * ndcZ + m33; dest.div(w); return dest; } /** * Project the given <tt>(x, y, z)</tt> position via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return winCoordsDest */ public Vector4f project(float x, float y, float z, int[] viewport, Vector4f winCoordsDest) { winCoordsDest.x = m00 * x + m10 * y + m20 * z + m30; winCoordsDest.y = m01 * x + m11 * y + m21 * z + m31; winCoordsDest.z = m02 * x + m12 * y + m22 * z + m32; winCoordsDest.w = m03 * x + m13 * y + m23 * z + m33; winCoordsDest.div(winCoordsDest.w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport[2] + viewport[0]; winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport[3] + viewport[1]; winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; return winCoordsDest; } /** * Project the given <tt>(x, y, z)</tt> position via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return winCoordsDest */ public Vector3f project(float x, float y, float z, int[] viewport, Vector3f winCoordsDest) { winCoordsDest.x = m00 * x + m10 * y + m20 * z + m30; winCoordsDest.y = m01 * x + m11 * y + m21 * z + m31; winCoordsDest.z = m02 * x + m12 * y + m22 * z + m32; float w = m03 * x + m13 * y + m23 * z + m33; winCoordsDest.div(w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport[2] + viewport[0]; winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport[3] + viewport[1]; winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; return winCoordsDest; } /** * Project the given <code>position</code> via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, int[], Vector4f) * * @param position * the position to project into window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return winCoordsDest */ public Vector4f project(Vector3f position, int[] viewport, Vector4f winCoordsDest) { return project(position.x, position.y, position.z, viewport, winCoordsDest); } /** * Project the given <code>position</code> via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, int[], Vector4f) * * @param position * the position to project into window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return winCoordsDest */ public Vector3f project(Vector3f position, int[] viewport, Vector3f winCoordsDest) { return project(position.x, position.y, position.z, viewport, winCoordsDest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt> and store the result in <code>dest</code>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return dest */ public Matrix4f reflect(float a, float b, float c, float d, Matrix4f dest) { float da = a + a, db = b + b, dc = c + c, dd = d + d; float rm00 = 1.0f - da * a; float rm01 = -da * b; float rm02 = -da * c; float rm10 = -db * a; float rm11 = 1.0f - db * b; float rm12 = -db * c; float rm20 = -dc * a; float rm21 = -dc * b; float rm22 = 1.0f - dc * c; float rm30 = -dd * a; float rm31 = -dd * b; float rm32 = -dd * c; // matrix multiplication dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return dest; } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f reflect(float a, float b, float c, float d) { return reflect(a, b, c, d, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @return this */ public Matrix4f reflect(float nx, float ny, float nz, float px, float py, float pz) { return reflect(nx, ny, nz, px, py, pz, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane, and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @param dest * will hold the result * @return dest */ public Matrix4f reflect(float nx, float ny, float nz, float px, float py, float pz, Matrix4f dest) { float invLength = 1.0f / (float) Math.sqrt(nx * nx + ny * ny + nz * nz); float nnx = nx * invLength; float nny = ny * invLength; float nnz = nz * invLength; /* See: http://mathworld.wolfram.com/Plane.html */ return reflect(nnx, nny, nnz, -nnx * px - nny * py - nnz * pz, dest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param normal * the plane normal * @param point * a point on the plane * @return this */ public Matrix4f reflect(Vector3f normal, Vector3f point) { return reflect(normal.x, normal.y, normal.z, point.x, point.y, point.z); } /** * Apply a mirror/reflection transformation to this matrix that reflects about a plane * specified via the plane orientation and a point on the plane. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param orientation * the plane orientation * @param point * a point on the plane * @return this */ public Matrix4f reflect(Quaternionf orientation, Vector3f point) { return reflect(orientation, point, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about a plane * specified via the plane orientation and a point on the plane, and store the result in <code>dest</code>. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param orientation * the plane orientation relative to an implied normal vector of <tt>(0, 0, 1)</tt> * @param point * a point on the plane * @param dest * will hold the result * @return dest */ public Matrix4f reflect(Quaternionf orientation, Vector3f point, Matrix4f dest) { double num1 = orientation.x + orientation.x; double num2 = orientation.y + orientation.y; double num3 = orientation.z + orientation.z; float normalX = (float) (orientation.x * num3 + orientation.w * num2); float normalY = (float) (orientation.y * num3 - orientation.w * num1); float normalZ = (float) (1.0 - (orientation.x * num1 + orientation.y * num2)); return reflect(normalX, normalY, normalZ, point.x, point.y, point.z, dest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane, and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param normal * the plane normal * @param point * a point on the plane * @param dest * will hold the result * @return dest */ public Matrix4f reflect(Vector3f normal, Vector3f point, Matrix4f dest) { return reflect(normal.x, normal.y, normal.z, point.x, point.y, point.z, dest); } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f reflection(float a, float b, float c, float d) { float da = a + a, db = b + b, dc = c + c, dd = d + d; m00 = 1.0f - da * a; m01 = -da * b; m02 = -da * c; m03 = 0.0f; m10 = -db * a; m11 = 1.0f - db * b; m12 = -db * c; m13 = 0.0f; m20 = -dc * a; m21 = -dc * b; m22 = 1.0f - dc * c; m23 = 0.0f; m30 = -dd * a; m31 = -dd * b; m32 = -dd * c; m33 = 1.0f; return this; } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the plane normal and a point on the plane. * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @return this */ public Matrix4f reflection(float nx, float ny, float nz, float px, float py, float pz) { float invLength = 1.0f / (float) Math.sqrt(nx * nx + ny * ny + nz * nz); float nnx = nx * invLength; float nny = ny * invLength; float nnz = nz * invLength; /* See: http://mathworld.wolfram.com/Plane.html */ return reflection(nnx, nny, nnz, -nnx * px - nny * py - nnz * pz); } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the plane normal and a point on the plane. * * @param normal * the plane normal * @param point * a point on the plane * @return this */ public Matrix4f reflection(Vector3f normal, Vector3f point) { return reflection(normal.x, normal.y, normal.z, point.x, point.y, point.z); } /** * Set this matrix to a mirror/reflection transformation that reflects about a plane * specified via the plane orientation and a point on the plane. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * * @param orientation * the plane orientation * @param point * a point on the plane * @return this */ public Matrix4f reflection(Quaternionf orientation, Vector3f point) { double num1 = orientation.x + orientation.x; double num2 = orientation.y + orientation.y; double num3 = orientation.z + orientation.z; float normalX = (float) (orientation.x * num3 + orientation.w * num2); float normalY = (float) (orientation.y * num3 - orientation.w * num1); float normalZ = (float) (1.0 - (orientation.x * num1 + orientation.y * num2)); return reflection(normalX, normalY, normalZ, point.x, point.y, point.z); } /** * Get the row at the given <code>row</code> index, starting with <code>0</code>. * * @param row * the row index in <tt>[0..3]</tt> * @param dest * will hold the row components * @return the passed in destination * @throws IndexOutOfBoundsException if <code>row</code> is not in <tt>[0..3]</tt> */ public Vector4f getRow(int row, Vector4f dest) throws IndexOutOfBoundsException { switch (row) { case 0: dest.x = m00; dest.y = m10; dest.z = m20; dest.w = m30; break; case 1: dest.x = m01; dest.y = m11; dest.z = m21; dest.w = m31; break; case 2: dest.x = m02; dest.y = m12; dest.z = m22; dest.w = m32; break; case 3: dest.x = m03; dest.y = m13; dest.z = m23; dest.w = m33; break; default: throw new IndexOutOfBoundsException(); } return dest; } /** * Get the column at the given <code>column</code> index, starting with <code>0</code>. * * @param column * the column index in <tt>[0..3]</tt> * @param dest * will hold the column components * @return the passed in destination * @throws IndexOutOfBoundsException if <code>column</code> is not in <tt>[0..3]</tt> */ public Vector4f getColumn(int column, Vector4f dest) throws IndexOutOfBoundsException { switch (column) { case 0: dest.x = m00; dest.y = m01; dest.z = m02; dest.w = m03; break; case 1: dest.x = m10; dest.y = m11; dest.z = m12; dest.w = m13; break; case 2: dest.x = m20; dest.y = m21; dest.z = m22; dest.w = m23; break; case 3: dest.x = m30; dest.y = m31; dest.z = m32; dest.w = m32; break; default: throw new IndexOutOfBoundsException(); } return dest; } /** * Compute a normal matrix from the upper left 3x3 submatrix of <code>this</code> * and store it into the upper left 3x3 submatrix of <code>this</code>. * All other values of <code>this</code> will be set to {@link #identity() identity}. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * <p> * Please note that, if <code>this</code> is an orthogonal matrix or a matrix whose columns are orthogonal vectors, * then this method <i>need not</i> be invoked, since in that case <code>this</code> itself is its normal matrix. * In that case, use {@link #set3x3(Matrix4f)} to set a given Matrix4f to only the upper left 3x3 submatrix * of this matrix. * * @see #set3x3(Matrix4f) * * @return this */ public Matrix4f normal() { return normal(this); } /** * Compute a normal matrix from the upper left 3x3 submatrix of <code>this</code> * and store it into the upper left 3x3 submatrix of <code>dest</code>. * All other values of <code>dest</code> will be set to {@link #identity() identity}. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * <p> * Please note that, if <code>this</code> is an orthogonal matrix or a matrix whose columns are orthogonal vectors, * then this method <i>need not</i> be invoked, since in that case <code>this</code> itself is its normal matrix. * In that case, use {@link #set3x3(Matrix4f)} to set a given Matrix4f to only the upper left 3x3 submatrix * of this matrix. * * @see #set3x3(Matrix4f) * * @param dest * will hold the result * @return dest */ public Matrix4f normal(Matrix4f dest) { float det = determinant3x3(); float s = 1.0f / det; /* Invert and transpose in one go */ float nm00 = (m11 * m22 - m21 * m12) * s; float nm01 = (m20 * m12 - m10 * m22) * s; float nm02 = (m10 * m21 - m20 * m11) * s; float nm03 = 0.0f; float nm10 = (m21 * m02 - m01 * m22) * s; float nm11 = (m00 * m22 - m20 * m02) * s; float nm12 = (m20 * m01 - m00 * m21) * s; float nm13 = 0.0f; float nm20 = (m01 * m12 - m11 * m02) * s; float nm21 = (m10 * m02 - m00 * m12) * s; float nm22 = (m00 * m11 - m10 * m01) * s; float nm23 = 0.0f; float nm30 = 0.0f; float nm31 = 0.0f; float nm32 = 0.0f; float nm33 = 1.0f; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = nm30; dest.m31 = nm31; dest.m32 = nm32; dest.m33 = nm33; return dest; } /** * Compute a normal matrix from the upper left 3x3 submatrix of <code>this</code> * and store it into <code>dest</code>. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * <p> * Please note that, if <code>this</code> is an orthogonal matrix or a matrix whose columns are orthogonal vectors, * then this method <i>need not</i> be invoked, since in that case <code>this</code> itself is its normal matrix. * In that case, use {@link Matrix3f#set(Matrix4f)} to set a given Matrix3f to only the upper left 3x3 submatrix * of this matrix. * * @see Matrix3f#set(Matrix4f) * @see #get3x3(Matrix3f) * * @param dest * will hold the result * @return dest */ public Matrix3f normal(Matrix3f dest) { float det = determinant3x3(); float s = 1.0f / det; /* Invert and transpose in one go */ dest.m00 = (m11 * m22 - m21 * m12) * s; dest.m01 = (m20 * m12 - m10 * m22) * s; dest.m02 = (m10 * m21 - m20 * m11) * s; dest.m10 = (m21 * m02 - m01 * m22) * s; dest.m11 = (m00 * m22 - m20 * m02) * s; dest.m12 = (m20 * m01 - m00 * m21) * s; dest.m20 = (m01 * m12 - m11 * m02) * s; dest.m21 = (m10 * m02 - m00 * m12) * s; dest.m22 = (m00 * m11 - m10 * m01) * s; return dest; } /** * Normalize the upper left 3x3 submatrix of this matrix. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @return this */ public Matrix4f normalize3x3() { return normalize3x3(this); } /** * Normalize the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @param dest * will hold the result * @return dest */ public Matrix4f normalize3x3(Matrix4f dest) { float invXlen = (float) (1.0 / Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02)); float invYlen = (float) (1.0 / Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12)); float invZlen = (float) (1.0 / Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22)); dest.m00 = m00 * invXlen; dest.m01 = m01 * invXlen; dest.m02 = m02 * invXlen; dest.m10 = m10 * invYlen; dest.m11 = m11 * invYlen; dest.m12 = m12 * invYlen; dest.m20 = m20 * invZlen; dest.m21 = m21 * invZlen; dest.m22 = m22 * invZlen; return dest; } /** * Normalize the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @param dest * will hold the result * @return dest */ public Matrix3f normalize3x3(Matrix3f dest) { float invXlen = (float) (1.0 / Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02)); float invYlen = (float) (1.0 / Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12)); float invZlen = (float) (1.0 / Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22)); dest.m00 = m00 * invXlen; dest.m01 = m01 * invXlen; dest.m02 = m02 * invXlen; dest.m10 = m10 * invYlen; dest.m11 = m11 * invYlen; dest.m12 = m12 * invYlen; dest.m20 = m20 * invZlen; dest.m21 = m21 * invZlen; dest.m22 = m22 * invZlen; return dest; } /** * Calculate a frustum plane of <code>this</code> matrix, which * can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>planeEquation</code>. * <p> * Generally, this method computes the frustum plane in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The frustum plane will be given in the form of a general plane equation: * <tt>a*x + b*y + c*z + d = 0</tt>, where the given {@link Vector4f} components will * hold the <tt>(a, b, c, d)</tt> values of the equation. * <p> * The plane normal, which is <tt>(a, b, c)</tt>, is directed "inwards" of the frustum. * Any plane/point test using <tt>a*x + b*y + c*z + d</tt> therefore will yield a result greater than zero * if the point is within the frustum (i.e. at the <i>positive</i> side of the frustum plane). * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param plane * one of the six possible planes, given as numeric constants * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} * @param planeEquation * will hold the computed plane equation. * The plane equation will be normalized, meaning that <tt>(a, b, c)</tt> will be a unit vector * @return planeEquation */ public Vector4f frustumPlane(int plane, Vector4f planeEquation) { switch (plane) { case PLANE_NX: planeEquation.set(m03 + m00, m13 + m10, m23 + m20, m33 + m30).normalize3(); break; case PLANE_PX: planeEquation.set(m03 - m00, m13 - m10, m23 - m20, m33 - m30).normalize3(); break; case PLANE_NY: planeEquation.set(m03 + m01, m13 + m11, m23 + m21, m33 + m31).normalize3(); break; case PLANE_PY: planeEquation.set(m03 - m01, m13 - m11, m23 - m21, m33 - m31).normalize3(); break; case PLANE_NZ: planeEquation.set(m03 + m02, m13 + m12, m23 + m22, m33 + m32).normalize3(); break; case PLANE_PZ: planeEquation.set(m03 - m02, m13 - m12, m23 - m22, m33 - m32).normalize3(); break; default: throw new IllegalArgumentException("plane"); //$NON-NLS-1$ } return planeEquation; } /** * Compute the corner coordinates of the frustum defined by <code>this</code> matrix, which * can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>point</code>. * <p> * Generally, this method computes the frustum corners in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * Reference: <a href="http://geomalgorithms.com/a05-_intersect-1.html">http://geomalgorithms.com</a> * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param corner * one of the eight possible corners, given as numeric constants * {@link #CORNER_NXNYNZ}, {@link #CORNER_PXNYNZ}, {@link #CORNER_PXPYNZ}, {@link #CORNER_NXPYNZ}, * {@link #CORNER_PXNYPZ}, {@link #CORNER_NXNYPZ}, {@link #CORNER_NXPYPZ}, {@link #CORNER_PXPYPZ} * @param point * will hold the resulting corner point coordinates * @return point */ public Vector3f frustumCorner(int corner, Vector3f point) { float d1, d2, d3; float n1x, n1y, n1z, n2x, n2y, n2z, n3x, n3y, n3z; switch (corner) { case CORNER_NXNYNZ: // left, bottom, near n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXNYNZ: // right, bottom, near n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXPYNZ: // right, top, near n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_NXPYNZ: // left, top, near n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXNYPZ: // right, bottom, far n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_NXNYPZ: // left, bottom, far n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_NXPYPZ: // left, top, far n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_PXPYPZ: // right, top, far n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; default: throw new IllegalArgumentException("corner"); //$NON-NLS-1$ } float c23x, c23y, c23z; c23x = n2y * n3z - n2z * n3y; c23y = n2z * n3x - n2x * n3z; c23z = n2x * n3y - n2y * n3x; float c31x, c31y, c31z; c31x = n3y * n1z - n3z * n1y; c31y = n3z * n1x - n3x * n1z; c31z = n3x * n1y - n3y * n1x; float c12x, c12y, c12z; c12x = n1y * n2z - n1z * n2y; c12y = n1z * n2x - n1x * n2z; c12z = n1x * n2y - n1y * n2x; float invDot = 1.0f / (n1x * c23x + n1y * c23y + n1z * c23z); point.x = (-c23x * d1 - c31x * d2 - c12x * d3) * invDot; point.y = (-c23y * d1 - c31y * d2 - c12y * d3) * invDot; point.z = (-c23z * d1 - c31z * d2 - c12z * d3) * invDot; return point; } /** * Compute the eye/origin of the perspective frustum transformation defined by <code>this</code> matrix, * which can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>origin</code>. * <p> * Note that this method will only work using perspective projections obtained via one of the * perspective methods, such as {@link #perspective(float, float, float, float) perspective()} * or {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * Generally, this method computes the origin in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * Reference: <a href="http://geomalgorithms.com/a05-_intersect-1.html">http://geomalgorithms.com</a> * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param origin * will hold the origin of the coordinate system before applying <code>this</code> * perspective projection transformation * @return origin */ public Vector3f perspectiveOrigin(Vector3f origin) { /* * Simply compute the intersection point of the left, right and top frustum plane. */ float d1, d2, d3; float n1x, n1y, n1z, n2x, n2y, n2z, n3x, n3y, n3z; n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m00; n2y = m13 - m10; n2z = m23 - m20; d2 = m33 - m30; // right n3x = m03 - m01; n3y = m13 - m11; n3z = m23 - m21; d3 = m33 - m31; // top float c23x, c23y, c23z; c23x = n2y * n3z - n2z * n3y; c23y = n2z * n3x - n2x * n3z; c23z = n2x * n3y - n2y * n3x; float c31x, c31y, c31z; c31x = n3y * n1z - n3z * n1y; c31y = n3z * n1x - n3x * n1z; c31z = n3x * n1y - n3y * n1x; float c12x, c12y, c12z; c12x = n1y * n2z - n1z * n2y; c12y = n1z * n2x - n1x * n2z; c12z = n1x * n2y - n1y * n2x; float invDot = 1.0f / (n1x * c23x + n1y * c23y + n1z * c23z); origin.x = (-c23x * d1 - c31x * d2 - c12x * d3) * invDot; origin.y = (-c23y * d1 - c31y * d2 - c12y * d3) * invDot; origin.z = (-c23z * d1 - c31z * d2 - c12z * d3) * invDot; return origin; } /** * Return the vertical field-of-view angle in radians of this perspective transformation matrix. * <p> * Note that this method will only work using perspective projections obtained via one of the * perspective methods, such as {@link #perspective(float, float, float, float) perspective()} * or {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * For orthogonal transformations this method will return <tt>0.0</tt>. * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @return the vertical field-of-view angle in radians */ public float perspectiveFov() { /* * Compute the angle between the bottom and top frustum plane normals. */ float n1x, n1y, n1z, n2x, n2y, n2z; n1x = m03 + m01; n1y = m13 + m11; n1z = m23 + m21; // bottom n2x = m01 - m03; n2y = m11 - m13; n2z = m21 - m23; // top float n1len = (float) Math.sqrt(n1x * n1x + n1y * n1y + n1z * n1z); float n2len = (float) Math.sqrt(n2x * n2x + n2y * n2y + n2z * n2z); return (float) Math.acos((n1x * n2x + n1y * n2y + n1z * n2z) / (n1len * n2len)); } /** * Extract the near clip plane distance from <code>this</code> perspective projection matrix. * <p> * This method only works if <code>this</code> is a perspective projection matrix, for example obtained via {@link #perspective(float, float, float, float)}. * * @return the near clip plane distance */ public float perspectiveNear() { return m32 / (m23 + m22); } /** * Extract the far clip plane distance from <code>this</code> perspective projection matrix. * <p> * This method only works if <code>this</code> is a perspective projection matrix, for example obtained via {@link #perspective(float, float, float, float)}. * * @return the far clip plane distance */ public float perspectiveFar() { return m32 / (m22 - m23); } /** * Obtain the direction of a ray starting at the center of the coordinate system and going * through the near frustum plane. * <p> * This method computes the <code>dir</code> vector in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The parameters <code>x</code> and <code>y</code> are used to interpolate the generated ray direction * from the bottom-left to the top-right frustum corners. * <p> * For optimal efficiency when building many ray directions over the whole frustum, * it is recommended to use this method only in order to compute the four corner rays at * <tt>(0, 0)</tt>, <tt>(1, 0)</tt>, <tt>(0, 1)</tt> and <tt>(1, 1)</tt> * and then bilinearly interpolating between them; or to use the {@link FrustumRayBuilder}. * <p> * Reference: <a href="http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param x * the interpolation factor along the left-to-right frustum planes, within <tt>[0..1]</tt> * @param y * the interpolation factor along the bottom-to-top frustum planes, within <tt>[0..1]</tt> * @param dir * will hold the normalized ray direction in the local frame of the coordinate system before * transforming to homogeneous clipping space using <code>this</code> matrix * @return dir */ public Vector3f frustumRayDir(float x, float y, Vector3f dir) { /* * This method works by first obtaining the frustum plane normals, * then building the cross product to obtain the corner rays, * and finally bilinearly interpolating to obtain the desired direction. * The code below uses a condense form of doing all this making use * of some mathematical identities to simplify the overall expression. */ float a = m10 * m23, b = m13 * m21, c = m10 * m21, d = m11 * m23, e = m13 * m20, f = m11 * m20; float g = m03 * m20, h = m01 * m23, i = m01 * m20, j = m03 * m21, k = m00 * m23, l = m00 * m21; float m = m00 * m13, n = m03 * m11, o = m00 * m11, p = m01 * m13, q = m03 * m10, r = m01 * m10; float m1x, m1y, m1z; m1x = (d + e + f - a - b - c) * (1.0f - y) + (a - b - c + d - e + f) * y; m1y = (j + k + l - g - h - i) * (1.0f - y) + (g - h - i + j - k + l) * y; m1z = (p + q + r - m - n - o) * (1.0f - y) + (m - n - o + p - q + r) * y; float m2x, m2y, m2z; m2x = (b - c - d + e + f - a) * (1.0f - y) + (a + b - c - d - e + f) * y; m2y = (h - i - j + k + l - g) * (1.0f - y) + (g + h - i - j - k + l) * y; m2z = (n - o - p + q + r - m) * (1.0f - y) + (m + n - o - p - q + r) * y; dir.x = m1x + (m2x - m1x) * x; dir.y = m1y + (m2y - m1y) * x; dir.z = m1z + (m2z - m1z) * x; dir.normalize(); return dir; } /** * Obtain the direction of <tt>+Z</tt> before the transformation represented by <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Z</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invert(); * inv.transformDirection(dir.set(0, 0, 1)).normalize(); * </pre> * If <code>this</code> is already an orthogonal matrix, then consider using {@link #normalizedPositiveZ(Vector3f)} instead. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Z</tt> * @return dir */ public Vector3f positiveZ(Vector3f dir) { dir.x = m10 * m21 - m11 * m20; dir.y = m20 * m01 - m21 * m00; dir.z = m00 * m11 - m01 * m10; dir.normalize(); return dir; } /** * Obtain the direction of <tt>+Z</tt> before the transformation represented by <code>this</code> <i>orthogonal</i> matrix is applied. * This method only produces correct results if <code>this</code> is an <i>orthogonal</i> matrix. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Z</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).transpose(); * inv.transformDirection(dir.set(0, 0, 1)).normalize(); * </pre> * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Z</tt> * @return dir */ public Vector3f normalizedPositiveZ(Vector3f dir) { dir.x = m02; dir.y = m12; dir.z = m22; return dir; } /** * Obtain the direction of <tt>+X</tt> before the transformation represented by <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+X</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invert(); * inv.transformDirection(dir.set(1, 0, 0)).normalize(); * </pre> * If <code>this</code> is already an orthogonal matrix, then consider using {@link #normalizedPositiveX(Vector3f)} instead. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+X</tt> * @return dir */ public Vector3f positiveX(Vector3f dir) { dir.x = m11 * m22 - m12 * m21; dir.y = m02 * m21 - m01 * m22; dir.z = m01 * m12 - m02 * m11; dir.normalize(); return dir; } /** * Obtain the direction of <tt>+X</tt> before the transformation represented by <code>this</code> <i>orthogonal</i> matrix is applied. * This method only produces correct results if <code>this</code> is an <i>orthogonal</i> matrix. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+X</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).transpose(); * inv.transformDirection(dir.set(1, 0, 0)).normalize(); * </pre> * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+X</tt> * @return dir */ public Vector3f normalizedPositiveX(Vector3f dir) { dir.x = m00; dir.y = m10; dir.z = m20; return dir; } /** * Obtain the direction of <tt>+Y</tt> before the transformation represented by <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Y</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invert(); * inv.transformDirection(dir.set(0, 1, 0)).normalize(); * </pre> * If <code>this</code> is already an orthogonal matrix, then consider using {@link #normalizedPositiveY(Vector3f)} instead. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Y</tt> * @return dir */ public Vector3f positiveY(Vector3f dir) { dir.x = m12 * m20 - m10 * m22; dir.y = m00 * m22 - m02 * m20; dir.z = m02 * m10 - m00 * m12; dir.normalize(); return dir; } /** * Obtain the direction of <tt>+Y</tt> before the transformation represented by <code>this</code> <i>orthogonal</i> matrix is applied. * This method only produces correct results if <code>this</code> is an <i>orthogonal</i> matrix. * <p> * This method uses the rotation component of the upper left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Y</tt> by <code>this</code> matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).transpose(); * inv.transformDirection(dir.set(0, 1, 0)).normalize(); * </pre> * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Y</tt> * @return dir */ public Vector3f normalizedPositiveY(Vector3f dir) { dir.x = m01; dir.y = m11; dir.z = m21; return dir; } /** * Obtain the position that gets transformed to the origin by <code>this</code> {@link #isAffine() affine} matrix. * This can be used to get the position of the "camera" from a given <i>view</i> transformation matrix. * <p> * This method only works with {@link #isAffine() affine} matrices. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invertAffine(); * inv.transformPosition(origin.set(0, 0, 0)); * </pre> * * @param origin * will hold the position transformed to the origin * @return origin */ public Vector3f originAffine(Vector3f origin) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float d = m01 * m12 - m02 * m11; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float j = m21 * m32 - m22 * m31; origin.x = -m10 * j + m11 * h - m12 * g; origin.y = m00 * j - m01 * h + m02 * g; origin.z = -m30 * d + m31 * b - m32 * a; return origin; } /** * Obtain the position that gets transformed to the origin by <code>this</code> matrix. * This can be used to get the position of the "camera" from a given <i>view/projection</i> transformation matrix. * <p> * This method is equivalent to the following code: * <pre> * Matrix4f inv = new Matrix4f(this).invert(); * inv.transformPosition(origin.set(0, 0, 0)); * </pre> * * @param origin * will hold the position transformed to the origin * @return origin */ public Vector3f origin(Vector3f origin) { float a = m00 * m11 - m01 * m10; float b = m00 * m12 - m02 * m10; float c = m00 * m13 - m03 * m10; float d = m01 * m12 - m02 * m11; float e = m01 * m13 - m03 * m11; float f = m02 * m13 - m03 * m12; float g = m20 * m31 - m21 * m30; float h = m20 * m32 - m22 * m30; float i = m20 * m33 - m23 * m30; float j = m21 * m32 - m22 * m31; float k = m21 * m33 - m23 * m31; float l = m22 * m33 - m23 * m32; float det = a * l - b * k + c * j + d * i - e * h + f * g; float invDet = 1.0f / det; float nm30 = (-m10 * j + m11 * h - m12 * g) * invDet; float nm31 = ( m00 * j - m01 * h + m02 * g) * invDet; float nm32 = (-m30 * d + m31 * b - m32 * a) * invDet; float nm33 = det / ( m20 * d - m21 * b + m22 * a); float x = nm30 * nm33; float y = nm31 * nm33; float z = nm32 * nm33; return origin.set(x, y, z); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <code>light</code>. * <p> * If <tt>light.w</tt> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param light * the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f shadow(Vector4f light, float a, float b, float c, float d) { return shadow(light.x, light.y, light.z, light.w, a, b, c, d, this); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <code>light</code> * and store the result in <code>dest</code>. * <p> * If <tt>light.w</tt> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param light * the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return dest */ public Matrix4f shadow(Vector4f light, float a, float b, float c, float d, Matrix4f dest) { return shadow(light.x, light.y, light.z, light.w, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param lightX * the x-component of the light's vector * @param lightY * the y-component of the light's vector * @param lightZ * the z-component of the light's vector * @param lightW * the w-component of the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d) { return shadow(lightX, lightY, lightZ, lightW, a, b, c, d, this); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt> * and store the result in <code>dest</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param lightX * the x-component of the light's vector * @param lightY * the y-component of the light's vector * @param lightZ * the z-component of the light's vector * @param lightW * the w-component of the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return dest */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d, Matrix4f dest) { // normalize plane float invPlaneLen = (float) (1.0 / Math.sqrt(a*a + b*b + c*c)); float an = a * invPlaneLen; float bn = b * invPlaneLen; float cn = c * invPlaneLen; float dn = d * invPlaneLen; float dot = an * lightX + bn * lightY + cn * lightZ + dn * lightW; // compute right matrix elements float rm00 = dot - an * lightX; float rm01 = -an * lightY; float rm02 = -an * lightZ; float rm03 = -an * lightW; float rm10 = -bn * lightX; float rm11 = dot - bn * lightY; float rm12 = -bn * lightZ; float rm13 = -bn * lightW; float rm20 = -cn * lightX; float rm21 = -cn * lightY; float rm22 = dot - cn * lightZ; float rm23 = -cn * lightW; float rm30 = -dn * lightX; float rm31 = -dn * lightY; float rm32 = -dn * lightZ; float rm33 = dot - dn * lightW; // matrix multiplication float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02 + m30 * rm03; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02 + m31 * rm03; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02 + m32 * rm03; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02 + m33 * rm03; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12 + m30 * rm13; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12 + m31 * rm13; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12 + m32 * rm13; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12 + m33 * rm13; float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 + m30 * rm23; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 + m31 * rm23; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 + m32 * rm23; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 + m33 * rm23; dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30 * rm33; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31 * rm33; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32 * rm33; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33 * rm33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return dest; } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <code>light</code> * and store the result in <code>dest</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <tt>light.w</tt> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param light * the light's vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @param dest * will hold the result * @return dest */ public Matrix4f shadow(Vector4f light, Matrix4f planeTransform, Matrix4f dest) { // compute plane equation by transforming (y = 0) float a = planeTransform.m10; float b = planeTransform.m11; float c = planeTransform.m12; float d = -a * planeTransform.m30 - b * planeTransform.m31 - c * planeTransform.m32; return shadow(light.x, light.y, light.z, light.w, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <code>light</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <tt>light.w</tt> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param light * the light's vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @return this */ public Matrix4f shadow(Vector4f light, Matrix4f planeTransform) { return shadow(light, planeTransform, this); } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt> * and store the result in <code>dest</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param lightX * the x-component of the light vector * @param lightY * the y-component of the light vector * @param lightZ * the z-component of the light vector * @param lightW * the w-component of the light vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @param dest * will hold the result * @return dest */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, Matrix4f planeTransform, Matrix4f dest) { // compute plane equation by transforming (y = 0) float a = planeTransform.m10; float b = planeTransform.m11; float c = planeTransform.m12; float d = -a * planeTransform.m30 - b * planeTransform.m31 - c * planeTransform.m32; return shadow(lightX, lightY, lightZ, lightW, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param lightX * the x-component of the light vector * @param lightY * the y-component of the light vector * @param lightZ * the z-component of the light vector * @param lightW * the w-component of the light vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @return this */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, Matrix4f planeTransform) { return shadow(lightX, lightY, lightZ, lightW, planeTransform, this); } /** * Set this matrix to a cylindrical billboard transformation that rotates the local +Z axis of a given object with position <code>objPos</code> towards * a target position at <code>targetPos</code> while constraining a cylindrical rotation around the given <code>up</code> vector. * <p> * This method can be used to create the complete model transformation for a given object, including the translation of the object to * its position <code>objPos</code>. * * @param objPos * the position of the object to rotate towards <code>targetPos</code> * @param targetPos * the position of the target (for example the camera) towards which to rotate the object * @param up * the rotation axis (must be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f billboardCylindrical(Vector3f objPos, Vector3f targetPos, Vector3f up) { float dirX = targetPos.x - objPos.x; float dirY = targetPos.y - objPos.y; float dirZ = targetPos.z - objPos.z; // left = up x dir float leftX = up.y * dirZ - up.z * dirY; float leftY = up.z * dirX - up.x * dirZ; float leftZ = up.x * dirY - up.y * dirX; // normalize left float invLeftLen = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLen; leftY *= invLeftLen; leftZ *= invLeftLen; // recompute dir by constraining rotation around 'up' // dir = left x up dirX = leftY * up.z - leftZ * up.y; dirY = leftZ * up.x - leftX * up.z; dirZ = leftX * up.y - leftY * up.x; // normalize dir float invDirLen = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLen; dirY *= invDirLen; dirZ *= invDirLen; // set matrix elements m00 = leftX; m01 = leftY; m02 = leftZ; m03 = 0.0f; m10 = up.x; m11 = up.y; m12 = up.z; m13 = 0.0f; m20 = dirX; m21 = dirY; m22 = dirZ; m23 = 0.0f; m30 = objPos.x; m31 = objPos.y; m32 = objPos.z; m33 = 1.0f; return this; } /** * Set this matrix to a spherical billboard transformation that rotates the local +Z axis of a given object with position <code>objPos</code> towards * a target position at <code>targetPos</code>. * <p> * This method can be used to create the complete model transformation for a given object, including the translation of the object to * its position <code>objPos</code>. * <p> * If preserving an <i>up</i> vector is not necessary when rotating the +Z axis, then a shortest arc rotation can be obtained * using {@link #billboardSpherical(Vector3f, Vector3f)}. * * @see #billboardSpherical(Vector3f, Vector3f) * * @param objPos * the position of the object to rotate towards <code>targetPos</code> * @param targetPos * the position of the target (for example the camera) towards which to rotate the object * @param up * the up axis used to orient the object * @return this */ public Matrix4f billboardSpherical(Vector3f objPos, Vector3f targetPos, Vector3f up) { float dirX = targetPos.x - objPos.x; float dirY = targetPos.y - objPos.y; float dirZ = targetPos.z - objPos.z; // normalize dir float invDirLen = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= invDirLen; dirY *= invDirLen; dirZ *= invDirLen; // left = up x dir float leftX = up.y * dirZ - up.z * dirY; float leftY = up.z * dirX - up.x * dirZ; float leftZ = up.x * dirY - up.y * dirX; // normalize left float invLeftLen = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ); leftX *= invLeftLen; leftY *= invLeftLen; leftZ *= invLeftLen; // up = dir x left float upX = dirY * leftZ - dirZ * leftY; float upY = dirZ * leftX - dirX * leftZ; float upZ = dirX * leftY - dirY * leftX; // set matrix elements m00 = leftX; m01 = leftY; m02 = leftZ; m03 = 0.0f; m10 = upX; m11 = upY; m12 = upZ; m13 = 0.0f; m20 = dirX; m21 = dirY; m22 = dirZ; m23 = 0.0f; m30 = objPos.x; m31 = objPos.y; m32 = objPos.z; m33 = 1.0f; return this; } /** * Set this matrix to a spherical billboard transformation that rotates the local +Z axis of a given object with position <code>objPos</code> towards * a target position at <code>targetPos</code> using a shortest arc rotation by not preserving any <i>up</i> vector of the object. * <p> * This method can be used to create the complete model transformation for a given object, including the translation of the object to * its position <code>objPos</code>. * <p> * In order to specify an <i>up</i> vector which needs to be maintained when rotating the +Z axis of the object, * use {@link #billboardSpherical(Vector3f, Vector3f, Vector3f)}. * * @see #billboardSpherical(Vector3f, Vector3f, Vector3f) * * @param objPos * the position of the object to rotate towards <code>targetPos</code> * @param targetPos * the position of the target (for example the camera) towards which to rotate the object * @return this */ public Matrix4f billboardSpherical(Vector3f objPos, Vector3f targetPos) { float toDirX = targetPos.x - objPos.x; float toDirY = targetPos.y - objPos.y; float toDirZ = targetPos.z - objPos.z; float x = -toDirY; float y = toDirX; float w = (float) Math.sqrt(toDirX * toDirX + toDirY * toDirY + toDirZ * toDirZ) + toDirZ; float invNorm = (float) (1.0 / Math.sqrt(x * x + y * y + w * w)); x *= invNorm; y *= invNorm; w *= invNorm; float q00 = (x + x) * x; float q11 = (y + y) * y; float q01 = (x + x) * y; float q03 = (x + x) * w; float q13 = (y + y) * w; m00 = 1.0f - q11; m01 = q01; m02 = -q13; m03 = 0.0f; m10 = q01; m11 = 1.0f - q00; m12 = q03; m13 = 0.0f; m20 = q13; m21 = -q03; m22 = 1.0f - q11 - q00; m23 = 0.0f; m30 = objPos.x; m31 = objPos.y; m32 = objPos.z; m33 = 1.0f; return this; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Float.floatToIntBits(m00); result = prime * result + Float.floatToIntBits(m01); result = prime * result + Float.floatToIntBits(m02); result = prime * result + Float.floatToIntBits(m03); result = prime * result + Float.floatToIntBits(m10); result = prime * result + Float.floatToIntBits(m11); result = prime * result + Float.floatToIntBits(m12); result = prime * result + Float.floatToIntBits(m13); result = prime * result + Float.floatToIntBits(m20); result = prime * result + Float.floatToIntBits(m21); result = prime * result + Float.floatToIntBits(m22); result = prime * result + Float.floatToIntBits(m23); result = prime * result + Float.floatToIntBits(m30); result = prime * result + Float.floatToIntBits(m31); result = prime * result + Float.floatToIntBits(m32); result = prime * result + Float.floatToIntBits(m33); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Matrix4f)) return false; Matrix4f other = (Matrix4f) obj; if (Float.floatToIntBits(m00) != Float.floatToIntBits(other.m00)) return false; if (Float.floatToIntBits(m01) != Float.floatToIntBits(other.m01)) return false; if (Float.floatToIntBits(m02) != Float.floatToIntBits(other.m02)) return false; if (Float.floatToIntBits(m03) != Float.floatToIntBits(other.m03)) return false; if (Float.floatToIntBits(m10) != Float.floatToIntBits(other.m10)) return false; if (Float.floatToIntBits(m11) != Float.floatToIntBits(other.m11)) return false; if (Float.floatToIntBits(m12) != Float.floatToIntBits(other.m12)) return false; if (Float.floatToIntBits(m13) != Float.floatToIntBits(other.m13)) return false; if (Float.floatToIntBits(m20) != Float.floatToIntBits(other.m20)) return false; if (Float.floatToIntBits(m21) != Float.floatToIntBits(other.m21)) return false; if (Float.floatToIntBits(m22) != Float.floatToIntBits(other.m22)) return false; if (Float.floatToIntBits(m23) != Float.floatToIntBits(other.m23)) return false; if (Float.floatToIntBits(m30) != Float.floatToIntBits(other.m30)) return false; if (Float.floatToIntBits(m31) != Float.floatToIntBits(other.m31)) return false; if (Float.floatToIntBits(m32) != Float.floatToIntBits(other.m32)) return false; if (Float.floatToIntBits(m33) != Float.floatToIntBits(other.m33)) return false; return true; } /** * Apply a picking transformation to this matrix using the given window coordinates <tt>(x, y)</tt> as the pick center * and the given <tt>(width, height)</tt> as the size of the picking region in window coordinates, and store the result * in <code>dest</code>. * * @param x * the x coordinate of the picking region center in window coordinates * @param y * the y coordinate of the picking region center in window coordinates * @param width * the width of the picking region in window coordinates * @param height * the height of the picking region in window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * the destination matrix, which will hold the result * @return dest */ public Matrix4f pick(float x, float y, float width, float height, int[] viewport, Matrix4f dest) { float sx = viewport[2] / width; float sy = viewport[3] / height; float tx = (viewport[2] + 2.0f * (viewport[0] - x)) / width; float ty = (viewport[3] + 2.0f * (viewport[1] - y)) / height; dest.m30 = m00 * tx + m10 * ty + m30; dest.m31 = m01 * tx + m11 * ty + m31; dest.m32 = m02 * tx + m12 * ty + m32; dest.m33 = m03 * tx + m13 * ty + m33; dest.m00 = m00 * sx; dest.m01 = m01 * sx; dest.m02 = m02 * sx; dest.m03 = m03 * sx; dest.m10 = m10 * sy; dest.m11 = m11 * sy; dest.m12 = m12 * sy; dest.m13 = m13 * sy; return dest; } /** * Apply a picking transformation to this matrix using the given window coordinates <tt>(x, y)</tt> as the pick center * and the given <tt>(width, height)</tt> as the size of the picking region in window coordinates. * * @param x * the x coordinate of the picking region center in window coordinates * @param y * the y coordinate of the picking region center in window coordinates * @param width * the width of the picking region in window coordinates * @param height * the height of the picking region in window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @return this */ public Matrix4f pick(float x, float y, float width, float height, int[] viewport) { return pick(x, y, width, height, viewport, this); } /** * Determine whether this matrix describes an affine transformation. This is the case iff its last row is equal to <tt>(0, 0, 0, 1)</tt>. * * @return <code>true</code> iff this matrix is affine; <code>false</code> otherwise */ public boolean isAffine() { return m03 == 0.0f && m13 == 0.0f && m23 == 0.0f && m33 == 1.0f; } /** * Exchange the values of <code>this</code> matrix with the given <code>other</code> matrix. * * @param other * the other matrix to exchange the values with * @return this */ public Matrix4f swap(Matrix4f other) { float tmp; tmp = m00; m00 = other.m00; other.m00 = tmp; tmp = m01; m01 = other.m01; other.m01 = tmp; tmp = m02; m02 = other.m02; other.m02 = tmp; tmp = m03; m03 = other.m03; other.m03 = tmp; tmp = m10; m10 = other.m10; other.m10 = tmp; tmp = m11; m11 = other.m11; other.m11 = tmp; tmp = m12; m12 = other.m12; other.m12 = tmp; tmp = m13; m13 = other.m13; other.m13 = tmp; tmp = m20; m20 = other.m20; other.m20 = tmp; tmp = m21; m21 = other.m21; other.m21 = tmp; tmp = m22; m22 = other.m22; other.m22 = tmp; tmp = m23; m23 = other.m23; other.m23 = tmp; tmp = m30; m30 = other.m30; other.m30 = tmp; tmp = m31; m31 = other.m31; other.m31 = tmp; tmp = m32; m32 = other.m32; other.m32 = tmp; tmp = m33; m33 = other.m33; other.m33 = tmp; return this; } /** * Apply an arcball view transformation to this matrix with the given <code>radius</code> and center <tt>(centerX, centerY, centerZ)</tt> * position of the arcball and the specified X and Y rotation angles, and store the result in <code>dest</code>. * <p> * This method is equivalent to calling: <tt>translate(0, 0, -radius).rotateX(angleX).rotateY(angleY).translate(-centerX, -centerY, -centerZ)</tt> * * @param radius * the arcball radius * @param centerX * the x coordinate of the center position of the arcball * @param centerY * the y coordinate of the center position of the arcball * @param centerZ * the z coordinate of the center position of the arcball * @param angleX * the rotation angle around the X axis in radians * @param angleY * the rotation angle around the Y axis in radians * @param dest * will hold the result * @return dest */ public Matrix4f arcball(float radius, float centerX, float centerY, float centerZ, float angleX, float angleY, Matrix4f dest) { float m30 = m20 * -radius + this.m30; float m31 = m21 * -radius + this.m31; float m32 = m22 * -radius + this.m32; float m33 = m23 * -radius + this.m33; float cos = (float) Math.cos(angleX); float sin = (float) Math.sin(angleX); float nm10 = m10 * cos + m20 * sin; float nm11 = m11 * cos + m21 * sin; float nm12 = m12 * cos + m22 * sin; float nm13 = m13 * cos + m23 * sin; float m20 = this.m20 * cos - m10 * sin; float m21 = this.m21 * cos - m11 * sin; float m22 = this.m22 * cos - m12 * sin; float m23 = this.m23 * cos - m13 * sin; cos = (float) Math.cos(angleY); sin = (float) Math.sin(angleY); float nm00 = m00 * cos - m20 * sin; float nm01 = m01 * cos - m21 * sin; float nm02 = m02 * cos - m22 * sin; float nm03 = m03 * cos - m23 * sin; float nm20 = m00 * sin + m20 * cos; float nm21 = m01 * sin + m21 * cos; float nm22 = m02 * sin + m22 * cos; float nm23 = m03 * sin + m23 * cos; dest.m30 = -nm00 * centerX - nm10 * centerY - nm20 * centerZ + m30; dest.m31 = -nm01 * centerX - nm11 * centerY - nm21 * centerZ + m31; dest.m32 = -nm02 * centerX - nm12 * centerY - nm22 * centerZ + m32; dest.m33 = -nm03 * centerX - nm13 * centerY - nm23 * centerZ + m33; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; return dest; } /** * Apply an arcball view transformation to this matrix with the given <code>radius</code> and <code>center</code> * position of the arcball and the specified X and Y rotation angles, and store the result in <code>dest</code>. * <p> * This method is equivalent to calling: <tt>translate(0, 0, -radius).rotateX(angleX).rotateY(angleY).translate(-center.x, -center.y, -center.z)</tt> * * @param radius * the arcball radius * @param center * the center position of the arcball * @param angleX * the rotation angle around the X axis in radians * @param angleY * the rotation angle around the Y axis in radians * @param dest * will hold the result * @return dest */ public Matrix4f arcball(float radius, Vector3f center, float angleX, float angleY, Matrix4f dest) { return arcball(radius, center.x, center.y, center.z, angleX, angleY, dest); } /** * Apply an arcball view transformation to this matrix with the given <code>radius</code> and center <tt>(centerX, centerY, centerZ)</tt> * position of the arcball and the specified X and Y rotation angles. * <p> * This method is equivalent to calling: <tt>translate(0, 0, -radius).rotateX(angleX).rotateY(angleY).translate(-centerX, -centerY, -centerZ)</tt> * * @param radius * the arcball radius * @param centerX * the x coordinate of the center position of the arcball * @param centerY * the y coordinate of the center position of the arcball * @param centerZ * the z coordinate of the center position of the arcball * @param angleX * the rotation angle around the X axis in radians * @param angleY * the rotation angle around the Y axis in radians * @return dest */ public Matrix4f arcball(float radius, float centerX, float centerY, float centerZ, float angleX, float angleY) { return arcball(radius, centerX, centerY, centerZ, angleX, angleY, this); } /** * Apply an arcball view transformation to this matrix with the given <code>radius</code> and <code>center</code> * position of the arcball and the specified X and Y rotation angles. * <p> * This method is equivalent to calling: <tt>translate(0, 0, -radius).rotateX(angleX).rotateY(angleY).translate(-center.x, -center.y, -center.z)</tt> * * @param radius * the arcball radius * @param center * the center position of the arcball * @param angleX * the rotation angle around the X axis in radians * @param angleY * the rotation angle around the Y axis in radians * @return this */ public Matrix4f arcball(float radius, Vector3f center, float angleX, float angleY) { return arcball(radius, center.x, center.y, center.z, angleX, angleY, this); } /** * Compute the axis-aligned bounding box of the frustum described by <code>this</code> matrix and store the minimum corner * coordinates in the given <code>min</code> and the maximum corner coordinates in the given <code>max</code> vector. * <p> * The matrix <code>this</code> is assumed to be the {@link #invert() inverse} of the origial view-projection matrix * for which to compute the axis-aligned bounding box in world-space. * <p> * The axis-aligned bounding box of the unit frustum is <tt>(-1, -1, -1)</tt>, <tt>(1, 1, 1)</tt>. * * @param min * will hold the minimum corner coordinates of the axis-aligned bounding box * @param max * will hold the maximum corner coordinates of the axis-aligned bounding box * @return this */ public Matrix4f frustumAabb(Vector3f min, Vector3f max) { float minX = Float.MAX_VALUE; float minY = Float.MAX_VALUE; float minZ = Float.MAX_VALUE; float maxX = -Float.MAX_VALUE; float maxY = -Float.MAX_VALUE; float maxZ = -Float.MAX_VALUE; for (int t = 0; t < 8; t++) { float x = ((t & 1) << 1) - 1.0f; float y = (((t >>> 1) & 1) << 1) - 1.0f; float z = (((t >>> 2) & 1) << 1) - 1.0f; float invW = 1.0f / (m03 * x + m13 * y + m23 * z + m33); float nx = (m00 * x + m10 * y + m20 * z + m30) * invW; float ny = (m01 * x + m11 * y + m21 * z + m31) * invW; float nz = (m02 * x + m12 * y + m22 * z + m32) * invW; minX = minX < nx ? minX : nx; minY = minY < ny ? minY : ny; minZ = minZ < nz ? minZ : nz; maxX = maxX > nx ? maxX : nx; maxY = maxY > ny ? maxY : ny; maxZ = maxZ > nz ? maxZ : nz; } min.x = minX; min.y = minY; min.z = minZ; max.x = maxX; max.y = maxY; max.z = maxZ; return this; } /** * Compute the <i>range matrix</i> for the Projected Grid transformation as described in chapter "2.4.2 Creating the range conversion matrix" * of the paper <a href="http://fileadmin.cs.lth.se/graphics/theses/projects/projgrid/projgrid-lq.pdf">Real-time water rendering - Introducing the projected grid concept</a> * based on the <i>inverse</i> of the view-projection matrix which is assumed to be <code>this</code>, and store that range matrix into <code>dest</code>. * <p> * If the projected grid will not be visible then this method returns <code>null</code>. * <p> * This method uses the <tt>y = 0</tt> plane for the projection. * * @param projector * the projector view-projection transformation * @param sLower * the lower (smallest) Y-coordinate which any transformed vertex might have while still being visible on the projected grid * @param sUpper * the upper (highest) Y-coordinate which any transformed vertex might have while still being visible on the projected grid * @param dest * will hold the resulting range matrix * @return the computed range matrix; or <code>null</code> if the projected grid will not be visible */ public Matrix4f projectedGridRange(Matrix4f projector, float sLower, float sUpper, Matrix4f dest) { // Compute intersection with frustum edges and plane float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE; float maxX = -Float.MAX_VALUE, maxY = -Float.MAX_VALUE; boolean intersection = false; for (int t = 0; t < 3 * 4; t++) { float c0X, c0Y, c0Z; float c1X, c1Y, c1Z; if (t < 4) { // all x edges c0X = -1; c1X = +1; c0Y = c1Y = ((t & 1) << 1) - 1.0f; c0Z = c1Z = (((t >>> 1) & 1) << 1) - 1.0f; } else if (t < 8) { // all y edges c0Y = -1; c1Y = +1; c0X = c1X = ((t & 1) << 1) - 1.0f; c0Z = c1Z = (((t >>> 1) & 1) << 1) - 1.0f; } else { // all z edges c0Z = -1; c1Z = +1; c0X = c1X = ((t & 1) << 1) - 1.0f; c0Y = c1Y = (((t >>> 1) & 1) << 1) - 1.0f; } // unproject corners float invW = 1.0f / (m03 * c0X + m13 * c0Y + m23 * c0Z + m33); float p0x = (m00 * c0X + m10 * c0Y + m20 * c0Z + m30) * invW; float p0y = (m01 * c0X + m11 * c0Y + m21 * c0Z + m31) * invW; float p0z = (m02 * c0X + m12 * c0Y + m22 * c0Z + m32) * invW; invW = 1.0f / (m03 * c1X + m13 * c1Y + m23 * c1Z + m33); float p1x = (m00 * c1X + m10 * c1Y + m20 * c1Z + m30) * invW; float p1y = (m01 * c1X + m11 * c1Y + m21 * c1Z + m31) * invW; float p1z = (m02 * c1X + m12 * c1Y + m22 * c1Z + m32) * invW; float dirX = p1x - p0x; float dirY = p1y - p0y; float dirZ = p1z - p0z; float invDenom = 1.0f / dirY; // test for intersection for (int s = 0; s < 2; s++) { float isectT = -(p0y + (s == 0 ? sLower : sUpper)) * invDenom; if (isectT >= 0.0f && isectT <= 1.0f) { intersection = true; // project with projector matrix float ix = p0x + isectT * dirX; float iz = p0z + isectT * dirZ; invW = 1.0f / (projector.m03 * ix + projector.m23 * iz + projector.m33); float px = (projector.m00 * ix + projector.m20 * iz + projector.m30) * invW; float py = (projector.m01 * ix + projector.m21 * iz + projector.m31) * invW; minX = minX < px ? minX : px; minY = minY < py ? minY : py; maxX = maxX > px ? maxX : px; maxY = maxY > py ? maxY : py; } } } if (!intersection) return null; // <- projected grid is not visible return dest.set(maxX - minX, 0, 0, 0, 0, maxY - minY, 0, 0, 0, 0, 1, 0, minX, minY, 0, 1); } /** * Change the near and far clip plane distances of <code>this</code> perspective frustum transformation matrix * and store the result in <code>dest</code>. * <p> * This method only works if <code>this</code> is a perspective projection frustum transformation, for example obtained * via {@link #perspective(float, float, float, float) perspective()} or {@link #frustum(float, float, float, float, float, float) frustum()}. * * @see #perspective(float, float, float, float) * @see #frustum(float, float, float, float, float, float) * * @param near * the new near clip plane distance * @param far * the new far clip plane distance * @param dest * will hold the resulting matrix * @return dest */ public Matrix4f perspectiveFrustumSlice(float near, float far, Matrix4f dest) { float invOldNear = (m23 + m22) / m32; float invNearFar = 1.0f / (near - far); dest.m00 = m00 * invOldNear * near; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m10 = m10; dest.m11 = m11 * invOldNear * near; dest.m12 = m12; dest.m13 = m13; dest.m20 = m20; dest.m21 = m21; dest.m22 = (far + near) * invNearFar; dest.m23 = m23; dest.m30 = m30; dest.m31 = m31; dest.m32 = (far + far) * near * invNearFar; dest.m33 = m33; return dest; } /** * Build an ortographic projection transformation that fits the view-projection transformation represented by <code>this</code> * into the given affine <code>view</code> transformation. * <p> * The transformation represented by <code>this</code> must be given as the {@link #invert() inverse} of a typical combined camera view-projection * transformation, whose projection can be either orthographic or perspective. * <p> * The <code>view</code> must be an {@link #isAffine() affine} transformation which in the application of Cascaded Shadow Maps is usually the light view transformation. * It be obtained via any affine transformation or for example via {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()}. * <p> * Reference: <a href="http://developer.download.nvidia.com/SDK/10.5/opengl/screenshots/samples/cascaded_shadow_maps.html">OpenGL SDK - Cascaded Shadow Maps</a> * * @param view * the view transformation to build a corresponding orthographic projection to fit the frustum of <code>this</code> * @param dest * will hold the crop projection transformation * @return dest */ public Matrix4f orthoCrop(Matrix4f view, Matrix4f dest) { // determine min/max world z and min/max orthographically view-projected x/y float minX = Float.MAX_VALUE, maxX = -Float.MAX_VALUE; float minY = Float.MAX_VALUE, maxY = -Float.MAX_VALUE; float minZ = Float.MAX_VALUE, maxZ = -Float.MAX_VALUE; for (int t = 0; t < 8; t++) { float x = ((t & 1) << 1) - 1.0f; float y = (((t >>> 1) & 1) << 1) - 1.0f; float z = (((t >>> 2) & 1) << 1) - 1.0f; float invW = 1.0f / (m03 * x + m13 * y + m23 * z + m33); float wx = (m00 * x + m10 * y + m20 * z + m30) * invW; float wy = (m01 * x + m11 * y + m21 * z + m31) * invW; float wz = (m02 * x + m12 * y + m22 * z + m32) * invW; invW = 1.0f / (view.m03 * wx + view.m13 * wy + view.m23 * wz + view.m33); float vx = view.m00 * wx + view.m10 * wy + view.m20 * wz + view.m30; float vy = view.m01 * wx + view.m11 * wy + view.m21 * wz + view.m31; float vz = (view.m02 * wx + view.m12 * wy + view.m22 * wz + view.m32) * invW; minX = minX < vx ? minX : vx; maxX = maxX > vx ? maxX : vx; minY = minY < vy ? minY : vy; maxY = maxY > vy ? maxY : vy; minZ = minZ < vz ? minZ : vz; maxZ = maxZ > vz ? maxZ : vz; } // build crop projection matrix to fit 'this' frustum into view return dest.setOrtho(minX, maxX, minY, maxY, -maxZ, -minZ); } /** * Set <code>this</code> matrix to a perspective transformation that maps the trapezoid spanned by the four corner coordinates * <code>(p0x, p0y)</code>, <code>(p1x, p1y)</code>, <code>(p2x, p2y)</code> and <code>(p3x, p3y)</code> to the unit square <tt>[(-1, -1)..(+1, +1)]</tt>. * <p> * The corner coordinates are given in counter-clockwise order starting from the <i>left</i> corner on the smaller parallel side of the trapezoid * seen when looking at the trapezoid oriented with its shorter parallel edge at the bottom and its longer parallel edge at the top. * <p> * Reference: <a href="https://kenai.com/downloads/wpbdc/Documents/tsm.pdf">Notes On Implementation Of Trapezoidal Shadow Maps</a> * * @param p0x * the x coordinate of the left corner at the shorter edge of the trapezoid * @param p0y * the y coordinate of the left corner at the shorter edge of the trapezoid * @param p1x * the x coordinate of the right corner at the shorter edge of the trapezoid * @param p1y * the y coordinate of the right corner at the shorter edge of the trapezoid * @param p2x * the x coordinate of the right corner at the longer edge of the trapezoid * @param p2y * the y coordinate of the right corner at the longer edge of the trapezoid * @param p3x * the x coordinate of the left corner at the longer edge of the trapezoid * @param p3y * the y coordinate of the left corner at the longer edge of the trapezoid * @return this */ public Matrix4f trapezoidCrop(float p0x, float p0y, float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { float aX = p1y - p0y, aY = p0x - p1x; float m00 = aY; float m10 = -aX; float m30 = aX * p0y - aY * p0x; float m01 = aX; float m11 = aY; float m31 = -(aX * p0x + aY * p0y); float c3x = m00 * p3x + m10 * p3y + m30; float c3y = m01 * p3x + m11 * p3y + m31; float s = -c3x / c3y; m00 += s * m01; m10 += s * m11; m30 += s * m31; float d1x = m00 * p1x + m10 * p1y + m30; float d2x = m00 * p2x + m10 * p2y + m30; float d = d1x * c3y / (d2x - d1x); m31 += d; float sx = 2.0f / d2x; float sy = 1.0f / (c3y + d); float u = (sy + sy) * d / (1.0f - sy * d); float m03 = m01 * sy; float m13 = m11 * sy; float m33 = m31 * sy; m01 = (u + 1.0f) * m03; m11 = (u + 1.0f) * m13; m31 = (u + 1.0f) * m33 - u; m00 = sx * m00 - m03; m10 = sx * m10 - m13; m30 = sx * m30 - m33; return set(m00, m01, 0, m03, m10, m11, 0, m13, 0, 0, 1, 0, m30, m31, 0, m33); } /** * Transform the axis-aligned box given as the minimum corner <tt>(minX, minY, minZ)</tt> and maximum corner <tt>(maxX, maxY, maxZ)</tt> * by <code>this</code> {@link #isAffine() affine} matrix and compute the axis-aligned box of the result whose minimum corner is stored in <code>outMin</code> * and maximum corner stored in <code>outMax</code>. * <p> * Reference: <a href="http://dev.theomader.com/transform-bounding-boxes/">http://dev.theomader.com</a> * * @param minX * the x coordinate of the minimum corner of the axis-aligned box * @param minY * the y coordinate of the minimum corner of the axis-aligned box * @param minZ * the z coordinate of the minimum corner of the axis-aligned box * @param maxX * the x coordinate of the maximum corner of the axis-aligned box * @param maxY * the y coordinate of the maximum corner of the axis-aligned box * @param maxZ * the y coordinate of the maximum corner of the axis-aligned box * @param outMin * will hold the minimum corner of the resulting axis-aligned box * @param outMax * will hold the maximum corner of the resulting axis-aligned box * @return this */ public Matrix4f transformAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, Vector3f outMin, Vector3f outMax) { float xax = m00 * minX, xay = m01 * minX, xaz = m02 * minX; float xbx = m00 * maxX, xby = m01 * maxX, xbz = m02 * maxX; float yax = m10 * minY, yay = m11 * minY, yaz = m12 * minY; float ybx = m10 * maxY, yby = m11 * maxY, ybz = m12 * maxY; float zax = m20 * minZ, zay = m21 * minZ, zaz = m22 * minZ; float zbx = m20 * maxZ, zby = m21 * maxZ, zbz = m22 * maxZ; float xminx, xminy, xminz, yminx, yminy, yminz, zminx, zminy, zminz; float xmaxx, xmaxy, xmaxz, ymaxx, ymaxy, ymaxz, zmaxx, zmaxy, zmaxz; if (xax < xbx) { xminx = xax; xmaxx = xbx; } else { xminx = xbx; xmaxx = xax; } if (xay < xby) { xminy = xay; xmaxy = xby; } else { xminy = xby; xmaxy = xay; } if (xaz < xbz) { xminz = xaz; xmaxz = xbz; } else { xminz = xbz; xmaxz = xaz; } if (yax < ybx) { yminx = yax; ymaxx = ybx; } else { yminx = ybx; ymaxx = yax; } if (yay < yby) { yminy = yay; ymaxy = yby; } else { yminy = yby; ymaxy = yay; } if (yaz < ybz) { yminz = yaz; ymaxz = ybz; } else { yminz = ybz; ymaxz = yaz; } if (zax < zbx) { zminx = zax; zmaxx = zbx; } else { zminx = zbx; zmaxx = zax; } if (zay < zby) { zminy = zay; zmaxy = zby; } else { zminy = zby; zmaxy = zay; } if (zaz < zbz) { zminz = zaz; zmaxz = zbz; } else { zminz = zbz; zmaxz = zaz; } outMin.x = xminx + yminx + zminx + m30; outMin.y = xminy + yminy + zminy + m31; outMin.z = xminz + yminz + zminz + m32; outMax.x = xmaxx + ymaxx + zmaxx + m30; outMax.y = xmaxy + ymaxy + zmaxy + m31; outMax.z = xmaxz + ymaxz + zmaxz + m32; return this; } /** * Transform the axis-aligned box given as the minimum corner <code>min</code> and maximum corner <code>max</code> * by <code>this</code> {@link #isAffine() affine} matrix and compute the axis-aligned box of the result whose minimum corner is stored in <code>outMin</code> * and maximum corner stored in <code>outMax</code>. * * @param min * the minimum corner of the axis-aligned box * @param max * the maximum corner of the axis-aligned box * @param outMin * will hold the minimum corner of the resulting axis-aligned box * @param outMax * will hold the maximum corner of the resulting axis-aligned box * @return this */ public Matrix4f transformAab(Vector3f min, Vector3f max, Vector3f outMin, Vector3f outMax) { return transformAab(min.x, min.y, min.z, max.x, max.y, max.z, outMin, outMax); } }
Add Matrix4f.scaleLocal()
src/org/joml/Matrix4f.java
Add Matrix4f.scaleLocal()
Java
mit
397c5257c54e4eeedb5b5bbd4a51c1d7e83d96b2
0
smblott-github/intent_radio,smblott-github/intent_radio,smblott-github/intent_radio
package org.smblott.intentradio; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import android.content.Context; import android.widget.Toast; import android.util.Log; public class Logger { private static Context context = null; private static boolean debugging = false; private static String name = null; private static FileOutputStream file = null; private static DateFormat format = null; /* ******************************************************************** * Initialisation... */ public static void init(Context acontext) { context = acontext; name = context.getString(R.string.app_name); } /* ******************************************************************** * Enable/disable... */ public static void state(String how) { if ( how.equals("debug") || how.equals("yes") || how.equals("on") || how.equals("start") ) { start(); return; } if ( how.equals("nodebug") || how.equals("no") || how.equals("off") || how.equals("stop") ) { stop(); return; } Log.d(name, "Logger: invalid state: " + how); } /* ******************************************************************** * State changes... */ private static void start() { if ( debugging ) return; if ( format == null ) format = new SimpleDateFormat("HH:mm:ss "); debugging = true; try { File log_file = new File(context.getExternalFilesDir(null), context.getString(R.string.intent_log_file)); file = new FileOutputStream(log_file); } catch (Exception e) { file = null; } log("Logger: -> on"); } private static void stop() { log("Logger: -> off"); if ( file != null ) { try { file.close(); } catch (Exception e) { } file = null; } debugging = false; } /* ******************************************************************** * Logging methods... */ public static void log(String msg) { if ( ! debugging || msg == null ) return; msg = format.format(new Date()) + msg; Log.d(name, msg); log_file(msg); } public static void toast(String msg) { if ( msg == null ) return; Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); log(msg); } private static void log_file(String msg) { if ( file != null ) try { file.write((msg+"\n").getBytes()); file.flush(); } catch (Exception e) {} } }
src/org/smblott/intentradio/Logger.java
package org.smblott.intentradio; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import android.content.Context; import android.widget.Toast; import android.util.Log; public class Logger { private static Context context = null; private static boolean debugging = false; private static String name = null; private static FileOutputStream file = null; private static DateFormat format = null; /* ******************************************************************** * Initialisation... */ public static void init(Context acontext) { context = acontext; name = context.getString(R.string.app_name); } /* ******************************************************************** * Enable/disable... */ public static void state(String how) { if ( how.equals("debug") || how.equals("yes") || how.equals("on") || how.equals("start") ) { start(); return; } if ( how.equals("nodebug") || how.equals("no") || how.equals("off") || how.equals("stop") ) { stop(); return; } Log.d(name, "Logger: invalid state: " + how); } /* ******************************************************************** * State changes... */ private static void start() { if ( debugging ) return; debugging = true; format = new SimpleDateFormat("HH:mm:ss "); try { File log_file = new File(context.getExternalFilesDir(null), context.getString(R.string.intent_log_file)); file = new FileOutputStream(log_file); } catch (Exception e) { file = null; } log("Logger: -> on"); } private static void stop() { log("Logger: -> off"); if ( file != null ) { try { file.close(); } catch (Exception e) { } file = null; } debugging = false; } /* ******************************************************************** * Logging methods... */ public static void log(String msg) { if ( ! debugging || msg == null ) return; Log.d(name, msg); log_file(msg); } public static void toast(String msg) { if ( msg == null ) return; Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); log(msg); } private static void log_file(String msg) { if ( file == null ) return; String stamp = format.format(new Date()); try { file.write((stamp+msg+"\n").getBytes()); file.flush(); } catch (Exception e) {} } }
Logger timestamps.
src/org/smblott/intentradio/Logger.java
Logger timestamps.
Java
mit
6698a79f23b55598cfeabbd1cfa8c5cb254273c0
0
Bouowmx/APCS
import static java.lang.System.out; import java.util.ArrayDeque; import java.util.Scanner; public class RPNCalculator { private static ArrayDeque<Long> stack = new ArrayDeque<Long>(); private RPNCalculator() {} public static Long evaluate(String expression) { if (!(expression.matches("[ 0-9+\\-\\*/%]*")) || (expression.contains("."))) { out.println("Invalid expression: only digits 0-9 and operators +, -, *, /, % allowed."); return null; } Scanner parser = new Scanner(expression).useDelimiter(" "); while (parser.hasNext()) { String next = parser.next(); if ((next.length() == 1) && (next.matches("[+\\-\\*/%]"))) { if (stack.size() < 2) { out.println("Invalid expression: too many operators."); stack.clear(); return null; } long second = stack.pop().longValue(); long first = stack.pop().longValue(); if (next.equals("+")) {stack.push(first + second);} if (next.equals("-")) {stack.push(first - second);} if (next.equals("*")) {stack.push(first * second);} if (next.equals("/")) {stack.push(first / second);} if (next.equals("%")) {stack.push(first % second);} } else { <<<<<<< HEAD if (next.matches("[+\\-\\*/%]+")) { out.println("Invalid expression: separate values and operators with spaces."); return null; } ======= if ((next.contains("+")) || (next.contains("-")) || (next.contains("*")) || (next.contains("/")) || (next.contains("%"))) { //I couldn't get a regular expression to work. out.println("Invalid expression: separate values and operators with spaces."); stack.clear(); return null; } >>>>>>> 23f55099f5810898e0b5ac2cf58196cab733c79b stack.push(new Long(next)); } } if (stack.size() > 1) { out.println("Invalid expression: too many values."); stack.clear(); return null; } return stack.pop(); } public static void main(String[] args) { out.println("RPN Calculator. Type in an expression, with values and operators separated by spaces, in reverse Polish or postfix notation and press Enter to print the result. Integers (between -2^63 and 2^63 - 1) only because Java is finicky with types. Press q or Ctrl + C to quit."); out.print(">> "); Scanner scanner = new Scanner(System.in); for (;;) { String next = ""; for (;;) { next = scanner.nextLine().trim(); if (next.equals("")) {out.print(">> ");} else {break;} } if (next.equals("q")) {return;} Long nextEvaluate = evaluate(next); if (nextEvaluate != null) {out.println(nextEvaluate);} out.print(">> "); } } } <<<<<<< HEAD ======= >>>>>>> 23f55099f5810898e0b5ac2cf58196cab733c79b
13-RPNCalculator/RPNCalculator.java
import static java.lang.System.out; import java.util.ArrayDeque; import java.util.Scanner; public class RPNCalculator { private static ArrayDeque<Long> stack = new ArrayDeque<Long>(); private RPNCalculator() {} public static Long evaluate(String expression) { if (!(expression.matches("[ 0-9+\\-\\*/%]*")) || (expression.contains("."))) { out.println("Invalid expression: only digits 0-9 and operators +, -, *, /, % allowed."); return null; } Scanner parser = new Scanner(expression).useDelimiter(" "); while (parser.hasNext()) { String next = parser.next(); if ((next.length() == 1) && (next.matches("[+\\-\\*/%]"))) { if (stack.size() < 2) { out.println("Invalid expression: too many operators."); stack.clear(); return null; } long second = stack.pop().longValue(); long first = stack.pop().longValue(); if (next.equals("+")) {stack.push(first + second);} if (next.equals("-")) {stack.push(first - second);} if (next.equals("*")) {stack.push(first * second);} if (next.equals("/")) {stack.push(first / second);} if (next.equals("%")) {stack.push(first % second);} } else { if ((next.contains("+")) || (next.contains("-")) || (next.contains("*")) || (next.contains("/")) || (next.contains("%"))) { //I couldn't get a regular expression to work. out.println("Invalid expression: separate values and operators with spaces."); stack.clear(); return null; } stack.push(new Long(next)); } } if (stack.size() > 1) { out.println("Invalid expression: too many values."); stack.clear(); return null; } return stack.pop(); } public static void main(String[] args) { out.println("RPN Calculator. Type in an expression in reverse Polish or postfix notation and press Enter to print the result. Integers only because Java is finicky with types. Press q or Ctrl + C to quit."); out.print(">> "); Scanner scanner = new Scanner(System.in); for (;;) { String next = ""; for (;;) { next = scanner.nextLine().trim(); if (!(next.equals(""))) {break;} } if (next.equals("q")) {return;} Long nextEvaluate = evaluate(next); if (nextEvaluate != null) {out.println(nextEvaluate);} out.print(">> "); } } }
RPNCalculator: Git misbehaves
13-RPNCalculator/RPNCalculator.java
RPNCalculator: Git misbehaves
Java
mit
1c79cbee45573ca958d7149bc7e1a0d34c3936d2
0
tripu/validator,sammuelyee/validator,YOTOV-LIMITED/validator,tripu/validator,validator/validator,tripu/validator,sammuelyee/validator,sammuelyee/validator,YOTOV-LIMITED/validator,validator/validator,sammuelyee/validator,YOTOV-LIMITED/validator,YOTOV-LIMITED/validator,validator/validator,validator/validator,sammuelyee/validator,takenspc/validator,takenspc/validator,takenspc/validator,tripu/validator,validator/validator,takenspc/validator,takenspc/validator,YOTOV-LIMITED/validator,tripu/validator
/* * This file is part of the RELAX NG schemas far (X)HTML5. * Please see the file named LICENSE in the relaxng directory for * license details. */ package org.whattf.syntax; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import nu.validator.validation.SimpleDocumentValidator; import nu.validator.xml.SystemErrErrorHandler; import org.xml.sax.SAXException; import com.thaiopensource.xml.sax.CountingErrorHandler; /** * * @version $Id$ * @author hsivonen */ public class Driver { private SimpleDocumentValidator validator; private static final String PATH = "syntax/relaxng/tests/"; private PrintWriter err; private PrintWriter out; private SystemErrErrorHandler errorHandler; private CountingErrorHandler countingErrorHandler; private boolean failed = false; private boolean verbose; /** * @param basePath */ public Driver(boolean verbose) throws IOException { this.errorHandler = new SystemErrErrorHandler(); this.countingErrorHandler = new CountingErrorHandler(); this.verbose = verbose; validator = new SimpleDocumentValidator(); try { this.err = new PrintWriter(new OutputStreamWriter(System.err, "UTF-8")); this.out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); } catch (Exception e) { // If this happens, the JDK is too broken anyway throw new RuntimeException(e); } } private void checkHtmlFile(File file) throws IOException, SAXException { if (!file.exists()) { if (verbose) { out.println(String.format("\"%s\": warning: File not found.", file.toURI().toURL().toString())); out.flush(); } return; } if (verbose) { out.println(file); out.flush(); } if (isHtml(file)) { validator.checkHtmlFile(file, true); } else if (isXhtml(file)) { validator.checkXmlFile(file); } else { if (verbose) { out.println(String.format( "\"%s\": warning: File was not checked." + " Files must have a .html, .xhtml, .htm," + " or .xht extension.", file.toURI().toURL().toString())); out.flush(); } } } private boolean isXhtml(File file) { String name = file.getName(); return name.endsWith(".xhtml") || name.endsWith(".xht"); } private boolean isHtml(File file) { String name = file.getName(); return name.endsWith(".html") || name.endsWith(".htm"); } private boolean isCheckableFile(File file) { return file.isFile() && (isHtml(file) || isXhtml(file)); } private void recurseDirectory(File directory) throws SAXException, IOException { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { recurseDirectory(file); } else { checkHtmlFile(file); } } } private void checkFiles(List<File> files) { for (File file : files) { errorHandler.reset(); try { if (file.isDirectory()) { recurseDirectory(file); } else { checkHtmlFile(file); } } catch (IOException e) { } catch (SAXException e) { } if (errorHandler.isInError()) { failed = true; } } } private void checkInvalidFiles(List<File> files) { for (File file : files) { countingErrorHandler.reset(); try { if (file.isDirectory()) { recurseDirectory(file); } else { checkHtmlFile(file); } } catch (IOException e) { } catch (SAXException e) { } if (!countingErrorHandler.getHadErrorOrFatalError()) { failed = true; try { err.println(String.format( "\"%s\": error: Document was supposed to be" + " invalid but was not.", file.toURI().toURL().toString())); err.flush(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } } private enum State { EXPECTING_INVALID_FILES, EXPECTING_VALID_FILES, EXPECTING_ANYTHING } private void checkTestDirectoryAgainstSchema(File directory, String schemaUrl) throws SAXException, Exception { validator.setUpMainSchema(schemaUrl, errorHandler); checkTestFiles(directory, State.EXPECTING_ANYTHING); } private void checkTestFiles(File directory, State state) throws SAXException { File[] files = directory.listFiles(); List<File> validFiles = new ArrayList<File>(); List<File> invalidFiles = new ArrayList<File>(); if (files == null) { if (verbose) { try { out.println(String.format( "\"%s\": warning: No files found in directory.", directory.toURI().toURL().toString())); out.flush(); } catch (MalformedURLException mue) { throw new RuntimeException(mue); } } return; } for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { if (state != State.EXPECTING_ANYTHING) { checkTestFiles(file, state); } else if ("invalid".equals(file.getName())) { checkTestFiles(file, State.EXPECTING_INVALID_FILES); } else if ("valid".equals(file.getName())) { checkTestFiles(file, State.EXPECTING_VALID_FILES); } else { checkTestFiles(file, State.EXPECTING_ANYTHING); } } else if (isCheckableFile(file)) { if (state == State.EXPECTING_INVALID_FILES) { invalidFiles.add(file); } else if (state == State.EXPECTING_VALID_FILES) { validFiles.add(file); } else if (file.getPath().indexOf("notvalid") > 0) { invalidFiles.add(file); } else { validFiles.add(file); } } } if (validFiles.size() > 0) { validator.setUpValidatorAndParsers(errorHandler, false); checkFiles(validFiles); } if (invalidFiles.size() > 0) { validator.setUpValidatorAndParsers(countingErrorHandler, false); checkInvalidFiles(invalidFiles); } } public boolean runTestSuite() throws SAXException, Exception { checkTestDirectoryAgainstSchema(new File(PATH + "html5core-plus-web-forms2/"), "http://s.validator.nu/html5/xhtml5core-plus-web-forms2.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "html/"), "http://s.validator.nu/html5-all.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "xhtml/"), "http://s.validator.nu/xhtml5-all.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "html-its/"), "http://s.validator.nu/html5-all.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "html-rdfa/"), "http://s.validator.nu/html5-all.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "html-rdfalite/"), "http://s.validator.nu/html5-rdfalite.rnc"); if (verbose) { if (failed) { out.println("Failure!"); out.flush(); } else { out.println("Success!"); out.flush(); } } return !failed; } /** * @param args * @throws SAXException */ public static void main(String[] args) throws SAXException, Exception { boolean verbose = ((args.length == 1) && "-v".equals(args[0])); Driver d = new Driver(verbose); if (d.runTestSuite()) { System.exit(0); } else { System.exit(-1); } } }
src/nu/validator/client/Driver.java
/* * This file is part of the RELAX NG schemas far (X)HTML5. * Please see the file named LICENSE in the relaxng directory for * license details. */ package org.whattf.syntax; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import nu.validator.validation.SimpleValidator; import nu.validator.xml.SystemErrErrorHandler; import org.xml.sax.SAXException; import com.thaiopensource.xml.sax.CountingErrorHandler; /** * * @version $Id$ * @author hsivonen */ public class Driver { private SimpleValidator validator; private static final String PATH = "syntax/relaxng/tests/"; private PrintWriter err; private PrintWriter out; private SystemErrErrorHandler errorHandler; private CountingErrorHandler countingErrorHandler; private boolean failed = false; private boolean verbose; /** * @param basePath */ public Driver(boolean verbose) throws IOException { this.errorHandler = new SystemErrErrorHandler(); this.countingErrorHandler = new CountingErrorHandler(); this.verbose = verbose; validator = new SimpleValidator(); try { this.err = new PrintWriter(new OutputStreamWriter(System.err, "UTF-8")); this.out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); } catch (Exception e) { // If this happens, the JDK is too broken anyway throw new RuntimeException(e); } } private void checkHtmlFile(File file) throws IOException, SAXException { if (!file.exists()) { if (verbose) { out.println(String.format("\"%s\": warning: File not found.", file.toURI().toURL().toString())); out.flush(); } return; } if (verbose) { out.println(file); out.flush(); } if (isHtml(file)) { validator.checkHtmlFile(file, true); } else if (isXhtml(file)) { validator.checkXmlFile(file); } else { if (verbose) { out.println(String.format( "\"%s\": warning: File was not checked." + " Files must have a .html, .xhtml, .htm," + " or .xht extension.", file.toURI().toURL().toString())); out.flush(); } } } private boolean isXhtml(File file) { String name = file.getName(); return name.endsWith(".xhtml") || name.endsWith(".xht"); } private boolean isHtml(File file) { String name = file.getName(); return name.endsWith(".html") || name.endsWith(".htm"); } private boolean isCheckableFile(File file) { return file.isFile() && (isHtml(file) || isXhtml(file)); } private void recurseDirectory(File directory) throws SAXException, IOException { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { recurseDirectory(file); } else { checkHtmlFile(file); } } } private void checkFiles(List<File> files) { for (File file : files) { errorHandler.reset(); try { if (file.isDirectory()) { recurseDirectory(file); } else { checkHtmlFile(file); } } catch (IOException e) { } catch (SAXException e) { } if (errorHandler.isInError()) { failed = true; } } } private void checkInvalidFiles(List<File> files) { for (File file : files) { countingErrorHandler.reset(); try { if (file.isDirectory()) { recurseDirectory(file); } else { checkHtmlFile(file); } } catch (IOException e) { } catch (SAXException e) { } if (!countingErrorHandler.getHadErrorOrFatalError()) { failed = true; try { err.println(String.format( "\"%s\": error: Document was supposed to be" + " invalid but was not.", file.toURI().toURL().toString())); err.flush(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } } private enum State { EXPECTING_INVALID_FILES, EXPECTING_VALID_FILES, EXPECTING_ANYTHING } private void checkTestDirectoryAgainstSchema(File directory, String schemaUrl) throws SAXException, Exception { validator.setUpMainSchema(schemaUrl, errorHandler); checkTestFiles(directory, State.EXPECTING_ANYTHING); } private void checkTestFiles(File directory, State state) throws SAXException { File[] files = directory.listFiles(); List<File> validFiles = new ArrayList<File>(); List<File> invalidFiles = new ArrayList<File>(); if (files == null) { if (verbose) { try { out.println(String.format( "\"%s\": warning: No files found in directory.", directory.toURI().toURL().toString())); out.flush(); } catch (MalformedURLException mue) { throw new RuntimeException(mue); } } return; } for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { if (state != State.EXPECTING_ANYTHING) { checkTestFiles(file, state); } else if ("invalid".equals(file.getName())) { checkTestFiles(file, State.EXPECTING_INVALID_FILES); } else if ("valid".equals(file.getName())) { checkTestFiles(file, State.EXPECTING_VALID_FILES); } else { checkTestFiles(file, State.EXPECTING_ANYTHING); } } else if (isCheckableFile(file)) { if (state == State.EXPECTING_INVALID_FILES) { invalidFiles.add(file); } else if (state == State.EXPECTING_VALID_FILES) { validFiles.add(file); } else if (file.getPath().indexOf("notvalid") > 0) { invalidFiles.add(file); } else { validFiles.add(file); } } } if (validFiles.size() > 0) { validator.setUpValidatorAndParsers(errorHandler, false); checkFiles(validFiles); } if (invalidFiles.size() > 0) { validator.setUpValidatorAndParsers(countingErrorHandler, false); checkInvalidFiles(invalidFiles); } } public boolean runTestSuite() throws SAXException, Exception { checkTestDirectoryAgainstSchema(new File(PATH + "html5core-plus-web-forms2/"), "http://s.validator.nu/html5/xhtml5core-plus-web-forms2.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "html/"), "http://s.validator.nu/html5-all.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "xhtml/"), "http://s.validator.nu/xhtml5-all.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "html-its/"), "http://s.validator.nu/html5-all.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "html-rdfa/"), "http://s.validator.nu/html5-all.rnc"); checkTestDirectoryAgainstSchema(new File(PATH + "html-rdfalite/"), "http://s.validator.nu/html5-rdfalite.rnc"); if (verbose) { if (failed) { out.println("Failure!"); out.flush(); } else { out.println("Success!"); out.flush(); } } return !failed; } /** * @param args * @throws SAXException */ public static void main(String[] args) throws SAXException, Exception { boolean verbose = ((args.length == 1) && "-v".equals(args[0])); Driver d = new Driver(verbose); if (d.runTestSuite()) { System.exit(0); } else { System.exit(-1); } } }
SimpleValidator is now SimpleDocumentValidator. --HG-- extra : transplant_source : N%B5%D8%82%E5f%E1%23%94%23%FD%D5cV%E7%85%F3o%0E%81
src/nu/validator/client/Driver.java
SimpleValidator is now SimpleDocumentValidator.
Java
mit
9757c42d6fd43246a5f8d3902e6716b6d9c4c397
0
kapadiamush/Eve-s-Adventure
package controllers; import java.util.ArrayList; import java.util.Random; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; import models.Coordinate; import models.campaign.KarelCode; import models.campaign.World; import models.gridobjects.creatures.Creature; import models.gridobjects.items.Bamboo; import models.gridobjects.items.Item; import models.gridobjects.items.Shrub; import models.gridobjects.items.Tree; import views.MainApp; import views.grid.GridWorld; import views.karel.KarelTable; import views.scenes.LoadMenuScene; import views.scenes.LoadSessionScene; import views.scenes.MainMenuScene; import views.scenes.SandboxScene; import views.tabs.GameTabs; /** * * @author Anthony Wong * @author Megan Murray * */ public final class ButtonHandlers { public static final void SANDBOX_MODE_BUTTON_HANDLER(ActionEvent e) { System.out.println("SANDBOX_MODE_BUTTON_HANDLER CALLED"); MainApp.changeScenes(LoadMenuScene.getInstance()); } public static final void ADVENTURE_MODE_BUTTON_HANDLER(ActionEvent e) { System.out.println("ADVENTURE_MODE_BUTTON_HANDLER CALLED"); MainApp.changeScenes(LoadMenuScene.getInstance()); } public static final void LOAD_SESSION_BUTTON_HANDLER(ActionEvent e) { System.out.println("LOAD_SESSION_BUTTON_HANDLER CALLED"); MainApp.changeScenes(LoadSessionScene.getInstance()); } public static final void NEW_SESSION_BUTTON_HANDLER(ActionEvent e) { System.out.println("NEW_SESSION_BUTTON_HANDLER CALLED"); MainApp.changeScenes(SandboxScene.getInstance()); } public static final void CANCEL_BUTTON_HANDLER(ActionEvent e) { System.out.println("CANCEL_BUTTON_HANDLER CALLED"); MainApp.changeScenes(LoadMenuScene.getInstance()); } public static final void BACK_HOMESCREEN_BUTTON_HANDLER(ActionEvent e) { System.out.println("BACK_HOMESCREEN_BUTTON_HANDLER CALLED"); MainApp.changeScenes(MainMenuScene.getInstance()); } /** * InstuctionsTab.java */ public static final void IF_BUTTON_HANDLER(ActionEvent e) { KarelTable.getInstance().addInstructionsCode(KarelCode.IFSTATEMENT); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.IFSTATEMENT); return; } GameTabs.getInstance().disableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().disableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.CONDITIONS_TAB_VALUE); } public static final void END_IF_BUTTON_HANDLER(ActionEvent e) { } public static final void ELSE_BUTTON_HANDLER(ActionEvent e) { KarelTable.getInstance().addInstructionsCode(KarelCode.ELSESTATEMENT); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { // TODO KarelTable.getInstance().replaceCode(KarelCode.ELSESTATEMENT); return; } GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void END_ELSE_BUTTON_HANDLER(ActionEvent e) { } public static final void WHILE_BUTTON_HANDLER(ActionEvent e) { KarelTable.getInstance().addInstructionsCode(KarelCode.WHILESTATEMENT); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.WHILESTATEMENT); return; } GameTabs.getInstance().disableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().disableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.CONDITIONS_TAB_VALUE); } public static final void END_WHILE_BUTTON_HANDLER(ActionEvent e) { } public static final void TASK_BUTTON_HANDLER(ActionEvent e) { } public static final void LOOP_BUTTON_HANDLER(ActionEvent e) { KarelTable.getInstance().addInstructionsCode(KarelCode.LOOPSTATEMENT); GameTabs.getInstance().disableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().disableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.NUMBERS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.NUMBERS_TAB_VALUE); } public static final void END_LOOP_BUTTON_HANDLER(ActionEvent e) { } /** * ConditionalsTab.java */ public static final void FRONT_IS_CLEAR_BUTTON_HANDLER(ActionEvent e) { System.out.println("FRONT_IS_CLEAR_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FRONTISCLEAR); return; } KarelTable.getInstance().addCode(KarelCode.FRONTISCLEAR); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void NEXT_TO_A_FRIEND_BUTTON_HANDLER(ActionEvent e) { System.out.println("NEXT_TO_A_FRIEND_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.NEXTTOAFRIEND); return; } KarelTable.getInstance().addCode(KarelCode.NEXTTOAFRIEND); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void FACING_NORTH_BUTTON_HANDLER(ActionEvent e) { System.out.println("FACING_NORTH_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FACINGNORTH); return; } KarelTable.getInstance().addCode(KarelCode.FACINGNORTH); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void FACING_SOUTH_BUTTON_HANDLER(ActionEvent e) { System.out.println("FACING_SOUTH_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FACINGSOUTH); return; } KarelTable.getInstance().addCode(KarelCode.FACINGSOUTH); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void FACING_EAST_BUTTON_HANDLER(ActionEvent e) { System.out.println("FACING_EAST_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FACINGEAST); return; } KarelTable.getInstance().addCode(KarelCode.FACINGEAST); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void FACING_WEST_BUTTON_HANDLER(ActionEvent e) { System.out.println("FACING_WEST_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FACINGWEST); return; } KarelTable.getInstance().addCode(KarelCode.FACINGWEST); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void BAG_IS_EMPTY_BUTTON_HANDLER(ActionEvent e) { System.out.println("BAG_IS_EMPTY_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.BAGISEMPTY); return; } KarelTable.getInstance().addCode(KarelCode.BAGISEMPTY); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } /** * OperationsTab.java */ public static final void MOVE_BUTTON_HANDLER(ActionEvent e) { System.out.println("MOVE_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.MOVE); return; } KarelTable.getInstance().addCode(KarelCode.MOVE); } public static final void SLEEP_BUTTON_HANDLER(ActionEvent e) { System.out.println("SLEEP_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.SLEEP); return; } KarelTable.getInstance().addCode(KarelCode.SLEEP); } public static final void WAKE_UP_BUTTON_HANDLER(ActionEvent e) { System.out.println("WAKE_UP_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.WAKEUP); return; } KarelTable.getInstance().addCode(KarelCode.WAKEUP); } public static final void TURN_RIGHT_BUTTON_HANDLER(ActionEvent e) { System.out.println("TURN_RIGHT_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.TURNRIGHT); return; } KarelTable.getInstance().addCode(KarelCode.TURNRIGHT); } public static final void PICK_UP_BAMBOO_BUTTON_HANDLER(ActionEvent e) { System.out.println("PICK_UP_BAMBOO_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.PICKBAMBOO); return; } KarelTable.getInstance().addCode(KarelCode.PICKBAMBOO); } public static final void PUT_BAMBOO_BUTTON_HANDLER(ActionEvent e) { System.out.println("PUT_BAMBOO_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.PUTBAMBOO); return; } KarelTable.getInstance().addCode(KarelCode.PUTBAMBOO); } public static final void NUMBERS_BUTTON_HANDLER(ActionEvent e) { System.out.println("NUMBERS_BUTTON_HANDLER"); String value = ((Button) e.getSource()).getText(); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(value); return; } KarelTable.getInstance().addCode(value); GameTabs.getInstance().disableTab(GameTabs.NUMBERS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } /** * Popup for if a grid space is not empty * Asks to replace object or just cancel * * @newObject the object the user is trying to put into the square */ public static void popup(String newObject){ String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("There is already an object in this space. \nReplace " + oldObject + " with " + newObject + "?")); Scene dialogScene = new Scene(dialogVbox, 300, 200); final Button REPLACE = new Button("Replace"); REPLACE.setMaxWidth(100); final Button CANCEL = new Button("Cancel"); REPLACE.setMaxWidth(100); dialogVbox.getChildren().addAll(REPLACE, CANCEL); dialog.setScene(dialogScene); dialog.show(); CANCEL.setOnAction( new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ dialog.close(); } } ); REPLACE.setOnAction( new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ dialog.close(); if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo")) RMITEM_BUTTON_HANDLER(null); if (oldObject.equals("Friend")) RMCREATURE_BUTTON_HANDLER(null); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(newObject); switch(newObject){ case "Tree": Tree tree = new Tree(4); tree.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(tree); GridWorld.getInstance().getWorld().printWorld(); break; case "Shrub": Shrub shrub = new Shrub(4, false); shrub.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(shrub); GridWorld.getInstance().getWorld().printWorld(); break; case "Bamboo": Bamboo bamboo = new Bamboo(4); bamboo.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(bamboo); GridWorld.getInstance().getWorld().printWorld(); case "Friend": Coordinate cords = new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate()); Creature Friend = new Creature("Friend", cords); Friend.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addCreature(Friend); GridWorld.getInstance().getWorld().printWorld(); default: break; } } } ); } /** * Popup if they try to put something where Eve is * @newObject the object the user is trying to put into the square */ public static void EvePop(){ final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("This space is already full. \nYou can't put an Object here.")); Scene dialogScene = new Scene(dialogVbox, 300, 200); final Button OKAY = new Button("Okay"); dialogVbox.getChildren().add(OKAY); dialog.setScene(dialogScene); dialog.show(); OKAY.setOnAction( new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ dialog.close(); } } ); } /** * Popup if they try delete the wrong thing * @newObject the object the user is trying to put into the square */ public static void DeletePop(){ String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("This space is a(n) "+ oldObject +". \nUse the Remove"+oldObject+" button.")); Scene dialogScene = new Scene(dialogVbox, 300, 200); final Button OKAY = new Button("Okay"); dialogVbox.getChildren().add(OKAY); dialog.setScene(dialogScene); dialog.show(); OKAY.setOnAction( new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ dialog.close(); } } ); } /** * ItemsTab.java */ public static final void RMITEM_BUTTON_HANDLER(ActionEvent e){ System.out.println("RMITEM_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); switch(oldObject){ case "Tree": GridWorld.getInstance().getWorld().removeItem(new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate())); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(""); break; case "Shrub": GridWorld.getInstance().getWorld().removeItem(new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate())); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(""); break; case "Bamboo": GridWorld.getInstance().getWorld().removeItem(new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate())); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(""); default: break; } } public static final void SHRUB_BUTTON_HANDLER(ActionEvent e){ System.out.println("SHRUB_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Eve!")) EvePop(); else if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ popup("Shrub"); } else GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Shrub"); Shrub shrub = new Shrub(4, false); shrub.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(shrub); GridWorld.getInstance().getWorld().printWorld(); } public static final void TREE_BUTTON_HANDLER(ActionEvent e){ String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Eve!")) EvePop(); else if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ popup("Tree"); } else{ GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Tree"); Tree tree = new Tree(4); tree.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(tree); GridWorld.getInstance().getWorld().printWorld(); } } public static final void BAMBOO_BUTTON_HANDLER(ActionEvent e){ System.out.println("BAMBOO_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Eve!")) EvePop(); else if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ popup("Bamboo"); } else{ GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Bamboo"); Bamboo bamboo = new Bamboo(4); bamboo.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(bamboo); GridWorld.getInstance().getWorld().printWorld(); } } /** * CreaturesTab.java */ public static final void RMCREATURE_BUTTON_HANDLER(ActionEvent e){ String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ } System.out.println("RMCREATURE_BUTTON_HANDLER"); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(""); GridWorld.getInstance().getWorld().removeCreature(new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate())); } public static final void EVE_BUTTON_HANDLER(ActionEvent e){ System.out.println("EVE_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); for(int y=0; y < GridWorld.gridButtons.length; y++){ for(int x=0; x < GridWorld.gridButtons[y].length; x++){ if (GridWorld.gridButtons[y][x].getText().equals("Eve!")){ //frontend move GridWorld.gridButtons[y][x].setText(" "); //backend move System.out.println("X: " + x + "Y: " + y); Creature eve = GridWorld.getInstance().getWorld().removeCreature(new Coordinate(y,x)); eve.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); eve.setDirection(Coordinate.DOWN); GridWorld.getInstance().getWorld().addCreature(eve); } } } if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ EvePop(); } else{ GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Eve!"); Coordinate cords = new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate()); Creature Eve = new Creature("Eve!", cords); Eve.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addCreature(Eve); GridWorld.getInstance().getWorld().printWorld(); } } public static final void FRIENDS_BUTTON_HANDLER(ActionEvent e){ System.out.println("FRIENDS_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Eve!")){ popup("Friend"); } else GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Friend"); Coordinate cords = new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate()); Creature Friend = new Creature("Friend", cords); Friend.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addCreature(Friend); GridWorld.getInstance().getWorld().printWorld(); } public static final void GridWorld_BUTTON_HANDLER(ActionEvent e){ } public static final void BACK_BUTTON_HANDLER(ActionEvent e){ System.out.println("BACK_BUTTON_HANDLER CALLED"); } public static final void FORWARD_BUTTON_HANDLER(ActionEvent e){ System.out.println("FORWARD_BUTTON_HANDLER CALLED"); } public static final void PLAY_BUTTON_HANDLER(ActionEvent e){ System.out.println("PLAY_BUTTON_HANDLER CALLED"); ArrayList<String> karelCode = KarelTable.getInstance().getKarelCode(); if(karelCode.isEmpty()){ System.out.println("karelCode is empty!"); return; } World world = SandboxScene.getWorld(); System.out.println(KarelTable.getInstance().getKarelCode()); Interpreter interpreter = new Interpreter(karelCode, world); world.printWorld(); interpreter.start(); //starts the code world.printWorld(); } public static final void RESET_BUTTON_HANDLER(ActionEvent e) { System.out.println("RESET_BUTTON_HANDLER CALLED"); } public static final void REPLACE_BUTTON_HANDLER(ActionEvent e) { System.out.println("REPLACE_BUTTON_HANDLER CALLED"); } public static final void QUIT_MENU_HANDLER(ActionEvent e) { System.out.println("Quit sandbox mode. Returned to home screen."); MainApp.changeScenes(MainMenuScene.getInstance()); } public static final void SAVE_MENU_HANDLER(ActionEvent e) { System.out.println("Saved!"); } }
src/controllers/ButtonHandlers.java
package controllers; import java.util.ArrayList; import java.util.Random; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; import models.Coordinate; import models.campaign.KarelCode; import models.campaign.World; import models.gridobjects.creatures.Creature; import models.gridobjects.items.Bamboo; import models.gridobjects.items.Item; import models.gridobjects.items.Shrub; import models.gridobjects.items.Tree; import views.MainApp; import views.grid.GridWorld; import views.karel.KarelTable; import views.scenes.LoadMenuScene; import views.scenes.LoadSessionScene; import views.scenes.MainMenuScene; import views.scenes.SandboxScene; import views.tabs.GameTabs; /** * * @author Anthony Wong * @author Megan Murray * */ public final class ButtonHandlers { public static final void SANDBOX_MODE_BUTTON_HANDLER(ActionEvent e) { System.out.println("SANDBOX_MODE_BUTTON_HANDLER CALLED"); MainApp.changeScenes(LoadMenuScene.getInstance()); } public static final void ADVENTURE_MODE_BUTTON_HANDLER(ActionEvent e) { System.out.println("ADVENTURE_MODE_BUTTON_HANDLER CALLED"); MainApp.changeScenes(LoadMenuScene.getInstance()); } public static final void LOAD_SESSION_BUTTON_HANDLER(ActionEvent e) { System.out.println("LOAD_SESSION_BUTTON_HANDLER CALLED"); MainApp.changeScenes(LoadSessionScene.getInstance()); } public static final void NEW_SESSION_BUTTON_HANDLER(ActionEvent e) { System.out.println("NEW_SESSION_BUTTON_HANDLER CALLED"); MainApp.changeScenes(SandboxScene.getInstance()); } public static final void CANCEL_BUTTON_HANDLER(ActionEvent e) { System.out.println("CANCEL_BUTTON_HANDLER CALLED"); MainApp.changeScenes(LoadMenuScene.getInstance()); } public static final void BACK_HOMESCREEN_BUTTON_HANDLER(ActionEvent e) { System.out.println("BACK_HOMESCREEN_BUTTON_HANDLER CALLED"); MainApp.changeScenes(MainMenuScene.getInstance()); } /** * InstuctionsTab.java */ public static final void IF_BUTTON_HANDLER(ActionEvent e) { KarelTable.getInstance().addInstructionsCode(KarelCode.IFSTATEMENT); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.IFSTATEMENT); return; } GameTabs.getInstance().disableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().disableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.CONDITIONS_TAB_VALUE); } public static final void END_IF_BUTTON_HANDLER(ActionEvent e) { } public static final void ELSE_BUTTON_HANDLER(ActionEvent e) { KarelTable.getInstance().addInstructionsCode(KarelCode.ELSESTATEMENT); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { // TODO KarelTable.getInstance().replaceCode(KarelCode.ELSESTATEMENT); return; } GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void END_ELSE_BUTTON_HANDLER(ActionEvent e) { } public static final void WHILE_BUTTON_HANDLER(ActionEvent e) { KarelTable.getInstance().addInstructionsCode(KarelCode.WHILESTATEMENT); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.WHILESTATEMENT); return; } GameTabs.getInstance().disableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().disableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.CONDITIONS_TAB_VALUE); } public static final void END_WHILE_BUTTON_HANDLER(ActionEvent e) { } public static final void TASK_BUTTON_HANDLER(ActionEvent e) { } public static final void LOOP_BUTTON_HANDLER(ActionEvent e) { KarelTable.getInstance().addInstructionsCode(KarelCode.LOOPSTATEMENT); GameTabs.getInstance().disableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().disableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.NUMBERS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.NUMBERS_TAB_VALUE); } public static final void END_LOOP_BUTTON_HANDLER(ActionEvent e) { } /** * ConditionalsTab.java */ public static final void FRONT_IS_CLEAR_BUTTON_HANDLER(ActionEvent e) { System.out.println("FRONT_IS_CLEAR_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FRONTISCLEAR); return; } KarelTable.getInstance().addCode(KarelCode.FRONTISCLEAR); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void NEXT_TO_A_FRIEND_BUTTON_HANDLER(ActionEvent e) { System.out.println("NEXT_TO_A_FRIEND_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.NEXTTOAFRIEND); return; } KarelTable.getInstance().addCode(KarelCode.NEXTTOAFRIEND); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void FACING_NORTH_BUTTON_HANDLER(ActionEvent e) { System.out.println("FACING_NORTH_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FACINGNORTH); return; } KarelTable.getInstance().addCode(KarelCode.FACINGNORTH); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void FACING_SOUTH_BUTTON_HANDLER(ActionEvent e) { System.out.println("FACING_SOUTH_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FACINGSOUTH); return; } KarelTable.getInstance().addCode(KarelCode.FACINGSOUTH); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void FACING_EAST_BUTTON_HANDLER(ActionEvent e) { System.out.println("FACING_EAST_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FACINGEAST); return; } KarelTable.getInstance().addCode(KarelCode.FACINGEAST); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void FACING_WEST_BUTTON_HANDLER(ActionEvent e) { System.out.println("FACING_WEST_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.FACINGWEST); return; } KarelTable.getInstance().addCode(KarelCode.FACINGWEST); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } public static final void BAG_IS_EMPTY_BUTTON_HANDLER(ActionEvent e) { System.out.println("BAG_IS_EMPTY_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.BAGISEMPTY); return; } KarelTable.getInstance().addCode(KarelCode.BAGISEMPTY); GameTabs.getInstance().disableTab(GameTabs.CONDITIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } /** * OperationsTab.java */ public static final void MOVE_BUTTON_HANDLER(ActionEvent e) { System.out.println("MOVE_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.MOVE); return; } KarelTable.getInstance().addCode(KarelCode.MOVE); } public static final void SLEEP_BUTTON_HANDLER(ActionEvent e) { System.out.println("SLEEP_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.SLEEP); return; } KarelTable.getInstance().addCode(KarelCode.SLEEP); } public static final void WAKE_UP_BUTTON_HANDLER(ActionEvent e) { System.out.println("WAKE_UP_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.WAKEUP); return; } KarelTable.getInstance().addCode(KarelCode.WAKEUP); } public static final void TURN_RIGHT_BUTTON_HANDLER(ActionEvent e) { System.out.println("TURN_RIGHT_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.TURNRIGHT); return; } KarelTable.getInstance().addCode(KarelCode.TURNRIGHT); } public static final void PICK_UP_BAMBOO_BUTTON_HANDLER(ActionEvent e) { System.out.println("PICK_UP_BAMBOO_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.PICKBAMBOO); return; } KarelTable.getInstance().addCode(KarelCode.PICKBAMBOO); } public static final void PUT_BAMBOO_BUTTON_HANDLER(ActionEvent e) { System.out.println("PUT_BAMBOO_BUTTON_HANDLER"); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(KarelCode.PUTBAMBOO); return; } KarelTable.getInstance().addCode(KarelCode.PUTBAMBOO); } public static final void NUMBERS_BUTTON_HANDLER(ActionEvent e) { System.out.println("NUMBERS_BUTTON_HANDLER"); String value = ((Button) e.getSource()).getText(); if (KarelTable.getInstance().isREPLACE_BUTTON_ON()) { KarelTable.getInstance().replaceCode(value); return; } KarelTable.getInstance().addCode(value); GameTabs.getInstance().disableTab(GameTabs.NUMBERS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.INSTRUCTIONS_TAB_VALUE); GameTabs.getInstance().enableTab(GameTabs.OPERATIONS_TAB_VALUE); GameTabs.getInstance().switchTab(GameTabs.OPERATIONS_TAB_VALUE); } /** * Popup for if a grid space is not empty * Asks to replace object or just cancel * * @newObject the object the user is trying to put into the square */ public static void popup(String newObject){ String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("There is already an object in this space. \nReplace " + oldObject + " with " + newObject + "?")); Scene dialogScene = new Scene(dialogVbox, 300, 200); final Button REPLACE = new Button("Replace"); REPLACE.setMaxWidth(100); final Button CANCEL = new Button("Cancel"); REPLACE.setMaxWidth(100); dialogVbox.getChildren().addAll(REPLACE, CANCEL); dialog.setScene(dialogScene); dialog.show(); CANCEL.setOnAction( new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ dialog.close(); } } ); REPLACE.setOnAction( new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ dialog.close(); if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo")) RMITEM_BUTTON_HANDLER(null); if (oldObject.equals("Friend")) RMCREATURE_BUTTON_HANDLER(null); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(newObject); switch(newObject){ case "Tree": Tree tree = new Tree(4); tree.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(tree); GridWorld.getInstance().getWorld().printWorld(); break; case "Shrub": Shrub shrub = new Shrub(4, false); shrub.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(shrub); GridWorld.getInstance().getWorld().printWorld(); break; case "Bamboo": Bamboo bamboo = new Bamboo(4); bamboo.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(bamboo); GridWorld.getInstance().getWorld().printWorld(); case "Friend": Coordinate cords = new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate()); Creature Friend = new Creature("Friend", cords); Friend.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addCreature(Friend); GridWorld.getInstance().getWorld().printWorld(); default: break; } } } ); } /** * Popup if they try to put something where Eve is * @newObject the object the user is trying to put into the square */ public static void EvePop(){ final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("This space is already full. \nYou can't put an Object here.")); Scene dialogScene = new Scene(dialogVbox, 300, 200); final Button OKAY = new Button("Okay"); dialogVbox.getChildren().add(OKAY); dialog.setScene(dialogScene); dialog.show(); OKAY.setOnAction( new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ dialog.close(); } } ); } /** * Popup if they try delete the wrong thing * @newObject the object the user is trying to put into the square */ public static void DeletePop(){ String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("This space is a(n) "+ oldObject +". \nUse the Remove"+oldObject+" button.")); Scene dialogScene = new Scene(dialogVbox, 300, 200); final Button OKAY = new Button("Okay"); dialogVbox.getChildren().add(OKAY); dialog.setScene(dialogScene); dialog.show(); OKAY.setOnAction( new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ dialog.close(); } } ); } /** * ItemsTab.java */ public static final void RMITEM_BUTTON_HANDLER(ActionEvent e){ System.out.println("RMITEM_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); switch(oldObject){ case "Tree": GridWorld.getInstance().getWorld().removeItem(new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate())); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(""); break; case "Shrub": GridWorld.getInstance().getWorld().removeItem(new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate())); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(""); break; case "Bamboo": GridWorld.getInstance().getWorld().removeItem(new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate())); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(""); default: break; } } public static final void SHRUB_BUTTON_HANDLER(ActionEvent e){ System.out.println("SHRUB_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Eve!")) EvePop(); else if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ popup("Shrub"); } else GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Shrub"); Shrub shrub = new Shrub(4, false); shrub.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(shrub); GridWorld.getInstance().getWorld().printWorld(); } public static final void TREE_BUTTON_HANDLER(ActionEvent e){ String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Eve!")) EvePop(); else if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ popup("Tree"); } else{ GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Tree"); Tree tree = new Tree(4); tree.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(tree); GridWorld.getInstance().getWorld().printWorld(); } } public static final void BAMBOO_BUTTON_HANDLER(ActionEvent e){ System.out.println("BAMBOO_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Eve!")) EvePop(); else if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ popup("Bamboo"); } else{ GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Bamboo"); Bamboo bamboo = new Bamboo(4); bamboo.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addItem(bamboo); GridWorld.getInstance().getWorld().printWorld(); } } /** * CreaturesTab.java */ public static final void RMCREATURE_BUTTON_HANDLER(ActionEvent e){ String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ } System.out.println("RMCREATURE_BUTTON_HANDLER"); GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText(""); GridWorld.getInstance().getWorld().removeCreature(new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate())); } public static final void EVE_BUTTON_HANDLER(ActionEvent e){ System.out.println("EVE_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); for(int y=0; y < GridWorld.gridButtons.length; y++){ for(int x=0; x < GridWorld.gridButtons[y].length; x++){ if (GridWorld.gridButtons[y][x].getText().equals("Eve!")){ //frontend move GridWorld.gridButtons[y][x].setText(" "); //backend move System.out.println("X: " + x + "Y: " + y); Creature eve = GridWorld.getInstance().getWorld().removeCreature(new Coordinate(y,x)); eve.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); eve.setDirection(Coordinate.DOWN); GridWorld.getInstance().getWorld().addCreature(eve); } } } if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Friend")){ EvePop(); } else{ GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Eve!"); Coordinate cords = new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate()); Creature Eve = new Creature("Eve!", cords); Eve.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addCreature(Eve); GridWorld.getInstance().getWorld().printWorld(); } } public static final void FRIENDS_BUTTON_HANDLER(ActionEvent e){ System.out.println("FRIENDS_BUTTON_HANDLER"); String oldObject = GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].getText(); if (oldObject.equals("Tree") || oldObject.equals("Shrub") || oldObject.equals("Bamboo") || oldObject.equals("Eve!")){ popup("Friend"); } else GridWorld.gridButtons[GridWorld.getXCoordinate()][GridWorld.getYCoordinate()].setText("Friend"); Coordinate cords = new Coordinate(GridWorld.getXCoordinate(),GridWorld.getYCoordinate()); Creature Friend = new Creature("Friend", cords); Friend.setCoordinates(new Coordinate(GridWorld.getXCoordinate(), GridWorld.getYCoordinate())); if(GridWorld.getInstance().getWorld() == null) System.out.println("Uninitalized world"); GridWorld.getInstance().getWorld().addCreature(Friend); GridWorld.getInstance().getWorld().printWorld(); } public static final void GridWorld_BUTTON_HANDLER(ActionEvent e){ } public static final void BACK_BUTTON_HANDLER(ActionEvent e){ System.out.println("BACK_BUTTON_HANDLER CALLED"); } public static final void FORWARD_BUTTON_HANDLER(ActionEvent e){ System.out.println("FORWARD_BUTTON_HANDLER CALLED"); } public static final void PLAY_BUTTON_HANDLER(ActionEvent e){ System.out.println("PLAY_BUTTON_HANDLER CALLED"); ArrayList<String> karelCode = KarelTable.getInstance().getKarelCode(); World world = SandboxScene.getWorld(); System.out.println(KarelTable.getInstance().getKarelCode()); Interpreter interpreter = new Interpreter(karelCode, world); world.printWorld(); interpreter.start(); //starts the code world.printWorld(); } public static final void RESET_BUTTON_HANDLER(ActionEvent e) { System.out.println("RESET_BUTTON_HANDLER CALLED"); } public static final void REPLACE_BUTTON_HANDLER(ActionEvent e) { System.out.println("REPLACE_BUTTON_HANDLER CALLED"); } public static final void QUIT_MENU_HANDLER(ActionEvent e) { System.out.println("Quit sandbox mode. Returned to home screen."); MainApp.changeScenes(MainMenuScene.getInstance()); } public static final void SAVE_MENU_HANDLER(ActionEvent e) { System.out.println("Saved!"); } }
Fix the karelCode bug.
src/controllers/ButtonHandlers.java
Fix the karelCode bug.
Java
mit
aadd20b15c4c466cfea880fd87f0ac6766ac804b
0
cs2103aug2014-t17-1j/main
package taskDo; import java.util.ArrayList; import Parser.ParsedResult; import commandFactory.CommandType; import commandFactory.Search; import commonClasses.Constants; import commonClasses.SummaryReport; public class UpdateSummaryReport { public static void update(ParsedResult parsedResult){ Search search = new Search(); updateDisplayTaskList(search.searchByDate(parsedResult)); SummaryReport.sortByDueDate(); determineFeedbackMsg(parsedResult.getCommandType()); } public static void updateForDisplay(ParsedResult parsedResult, ArrayList<Task> displayList){ updateDisplayTaskList(displayList); SummaryReport.sortByDueDate(); determineFeedbackMsg(parsedResult.getCommandType()); } public static void updateForSearch(ParsedResult parsedResult, ArrayList<Task> displayList){ updateDisplayTaskList(displayList); SummaryReport.sortByDueDate(); if(displayList.isEmpty()){ updateFeedbackMsg(Constants.MESSAGE_FAIL_SEARCH); }else{updateFeedbackMsg(Constants.MESSAGE_SUCCESS_SEARCH);} } private static void updateDisplayTaskList(ArrayList<Task> displayList) { SummaryReport.setDisplayList(displayList); } private static void determineFeedbackMsg(CommandType commandType) { switch(commandType){ case ADD: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_ADD); break; case DELETE: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_DELETE); break; case EDIT: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_EDIT); break; case DISPLAY: updateFeedbackMsg(Constants.MESSAGE_DISPLAY); break; case UNDO: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_UNDO); break; case REDO: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_REDO); break; case COMPLETED: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_COMPLETED); break; case SEARCH: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_SEARCH); break; default: break; } } private static void updateFeedbackMsg(String feedbackMsg) { SummaryReport.setFeedBackMsg(feedbackMsg); } }
src/taskDo/UpdateSummaryReport.java
package taskDo; import java.util.ArrayList; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import Parser.ParsedResult; import commandFactory.CommandType; import commandFactory.Search; import commonClasses.Constants; import commonClasses.SummaryReport; public class UpdateSummaryReport { public static void update(ParsedResult parsedResult){ Search search = new Search(); updateHeader(parsedResult.getTaskDetails()); updateDisplayTaskList(search.searchByDate(parsedResult)); SummaryReport.sortByDueDate(); determineFeedbackMsg(parsedResult.getCommandType()); } public static void updateForDisplay(ParsedResult parsedResult, ArrayList<Task> displayList){ updateHeader(parsedResult.getTaskDetails()); updateDisplayTaskList(displayList); SummaryReport.sortByDueDate(); determineFeedbackMsg(parsedResult.getCommandType()); } public static void updateForSearch(ParsedResult parsedResult, ArrayList<Task> displayList){ updateHeader(parsedResult.getTaskDetails()); updateDisplayTaskList(displayList); SummaryReport.sortByDueDate(); if(displayList.isEmpty()){ updateFeedbackMsg(Constants.MESSAGE_FAIL_SEARCH); }else{updateFeedbackMsg(Constants.MESSAGE_SUCCESS_SEARCH);} } private static void updateHeader(Task task) { if(isSomeday(task)) { SummaryReport.setHeader(Constants.MESSAGE_SOMEDAY); } else { DateTimeFormatter dateFormat = DateTimeFormat.forPattern("dd-MM-yyyy"); String dateDisplay = dateFormat.print(task.getDueDate().toLocalDate()); SummaryReport.setHeader(dateDisplay); } } private static boolean isSomeday(Task refTask) { return refTask.getDueDate().toLocalDate().getYear() == Constants.NILL_YEAR; } private static void updateDisplayTaskList(ArrayList<Task> displayList) { SummaryReport.setDisplayList(displayList); } private static void determineFeedbackMsg(CommandType commandType) { switch(commandType){ case ADD: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_ADD); break; case DELETE: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_DELETE); break; case EDIT: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_EDIT); break; case DISPLAY: updateFeedbackMsg(Constants.MESSAGE_DISPLAY); break; case UNDO: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_UNDO); break; case REDO: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_REDO); break; case COMPLETED: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_COMPLETED); break; case SEARCH: updateFeedbackMsg(Constants.MESSAGE_SUCCESS_SEARCH); break; default: break; } } private static void updateFeedbackMsg(String feedbackMsg) { SummaryReport.setFeedBackMsg(feedbackMsg); } }
cancel display header
src/taskDo/UpdateSummaryReport.java
cancel display header
Java
epl-1.0
17eb511d4498c35eef2c4701d96fc9f60a237768
0
inevo/mondrian,inevo/mondrian
/* // $Id$ // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // Copyright (C) 2003-2009 Julian Hyde // All Rights Reserved. // You must accept the terms of that agreement to use this software. // // jhyde, Feb 14, 2003 */ package mondrian.test; import mondrian.olap.*; import mondrian.olap.type.NumericType; import mondrian.olap.type.Type; import mondrian.rolap.RolapConnectionProperties; import mondrian.spi.UserDefinedFunction; import mondrian.spi.Dialect; import mondrian.util.Bug; import mondrian.calc.ResultStyle; import java.util.regex.Pattern; import java.util.*; import junit.framework.Assert; /** * <code>BasicQueryTest</code> is a test case which tests simple queries * against the FoodMart database. * * @author jhyde * @since Feb 14, 2003 * @version $Id$ */ public class BasicQueryTest extends FoodMartTestCase { static final String EmptyResult = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "Axis #2:\n"; private static final String timeWeekly = TestContext.hierarchyName("Time", "Weekly"); private MondrianProperties props = MondrianProperties.instance(); public BasicQueryTest() { super(); } public BasicQueryTest(String name) { super(name); } private static final QueryAndResult[] sampleQueries = { // 0 new QueryAndResult( "select {[Measures].[Unit Sales]} on columns\n" + " from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Row #0: 266,773\n"), // 1 new QueryAndResult( "select\n" + " {[Measures].[Unit Sales]} on columns,\n" + " order(except([Promotion Media].[Media Type].members,{[Promotion Media].[Media Type].[No Media]}),[Measures].[Unit Sales],DESC) on rows\n" + "from Sales ", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Promotion Media].[All Media].[Daily Paper, Radio, TV]}\n" + "{[Promotion Media].[All Media].[Daily Paper]}\n" + "{[Promotion Media].[All Media].[Product Attachment]}\n" + "{[Promotion Media].[All Media].[Daily Paper, Radio]}\n" + "{[Promotion Media].[All Media].[Cash Register Handout]}\n" + "{[Promotion Media].[All Media].[Sunday Paper, Radio]}\n" + "{[Promotion Media].[All Media].[Street Handout]}\n" + "{[Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Promotion Media].[All Media].[Bulk Mail]}\n" + "{[Promotion Media].[All Media].[In-Store Coupon]}\n" + "{[Promotion Media].[All Media].[TV]}\n" + "{[Promotion Media].[All Media].[Sunday Paper, Radio, TV]}\n" + "{[Promotion Media].[All Media].[Radio]}\n" + "Row #0: 9,513\n" + "Row #1: 7,738\n" + "Row #2: 7,544\n" + "Row #3: 6,891\n" + "Row #4: 6,697\n" + "Row #5: 5,945\n" + "Row #6: 5,753\n" + "Row #7: 4,339\n" + "Row #8: 4,320\n" + "Row #9: 3,798\n" + "Row #10: 3,607\n" + "Row #11: 2,726\n" + "Row #12: 2,454\n"), // 2 new QueryAndResult( "select\n" + " { [Measures].[Units Shipped], [Measures].[Units Ordered] } on columns,\n" + " NON EMPTY [Store].[Store Name].members on rows\n" + "from Warehouse", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Units Shipped]}\n" + "{[Measures].[Units Ordered]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Row #0: 10759.0\n" + "Row #0: 11699.0\n" + "Row #1: 24587.0\n" + "Row #1: 26463.0\n" + "Row #2: 23835.0\n" + "Row #2: 26270.0\n" + "Row #3: 1696.0\n" + "Row #3: 1875.0\n" + "Row #4: 8515.0\n" + "Row #4: 9109.0\n" + "Row #5: 32393.0\n" + "Row #5: 35797.0\n" + "Row #6: 2348.0\n" + "Row #6: 2454.0\n" + "Row #7: 22734.0\n" + "Row #7: 24610.0\n" + "Row #8: 24110.0\n" + "Row #8: 26703.0\n" + "Row #9: 11889.0\n" + "Row #9: 12828.0\n" + "Row #10: 32411.0\n" + "Row #10: 35930.0\n" + "Row #11: 1860.0\n" + "Row #11: 2074.0\n" + "Row #12: 10589.0\n" + "Row #12: 11426.0\n"), // 3 new QueryAndResult( "with member [Measures].[Store Sales Last Period] as " + " '([Measures].[Store Sales], Time.[Time].PrevMember)',\n" + " format='#,###.00'\n" + "select\n" + " {[Measures].[Store Sales Last Period]} on columns,\n" + " {TopCount([Product].[Product Department].members,5, [Measures].[Store Sales Last Period])} on rows\n" + "from Sales\n" + "where ([Time].[1998])", "Axis #0:\n" + "{[Time].[1998]}\n" + "Axis #1:\n" + "{[Measures].[Store Sales Last Period]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "Row #0: 82,248.42\n" + "Row #1: 67,609.82\n" + "Row #2: 60,469.89\n" + "Row #3: 55,207.50\n" + "Row #4: 39,774.34\n"), // 4 new QueryAndResult( "with member [Measures].[Total Store Sales] as 'Sum(YTD(),[Measures].[Store Sales])', format_string='#.00'\n" + "select\n" + " {[Measures].[Total Store Sales]} on columns,\n" + " {TopCount([Product].[Product Department].members,5, [Measures].[Total Store Sales])} on rows\n" + "from Sales\n" + "where ([Time].[1997].[Q2].[4])", "Axis #0:\n" + "{[Time].[1997].[Q2].[4]}\n" + "Axis #1:\n" + "{[Measures].[Total Store Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "Row #0: 26526.67\n" + "Row #1: 21897.10\n" + "Row #2: 19980.90\n" + "Row #3: 17882.63\n" + "Row #4: 12963.23\n"), // 5 new QueryAndResult( "with member [Measures].[Store Profit Rate] as '([Measures].[Store Sales]-[Measures].[Store Cost])/[Measures].[Store Cost]', format = '#.00%'\n" + "select\n" + " {[Measures].[Store Cost],[Measures].[Store Sales],[Measures].[Store Profit Rate]} on columns,\n" + " Order([Product].[Product Department].members, [Measures].[Store Profit Rate], BDESC) on rows\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[Store Profit Rate]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Breakfast Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Carousel]}\n" + "{[Product].[All Products].[Food].[Canned Products]}\n" + "{[Product].[All Products].[Food].[Baking Goods]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Non-Consumable].[Health and Hygiene]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Baked Goods]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Periodicals]}\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Seafood]}\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Meat]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Starchy Foods]}\n" + "{[Product].[All Products].[Food].[Eggs]}\n" + "{[Product].[All Products].[Food].[Snacks]}\n" + "{[Product].[All Products].[Food].[Dairy]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "{[Product].[All Products].[Non-Consumable].[Checkout]}\n" + "Row #0: 2,756.80\n" + "Row #0: 6,941.46\n" + "Row #0: 151.79%\n" + "Row #1: 595.97\n" + "Row #1: 1,500.11\n" + "Row #1: 151.71%\n" + "Row #2: 1,317.13\n" + "Row #2: 3,314.52\n" + "Row #2: 151.65%\n" + "Row #3: 15,370.61\n" + "Row #3: 38,670.41\n" + "Row #3: 151.59%\n" + "Row #4: 5,576.79\n" + "Row #4: 14,029.08\n" + "Row #4: 151.56%\n" + "Row #5: 12,972.99\n" + "Row #5: 32,571.86\n" + "Row #5: 151.07%\n" + "Row #6: 26,963.34\n" + "Row #6: 67,609.82\n" + "Row #6: 150.75%\n" + "Row #7: 6,564.09\n" + "Row #7: 16,455.43\n" + "Row #7: 150.69%\n" + "Row #8: 11,069.53\n" + "Row #8: 27,748.53\n" + "Row #8: 150.67%\n" + "Row #9: 22,030.66\n" + "Row #9: 55,207.50\n" + "Row #9: 150.59%\n" + "Row #10: 3,614.55\n" + "Row #10: 9,056.76\n" + "Row #10: 150.56%\n" + "Row #11: 32,831.33\n" + "Row #11: 82,248.42\n" + "Row #11: 150.52%\n" + "Row #12: 1,520.70\n" + "Row #12: 3,809.14\n" + "Row #12: 150.49%\n" + "Row #13: 10,108.87\n" + "Row #13: 25,318.93\n" + "Row #13: 150.46%\n" + "Row #14: 1,465.42\n" + "Row #14: 3,669.89\n" + "Row #14: 150.43%\n" + "Row #15: 15,894.53\n" + "Row #15: 39,774.34\n" + "Row #15: 150.24%\n" + "Row #16: 24,170.73\n" + "Row #16: 60,469.89\n" + "Row #16: 150.18%\n" + "Row #17: 4,705.91\n" + "Row #17: 11,756.07\n" + "Row #17: 149.82%\n" + "Row #18: 3,684.90\n" + "Row #18: 9,200.76\n" + "Row #18: 149.69%\n" + "Row #19: 5,827.58\n" + "Row #19: 14,550.05\n" + "Row #19: 149.68%\n" + "Row #20: 12,228.85\n" + "Row #20: 30,508.85\n" + "Row #20: 149.48%\n" + "Row #21: 2,830.92\n" + "Row #21: 7,058.60\n" + "Row #21: 149.34%\n" + "Row #22: 1,525.04\n" + "Row #22: 3,767.71\n" + "Row #22: 147.06%\n"), // 6 new QueryAndResult( "with\n" + " member [Product].[All Products].[Drink].[Percent of Alcoholic Drinks] as '[Product].[All Products].[Drink].[Alcoholic Beverages]/[Product].[All Products].[Drink]',\n" + " format_string = '#.00%'\n" + "select\n" + " { [Product].[All Products].[Drink].[Percent of Alcoholic Drinks] } on columns,\n" + " order([Customers].[All Customers].[USA].[WA].Children, [Product].[All Products].[Drink].[Percent of Alcoholic Drinks],BDESC) on rows\n" + "from Sales\n" + "where ([Measures].[Unit Sales])", "Axis #0:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #1:\n" + "{[Product].[All Products].[Drink].[Percent of Alcoholic Drinks]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "Row #0: 44.05%\n" + "Row #1: 34.41%\n" + "Row #2: 34.20%\n" + "Row #3: 32.93%\n" + "Row #4: 31.05%\n" + "Row #5: 30.84%\n" + "Row #6: 30.69%\n" + "Row #7: 29.81%\n" + "Row #8: 28.82%\n" + "Row #9: 28.70%\n" + "Row #10: 28.37%\n" + "Row #11: 26.67%\n" + "Row #12: 26.60%\n" + "Row #13: 26.47%\n" + "Row #14: 26.42%\n" + "Row #15: 26.28%\n" + "Row #16: 25.96%\n" + "Row #17: 24.70%\n" + "Row #18: 21.89%\n" + "Row #19: 21.47%\n" + "Row #20: 17.47%\n" + "Row #21: 13.79%\n"), // 7 new QueryAndResult( "with member [Measures].[Accumulated Sales] as 'Sum(YTD(),[Measures].[Store Sales])'\n" + "select\n" + " {[Measures].[Store Sales],[Measures].[Accumulated Sales]} on columns,\n" + " {Descendants([Time].[1997],[Time].[Month])} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[Accumulated Sales]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1].[1]}\n" + "{[Time].[1997].[Q1].[2]}\n" + "{[Time].[1997].[Q1].[3]}\n" + "{[Time].[1997].[Q2].[4]}\n" + "{[Time].[1997].[Q2].[5]}\n" + "{[Time].[1997].[Q2].[6]}\n" + "{[Time].[1997].[Q3].[7]}\n" + "{[Time].[1997].[Q3].[8]}\n" + "{[Time].[1997].[Q3].[9]}\n" + "{[Time].[1997].[Q4].[10]}\n" + "{[Time].[1997].[Q4].[11]}\n" + "{[Time].[1997].[Q4].[12]}\n" + "Row #0: 45,539.69\n" + "Row #0: 45,539.69\n" + "Row #1: 44,058.79\n" + "Row #1: 89,598.48\n" + "Row #2: 50,029.87\n" + "Row #2: 139,628.35\n" + "Row #3: 42,878.25\n" + "Row #3: 182,506.60\n" + "Row #4: 44,456.29\n" + "Row #4: 226,962.89\n" + "Row #5: 45,331.73\n" + "Row #5: 272,294.62\n" + "Row #6: 50,246.88\n" + "Row #6: 322,541.50\n" + "Row #7: 46,199.04\n" + "Row #7: 368,740.54\n" + "Row #8: 43,825.97\n" + "Row #8: 412,566.51\n" + "Row #9: 42,342.27\n" + "Row #9: 454,908.78\n" + "Row #10: 53,363.71\n" + "Row #10: 508,272.49\n" + "Row #11: 56,965.64\n" + "Row #11: 565,238.13\n"), // 8 new QueryAndResult( "select {[Measures].[Promotion Sales]} on columns\n" + " from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Promotion Sales]}\n" + "Row #0: 151,211.21\n"), }; public void testSample0() { assertQueryReturns(sampleQueries[0].query, sampleQueries[0].result); } public void testSample1() { assertQueryReturns(sampleQueries[1].query, sampleQueries[1].result); } public void testSample2() { assertQueryReturns(sampleQueries[2].query, sampleQueries[2].result); } public void testSample3() { assertQueryReturns(sampleQueries[3].query, sampleQueries[3].result); } public void testSample4() { assertQueryReturns(sampleQueries[4].query, sampleQueries[4].result); } public void testSample5() { assertQueryReturns(sampleQueries[5].query, sampleQueries[5].result); } public void testSample6() { assertQueryReturns(sampleQueries[6].query, sampleQueries[6].result); } public void testSample7() { assertQueryReturns(sampleQueries[7].query, sampleQueries[7].result); } public void testSample8() { if (TestContext.instance().getDialect().getDatabaseProduct() == Dialect.DatabaseProduct.INFOBRIGHT) { // Skip this test on Infobright, because [Promotion Sales] is // defined wrong. return; } assertQueryReturns(sampleQueries[8].query, sampleQueries[8].result); } public void testGoodComments() { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]/* trailing comment*/", EmptyResult); String[] comments = { "-- a basic comment\n", "// another basic comment\n", "/* yet another basic comment */", "-- a more complicated comment test\n", "-- to make it more intesting, -- we'll nest this comment\n", "-- also, \"we can put a string in the comment\"\n", "-- also, 'even a single quote string'\n", "---- and, the comment delimiter is looong\n", "/*\n" + " * next, how about a comment block?\n" + " * with several lines.\n" + " * also, \"we can put a string in the comment\"\n" + " * also, 'even a single quote string'\n" + " * also, -- another style comment is happy\n" + " */\n", "/* a simple /* nested */ comment */", "/*\n" + " * a multiline /* nested */ comment\n" + "*/", "/*\n" + " * a multiline\n" + " * /* multiline\n" + " * * nested comment\n" + " * */\n" + "*/", "/*\n" + " * a multiline\n" + " * /* multiline\n" + " * /* deeply\n" + " * /* really /* deeply */\n" + " * * nested comment\n" + " * */\n" + " * */\n" + " * */\n" + "*/", "-- single-line comment containing /* multiline */ comment\n", "/* multi-line comment containing -- single-line comment */", }; List<String> allCommentList = new ArrayList<String>(); for (String comment : comments) { allCommentList.add(comment); if (comment.indexOf("\n") >= 0) { allCommentList.add(comment.replaceAll("\n", "\r\n")); allCommentList.add(comment.replaceAll("\n", "\n\r")); allCommentList.add(comment.replaceAll("\n", " \n \n ")); } } allCommentList.add(""); final String[] allComments = allCommentList.toArray(new String[allCommentList.size()]); // The last element of the array is the concatenation of all other // comments. StringBuilder buf = new StringBuilder(); for (String allComment : allComments) { buf.append(allComment); } allComments[allComments.length - 1] = buf.toString(); // Comment at start of query. for (String comment : allComments) { assertQueryReturns( comment + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment after SELECT. for (String comment : allComments) { assertQueryReturns( "SELECT" + comment + "{} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment within braces. for (String comment : allComments) { assertQueryReturns( "SELECT {" + comment + "} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment after axis name. for (String comment : allComments) { assertQueryReturns( "SELECT {} ON ROWS" + comment + ", {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment before slicer. for (String comment : allComments) { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales] WHERE" + comment + "([Gender].[F])", "Axis #0:\n" + "{[Gender].[All Gender].[F]}\n" + "Axis #1:\n" + "Axis #2:\n"); } // Comment after query. for (String comment : allComments) { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]" + comment, EmptyResult); } assertQueryReturns( "-- a comment test with carriage returns at the end of the lines\r\n" + "-- first, more than one single-line comment in a row\r\n" + "-- and, to make it more intesting, -- we'll nest this comment\r\n" + "-- also, \"we can put a string in the comment\"\r\n" + "-- also, 'even a single quote string'\r\n" + "---- and, the comment delimiter is looong\r\n" + "/*\r\n" + " * next, now about a comment block?\r\n" + " * with several lines.\r\n" + " * also, \"we can put a string in the comment\"\r\n" + " * also, 'even a single quote comment'\r\n" + " * also, -- another style comment is heppy\r\n" + " * also, // another style comment is heppy\r\n" + " */\r\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]\r", EmptyResult); assertQueryReturns( "/* a simple /* nested */ comment */\n" + "/*\n" + " * a multiline /* nested */ comment\n" + "*/\n" + "/*\n" + " * a multiline\n" + " * /* multiline\n" + " * * nested comment\n" + " * */\n" + "*/\n" + "/*\n" + " * a multiline\n" + " * /* multiline\n" + " * /* deeply\n" + " * /* really /* deeply */\n" + " * * nested comment\n" + " * */\n" + " * */\n" + " * */\n" + "*/\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); assertQueryReturns( "-- an entire select statement commented out\n" + "-- SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];\n" + "/*SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];*/\n" + "// SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); assertQueryReturns( "// now for some comments in a larger command\n" + "with // create calculate measure [Product].[All Products].[Drink].[Percent of Alcoholic Drinks]\n" + " member [Product].[All Products].[Drink].[Percent of Alcoholic Drinks]/*the measure name*/as ' // begin the definition of the measure next\n" + " [Product]./****this is crazy****/[All Products].[Drink].[Alcoholic Beverages]/[Product].[All Products].[Drink]', // divide number of alcoholic drinks by total # of drinks\n" + " format_string = '#.00%' // a custom format for our measure\n" + "select\n" + " { [Product]/**** still crazy ****/.[All Products].[Drink].[Percent of Alcoholic Drinks] } on columns,\n" + " order(/****do not put a comment inside square brackets****/[Customers].[All Customers].[USA].[WA].Children, [Product].[All Products].[Drink].[Percent of Alcoholic Drinks],BDESC) on rows\n" + "from Sales\n" + "where ([Measures].[Unit Sales] /****,[Time].[1997]****/) -- a comment at the end of the command", "Axis #0:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #1:\n" + "{[Product].[All Products].[Drink].[Percent of Alcoholic Drinks]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "Row #0: 44.05%\n" + "Row #1: 34.41%\n" + "Row #2: 34.20%\n" + "Row #3: 32.93%\n" + "Row #4: 31.05%\n" + "Row #5: 30.84%\n" + "Row #6: 30.69%\n" + "Row #7: 29.81%\n" + "Row #8: 28.82%\n" + "Row #9: 28.70%\n" + "Row #10: 28.37%\n" + "Row #11: 26.67%\n" + "Row #12: 26.60%\n" + "Row #13: 26.47%\n" + "Row #14: 26.42%\n" + "Row #15: 26.28%\n" + "Row #16: 25.96%\n" + "Row #17: 24.70%\n" + "Row #18: 21.89%\n" + "Row #19: 21.47%\n" + "Row #20: 17.47%\n" + "Row #21: 13.79%\n"); } public void testBadComments() { // Comments cannot appear inside identifiers. assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[/***an illegal comment****/Marital Status].[S]}", "Failed to parse query"); // Nested comments must be closed. assertQueryThrows( "/* a simple /* nested * comment */\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", "Failed to parse query"); // We do NOT support \r as a line-end delimiter. (Too bad, Mac users.) assertQueryThrows( "SELECT {} ON COLUMNS -- comment terminated by CR only\r, {} ON ROWS FROM [Sales]", "Failed to parse query"); } /** * Tests that a query whose axes are empty works; bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-52">MONDRIAN-52</a>. */ public void testBothAxesEmpty() { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); // expression which evaluates to empty set assertQueryReturns( "SELECT Filter({[Gender].MEMBERS}, 1 = 0) ON COLUMNS, \n" + "{} ON ROWS\n" + "FROM [Sales]", EmptyResult); // with slicer assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS \n" + "FROM [Sales] WHERE ([Gender].[F])", "Axis #0:\n" + "{[Gender].[All Gender].[F]}\n" + "Axis #1:\n" + "Axis #2:\n"); } /** * Tests that a slicer with multiple values gives an error; bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-96">MONDRIAN-96</a>. */ public void testCompoundSlicerFails() { // two tuples assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {([Marital Status].[S]),\n" + " ([Marital Status].[M])}", "Axis #0:\n" + "{[Marital Status].[All Marital Status].[S]}\n" + "{[Marital Status].[All Marital Status].[M]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n"); // set with incompatible members assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[Marital Status].[S],\n" + " [Product]}", "All arguments to function '{}' must have same hierarchy."); // expression which evaluates to a set with zero members used to be an // error - now it's ok; cells are null because they are aggregating over // nothing assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, 1 = 0)", "Axis #0:\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: \n" + "Row #1: \n" + "Row #2: \n"); // expression which evaluates to a not-null member is ok assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE ({Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] = 266773)}.Item(0))", "Axis #0:\n" + "{[Marital Status].[All Marital Status]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n"); // Expression which evaluates to a null member used to be an error; now // it is an unsatisfiable condition, so cells come out empty. // Confirmed with SSAS 2005. assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE [Marital Status].Parent", "Axis #0:\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: \n" + "Row #1: \n" + "Row #2: \n"); // expression which evaluates to a set with one member is ok assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] = 266773)", "Axis #0:\n" + "{[Marital Status].[All Marital Status]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n"); // slicer expression which evaluates to three tuples is not ok assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] <= 266773)", "Axis #0:\n" + "{[Marital Status].[All Marital Status]}\n" + "{[Marital Status].[All Marital Status].[M]}\n" + "{[Marital Status].[All Marital Status].[S]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n"); // set with incompatible members assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[Marital Status].[S],\n" + " [Product]}", "All arguments to function '{}' must have same hierarchy."); // two members of same dimension in columns and rows assertQueryThrows( "SELECT CrossJoin(\n" + " {[Measures].[Unit Sales]},\n" + " {[Gender].[M]}) ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]", "Hierarchy '[Gender]' appears in more than one independent axis."); // two members of same dimension in rows and filter assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Marital Status].[S], [Gender].[F])", "Hierarchy '[Gender]' appears in more than one independent axis."); // members of different hierarchies of the same dimension in rows and // filter assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Time].[1997].Children} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Marital Status].[S], " + timeWeekly + ".[1997].[20])", "Axis #0:\n" + "{[Marital Status].[All Marital Status].[S], [Time].[Weekly].[All Weeklys].[1997].[20]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: \n" + "Row #1: 3,523\n" + "Row #2: \n" + "Row #3: \n"); // two members of same dimension in slicer tuple assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Marital Status].[S], [Marital Status].[M])", "Tuple contains more than one member of hierarchy '[Marital Status]'."); // two members of different hierarchies of the same dimension in the // slicer tuple assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Time].[1997].[Q1], " + timeWeekly + ".[1997].[4])", "Axis #0:\n" + "{[Time].[1997].[Q1], [Time].[Weekly].[All Weeklys].[1997].[4]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 4,908\n" + "Row #1: 2,354\n" + "Row #2: 2,554\n"); // testcase for bug MONDRIAN-68, "Member appears in slicer and other // axis should be illegal" assertQueryThrows( "select\n" + "{[Measures].[Unit Sales]} on columns,\n" + "{([Product].[All Products], [Time].[1997])} ON rows\n" + "from Sales\n" + "where ([Time].[1997])", "Hierarchy '[Time]' appears in more than one independent axis."); // different hierarchies of same dimension on slicer and other axis assertQueryReturns( "select\n" + "{[Measures].[Unit Sales]} on columns,\n" + "{([Product].[All Products], " + timeWeekly + ".[1997])} ON rows\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products], [Time].[Weekly].[All Weeklys].[1997]}\n" + "Row #0: 266,773\n"); } public void testEmptyTupleSlicerFails() { assertQueryThrows( "select [Measures].[Unit Sales] on 0,\n" + "[Product].Children on 1\n" + "from [Warehouse and Sales]\n" + "where ()", "Syntax error at line 4, column 10, token ')'"); } /** * Requires the use of a sparse segment, because the product dimension * has 6 atttributes, the product of whose cardinalities is ~8M. If we * use a dense segment, we run out of memory trying to allocate a huge * array. */ public void testBigQuery() { Result result = executeQuery( "SELECT {[Measures].[Unit Sales]} on columns,\n" + " {[Product].members} on rows\n" + "from Sales"); final int rowCount = result.getAxes()[1].getPositions().size(); assertEquals(2256, rowCount); assertEquals( "152", result.getCell( new int[]{ 0, rowCount - 1 }).getFormattedValue()); } public void testNonEmpty1() { assertSize( "select\n" + " NON EMPTY CrossJoin({[Product].[All Products].[Drink].Children},\n" + " {[Customers].[All Customers].[USA].[WA].[Bellingham]}) on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", 8, 2); } public void testNonEmpty2() { assertSize( "select\n" + " NON EMPTY CrossJoin(\n" + " {[Product].[All Products].Children},\n" + " {[Customers].[All Customers].[USA].[WA].[Bellingham]}) on rows,\n" + " NON EMPTY CrossJoin(\n" + " {[Measures].[Unit Sales]},\n" + " { [Promotion Media].[All Media].[Cash Register Handout],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", 2, 2); } public void testOneDimensionalQueryWithTupleAsSlicer() { Result result = executeQuery( "select\n" + " [Product].[All Products].[Drink].children on columns\n" + "from Sales\n" + "where ([Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997])"); assertTrue(result.getAxes().length == 1); assertTrue(result.getAxes()[0].getPositions().size() == 3); assertTrue(result.getSlicerAxis().getPositions().size() == 1); assertTrue(result.getSlicerAxis().getPositions().get(0).size() == 3); } public void testSlicerIsEvaluatedBeforeAxes() { // about 10 products exceeded 20000 units in 1997, only 2 for Q1 assertSize( "SELECT {[Measures].[Unit Sales]} on columns,\n" + " filter({[Product].members}, [Measures].[Unit Sales] > 20000) on rows\n" + "FROM Sales\n" + "WHERE [Time].[1997].[Q1]", 1, 2); } public void testSlicerWithCalculatedMembers() { assertSize( "WITH MEMBER [Time].[1997].[H1] as ' Aggregate({[Time].[1997].[Q1], [Time].[1997].[Q2]})' \n" + " MEMBER [Measures].[Store Margin] as '[Measures].[Store Sales] - [Measures].[Store Cost]'\n" + "SELECT {[Gender].children} on columns,\n" + " filter({[Product].members}, [Gender].[F] > 10000) on rows\n" + "FROM Sales\n" + "WHERE ([Time].[1997].[H1], [Measures].[Store Margin])", 2, 6); } public void _testEver() { assertQueryReturns( "select\n" + " {[Measures].[Unit Sales], [Measures].[Ever]} on columns,\n" + " [Gender].members on rows\n" + "from Sales", "xxx"); } public void _testDairy() { assertQueryReturns( "with\n" + " member [Product].[Non dairy] as '[Product].[All Products] - [Product].[Food].[Dairy]'\n" + " member [Measures].[Dairy ever] as 'sum([Time].members, ([Measures].[Unit Sales],[Product].[Food].[Dairy]))'\n" + " set [Customers who never bought dairy] as 'filter([Customers].members, [Measures].[Dairy ever] = 0)'\n" + "select\n" + " {[Measures].[Unit Sales], [Measures].[Dairy ever]} on columns,\n" + " [Customers who never bought dairy] on rows\n" + "from Sales", "xxx"); } public void testSolveOrder() { assertQueryReturns( "WITH\n" + " MEMBER [Measures].[StoreType] AS \n" + " '[Store].CurrentMember.Properties(\"Store Type\")',\n" + " SOLVE_ORDER = 2\n" + " MEMBER [Measures].[ProfitPct] AS \n" + " '(Measures.[Store Sales] - Measures.[Store Cost]) / Measures.[Store Sales]',\n" + " SOLVE_ORDER = 1, FORMAT_STRING = '##.00%'\n" + "SELECT\n" + " { Descendants([Store].[USA], [Store].[Store Name])} ON COLUMNS,\n" + " { [Measures].[Store Sales], [Measures].[Store Cost], [Measures].[StoreType],\n" + " [Measures].[ProfitPct] } ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[CA].[Alameda].[HQ]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Axis #2:\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[StoreType]}\n" + "{[Measures].[ProfitPct]}\n" + "Row #0: \n" + "Row #0: 45,750.24\n" + "Row #0: 54,545.28\n" + "Row #0: 54,431.14\n" + "Row #0: 4,441.18\n" + "Row #0: 55,058.79\n" + "Row #0: 87,218.28\n" + "Row #0: 4,739.23\n" + "Row #0: 52,896.30\n" + "Row #0: 52,644.07\n" + "Row #0: 49,634.46\n" + "Row #0: 74,843.96\n" + "Row #0: 4,705.97\n" + "Row #0: 24,329.23\n" + "Row #1: \n" + "Row #1: 18,266.44\n" + "Row #1: 21,771.54\n" + "Row #1: 21,713.53\n" + "Row #1: 1,778.92\n" + "Row #1: 21,948.94\n" + "Row #1: 34,823.56\n" + "Row #1: 1,896.62\n" + "Row #1: 21,121.96\n" + "Row #1: 20,956.80\n" + "Row #1: 19,795.49\n" + "Row #1: 29,959.28\n" + "Row #1: 1,880.34\n" + "Row #1: 9,713.81\n" + "Row #2: HeadQuarters\n" + "Row #2: Gourmet Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Supermarket\n" + "Row #2: Deluxe Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Deluxe Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Mid-Size Grocery\n" + "Row #3: \n" + "Row #3: 60.07%\n" + "Row #3: 60.09%\n" + "Row #3: 60.11%\n" + "Row #3: 59.94%\n" + "Row #3: 60.14%\n" + "Row #3: 60.07%\n" + "Row #3: 59.98%\n" + "Row #3: 60.07%\n" + "Row #3: 60.19%\n" + "Row #3: 60.12%\n" + "Row #3: 59.97%\n" + "Row #3: 60.04%\n" + "Row #3: 60.07%\n"); } public void testSolveOrderNonMeasure() { assertQueryReturns( "WITH\n" + " MEMBER [Product].[ProdCalc] as '1', SOLVE_ORDER=1\n" + " MEMBER [Measures].[MeasuresCalc] as '2', SOLVE_ORDER=2\n" + " MEMBER [Time].[TimeCalc] as '3', SOLVE_ORDER=3\n" + "SELECT\n" + " { [Product].[ProdCalc] } ON columns,\n" + " {([Time].[TimeCalc], [Measures].[MeasuresCalc])} ON rows\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Product].[ProdCalc]}\n" + "Axis #2:\n" + "{[Time].[TimeCalc], [Measures].[MeasuresCalc]}\n" + "Row #0: 3\n"); } public void testSolveOrderNonMeasure2() { assertQueryReturns( "WITH\n" + " MEMBER [Store].[StoreCalc] as '0', SOLVE_ORDER=0\n" + " MEMBER [Product].[ProdCalc] as '1', SOLVE_ORDER=1\n" + "SELECT\n" + " { [Product].[ProdCalc] } ON columns,\n" + " { [Store].[StoreCalc] } ON rows\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Product].[ProdCalc]}\n" + "Axis #2:\n" + "{[Store].[StoreCalc]}\n" + "Row #0: 1\n"); } /** * Test what happens when the solve orders are the same. According to * http://msdn.microsoft.com/library/en-us/olapdmad/agmdxadvanced_6jn7.asp * if solve orders are the same then the dimension specified first * when defining the cube wins. * * <p>In the first test, the answer should be 1 because Promotions * comes before Customers in the FoodMart.xml schema. */ public void testSolveOrderAmbiguous1() { assertQueryReturns( "WITH\n" + " MEMBER [Promotions].[Calc] AS '1'\n" + " MEMBER [Customers].[Calc] AS '2'\n" + "SELECT\n" + " { [Promotions].[Calc] } ON COLUMNS,\n" + " { [Customers].[Calc] } ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Promotions].[Calc]}\n" + "Axis #2:\n" + "{[Customers].[Calc]}\n" + "Row #0: 1\n"); } /** * In the second test, the answer should be 2 because Product comes before * Promotions in the FoodMart.xml schema. */ public void testSolveOrderAmbiguous2() { assertQueryReturns( "WITH\n" + " MEMBER [Promotions].[Calc] AS '1'\n" + " MEMBER [Product].[Calc] AS '2'\n" + "SELECT\n" + " { [Promotions].[Calc] } ON COLUMNS,\n" + " { [Product].[Calc] } ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Promotions].[Calc]}\n" + "Axis #2:\n" + "{[Product].[Calc]}\n" + "Row #0: 2\n"); } public void testCalculatedMemberWhichIsNotAMeasure() { assertQueryReturns( "WITH MEMBER [Product].[BigSeller] AS\n" + " 'IIf([Product].[Drink].[Alcoholic Beverages].[Beer and Wine] > 100, \"Yes\",\"No\")'\n" + "SELECT {[Product].[BigSeller],[Product].children} ON COLUMNS,\n" + " {[Store].[All Stores].[USA].[CA].children} ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Product].[BigSeller]}\n" + "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "Row #0: No\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n" + "Row #1: Yes\n" + "Row #1: 1,945\n" + "Row #1: 15,438\n" + "Row #1: 3,950\n" + "Row #2: Yes\n" + "Row #2: 2,422\n" + "Row #2: 18,294\n" + "Row #2: 4,947\n" + "Row #3: Yes\n" + "Row #3: 2,560\n" + "Row #3: 18,369\n" + "Row #3: 4,706\n" + "Row #4: No\n" + "Row #4: 175\n" + "Row #4: 1,555\n" + "Row #4: 387\n"); } public void testMultipleCalculatedMembersWhichAreNotMeasures() { assertQueryReturns( "WITH\n" + " MEMBER [Store].[x] AS '1'\n" + " MEMBER [Product].[x] AS '1'\n" + "SELECT {[Store].[x]} ON COLUMNS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[x]}\n" + "Row #0: 1\n"); } /** * There used to be something wrong with non-measure calculated members * where the ordering of the WITH MEMBER would determine whether or not * the member would be found in the cube. This test would fail but the * previous one would work ok. (see sf#1084651) */ public void testMultipleCalculatedMembersWhichAreNotMeasures2() { assertQueryReturns( "WITH\n" + " MEMBER [Product].[x] AS '1'\n" + " MEMBER [Store].[x] AS '1'\n" + "SELECT {[Store].[x]} ON COLUMNS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[x]}\n" + "Row #0: 1\n"); } /** * This one had the same problem. It wouldn't find the * [Store].[All Stores].[x] member because it has the same leaf * name as [Product].[All Products].[x]. (see sf#1084651) */ public void testMultipleCalculatedMembersWhichAreNotMeasures3() { assertQueryReturns( "WITH\n" + " MEMBER [Product].[All Products].[x] AS '1'\n" + " MEMBER [Store].[All Stores].[x] AS '1'\n" + "SELECT {[Store].[All Stores].[x]} ON COLUMNS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[x]}\n" + "Row #0: 1\n"); } public void testConstantString() { String s = executeExpr(" \"a string\" "); assertEquals("a string", s); } public void testConstantNumber() { String s = executeExpr(" 1234 "); assertEquals("1,234", s); } public void testCyclicalCalculatedMembers() { Util.discard( executeQuery( "WITH\n" + " MEMBER [Product].[X] AS '[Product].[Y]'\n" + " MEMBER [Product].[Y] AS '[Product].[X]'\n" + "SELECT\n" + " {[Product].[X]} ON COLUMNS,\n" + " {Store.[Store Name].Members} ON ROWS\n" + "FROM Sales")); } /** * Disabled test. It used throw an 'infinite loop' error (which is what * Plato does). But now we revert to the context of the default member when * calculating calculated members (we used to stay in the context of the * calculated member), and we get a result. */ public void testCycle() { if (false) { assertExprThrows("[Time].[1997].[Q4]", "infinite loop"); } else { String s = executeExpr("[Time].[1997].[Q4]"); assertEquals("72,024", s); } } public void testHalfYears() { Util.discard( executeQuery( "WITH MEMBER [Measures].[ProfitPercent] AS\n" + " '([Measures].[Store Sales]-[Measures].[Store Cost])/([Measures].[Store Cost])',\n" + " FORMAT_STRING = '#.00%', SOLVE_ORDER = 1\n" + " MEMBER [Time].[First Half 97] AS '[Time].[1997].[Q1] + [Time].[1997].[Q2]'\n" + " MEMBER [Time].[Second Half 97] AS '[Time].[1997].[Q3] + [Time].[1997].[Q4]'\n" + " SELECT {[Time].[First Half 97],\n" + " [Time].[Second Half 97],\n" + " [Time].[1997].CHILDREN} ON COLUMNS,\n" + " {[Store].[Store Country].[USA].CHILDREN} ON ROWS\n" + " FROM [Sales]\n" + " WHERE ([Measures].[ProfitPercent])")); } public void _testHalfYearsTrickyCase() { Util.discard( executeQuery( "WITH MEMBER MEASURES.ProfitPercent AS\n" + " '([Measures].[Store Sales]-[Measures].[Store Cost])/([Measures].[Store Cost])',\n" + " FORMAT_STRING = '#.00%', SOLVE_ORDER = 1\n" + " MEMBER [Time].[First Half 97] AS '[Time].[1997].[Q1] + [Time].[1997].[Q2]'\n" + " MEMBER [Time].[Second Half 97] AS '[Time].[1997].[Q3] + [Time].[1997].[Q4]'\n" + " SELECT {[Time].[First Half 97],\n" + " [Time].[Second Half 97],\n" + " [Time].[1997].CHILDREN} ON COLUMNS,\n" + " {[Store].[Store Country].[USA].CHILDREN} ON ROWS\n" + " FROM [Sales]\n" + " WHERE (MEASURES.ProfitPercent)")); } public void testAsSample7ButUsingVirtualCube() { Util.discard( executeQuery( "with member [Measures].[Accumulated Sales] as 'Sum(YTD(),[Measures].[Store Sales])'\n" + "select\n" + " {[Measures].[Store Sales],[Measures].[Accumulated Sales]} on columns,\n" + " {Descendants([Time].[1997],[Time].[Month])} on rows\n" + "from [Warehouse and Sales]")); } public void testVirtualCube() { assertQueryReturns( // Note that Unit Sales is independent of Warehouse. "select CrossJoin(\n" + " {[Warehouse].DefaultMember, [Warehouse].[USA].children},\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales], [Measures].[Units Shipped]}) on columns,\n" + " [Time].[Time].children on rows\n" + "from [Warehouse and Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Warehouse].[All Warehouses], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Units Shipped]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 66,291\n" + "Row #0: 139,628.35\n" + "Row #0: 50951.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 8539.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 7994.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 34418.0\n" + "Row #1: 62,610\n" + "Row #1: 132,666.27\n" + "Row #1: 49187.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 15726.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 7575.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 25886.0\n" + "Row #2: 65,848\n" + "Row #2: 140,271.89\n" + "Row #2: 57789.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 20821.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 8673.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 28295.0\n" + "Row #3: 72,024\n" + "Row #3: 152,671.62\n" + "Row #3: 49799.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 15791.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 16666.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 17342.0\n"); } public void testUseDimensionAsShorthandForMember() { Util.discard( executeQuery( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Store], [Store].children} on rows\n" + "from [Sales]")); } public void _testMembersFunction() { Util.discard( executeQuery( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Customers].members(0)} on rows\n" + "from [Sales]")); } public void _testProduct2() { final Axis axis = getTestContext().executeAxis("{[Product2].members}"); System.out.println(TestContext.toString(axis.getPositions())); } private static final List<QueryAndResult> taglibQueries = Arrays.asList( // 0 new QueryAndResult( "select\n" + " {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} on columns,\n" + " CrossJoin(\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] },\n" + " [Product].[All Products].[Drink].children) on rows\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75\n" + "Row #0: 70.40\n" + "Row #0: 168.62\n" + "Row #1: 97\n" + "Row #1: 75.70\n" + "Row #1: 186.03\n" + "Row #2: 54\n" + "Row #2: 36.75\n" + "Row #2: 89.03\n" + "Row #3: 76\n" + "Row #3: 70.99\n" + "Row #3: 182.38\n" + "Row #4: 188\n" + "Row #4: 167.00\n" + "Row #4: 419.14\n" + "Row #5: 68\n" + "Row #5: 45.19\n" + "Row #5: 119.55\n" + "Row #6: 148\n" + "Row #6: 128.97\n" + "Row #6: 316.88\n" + "Row #7: 197\n" + "Row #7: 161.81\n" + "Row #7: 399.58\n" + "Row #8: 85\n" + "Row #8: 54.75\n" + "Row #8: 140.27\n" + "Row #9: 158\n" + "Row #9: 121.14\n" + "Row #9: 294.55\n" + "Row #10: 270\n" + "Row #10: 201.28\n" + "Row #10: 520.55\n" + "Row #11: 84\n" + "Row #11: 50.26\n" + "Row #11: 128.32\n"), // 1 new QueryAndResult( "select\n" + " [Product].[All Products].[Drink].children on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75\n" + "Row #0: 76\n" + "Row #0: 148\n" + "Row #0: 158\n" + "Row #0: 168.62\n" + "Row #0: 182.38\n" + "Row #0: 316.88\n" + "Row #0: 294.55\n" + "Row #1: 97\n" + "Row #1: 188\n" + "Row #1: 197\n" + "Row #1: 270\n" + "Row #1: 186.03\n" + "Row #1: 419.14\n" + "Row #1: 399.58\n" + "Row #1: 520.55\n" + "Row #2: 54\n" + "Row #2: 68\n" + "Row #2: 85\n" + "Row #2: 84\n" + "Row #2: 89.03\n" + "Row #2: 119.55\n" + "Row #2: 140.27\n" + "Row #2: 128.32\n"), // 2 new QueryAndResult( "select\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]} on columns,\n" + " Order([Product].[Product Department].members, [Measures].[Store Sales], DESC) on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "{[Product].[All Products].[Food].[Baking Goods]}\n" + "{[Product].[All Products].[Food].[Dairy]}\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Baked Goods]}\n" + "{[Product].[All Products].[Food].[Snacks]}\n" + "{[Product].[All Products].[Food].[Starchy Foods]}\n" + "{[Product].[All Products].[Food].[Eggs]}\n" + "{[Product].[All Products].[Food].[Breakfast Foods]}\n" + "{[Product].[All Products].[Food].[Seafood]}\n" + "{[Product].[All Products].[Food].[Meat]}\n" + "{[Product].[All Products].[Food].[Canned Products]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Non-Consumable].[Health and Hygiene]}\n" + "{[Product].[All Products].[Non-Consumable].[Periodicals]}\n" + "{[Product].[All Products].[Non-Consumable].[Checkout]}\n" + "{[Product].[All Products].[Non-Consumable].[Carousel]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 37,792\n" + "Row #0: 82,248.42\n" + "Row #1: 30,545\n" + "Row #1: 67,609.82\n" + "Row #2: 26,655\n" + "Row #2: 55,207.50\n" + "Row #3: 19,026\n" + "Row #3: 39,774.34\n" + "Row #4: 20,245\n" + "Row #4: 38,670.41\n" + "Row #5: 12,885\n" + "Row #5: 30,508.85\n" + "Row #6: 12,037\n" + "Row #6: 25,318.93\n" + "Row #7: 7,870\n" + "Row #7: 16,455.43\n" + "Row #8: 6,884\n" + "Row #8: 14,550.05\n" + "Row #9: 5,262\n" + "Row #9: 11,756.07\n" + "Row #10: 4,132\n" + "Row #10: 9,200.76\n" + "Row #11: 3,317\n" + "Row #11: 6,941.46\n" + "Row #12: 1,764\n" + "Row #12: 3,809.14\n" + "Row #13: 1,714\n" + "Row #13: 3,669.89\n" + "Row #14: 1,812\n" + "Row #14: 3,314.52\n" + "Row #15: 27,038\n" + "Row #15: 60,469.89\n" + "Row #16: 16,284\n" + "Row #16: 32,571.86\n" + "Row #17: 4,294\n" + "Row #17: 9,056.76\n" + "Row #18: 1,779\n" + "Row #18: 3,767.71\n" + "Row #19: 841\n" + "Row #19: 1,500.11\n" + "Row #20: 13,573\n" + "Row #20: 27,748.53\n" + "Row #21: 6,838\n" + "Row #21: 14,029.08\n" + "Row #22: 4,186\n" + "Row #22: 7,058.60\n"), // 3 new QueryAndResult( "select\n" + " [Product].[All Products].[Drink].children on columns\n" + "from Sales\n" + "where ([Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997])", "Axis #0:\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997]}\n" + "Axis #1:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 158\n" + "Row #0: 270\n" + "Row #0: 84\n"), // 4 new QueryAndResult( "select\n" + " NON EMPTY CrossJoin([Product].[All Products].[Drink].children, [Customers].[All Customers].[USA].[WA].Children) on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "Row #0: \n" + "Row #0: 2\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 1.14\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 4\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 4\n" + "Row #1: 10.40\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 2.16\n" + "Row #2: \n" + "Row #2: 1\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 2.37\n" + "Row #2: \n" + "Row #2: \n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 24\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 46.09\n" + "Row #3: \n" + "Row #4: 3\n" + "Row #4: \n" + "Row #4: \n" + "Row #4: 8\n" + "Row #4: 2.10\n" + "Row #4: \n" + "Row #4: \n" + "Row #4: 9.63\n" + "Row #5: 6\n" + "Row #5: \n" + "Row #5: \n" + "Row #5: 5\n" + "Row #5: 8.06\n" + "Row #5: \n" + "Row #5: \n" + "Row #5: 6.21\n" + "Row #6: 3\n" + "Row #6: \n" + "Row #6: \n" + "Row #6: 7\n" + "Row #6: 7.80\n" + "Row #6: \n" + "Row #6: \n" + "Row #6: 15.00\n" + "Row #7: 14\n" + "Row #7: \n" + "Row #7: \n" + "Row #7: \n" + "Row #7: 36.10\n" + "Row #7: \n" + "Row #7: \n" + "Row #7: \n" + "Row #8: 3\n" + "Row #8: \n" + "Row #8: \n" + "Row #8: 16\n" + "Row #8: 10.29\n" + "Row #8: \n" + "Row #8: \n" + "Row #8: 32.20\n" + "Row #9: 3\n" + "Row #9: \n" + "Row #9: \n" + "Row #9: \n" + "Row #9: 10.56\n" + "Row #9: \n" + "Row #9: \n" + "Row #9: \n" + "Row #10: \n" + "Row #10: \n" + "Row #10: 15\n" + "Row #10: 11\n" + "Row #10: \n" + "Row #10: \n" + "Row #10: 34.79\n" + "Row #10: 15.67\n" + "Row #11: \n" + "Row #11: \n" + "Row #11: 7\n" + "Row #11: \n" + "Row #11: \n" + "Row #11: \n" + "Row #11: 17.44\n" + "Row #11: \n" + "Row #12: \n" + "Row #12: \n" + "Row #12: 22\n" + "Row #12: 9\n" + "Row #12: \n" + "Row #12: \n" + "Row #12: 32.35\n" + "Row #12: 17.43\n" + "Row #13: 7\n" + "Row #13: \n" + "Row #13: \n" + "Row #13: 4\n" + "Row #13: 4.77\n" + "Row #13: \n" + "Row #13: \n" + "Row #13: 15.16\n" + "Row #14: 4\n" + "Row #14: \n" + "Row #14: \n" + "Row #14: 4\n" + "Row #14: 3.64\n" + "Row #14: \n" + "Row #14: \n" + "Row #14: 9.64\n" + "Row #15: 2\n" + "Row #15: \n" + "Row #15: \n" + "Row #15: 7\n" + "Row #15: 6.86\n" + "Row #15: \n" + "Row #15: \n" + "Row #15: 8.38\n" + "Row #16: \n" + "Row #16: \n" + "Row #16: \n" + "Row #16: 28\n" + "Row #16: \n" + "Row #16: \n" + "Row #16: \n" + "Row #16: 61.98\n" + "Row #17: \n" + "Row #17: \n" + "Row #17: 3\n" + "Row #17: 4\n" + "Row #17: \n" + "Row #17: \n" + "Row #17: 10.56\n" + "Row #17: 8.96\n" + "Row #18: 6\n" + "Row #18: \n" + "Row #18: \n" + "Row #18: 3\n" + "Row #18: 7.16\n" + "Row #18: \n" + "Row #18: \n" + "Row #18: 8.10\n" + "Row #19: 7\n" + "Row #19: \n" + "Row #19: \n" + "Row #19: \n" + "Row #19: 15.63\n" + "Row #19: \n" + "Row #19: \n" + "Row #19: \n" + "Row #20: 3\n" + "Row #20: \n" + "Row #20: \n" + "Row #20: 13\n" + "Row #20: 6.96\n" + "Row #20: \n" + "Row #20: \n" + "Row #20: 12.22\n" + "Row #21: \n" + "Row #21: \n" + "Row #21: 16\n" + "Row #21: \n" + "Row #21: \n" + "Row #21: \n" + "Row #21: 45.08\n" + "Row #21: \n" + "Row #22: 3\n" + "Row #22: \n" + "Row #22: \n" + "Row #22: 18\n" + "Row #22: 6.39\n" + "Row #22: \n" + "Row #22: \n" + "Row #22: 21.08\n" + "Row #23: \n" + "Row #23: \n" + "Row #23: \n" + "Row #23: 21\n" + "Row #23: \n" + "Row #23: \n" + "Row #23: \n" + "Row #23: 33.22\n" + "Row #24: \n" + "Row #24: \n" + "Row #24: \n" + "Row #24: 9\n" + "Row #24: \n" + "Row #24: \n" + "Row #24: \n" + "Row #24: 22.65\n" + "Row #25: 2\n" + "Row #25: \n" + "Row #25: \n" + "Row #25: 9\n" + "Row #25: 6.80\n" + "Row #25: \n" + "Row #25: \n" + "Row #25: 18.90\n" + "Row #26: 3\n" + "Row #26: \n" + "Row #26: \n" + "Row #26: 9\n" + "Row #26: 1.50\n" + "Row #26: \n" + "Row #26: \n" + "Row #26: 23.01\n" + "Row #27: \n" + "Row #27: \n" + "Row #27: \n" + "Row #27: 22\n" + "Row #27: \n" + "Row #27: \n" + "Row #27: \n" + "Row #27: 50.71\n" + "Row #28: 4\n" + "Row #28: \n" + "Row #28: \n" + "Row #28: \n" + "Row #28: 5.16\n" + "Row #28: \n" + "Row #28: \n" + "Row #28: \n" + "Row #29: \n" + "Row #29: \n" + "Row #29: 20\n" + "Row #29: 14\n" + "Row #29: \n" + "Row #29: \n" + "Row #29: 48.02\n" + "Row #29: 28.80\n" + "Row #30: \n" + "Row #30: \n" + "Row #30: 14\n" + "Row #30: \n" + "Row #30: \n" + "Row #30: \n" + "Row #30: 19.96\n" + "Row #30: \n" + "Row #31: \n" + "Row #31: \n" + "Row #31: 10\n" + "Row #31: 40\n" + "Row #31: \n" + "Row #31: \n" + "Row #31: 26.36\n" + "Row #31: 74.49\n" + "Row #32: 6\n" + "Row #32: \n" + "Row #32: \n" + "Row #32: \n" + "Row #32: 17.01\n" + "Row #32: \n" + "Row #32: \n" + "Row #32: \n" + "Row #33: 4\n" + "Row #33: \n" + "Row #33: \n" + "Row #33: \n" + "Row #33: 2.80\n" + "Row #33: \n" + "Row #33: \n" + "Row #33: \n" + "Row #34: 4\n" + "Row #34: \n" + "Row #34: \n" + "Row #34: \n" + "Row #34: 7.98\n" + "Row #34: \n" + "Row #34: \n" + "Row #34: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: 46\n" + "Row #35: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: 81.71\n" + "Row #36: \n" + "Row #36: \n" + "Row #36: 21\n" + "Row #36: 6\n" + "Row #36: \n" + "Row #36: \n" + "Row #36: 37.93\n" + "Row #36: 14.73\n" + "Row #37: \n" + "Row #37: \n" + "Row #37: 3\n" + "Row #37: \n" + "Row #37: \n" + "Row #37: \n" + "Row #37: 7.92\n" + "Row #37: \n" + "Row #38: 25\n" + "Row #38: \n" + "Row #38: \n" + "Row #38: 3\n" + "Row #38: 51.65\n" + "Row #38: \n" + "Row #38: \n" + "Row #38: 2.34\n" + "Row #39: 3\n" + "Row #39: \n" + "Row #39: \n" + "Row #39: 4\n" + "Row #39: 4.47\n" + "Row #39: \n" + "Row #39: \n" + "Row #39: 9.20\n" + "Row #40: \n" + "Row #40: 1\n" + "Row #40: \n" + "Row #40: \n" + "Row #40: \n" + "Row #40: 1.47\n" + "Row #40: \n" + "Row #40: \n" + "Row #41: \n" + "Row #41: \n" + "Row #41: 15\n" + "Row #41: \n" + "Row #41: \n" + "Row #41: \n" + "Row #41: 18.88\n" + "Row #41: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: 3\n" + "Row #42: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: 3.75\n" + "Row #43: 9\n" + "Row #43: \n" + "Row #43: \n" + "Row #43: 10\n" + "Row #43: 31.41\n" + "Row #43: \n" + "Row #43: \n" + "Row #43: 15.12\n" + "Row #44: 3\n" + "Row #44: \n" + "Row #44: \n" + "Row #44: 3\n" + "Row #44: 7.41\n" + "Row #44: \n" + "Row #44: \n" + "Row #44: 2.55\n" + "Row #45: 3\n" + "Row #45: \n" + "Row #45: \n" + "Row #45: \n" + "Row #45: 1.71\n" + "Row #45: \n" + "Row #45: \n" + "Row #45: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: 7\n" + "Row #46: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: 11.86\n" + "Row #47: \n" + "Row #47: \n" + "Row #47: \n" + "Row #47: 3\n" + "Row #47: \n" + "Row #47: \n" + "Row #47: \n" + "Row #47: 2.76\n" + "Row #48: \n" + "Row #48: \n" + "Row #48: 4\n" + "Row #48: 5\n" + "Row #48: \n" + "Row #48: \n" + "Row #48: 4.50\n" + "Row #48: 7.27\n" + "Row #49: \n" + "Row #49: \n" + "Row #49: 7\n" + "Row #49: \n" + "Row #49: \n" + "Row #49: \n" + "Row #49: 10.01\n" + "Row #49: \n" + "Row #50: \n" + "Row #50: \n" + "Row #50: 5\n" + "Row #50: 4\n" + "Row #50: \n" + "Row #50: \n" + "Row #50: 12.88\n" + "Row #50: 5.28\n" + "Row #51: 2\n" + "Row #51: \n" + "Row #51: \n" + "Row #51: \n" + "Row #51: 2.64\n" + "Row #51: \n" + "Row #51: \n" + "Row #51: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: 5\n" + "Row #52: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: 12.34\n" + "Row #53: \n" + "Row #53: \n" + "Row #53: \n" + "Row #53: 5\n" + "Row #53: \n" + "Row #53: \n" + "Row #53: \n" + "Row #53: 3.41\n" + "Row #54: \n" + "Row #54: \n" + "Row #54: \n" + "Row #54: 4\n" + "Row #54: \n" + "Row #54: \n" + "Row #54: \n" + "Row #54: 2.44\n" + "Row #55: \n" + "Row #55: \n" + "Row #55: 2\n" + "Row #55: \n" + "Row #55: \n" + "Row #55: \n" + "Row #55: 6.92\n" + "Row #55: \n" + "Row #56: 13\n" + "Row #56: \n" + "Row #56: \n" + "Row #56: 7\n" + "Row #56: 23.69\n" + "Row #56: \n" + "Row #56: \n" + "Row #56: 7.07\n"), // 5 new QueryAndResult( "select from Sales\n" + "where ([Measures].[Store Sales], [Time].[1997], [Promotion Media].[All Media].[TV])", "Axis #0:\n" + "{[Measures].[Store Sales], [Time].[1997], [Promotion Media].[All Media].[TV]}\n" + "7,786.21")); public void testTaglib0() { assertQueryReturns( taglibQueries.get(0).query, taglibQueries.get(0).result); } public void testTaglib1() { assertQueryReturns( taglibQueries.get(1).query, taglibQueries.get(1).result); } public void testTaglib2() { assertQueryReturns( taglibQueries.get(2).query, taglibQueries.get(2).result); } public void testTaglib3() { assertQueryReturns( taglibQueries.get(3).query, taglibQueries.get(3).result); } public void testTaglib4() { assertQueryReturns( taglibQueries.get(4).query, taglibQueries.get(4).result); } public void testTaglib5() { assertQueryReturns( taglibQueries.get(5).query, taglibQueries.get(5).result); } public void testCellValue() { Result result = executeQuery( "select {[Measures].[Unit Sales],[Measures].[Store Sales]} on columns,\n" + " {[Gender].[M]} on rows\n" + "from Sales"); Cell cell = result.getCell(new int[]{0, 0}); Object value = cell.getValue(); assertTrue(value instanceof Number); assertEquals(135215, ((Number) value).intValue()); cell = result.getCell(new int[]{1, 0}); value = cell.getValue(); assertTrue(value instanceof Number); // Plato give 285011.12, Oracle gives 285011, MySQL gives 285964 (bug!) assertEquals(285011, ((Number) value).intValue()); } public void testDynamicFormat() { assertQueryReturns( "with member [Measures].[USales] as [Measures].[Unit Sales],\n" + " format_string = iif([Measures].[Unit Sales] > 50000, \"\\<b\\>#.00\\<\\/b\\>\", \"\\<i\\>#.00\\<\\/i\\>\")\n" + "select \n" + " {[Measures].[USales]} on columns,\n" + " {[Store Type].members} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[USales]}\n" + "Axis #2:\n" + "{[Store Type].[All Store Types]}\n" + "{[Store Type].[All Store Types].[Deluxe Supermarket]}\n" + "{[Store Type].[All Store Types].[Gourmet Supermarket]}\n" + "{[Store Type].[All Store Types].[HeadQuarters]}\n" + "{[Store Type].[All Store Types].[Mid-Size Grocery]}\n" + "{[Store Type].[All Store Types].[Small Grocery]}\n" + "{[Store Type].[All Store Types].[Supermarket]}\n" + "Row #0: <b>266773.00</b>\n" + "Row #1: <b>76837.00</b>\n" + "Row #2: <i>21333.00</i>\n" + "Row #3: \n" + "Row #4: <i>11491.00</i>\n" + "Row #5: <i>6557.00</i>\n" + "Row #6: <b>150555.00</b>\n"); } public void testFormatOfNulls() { assertQueryReturns( "with member [Measures].[Foo] as '([Measures].[Store Sales])',\n" + " format_string = '$#,##0.00;($#,##0.00);ZERO;NULL;Nil'\n" + "select\n" + " {[Measures].[Foo]} on columns,\n" + " {[Customers].[Country].members} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Foo]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[Canada]}\n" + "{[Customers].[All Customers].[Mexico]}\n" + "{[Customers].[All Customers].[USA]}\n" + "Row #0: NULL\n" + "Row #1: NULL\n" + "Row #2: $565,238.13\n"); } /** * If a measure (in this case, <code>[Measures].[Sales Count]</code>) * occurs only within a format expression, bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-14">MONDRIAN-14</a>. * causes an internal * error ("value not found") when the cell's formatted value is retrieved. */ public void testBugMondrian14() { assertQueryReturns( "with member [Measures].[USales] as '[Measures].[Unit Sales]',\n" + " format_string = iif([Measures].[Sales Count] > 30, \"#.00 good\",\"#.00 bad\")\n" + "select {[Measures].[USales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns,\n" + " Crossjoin({[Promotion Media].[All Media].[Radio], [Promotion Media].[All Media].[TV], [Promotion Media]. [All Media].[Sunday Paper], [Promotion Media].[All Media].[Street Handout]}, [Product].[All Products].[Drink].Children) ON rows\n" + "from [Sales] where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[USales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75.00 bad\n" + "Row #0: 70.40\n" + "Row #0: 168.62\n" + "Row #1: 97.00 good\n" + "Row #1: 75.70\n" + "Row #1: 186.03\n" + "Row #2: 54.00 bad\n" + "Row #2: 36.75\n" + "Row #2: 89.03\n" + "Row #3: 76.00 bad\n" + "Row #3: 70.99\n" + "Row #3: 182.38\n" + "Row #4: 188.00 good\n" + "Row #4: 167.00\n" + "Row #4: 419.14\n" + "Row #5: 68.00 bad\n" + "Row #5: 45.19\n" + "Row #5: 119.55\n" + "Row #6: 148.00 good\n" + "Row #6: 128.97\n" + "Row #6: 316.88\n" + "Row #7: 197.00 good\n" + "Row #7: 161.81\n" + "Row #7: 399.58\n" + "Row #8: 85.00 bad\n" + "Row #8: 54.75\n" + "Row #8: 140.27\n" + "Row #9: 158.00 good\n" + "Row #9: 121.14\n" + "Row #9: 294.55\n" + "Row #10: 270.00 good\n" + "Row #10: 201.28\n" + "Row #10: 520.55\n" + "Row #11: 84.00 bad\n" + "Row #11: 50.26\n" + "Row #11: 128.32\n"); } /** * This bug causes all of the format strings to be the same, because the * required expression [Measures].[Unit Sales] is not in the cache; bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-34">MONDRIAN-34</a>. */ public void testBugMondrian34() { assertQueryReturns( "with member [Measures].[xxx] as '[Measures].[Store Sales]',\n" + " format_string = IIf([Measures].[Unit Sales] > 100000, \"AAA######.00\",\"BBB###.00\")\n" + "select {[Measures].[xxx]} ON columns,\n" + " {[Product].[All Products].children} ON rows\n" + "from [Sales] where [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[xxx]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "Row #0: BBB48836.21\n" + "Row #1: AAA409035.59\n" + "Row #2: BBB107366.33\n"); } /** * Tuple as slicer causes {@link ClassCastException}; bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-36">MONDRIAN-36</a>. */ public void testBugMondrian36() { assertQueryReturns( "select {[Measures].[Unit Sales]} ON columns,\n" + " {[Gender].Children} ON rows\n" + "from [Sales]\n" + "where ([Time].[1997], [Customers])", "Axis #0:\n" + "{[Time].[1997], [Customers].[All Customers]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n"); } /** * Query with distinct-count measure and no other measures gives * {@link ArrayIndexOutOfBoundsException}; * <a href="http://jira.pentaho.com/browse/MONDRIAN-46">MONDRIAN-46</a>. */ public void testBugMondrian46() { getConnection().getCacheControl(null).flushSchemaCache(); assertQueryReturns( "select {[Measures].[Customer Count]} ON columns,\n" + " {([Promotion Media].[All Media], [Product].[All Products])} ON rows\n" + "from [Sales]\n" + "where [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Customer Count]}\n" + "Axis #2:\n" + "{[Promotion Media].[All Media], [Product].[All Products]}\n" + "Row #0: 5,581\n"); } /** Make sure that the "Store" cube is working. */ public void testStoreCube() { assertQueryReturns( "select {[Measures].members} on columns,\n" + " {[Store Type].members} on rows\n" + "from [Store]" + "where [Store].[USA].[CA]", "Axis #0:\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "Axis #1:\n" + "{[Measures].[Store Sqft]}\n" + "{[Measures].[Grocery Sqft]}\n" + "Axis #2:\n" + "{[Store Type].[All Store Types]}\n" + "{[Store Type].[All Store Types].[Deluxe Supermarket]}\n" + "{[Store Type].[All Store Types].[Gourmet Supermarket]}\n" + "{[Store Type].[All Store Types].[HeadQuarters]}\n" + "{[Store Type].[All Store Types].[Mid-Size Grocery]}\n" + "{[Store Type].[All Store Types].[Small Grocery]}\n" + "{[Store Type].[All Store Types].[Supermarket]}\n" + "Row #0: 69,764\n" + "Row #0: 44,868\n" + "Row #1: \n" + "Row #1: \n" + "Row #2: 23,688\n" + "Row #2: 15,337\n" + "Row #3: \n" + "Row #3: \n" + "Row #4: \n" + "Row #4: \n" + "Row #5: 22,478\n" + "Row #5: 15,321\n" + "Row #6: 23,598\n" + "Row #6: 14,210\n"); } public void testSchemaLevelTableIsBad() { // todo: <Level table="nonexistentTable"> } public void testSchemaLevelTableInAnotherHierarchy() { // todo: // <Cube> // <Hierarchy name="h1"><Table name="t1"/></Hierarchy> // <Hierarchy name="h2"> // <Table name="t2"/> // <Level tableName="t1"/> // </Hierarchy> // </Cube> } public void testSchemaLevelWithViewSpecifiesTable() { // todo: // <Hierarchy> // <View><SQL dialect="generic">select * from emp</SQL></View> // <Level tableName="emp"/> // </hierarchy> // Should get error that tablename is not allowed } public void testSchemaLevelOrdinalInOtherTable() { // todo: // Hierarchy is based upon a join. // Level's name expression is in a different table than its ordinal. } public void testSchemaTopLevelNotUnique() { // todo: // Should get error if the top level of a hierarchy does not have // uniqueNames="true" } /** * Bug 645744 happens when getting the children of a member crosses a table * boundary. The symptom */ public void testBug645744() { // minimal test case assertQueryReturns( "select {[Measures].[Unit Sales]} ON columns,\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].children} ON rows\n" + "from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Excellent]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Fabulous]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Skinner]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Token]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Washington]}\n" + "Row #0: 468\n" + "Row #1: 469\n" + "Row #2: 506\n" + "Row #3: 466\n" + "Row #4: 560\n"); // shorter test case executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns," + "ToggleDrillState({" + "([Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks])" + "}, {[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks]}) ON rows " + "from [Sales] where ([Time].[1997])"); } /** * The bug happened when a cell which was in cache was compared with a cell * which was not in cache. The compare method could not deal with the * {@link RuntimeException} which indicates that the cell is not in cache. */ public void testBug636687() { executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost],[Measures].[Store Sales]} ON columns, " + "Order(" + "{([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Beverages]), " + "Crossjoin({[Store].[All Stores].[USA].[CA].Children}, {[Product].[All Products].[Drink].[Beverages]}), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Dairy])}, " + "[Measures].[Store Cost], BDESC) ON rows " + "from [Sales] " + "where ([Time].[1997])"); executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns, " + "Order(" + "{([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[CA].[San Diego], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA].[Los Angeles], [Product].[All Products].[Drink].[Beverages]), " + "Crossjoin({[Store].[All Stores].[USA].[CA].[Los Angeles]}, {[Product].[All Products].[Drink].[Beverages].Children}), " + "([Store].[All Stores].[USA].[CA].[Beverly Hills], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[CA].[San Francisco], [Product].[All Products].[Drink].[Beverages])}, " + "[Measures].[Store Cost], BDESC) ON rows " + "from [Sales] " + "where ([Time].[1997])"); } /** * Bug 769114: Internal error ("not found") when executing * Order(TopCount). */ public void testBug769114() { assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns,\n" + " Order(TopCount({[Product].[Product Category].Members}, 10.0, [Measures].[Unit Sales]), [Measures].[Store Sales], ASC) ON rows\n" + "from [Sales]\n" + "where [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread]}\n" + "{[Product].[All Products].[Food].[Deli].[Meat]}\n" + "{[Product].[All Products].[Food].[Dairy].[Dairy]}\n" + "{[Product].[All Products].[Food].[Baking Goods].[Baking Goods]}\n" + "{[Product].[All Products].[Food].[Baking Goods].[Jams and Jellies]}\n" + "{[Product].[All Products].[Food].[Canned Foods].[Canned Soup]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Vegetables]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Produce].[Fruit]}\n" + "{[Product].[All Products].[Food].[Produce].[Vegetables]}\n" + "Row #0: 7,870\n" + "Row #0: 6,564.09\n" + "Row #0: 16,455.43\n" + "Row #1: 9,433\n" + "Row #1: 8,215.81\n" + "Row #1: 20,616.29\n" + "Row #2: 12,885\n" + "Row #2: 12,228.85\n" + "Row #2: 30,508.85\n" + "Row #3: 8,357\n" + "Row #3: 6,123.32\n" + "Row #3: 15,446.69\n" + "Row #4: 11,888\n" + "Row #4: 9,247.29\n" + "Row #4: 23,223.72\n" + "Row #5: 8,006\n" + "Row #5: 6,408.29\n" + "Row #5: 15,966.10\n" + "Row #6: 6,984\n" + "Row #6: 5,885.05\n" + "Row #6: 14,769.82\n" + "Row #7: 30,545\n" + "Row #7: 26,963.34\n" + "Row #7: 67,609.82\n" + "Row #8: 11,767\n" + "Row #8: 10,312.77\n" + "Row #8: 25,816.13\n" + "Row #9: 20,739\n" + "Row #9: 18,048.81\n" + "Row #9: 45,185.41\n"); } /** * Bug 793616: Deeply nested UNION function takes forever to validate. * (Problem was that each argument of a function was validated twice, hence * the validation time was <code>O(2 ^ depth)</code>.) */ public void _testBug793616() { if (props.TestExpDependencies.get() > 0) { // Don't run this test if dependency-checking is enabled. // Dependency checking will hugely slow down evaluation, and give // the false impression that the validation performance bug has // returned. return; } final long start = System.currentTimeMillis(); Connection connection = getTestContext().getFoodMartConnection(); final String queryString = "select {[Measures].[Unit Sales],\n" + " [Measures].[Store Cost],\n" + " [Measures].[Store Sales]} ON columns,\n" + "Hierarchize(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union\n" + "({([Gender].[All Gender],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers],\n" + " [Product].[All Products])},\n" + " Crossjoin ([Gender].[All Gender].Children,\n" + " {([Marital Status].[All Marital Status],\n" + " [Customers].[All Customers],\n" + " [Product].[All Products])})),\n" + " Crossjoin(Crossjoin({[Gender].[All Gender].[F]},\n" + " [Marital Status].[All Marital Status].Children),\n" + " {([Customers].[All Customers],\n" + " [Product].[All Products])})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[M])},\n" + " [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[M])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin(\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[S])}, [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status])},\n" + " [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children))) ON rows from [Sales] where [Time].[1997]"; Query query = connection.parseQuery(queryString); // If this call took longer than 10 seconds, the performance bug has // probably resurfaced again. final long afterParseMillis = System.currentTimeMillis(); final long afterParseNonDbMillis = afterParseMillis - Util.dbTimeMillis(); final long parseMillis = afterParseMillis - start; assertTrue( "performance problem: parse took " + parseMillis + " milliseconds", parseMillis <= 10000); Result result = connection.execute(query); assertEquals(59, result.getAxes()[1].getPositions().size()); // If this call took longer than 10 seconds, // or 2 seconds exclusing db access, // the performance bug has // probably resurfaced again. final long afterExecMillis = System.currentTimeMillis(); final long afterExecNonDbMillis = afterExecMillis - Util.dbTimeMillis(); final long execNonDbMillis = afterExecNonDbMillis - afterParseNonDbMillis; final long execMillis = (afterExecMillis - afterParseMillis); assertTrue( "performance problem: execute took " + execMillis + " milliseconds, " + execNonDbMillis + " milliseconds excluding db", execNonDbMillis <= 2000 && execMillis <= 30000); } public void testCatalogHierarchyBasedOnView() { // Don't run this test if aggregates are enabled: two levels mapped to // the "gender" column confuse the agg engine. if (props.ReadAggregates.get()) { return; } TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<Dimension name=\"Gender2\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\" primaryKey=\"customer_id\">\n" + " <View alias=\"gender2\">\n" + " <SQL dialect=\"generic\">\n" + " <![CDATA[SELECT * FROM customer]]>\n" + " </SQL>\n" + " <SQL dialect=\"oracle\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"derby\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"luciddb\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"db2\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"netezza\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " </View>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>", null); if (!testContext.getDialect().allowsFromQuery()) { return; } testContext.assertAxisReturns( "[Gender2].members", "[Gender2].[All Gender]\n" + "[Gender2].[All Gender].[F]\n" + "[Gender2].[All Gender].[M]"); } /** * Run a query against a large hierarchy, to make sure that we can generate * joins correctly. This probably won't work in MySQL. */ public void testCatalogHierarchyBasedOnView2() { // Don't run this test if aggregates are enabled: two levels mapped to // the "gender" column confuse the agg engine. if (props.ReadAggregates.get()) { return; } if (getTestContext().getDialect().allowsFromQuery()) { return; } TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<Dimension name=\"ProductView\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\" primaryKeyTable=\"productView\">\n" + " <View alias=\"productView\">\n" + " <SQL dialect=\"db2\"><![CDATA[\n" + "SELECT *\n" + "FROM \"product\", \"product_class\"\n" + "WHERE \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\"\n" + "]]>\n" + " </SQL>\n" + " <SQL dialect=\"mssql\"><![CDATA[\n" + "SELECT \"product\".\"product_id\",\n" + "\"product\".\"brand_name\",\n" + "\"product\".\"product_name\",\n" + "\"product\".\"SKU\",\n" + "\"product\".\"SRP\",\n" + "\"product\".\"gross_weight\",\n" + "\"product\".\"net_weight\",\n" + "\"product\".\"recyclable_package\",\n" + "\"product\".\"low_fat\",\n" + "\"product\".\"units_per_case\",\n" + "\"product\".\"cases_per_pallet\",\n" + "\"product\".\"shelf_width\",\n" + "\"product\".\"shelf_height\",\n" + "\"product\".\"shelf_depth\",\n" + "\"product_class\".\"product_class_id\",\n" + "\"product_class\".\"product_subcategory\",\n" + "\"product_class\".\"product_category\",\n" + "\"product_class\".\"product_department\",\n" + "\"product_class\".\"product_family\"\n" + "FROM \"product\" inner join \"product_class\"\n" + "ON \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\"\n" + "]]>\n" + " </SQL>\n" + " <SQL dialect=\"mysql\"><![CDATA[\n" + "SELECT `product`.`product_id`,\n" + "`product`.`brand_name`,\n" + "`product`.`product_name`,\n" + "`product`.`SKU`,\n" + "`product`.`SRP`,\n" + "`product`.`gross_weight`,\n" + "`product`.`net_weight`,\n" + "`product`.`recyclable_package`,\n" + "`product`.`low_fat`,\n" + "`product`.`units_per_case`,\n" + "`product`.`cases_per_pallet`,\n" + "`product`.`shelf_width`,\n" + "`product`.`shelf_height`,\n" + "`product`.`shelf_depth`,\n" + "`product_class`.`product_class_id`,\n" + "`product_class`.`product_family`,\n" + "`product_class`.`product_department`,\n" + "`product_class`.`product_category`,\n" + "`product_class`.`product_subcategory` \n" + "FROM `product`, `product_class`\n" + "WHERE `product`.`product_class_id` = `product_class`.`product_class_id`\n" + "]]>\n" + " </SQL>\n" + " <SQL dialect=\"generic\"><![CDATA[\n" + "SELECT *\n" + "FROM \"product\", \"product_class\"\n" + "WHERE \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\"\n" + "]]>\n" + " </SQL>\n" + " </View>\n" + " <Level name=\"Product Family\" column=\"product_family\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Product Department\" column=\"product_department\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Category\" column=\"product_category\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Subcategory\" column=\"product_subcategory\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Brand Name\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" column=\"product_name\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>"); testContext.assertQueryReturns( "select {[Measures].[Unit Sales]} on columns,\n" + " {[ProductView].[Drink].[Beverages].children} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Carbonated Beverages]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Drinks]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Hot Beverages]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Pure Juice Beverages]}\n" + "Row #0: 3,407\n" + "Row #1: 2,469\n" + "Row #2: 4,301\n" + "Row #3: 3,396\n"); } public void testCountDistinct() { assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on columns,\n" + " {[Gender].members} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #0: 5,581\n" + "Row #1: 131,558\n" + "Row #1: 2,755\n" + "Row #2: 135,215\n" + "Row #2: 2,826\n"); } /** * Turn off aggregate caching and run query with both use of aggregate * tables on and off - should result in the same answer. * Note that if the "mondrian.rolap.aggregates.Read" property is not true, * then no aggregate tables is be read in any event. */ public void testCountDistinctAgg() { boolean use_agg_orig = props.UseAggregates.get(); boolean do_caching_orig = props.DisableCaching.get(); // turn off caching props.DisableCaching.setString("true"); assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on rows,\n" + "NON EMPTY {[Time].[1997].[Q1].[1]} ON COLUMNS\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997].[Q1].[1]}\n" + "Axis #2:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Row #0: 21,628\n" + "Row #1: 1,396\n"); if (use_agg_orig) { props.UseAggregates.setString("false"); } else { props.UseAggregates.setString("true"); } assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on rows,\n" + "NON EMPTY {[Time].[1997].[Q1].[1]} ON COLUMNS\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997].[Q1].[1]}\n" + "Axis #2:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Row #0: 21,628\n" + "Row #1: 1,396\n"); if (use_agg_orig) { props.UseAggregates.setString("true"); } else { props.UseAggregates.setString("false"); } if (do_caching_orig) { props.DisableCaching.setString("true"); } else { props.DisableCaching.setString("false"); } } /** * * There are cross database order issues in this test. * * MySQL and Access show the rows as: * * [Store Size in SQFT].[All Store Size in SQFTs] * [Store Size in SQFT].[All Store Size in SQFTs].[null] * [Store Size in SQFT].[All Store Size in SQFTs].[<each distinct store * size>] * * Postgres shows: * * [Store Size in SQFT].[All Store Size in SQFTs] * [Store Size in SQFT].[All Store Size in SQFTs].[<each distinct store * size>] * [Store Size in SQFT].[All Store Size in SQFTs].[null] * * The test failure is due to some inherent differences in the way * Postgres orders NULLs in a result set, * compared with MySQL and Access. * * From the MySQL 4.X manual: * * When doing an ORDER BY, NULL values are presented first if you do * ORDER BY ... ASC and last if you do ORDER BY ... DESC. * * From the Postgres 8.0 manual: * * The null value sorts higher than any other value. In other words, * with ascending sort order, null values sort at the end, and with * descending sort order, null values sort at the beginning. * * Oracle also sorts nulls high by default. * * So, this test has expected results that vary depending on whether * the database is being used sorts nulls high or low. * */ public void testMemberWithNullKey() { if (!isDefaultNullMemberRepresentation()) { return; } Result result = executeQuery( "select {[Measures].[Unit Sales]} on columns,\n" + "{[Store Size in SQFT].members} on rows\n" + "from Sales"); String resultString = TestContext.toString(result); resultString = Pattern.compile("\\.0\\]").matcher(resultString).replaceAll("]"); // The members function hierarchizes its results, so nulls should // sort high, regardless of DBMS. Note that Oracle's driver says that // NULLs sort low, but it's lying. final boolean nullsSortHigh = false; int row = 0; final String expected = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store Size in SQFT].[All Store Size in SQFTs]}\n" // null is at the start in order under DBMSs that sort null low + (!nullsSortHigh ? "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" : "") + "{[Store Size in SQFT].[All Store Size in SQFTs].[20319]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[21215]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[22478]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23112]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23593]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23598]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23688]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23759]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[24597]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[27694]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[28206]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30268]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30584]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30797]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[33858]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[34452]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[34791]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[36509]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[38382]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[39696]}\n" // null is at the end in order for DBMSs that sort nulls high + (nullsSortHigh ? "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" : "") + "Row #" + row++ + ": 266,773\n" + (!nullsSortHigh ? "Row #" + row++ + ": 39,329\n" : "") + "Row #" + row++ + ": 26,079\n" + "Row #" + row++ + ": 25,011\n" + "Row #" + row++ + ": 2,117\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 25,663\n" + "Row #" + row++ + ": 21,333\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 41,580\n" + "Row #" + row++ + ": 2,237\n" + "Row #" + row++ + ": 23,591\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 35,257\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 24,576\n" + (nullsSortHigh ? "Row #" + row++ + ": 39,329\n" : ""); TestContext.assertEqualsVerbose(expected, resultString); } /** * Slicer contains <code>[Promotion Media].[Daily Paper]</code>, but * filter expression is in terms of <code>[Promotion Media].[Radio]</code>. */ public void testSlicerOverride() { assertQueryReturns( "with member [Measures].[Radio Unit Sales] as \n" + " '([Measures].[Unit Sales], [Promotion Media].[Radio])'\n" + "select {[Measures].[Unit Sales], [Measures].[Radio Unit Sales]} on columns,\n" + " filter([Product].[Product Department].members, [Promotion Media].[Radio] > 50) on rows\n" + "from Sales\n" + "where ([Promotion Media].[Daily Paper], [Time].[1997].[Q1])", "Axis #0:\n" + "{[Promotion Media].[All Media].[Daily Paper], [Time].[1997].[Q1]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Radio Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "Row #0: 692\n" + "Row #0: 87\n" + "Row #1: 447\n" + "Row #1: 63\n"); } public void testMembersOfLargeDimensionTheHardWay() { // Avoid this test if memory is scarce. if (Bug.avoidMemoryOverflow(TestContext.instance().getDialect())) { return; } final Connection connection = TestContext.instance().getFoodMartConnection(); String queryString = "select {[Measures].[Unit Sales]} on columns,\n" + "{[Customers].members} on rows\n" + "from Sales"; Query query = connection.parseQuery(queryString); Result result = connection.execute(query); assertEquals(10407, result.getAxes()[1].getPositions().size()); } public void testUnparse() { Connection connection = getConnection(); Query query = connection.parseQuery( "with member [Measures].[Rendite] as \n" + " '(([Measures].[Store Sales] - [Measures].[Store Cost])) / [Measures].[Store Cost]',\n" + " format_string = iif(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost] * 100 > \n" + " Parameter (\"UpperLimit\", NUMERIC, 151, \"Obere Grenze\"), \n" + " \"|#.00%|arrow='up'\",\n" + " iif(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost] * 100 < \n" + " Parameter(\"LowerLimit\", NUMERIC, 150, \"Untere Grenze\"),\n" + " \"|#.00%|arrow='down'\",\n" + " \"|#.00%|arrow='right'\"))\n" + "select {[Measures].members} on columns\n" + "from Sales"); final String s = Util.unparse(query); // Parentheses are added to reflect operator precedence, but that's ok. // Note that the doubled parentheses in line #2 of the query have been // reduced to a single level. TestContext.assertEqualsVerbose( "with member [Measures].[Rendite] as '(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost])', " + "format_string = IIf((((([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost]) * 100.0) > Parameter(\"UpperLimit\", NUMERIC, 151.0, \"Obere Grenze\")), " + "\"|#.00%|arrow='up'\", " + "IIf((((([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost]) * 100.0) < Parameter(\"LowerLimit\", NUMERIC, 150.0, \"Untere Grenze\")), " + "\"|#.00%|arrow='down'\", \"|#.00%|arrow='right'\"))\n" + "select {[Measures].Members} ON COLUMNS\n" + "from [Sales]\n", s); } public void testUnparse2() { Connection connection = getConnection(); Query query = connection.parseQuery( "with member [Measures].[Foo] as '1', " + "format_string='##0.00', " + "funny=IIf(1=1,\"x\"\"y\",\"foo\") " + "select {[Measures].[Foo]} on columns from Sales"); final String s = query.toString(); // The "format_string" property, a string literal, is now delimited by // double-quotes. This won't work in MSOLAP, but for Mondrian it's // consistent with the fact that property values are expressions, // not enclosed in single-quotes. TestContext.assertEqualsVerbose( "with member [Measures].[Foo] as '1.0', " + "format_string = \"##0.00\", " + "funny = IIf((1.0 = 1.0), \"x\"\"y\", \"foo\")\n" + "select {[Measures].[Foo]} ON COLUMNS\n" + "from [Sales]\n", s); } /** * Basically, the LookupCube function can evaluate a single MDX statement * against a cube other than the cube currently indicated by query context * to retrieve a single string or numeric result. * * <p>For example, the Budget cube in the FoodMart 2000 database contains * budget information that can be displayed by store. The Sales cube in the * FoodMart 2000 database contains sales information that can be displayed * by store. Since no virtual cube exists in the FoodMart 2000 database that * joins the Sales and Budget cubes together, comparing the two sets of * figures would be difficult at best. * * <p><b>Note<b> In many situations a virtual cube can be used to integrate * data from multiple cubes, which will often provide a simpler and more * efficient solution than the LookupCube function. This example uses the * LookupCube function for purposes of illustration. * * <p>The following MDX query, however, uses the LookupCube function to * retrieve unit sales information for each store from the Sales cube, * presenting it side by side with the budget information from the Budget * cube. */ public void _testLookupCube() { assertQueryReturns( "WITH MEMBER Measures.[Store Unit Sales] AS \n" + " 'LookupCube(\"Sales\", \"(\" + MemberToStr(Store.CurrentMember) + \", Measures.[Unit Sales])\")'\n" + "SELECT\n" + " {Measures.Amount, Measures.[Store Unit Sales]} ON COLUMNS,\n" + " Store.CA.CHILDREN ON ROWS\n" + "FROM Budget", ""); } /** * <p>Basket analysis is a topic better suited to data mining discussions, * but some basic forms of basket analysis can be handled through the use of * MDX queries. * * <p>For example, one method of basket analysis groups customers based on * qualification. In the following example, a qualified customer is one who * has more than $10,000 in store sales or more than 10 unit sales. The * following table illustrates such a report, run against the Sales cube in * FoodMart 2000 with qualified customers grouped by the Country and State * Province levels of the Customers dimension. The count and store sales * total of qualified customers is represented by the Qualified Count and * Qualified Sales columns, respectively. * * <p>To accomplish this basic form of basket analysis, the following MDX * query constructs two calculated members. The first calculated member uses * the MDX Count, Filter, and Descendants functions to create the Qualified * Count column, while the second calculated member uses the MDX Sum, * Filter, and Descendants functions to create the Qualified Sales column. * * <p>The key to this MDX query is the use of Filter and Descendants * together to screen out non-qualified customers. Once screened out, the * Sum and Count MDX functions can then be used to provide aggregation data * only on qualified customers. */ public void testBasketAnalysis() { assertQueryReturns( "WITH MEMBER [Measures].[Qualified Count] AS\n" + " 'COUNT(FILTER(DESCENDANTS(Customers.CURRENTMEMBER, [Customers].[Name]),\n" + " ([Measures].[Store Sales]) > 10000 OR ([Measures].[Unit Sales]) > 10))'\n" + "MEMBER [Measures].[Qualified Sales] AS\n" + " 'SUM(FILTER(DESCENDANTS(Customers.CURRENTMEMBER, [Customers].[Name]),\n" + " ([Measures].[Store Sales]) > 10000 OR ([Measures].[Unit Sales]) > 10),\n" + " ([Measures].[Store Sales]))'\n" + "SELECT {[Measures].[Qualified Count], [Measures].[Qualified Sales]} ON COLUMNS,\n" + " DESCENDANTS([Customers].[All Customers], [State Province], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Qualified Count]}\n" + "{[Measures].[Qualified Sales]}\n" + "Axis #2:\n" + "{[Customers].[All Customers]}\n" + "{[Customers].[All Customers].[Canada]}\n" + "{[Customers].[All Customers].[Canada].[BC]}\n" + "{[Customers].[All Customers].[Mexico]}\n" + "{[Customers].[All Customers].[Mexico].[DF]}\n" + "{[Customers].[All Customers].[Mexico].[Guerrero]}\n" + "{[Customers].[All Customers].[Mexico].[Jalisco]}\n" + "{[Customers].[All Customers].[Mexico].[Mexico]}\n" + "{[Customers].[All Customers].[Mexico].[Oaxaca]}\n" + "{[Customers].[All Customers].[Mexico].[Sinaloa]}\n" + "{[Customers].[All Customers].[Mexico].[Veracruz]}\n" + "{[Customers].[All Customers].[Mexico].[Yucatan]}\n" + "{[Customers].[All Customers].[Mexico].[Zacatecas]}\n" + "{[Customers].[All Customers].[USA]}\n" + "{[Customers].[All Customers].[USA].[CA]}\n" + "{[Customers].[All Customers].[USA].[OR]}\n" + "{[Customers].[All Customers].[USA].[WA]}\n" + "Row #0: 4,719.00\n" + "Row #0: 553,587.77\n" + "Row #1: .00\n" + "Row #1: \n" + "Row #2: .00\n" + "Row #2: \n" + "Row #3: .00\n" + "Row #3: \n" + "Row #4: .00\n" + "Row #4: \n" + "Row #5: .00\n" + "Row #5: \n" + "Row #6: .00\n" + "Row #6: \n" + "Row #7: .00\n" + "Row #7: \n" + "Row #8: .00\n" + "Row #8: \n" + "Row #9: .00\n" + "Row #9: \n" + "Row #10: .00\n" + "Row #10: \n" + "Row #11: .00\n" + "Row #11: \n" + "Row #12: .00\n" + "Row #12: \n" + "Row #13: 4,719.00\n" + "Row #13: 553,587.77\n" + "Row #14: 2,149.00\n" + "Row #14: 151,509.69\n" + "Row #15: 1,008.00\n" + "Row #15: 141,899.84\n" + "Row #16: 1,562.00\n" + "Row #16: 260,178.24\n"); } /** * Flushes the cache then runs {@link #testBasketAnalysis}, because this * test has been known to fail when run standalone. */ public void testBasketAnalysisAfterFlush() { getConnection().getCacheControl(null).flushSchemaCache(); testBasketAnalysis(); } /** * <b>How Can I Perform Complex String Comparisons?</b> * * <p>MDX can handle basic string comparisons, but does not include complex * string comparison and manipulation functions, for example, for finding * substrings in strings or for supporting case-insensitive string * comparisons. However, since MDX can take advantage of external function * libraries, this question is easily resolved using string manipulation * and comparison functions from the Microsoft Visual Basic for * Applications (VBA) external function library. * * <p>For example, you want to report the unit sales of all fruit-based * products -- not only the sales of fruit, but canned fruit, fruit snacks, * fruit juices, and so on. By using the LCase and InStr VBA functions, the * following results are easily accomplished in a single MDX query, without * complex set construction or explicit member names within the query. * * <p>The following MDX query demonstrates how to achieve the results * displayed in the previous table. For each member in the Product * dimension, the name of the member is converted to lowercase using the * LCase VBA function. Then, the InStr VBA function is used to discover * whether or not the name contains the word "fruit". This information is * used to then construct a set, using the Filter MDX function, from only * those members from the Product dimension that contain the substring * "fruit" in their names. */ public void testStringComparisons() { assertQueryReturns( "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " FILTER([Product].[Product Name].MEMBERS,\n" + " INSTR(LCASE([Product].CURRENTMEMBER.NAME), \"fruit\") <> 0) ON ROWS \n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Applause].[Applause Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Big City].[Big City Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Green Ribbon].[Green Ribbon Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Swell].[Swell Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Toucan].[Toucan Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Best Choice].[Best Choice Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Best Choice].[Best Choice Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Best Choice].[Best Choice Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Best Choice].[Best Choice Strawberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Strawberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fort West].[Fort West Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fort West].[Fort West Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fort West].[Fort West Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fort West].[Fort West Strawberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Horatio].[Horatio Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Horatio].[Horatio Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Horatio].[Horatio Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Horatio].[Horatio Strawberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Nationeel].[Nationeel Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Nationeel].[Nationeel Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Nationeel].[Nationeel Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Nationeel].[Nationeel Strawberry Fruit Roll]}\n" + "Row #0: 205\n" + "Row #1: 204\n" + "Row #2: 142\n" + "Row #3: 204\n" + "Row #4: 187\n" + "Row #5: 174\n" + "Row #6: 114\n" + "Row #7: 110\n" + "Row #8: 150\n" + "Row #9: 149\n" + "Row #10: 173\n" + "Row #11: 163\n" + "Row #12: 154\n" + "Row #13: 181\n" + "Row #14: 178\n" + "Row #15: 210\n" + "Row #16: 189\n" + "Row #17: 177\n" + "Row #18: 191\n" + "Row #19: 149\n" + "Row #20: 169\n" + "Row #21: 185\n" + "Row #22: 216\n" + "Row #23: 167\n" + "Row #24: 138\n"); } /** * Test case for * <a href="http://jira.pentaho.com/browse/MONDRIAN-539">MONDRIAN-539, * "Problem with the MID function getting last character in a string."</a>. */ public void testMid() { assertQueryReturns( "with\n" + "member measures.x as 'Mid(\"yahoo\",5, 1)'\n" + "select {measures.x} ON COLUMNS from [Sales] ", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[x]}\n" + "Row #0: o\n"); } /** * <b>How Can I Show Percentages as Measures?</b> * * <p>Another common business question easily answered through MDX is the * display of percent values created as available measures. * * <p>For example, the Sales cube in the FoodMart 2000 database contains * unit sales for each store in a given city, state, and country, organized * along the Sales dimension. A report is requested to show, for * California, the percentage of total unit sales attained by each city * with a store. The results are illustrated in the following table. * * <p>Because the parent of a member is typically another, aggregated * member in a regular dimension, this is easily achieved by the * construction of a calculated member, as demonstrated in the following MDX * query, using the CurrentMember and Parent MDX functions. */ public void testPercentagesAsMeasures() { assertQueryReturns( // todo: "Store.[USA].[CA]" should be "Store.CA" "WITH MEMBER Measures.[Unit Sales Percent] AS\n" + " '((Store.CURRENTMEMBER, Measures.[Unit Sales]) /\n" + " (Store.CURRENTMEMBER.PARENT, Measures.[Unit Sales])) ',\n" + " FORMAT_STRING = 'Percent'\n" + "SELECT {Measures.[Unit Sales], Measures.[Unit Sales Percent]} ON COLUMNS,\n" + " ORDER(DESCENDANTS(Store.[USA].[CA], Store.[Store City], SELF), \n" + " [Measures].[Unit Sales], ASC) ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Unit Sales Percent]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 2,117\n" + "Row #1: 2.83%\n" + "Row #2: 21,333\n" + "Row #2: 28.54%\n" + "Row #3: 25,635\n" + "Row #3: 34.30%\n" + "Row #4: 25,663\n" + "Row #4: 34.33%\n"); } /** * <b>How Can I Show Cumulative Sums as Measures?</b> * * <p>Another common business request, cumulative sums, is useful for * business reporting purposes. However, since aggregations are handled in a * hierarchical fashion, cumulative sums present some unique challenges in * Analysis Services. * * <p>The best way to create a cumulative sum is as a calculated measure in * MDX, using the Rank, Head, Order, and Sum MDX functions together. * * <p>For example, the following table illustrates a report that shows two * views of employee count in all stores and cities in California, sorted * by employee count. The first column shows the aggregated counts for each * store and city, while the second column shows aggregated counts for each * store, but cumulative counts for each city. * * <p>The cumulative number of employees for San Diego represents the value * of both Los Angeles and San Diego, the value for Beverly Hills represents * the cumulative total of Los Angeles, San Diego, and Beverly Hills, and so * on. * * <p>Since the members within the state of California have been ordered * from highest to lowest number of employees, this form of cumulative sum * measure provides a form of pareto analysis within each state. * * <p>To support this, the Order function is first used to reorder members * accordingly for both the Rank and Head functions. Once reordered, the * Rank function is used to supply the ranking of each tuple within the * reordered set of members, progressing as each member in the Store * dimension is examined. The value is then used to determine the number of * tuples to retrieve from the set of reordered members using the Head * function. Finally, the retrieved members are then added together using * the Sum function to obtain a cumulative sum. The following MDX query * demonstrates how all of this works in concert to provide cumulative * sums. * * <p>As an aside, a named set cannot be used in this situation to replace * the duplicate Order function calls. Named sets are evaluated once, when * a query is parsed -- since the set can change based on the fact that the * set can be different for each store member because the set is evaluated * for the children of multiple parents, the set does not change with * respect to its use in the Sum function. Since the named set is only * evaluated once, it would not satisfy the needs of this query. */ public void _testCumlativeSums() { assertQueryReturns( // todo: "[Store].[USA].[CA]" should be "Store.CA"; implement "AS" "WITH MEMBER Measures.[Cumulative No of Employees] AS\n" + " 'SUM(HEAD(ORDER({[Store].Siblings}, [Measures].[Number of Employees], BDESC) AS OrderedSiblings,\n" + " RANK([Store], OrderedSiblings)),\n" + " [Measures].[Number of Employees])'\n" + "SELECT {[Measures].[Number of Employees], [Measures].[Cumulative No of Employees]} ON COLUMNS,\n" + " ORDER(DESCENDANTS([Store].[USA].[CA], [Store State], AFTER), \n" + " [Measures].[Number of Employees], BDESC) ON ROWS\n" + "FROM HR", ""); } /** * <b>How Can I Implement a Logical AND or OR Condition in a WHERE * Clause?</b> * * <p>For SQL users, the use of AND and OR logical operators in the WHERE * clause of a SQL statement is an essential tool for constructing business * queries. However, the WHERE clause of an MDX statement serves a * slightly different purpose, and understanding how the WHERE clause is * used in MDX can assist in constructing such business queries. * * <p>The WHERE clause in MDX is used to further restrict the results of * an MDX query, in effect providing another dimension on which the results * of the query are further sliced. As such, only expressions that resolve * to a single tuple are allowed. The WHERE clause implicitly supports a * logical AND operation involving members across different dimensions, by * including the members as part of a tuple. To support logical AND * operations involving members within a single dimensions, as well as * logical OR operations, a calculated member needs to be defined in * addition to the use of the WHERE clause. * * <p>For example, the following MDX query illustrates the use of a * calculated member to support a logical OR. The query returns unit sales * by quarter and year for all food and drink related products sold in 1997, * run against the Sales cube in the FoodMart 2000 database. * * <p>The calculated member simply adds the values of the Unit Sales * measure for the Food and the Drink levels of the Product dimension * together. The WHERE clause is then used to restrict return of * information only to the calculated member, effectively implementing a * logical OR to return information for all time periods that contain unit * sales values for either food, drink, or both types of products. * * <p>You can use the Aggregate function in similar situations where all * measures are not aggregated by summing. To return the same results in the * above example using the Aggregate function, replace the definition for * the calculated member with this definition: * * <blockquote> * <code>'Aggregate({[Product].[Food], [Product].[Drink]})'</code> * </blockquote> */ public void testLogicalOps() { assertQueryReturns( "WITH MEMBER [Product].[Food OR Drink] AS\n" + " '([Product].[Food], Measures.[Unit Sales]) + ([Product].[Drink], Measures.[Unit Sales])'\n" + "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " DESCENDANTS(Time.[1997], [Quarter], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales\n" + "WHERE [Product].[Food OR Drink]", "Axis #0:\n" + "{[Product].[Food OR Drink]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997]}\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 216,537\n" + "Row #1: 53,785\n" + "Row #2: 50,720\n" + "Row #3: 53,505\n" + "Row #4: 58,527\n"); } /** * <p>A logical AND, by contrast, can be supported by using two different * techniques. If the members used to construct the logical AND reside on * different dimensions, all that is required is a WHERE clause that uses * a tuple representing all involved members. The following MDX query uses a * WHERE clause that effectively restricts the query to retrieve unit * sales for drink products in the USA, shown by quarter and year for 1997. */ public void testLogicalAnd() { assertQueryReturns( "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " DESCENDANTS([Time].[1997], [Quarter], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales\n" + "WHERE ([Product].[Drink], [Store].USA)", "Axis #0:\n" + "{[Product].[All Products].[Drink], [Store].[All Stores].[USA]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997]}\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 24,597\n" + "Row #1: 5,976\n" + "Row #2: 5,895\n" + "Row #3: 6,065\n" + "Row #4: 6,661\n"); } /** * <p>The WHERE clause in the previous MDX query effectively provides a * logical AND operator, in which all unit sales for 1997 are returned only * for drink products and only for those sold in stores in the USA. * * <p>If the members used to construct the logical AND condition reside on * the same dimension, you can use a calculated member or a named set to * filter out the unwanted members, as demonstrated in the following MDX * query. * * <p>The named set, [Good AND Pearl Stores], restricts the displayed unit * sales totals only to those stores that have sold both Good products and * Pearl products. */ public void _testSet() { assertQueryReturns( "WITH SET [Good AND Pearl Stores] AS\n" + " 'FILTER(Store.Members,\n" + " ([Product].[Good], Measures.[Unit Sales]) > 0 AND \n" + " ([Product].[Pearl], Measures.[Unit Sales]) > 0)'\n" + "SELECT DESCENDANTS([Time].[1997], [Quarter], SELF_AND_BEFORE) ON COLUMNS,\n" + " [Good AND Pearl Stores] ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Can I Use Custom Member Properties in MDX?</b> * * <p>Member properties are a good way of adding secondary business * information to members in a dimension. However, getting that information * out can be confusing -- member properties are not readily apparent in a * typical MDX query. * * <p>Member properties can be retrieved in one of two ways. The easiest * and most used method of retrieving member properties is to use the * DIMENSION PROPERTIES MDX statement when constructing an axis in an MDX * query. * * <p>For example, a member property in the Store dimension in the FoodMart * 2000 database details the total square feet for each store. The following * MDX query can retrieve this member property as part of the returned * cellset. */ public void testCustomMemberProperties() { assertQueryReturns( "SELECT {[Measures].[Units Shipped], [Measures].[Units Ordered]} ON COLUMNS,\n" + " NON EMPTY [Store].[Store Name].MEMBERS\n" + " DIMENSION PROPERTIES [Store].[Store Name].[Store Sqft] ON ROWS\n" + "FROM Warehouse", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Units Shipped]}\n" + "{[Measures].[Units Ordered]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Row #0: 10759.0\n" + "Row #0: 11699.0\n" + "Row #1: 24587.0\n" + "Row #1: 26463.0\n" + "Row #2: 23835.0\n" + "Row #2: 26270.0\n" + "Row #3: 1696.0\n" + "Row #3: 1875.0\n" + "Row #4: 8515.0\n" + "Row #4: 9109.0\n" + "Row #5: 32393.0\n" + "Row #5: 35797.0\n" + "Row #6: 2348.0\n" + "Row #6: 2454.0\n" + "Row #7: 22734.0\n" + "Row #7: 24610.0\n" + "Row #8: 24110.0\n" + "Row #8: 26703.0\n" + "Row #9: 11889.0\n" + "Row #9: 12828.0\n" + "Row #10: 32411.0\n" + "Row #10: 35930.0\n" + "Row #11: 1860.0\n" + "Row #11: 2074.0\n" + "Row #12: 10589.0\n" + "Row #12: 11426.0\n"); } /** * <p>The drawback to using the DIMENSION PROPERTIES statement is that, * for most client applications, the member property is not readily * apparent. If the previous MDX query is executed in the MDX sample * application shipped with SQL Server 2000 Analysis Services, for example, * you must double-click the name of the member in the grid to open the * Member Properties dialog box, which displays all of the member properties * shipped as part of the cellset, including the [Store].[Store Name].[Store * Sqft] member property. * * <p>The other method of retrieving member properties involves the creation * of a calculated member based on the member property. The following MDX * query brings back the total square feet for each store as a measure, * included in the COLUMNS axis. * * <p>The [Store SqFt] measure is constructed with the Properties MDX * function to retrieve the [Store SQFT] member property for each member in * the Store dimension. The benefit to this technique is that the calculated * member is readily apparent and easily accessible in client applications * that do not support member properties. */ public void _testMemberPropertyAsCalcMember() { assertQueryReturns( // todo: implement <member>.PROPERTIES "WITH MEMBER Measures.[Store SqFt] AS '[Store].CURRENTMEMBER.PROPERTIES(\"Store SQFT\")'\n" + "SELECT { [Measures].[Store SQFT], [Measures].[Units Shipped], [Measures].[Units Ordered] } ON COLUMNS,\n" + " [Store].[Store Name].MEMBERS ON ROWS\n" + "FROM Warehouse", ""); } /** * <b>How Can I Drill Down More Than One Level Deep, or Skip Levels When * Drilling Down?</b> * * <p>Drilling down is an essential ability for most OLAP products, and * Analysis Services is no exception. Several functions exist that support * drilling up and down the hierarchy of dimensions within a cube. * Typically, drilling up and down the hierarchy is done one level at a * time; think of this functionality as a zoom feature for OLAP data. * * <p>There are times, though, when the need to drill down more than one * level at the same time, or even skip levels when displaying information * about multiple levels, exists for a business scenario. * * <p>For example, you would like to show report results from a query of * the Sales cube in the FoodMart 2000 sample database showing sales totals * for individual cities and the subtotals for each country, as shown in the * following table. * * <p>The Customers dimension, however, has Country, State Province, and * City levels. In order to show the above report, you would have to show * the Country level and then drill down two levels to show the City * level, skipping the State Province level entirely. * * <p>However, the MDX ToggleDrillState and DrillDownMember functions * provide drill down functionality only one level below a specified set. To * drill down more than one level below a specified set, you need to use a * combination of MDX functions, including Descendants, Generate, and * Except. This technique essentially constructs a large set that includes * all levels between both upper and lower desired levels, then uses a * smaller set representing the undesired level or levels to remove the * appropriate members from the larger set. * * <p>The MDX Descendants function is used to construct a set consisting of * the descendants of each member in the Customers dimension. The * descendants are determined using the MDX Descendants function, with the * descendants of the City level and the level above, the State Province * level, for each member of the Customers dimension being added to the * set. * * <p>The MDX Generate function now creates a set consisting of all members * at the Country level as well as the members of the set generated by the * MDX Descendants function. Then, the MDX Except function is used to * exclude all members at the State Province level, so the returned set * contains members at the Country and City levels. * * <p>Note, however, that the previous MDX query will still order the * members according to their hierarchy. Although the returned set contains * members at the Country and City levels, the Country, State Province, * and City levels determine the order of the members. */ public void _testDrillingDownMoreThanOneLevel() { assertQueryReturns( // todo: implement "GENERATE" "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " EXCEPT(GENERATE([Customers].[Country].MEMBERS,\n" + " {DESCENDANTS([Customers].CURRENTMEMBER, [Customers].[City], SELF_AND_BEFORE)}),\n" + " {[Customers].[State Province].MEMBERS}) ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Do I Get the Topmost Members of a Level Broken Out by an Ancestor * Level?</b> * * <p>This type of MDX query is common when only the facts for the lowest * level of a dimension within a cube are needed, but information about * other levels within the same dimension may also be required to satisfy a * specific business scenario. * * <p>For example, a report that shows the unit sales for the store with * the highest unit sales from each country is needed for marketing * purposes. The following table provides an example of this report, run * against the Sales cube in the FoodMart 2000 sample database. * * <p>This looks simple enough, but the Country Name column provides * unexpected difficulty. The values for the Store Country column are taken * from the Store Country level of the Store dimension, so the Store * Country column is constructed as a calculated member as part of the MDX * query, using the MDX Ancestor and Name functions to return the country * names for each store. * * <p>A combination of the MDX Generate, TopCount, and Descendants * functions are used to create a set containing the top stores in unit * sales for each country. */ public void _testTopmost() { assertQueryReturns( // todo: implement "GENERATE" "WITH MEMBER Measures.[Country Name] AS \n" + " 'Ancestor(Store.CurrentMember, [Store Country]).Name'\n" + "SELECT {Measures.[Country Name], Measures.[Unit Sales]} ON COLUMNS,\n" + " GENERATE([Store Country].MEMBERS, \n" + " TOPCOUNT(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]),\n" + " 1, [Measures].[Unit Sales])) ON ROWS\n" + "FROM Sales", ""); } /** * <p>The MDX Descendants function is used to construct a set consisting of * only those members at the Store Name level in the Store dimension. Then, * the MDX TopCount function is used to return only the topmost store based * on the Unit Sales measure. The MDX Generate function then constructs a * set based on the topmost stores, following the hierarchy of the Store * dimension. * * <p>Alternate techniques, such as using the MDX Crossjoin function, may * not provide the desired results because non-related joins can occur. * Since the Store Country and Store Name levels are within the same * dimension, they cannot be cross-joined. Another dimension that provides * the same regional hierarchy structure, such as the Customers dimension, * can be employed with the Crossjoin function. But, using this technique * can cause non-related joins and return unexpected results. * * <p>For example, the following MDX query uses the Crossjoin function to * attempt to return the same desired results. * * <p>However, some unexpected surprises occur because the topmost member * in the Store dimension is cross-joined with all of the children of the * Customers dimension, as shown in the following table. * * <p>In this instance, the use of a calculated member to provide store * country names is easier to understand and debug than attempting to * cross-join across unrelated members */ public void testTopmost2() { assertQueryReturns( "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " CROSSJOIN(Customers.CHILDREN,\n" + " TOPCOUNT(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]),\n" + " 1, [Measures].[Unit Sales])) ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[Canada], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Customers].[All Customers].[Mexico], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Customers].[All Customers].[USA], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "Row #0: \n" + "Row #1: \n" + "Row #2: 41,580\n"); } /** * <b>How Can I Rank or Reorder Members?</b> * * <p>One of the issues commonly encountered in business scenarios is the * need to rank the members of a dimension according to their corresponding * measure values. The Order MDX function allows you to order a set based on * a string or numeric expression evaluated against the members of a set. * Combined with other MDX functions, the Order function can support * several different types of ranking. * * <p>For example, the Sales cube in the FoodMart 2000 database can be used * to show unit sales for each store. However, the business scenario * requires a report that ranks the stores from highest to lowest unit * sales, individually, of nonconsumable products. * * <p>Because of the requirement that stores be sorted individually, the * hierarchy must be broken (in other words, ignored) for the purpose of * ranking the stores. The Order function is capable of sorting within the * hierarchy, based on the topmost level represented in the set to be * sorted, or, by breaking the hierarchy, sorting all of the members of the * set as if they existed on the same level, with the same parent. * * <p>The following MDX query illustrates the use of the Order function to * rank the members according to unit sales. */ public void testRank() { assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS, \n" + " ORDER([Store].[Store Name].MEMBERS, (Measures.[Unit Sales]), BDESC) ON ROWS\n" + "FROM Sales\n" + "WHERE [Product].[Non-Consumable]", "Axis #0:\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[Canada].[BC].[Vancouver].[Store 19]}\n" + "{[Store].[All Stores].[Canada].[BC].[Victoria].[Store 20]}\n" + "{[Store].[All Stores].[Mexico].[DF].[Mexico City].[Store 9]}\n" + "{[Store].[All Stores].[Mexico].[DF].[San Andres].[Store 21]}\n" + "{[Store].[All Stores].[Mexico].[Guerrero].[Acapulco].[Store 1]}\n" + "{[Store].[All Stores].[Mexico].[Jalisco].[Guadalajara].[Store 5]}\n" + "{[Store].[All Stores].[Mexico].[Veracruz].[Orizaba].[Store 10]}\n" + "{[Store].[All Stores].[Mexico].[Yucatan].[Merida].[Store 8]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Camacho].[Store 4]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Hidalgo].[Store 12]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Hidalgo].[Store 18]}\n" + "{[Store].[All Stores].[USA].[CA].[Alameda].[HQ]}\n" + "Row #0: 7,940\n" + "Row #1: 6,712\n" + "Row #2: 5,076\n" + "Row #3: 4,947\n" + "Row #4: 4,706\n" + "Row #5: 4,639\n" + "Row #6: 4,479\n" + "Row #7: 4,428\n" + "Row #8: 3,950\n" + "Row #9: 2,140\n" + "Row #10: 442\n" + "Row #11: 390\n" + "Row #12: 387\n" + "Row #13: \n" + "Row #14: \n" + "Row #15: \n" + "Row #16: \n" + "Row #17: \n" + "Row #18: \n" + "Row #19: \n" + "Row #20: \n" + "Row #21: \n" + "Row #22: \n" + "Row #23: \n" + "Row #24: \n"); } /** * <b>How Can I Use Different Calculations for Different Levels in a * Dimension?</b> * * <p>This type of MDX query frequently occurs when different aggregations * are needed at different levels in a dimension. One easy way to support * such functionality is through the use of a calculated measure, created as * part of the query, which uses the MDX Descendants function in conjunction * with one of the MDX aggregation functions to provide results. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * supplies the [Units Ordered] measure, aggregated through the Sum * function. But, you would also like to see the average number of units * ordered per store. The following table demonstrates the desired results. * * <p>By using the following MDX query, the desired results can be * achieved. The calculated measure, [Average Units Ordered], supplies the * average number of ordered units per store by using the Avg, * CurrentMember, and Descendants MDX functions. */ public void testDifferentCalculationsForDifferentLevels() { assertQueryReturns( "WITH MEMBER Measures.[Average Units Ordered] AS\n" + " 'AVG(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]), [Measures].[Units Ordered])',\n" + " FORMAT_STRING='#.00'\n" + "SELECT {[Measures].[Units ordered], Measures.[Average Units Ordered]} ON COLUMNS,\n" + " [Store].[Store State].MEMBERS ON ROWS\n" + "FROM Warehouse", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Units Ordered]}\n" + "{[Measures].[Average Units Ordered]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[Canada].[BC]}\n" + "{[Store].[All Stores].[Mexico].[DF]}\n" + "{[Store].[All Stores].[Mexico].[Guerrero]}\n" + "{[Store].[All Stores].[Mexico].[Jalisco]}\n" + "{[Store].[All Stores].[Mexico].[Veracruz]}\n" + "{[Store].[All Stores].[Mexico].[Yucatan]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas]}\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[OR]}\n" + "{[Store].[All Stores].[USA].[WA]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: \n" + "Row #1: \n" + "Row #2: \n" + "Row #2: \n" + "Row #3: \n" + "Row #3: \n" + "Row #4: \n" + "Row #4: \n" + "Row #5: \n" + "Row #5: \n" + "Row #6: \n" + "Row #6: \n" + "Row #7: 66307.0\n" + "Row #7: 16576.75\n" + "Row #8: 44906.0\n" + "Row #8: 22453.00\n" + "Row #9: 116025.0\n" + "Row #9: 16575.00\n"); } /** * <p>This calculated measure is more powerful than it seems; if, for * example, you then want to see the average number of units ordered for * beer products in all of the stores in the California area, the following * MDX query can be executed with the same calculated measure. */ public void testDifferentCalculations2() { assertQueryReturns( // todo: "[Store].[USA].[CA]" should be "[Store].CA", // "[Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer]" // should be "[Product].[Beer]" "WITH MEMBER Measures.[Average Units Ordered] AS\n" + " 'AVG(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]), [Measures].[Units Ordered])'\n" + "SELECT {[Measures].[Units ordered], Measures.[Average Units Ordered]} ON COLUMNS,\n" + " [Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].CHILDREN ON ROWS\n" + "FROM Warehouse\n" + "WHERE [Store].[USA].[CA]", "Axis #0:\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "Axis #1:\n" + "{[Measures].[Units Ordered]}\n" + "{[Measures].[Average Units Ordered]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Good]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Pearl]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Top Measure]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Walrus]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 151.0\n" + "Row #1: 75.5\n" + "Row #2: 95.0\n" + "Row #2: 95.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #4: 211.0\n" + "Row #4: 105.5\n"); } /** * <b>How Can I Use Different Calculations for Different Dimensions?</b> * * <p>Each measure in a cube uses the same aggregation function across all * dimensions. However, there are times where a different aggregation * function may be needed to represent a measure for reporting purposes. Two * basic cases involve aggregating a single dimension using a different * aggregation function than the one used for other dimensions.<ul> * * <li>Aggregating minimums, maximums, or averages along a time * dimension</li> * * <li>Aggregating opening and closing period values along a time * dimension</li></ul> * * <p>The first case involves some knowledge of the behavior of the time * dimension specified in the cube. For instance, to create a calculated * measure that contains the average, along a time dimension, of measures * aggregated as sums along other dimensions, the average of the aggregated * measures must be taken over the set of averaging time periods, * constructed through the use of the Descendants MDX function. Minimum and * maximum values are more easily calculated through the use of the Min and * Max MDX functions, also combined with the Descendants function. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * contains information on ordered and shipped inventory; from it, a report * is requested to show the average number of units shipped, by product, to * each store. Information on units shipped is added on a monthly basis, so * the aggregated measure [Units Shipped] is divided by the count of * descendants, at the Month level, of the current member in the Time * dimension. This calculation provides a measure representing the average * number of units shipped per month, as demonstrated in the following MDX * query. */ public void _testDifferentCalculationsForDifferentDimensions() { assertQueryReturns( // todo: implement "NONEMPTYCROSSJOIN" "WITH MEMBER [Measures].[Avg Units Shipped] AS\n" + " '[Measures].[Units Shipped] / \n" + " COUNT(DESCENDANTS([Time].CURRENTMEMBER, [Time].[Month], SELF))'\n" + "SELECT {Measures.[Units Shipped], Measures.[Avg Units Shipped]} ON COLUMNS,\n" + "NONEMPTYCROSSJOIN(Store.CA.Children, Product.MEMBERS) ON ROWS\n" + "FROM Warehouse", ""); } /** * <p>The second case is easier to resolve, because MDX provides the * OpeningPeriod and ClosingPeriod MDX functions specifically to support * opening and closing period values. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * contains information on ordered and shipped inventory; from it, a report * is requested to show on-hand inventory at the end of every month. Because * the inventory on hand should equal ordered inventory minus shipped * inventory, the ClosingPeriod MDX function can be used to create a * calculated measure to supply the value of inventory on hand, as * demonstrated in the following MDX query. */ public void _testDifferentCalculationsForDifferentDimensions2() { assertQueryReturns( "WITH MEMBER Measures.[Closing Balance] AS\n" + " '([Measures].[Units Ordered], \n" + " CLOSINGPERIOD([Time].[Month], [Time].CURRENTMEMBER)) -\n" + " ([Measures].[Units Shipped], \n" + " CLOSINGPERIOD([Time].[Month], [Time].CURRENTMEMBER))'\n" + "SELECT {[Measures].[Closing Balance]} ON COLUMNS,\n" + " Product.MEMBERS ON ROWS\n" + "FROM Warehouse", ""); } /** * <b>How Can I Use Date Ranges in MDX?</b> * * <p>Date ranges are a frequently encountered problem. Business questions * use ranges of dates, but OLAP objects provide aggregated information in * date levels. * * <p>Using the technique described here, you can establish date ranges in * MDX queries at the level of granularity provided by a time dimension. * Date ranges cannot be established below the granularity of the dimension * without additional information. For example, if the lowest level of a * time dimension represents months, you will not be able to establish a * two-week date range without other information. Member properties can be * added to supply specific dates for members; using such member properties, * you can take advantage of the date and time functions provided by VBA and * Excel external function libraries to establish date ranges. * * <p>The easiest way to specify a static date range is by using the colon * (:) operator. This operator creates a naturally ordered set, using the * members specified on either side of the operator as the endpoints for the * ordered set. For example, to specify the first six months of 1998 from * the Time dimension in FoodMart 2000, the MDX syntax would resemble: * * <blockquote><pre>[Time].[1998].[1]:[Time].[1998].[6]</pre></blockquote> * * <p>For example, the Sales cube uses a time dimension that supports Year, * Quarter, and Month levels. To add a six-month and nine-month total, two * calculated members are created in the following MDX query. */ public void _testDateRange() { assertQueryReturns( // todo: implement "AddCalculatedMembers" "WITH MEMBER [Time].[1997].[Six Month] AS\n" + " 'SUM([Time].[1]:[Time].[6])'\n" + "MEMBER [Time].[1997].[Nine Month] AS\n" + " 'SUM([Time].[1]:[Time].[9])'\n" + "SELECT AddCalculatedMembers([Time].[1997].Children) ON COLUMNS,\n" + " [Product].Children ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Can I Use Rolling Date Ranges in MDX?</b> * * <p>There are several techniques that can be used in MDX to support * rolling date ranges. All of these techniques tend to fall into two * groups. The first group involves the use of relative hierarchical * functions to construct named sets or calculated members, and the second * group involves the use of absolute date functions from external function * libraries to construct named sets or calculated members. Both groups are * applicable in different business scenarios. * * <p>In the first group of techniques, typically a named set is * constructed which contains a number of periods from a time dimension. For * example, the following table illustrates a 12-month rolling period, in * which the figures for unit sales of the previous 12 months are shown. * * <p>The following MDX query accomplishes this by using a number of MDX * functions, including LastPeriods, Tail, Filter, Members, and Item, to * construct a named set containing only those members across all other * dimensions that share data with the time dimension at the Month level. * The example assumes that there is at least one measure, such as [Unit * Sales], with a value greater than zero in the current period. The Filter * function creates a set of months with unit sales greater than zero, while * the Tail function returns the last month in this set, the current month. * The LastPeriods function, finally, is then used to retrieve the last 12 * periods at this level, including the current period. */ public void _testRolling() { assertQueryReturns( "WITH SET Rolling12 AS\n" + " 'LASTPERIODS(12, TAIL(FILTER([Time].[Month].MEMBERS, \n" + " ([Customers].[All Customers], \n" + " [Education Level].[All Education Level],\n" + " [Gender].[All Gender],\n" + " [Marital Status].[All Marital Status],\n" + " [Product].[All Products], \n" + " [Promotion Media].[All Media],\n" + " [Promotions].[All Promotions],\n" + " [Store].[All Stores],\n" + " [Store Size in SQFT].[All Store Size in SQFT],\n" + " [Store Type].[All Store Type],\n" + " [Yearly Income].[All Yearly Income],\n" + " Measures.[Unit Sales]) >0),\n" + " 1).ITEM(0).ITEM(0))'\n" + "SELECT {[Measures].[Unit Sales]} ON COLUMNS, \n" + " Rolling12 ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Can I Use Different Calculations for Different Time Periods?</b> * * <p>A few techniques can be used, depending on the structure of the cube * being queried, to support different calculations for members depending * on the time period. The following example includes the MDX IIf function, * and is easy to use but difficult to maintain. This example works well for * ad hoc queries, but is not the ideal technique for client applications in * a production environment. * * <p>For example, the following table illustrates a standard and dynamic * forecast of warehouse sales, from the Warehouse cube in the FoodMart 2000 * database, for drink products. The standard forecast is double the * warehouse sales of the previous year, while the dynamic forecast varies * from month to month -- the forecast for January is 120 percent of * previous sales, while the forecast for July is 260 percent of previous * sales. * * <p>The most flexible way of handling this type of report is the use of * nested MDX IIf functions to return a multiplier to be used on the members * of the Products dimension, at the Drinks level. The following MDX query * demonstrates this technique. */ public void testDifferentCalcsForDifferentTimePeriods() { assertQueryReturns( // note: "[Product].[Drink Forecast - Standard]" // was "[Drink Forecast - Standard]" "WITH MEMBER [Product].[Drink Forecast - Standard] AS\n" + " '[Product].[All Products].[Drink] * 2'\n" + "MEMBER [Product].[Drink Forecast - Dynamic] AS \n" + " '[Product].[All Products].[Drink] * \n" + " IIF([Time].[Time].CurrentMember.Name = \"1\", 1.2,\n" + " IIF([Time].[Time].CurrentMember.Name = \"2\", 1.3,\n" + " IIF([Time].[Time].CurrentMember.Name = \"3\", 1.4,\n" + " IIF([Time].[Time].CurrentMember.Name = \"4\", 1.6,\n" + " IIF([Time].[Time].CurrentMember.Name = \"5\", 2.1,\n" + " IIF([Time].[Time].CurrentMember.Name = \"6\", 2.4,\n" + " IIF([Time].[Time].CurrentMember.Name = \"7\", 2.6,\n" + " IIF([Time].[Time].CurrentMember.Name = \"8\", 2.3,\n" + " IIF([Time].[Time].CurrentMember.Name = \"9\", 1.9,\n" + " IIF([Time].[Time].CurrentMember.Name = \"10\", 1.5,\n" + " IIF([Time].[Time].CurrentMember.Name = \"11\", 1.4,\n" + " IIF([Time].[Time].CurrentMember.Name = \"12\", 1.2, 1.0))))))))))))'\n" + "SELECT DESCENDANTS(Time.[1997], [Month], SELF) ON COLUMNS, \n" + " {[Product].CHILDREN, [Product].[Drink Forecast - Standard], [Product].[Drink Forecast - Dynamic]} ON ROWS\n" + "FROM Warehouse", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997].[Q1].[1]}\n" + "{[Time].[1997].[Q1].[2]}\n" + "{[Time].[1997].[Q1].[3]}\n" + "{[Time].[1997].[Q2].[4]}\n" + "{[Time].[1997].[Q2].[5]}\n" + "{[Time].[1997].[Q2].[6]}\n" + "{[Time].[1997].[Q3].[7]}\n" + "{[Time].[1997].[Q3].[8]}\n" + "{[Time].[1997].[Q3].[9]}\n" + "{[Time].[1997].[Q4].[10]}\n" + "{[Time].[1997].[Q4].[11]}\n" + "{[Time].[1997].[Q4].[12]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "{[Product].[Drink Forecast - Standard]}\n" + "{[Product].[Drink Forecast - Dynamic]}\n" + "Row #0: 881.847\n" + "Row #0: 579.051\n" + "Row #0: 476.292\n" + "Row #0: 618.722\n" + "Row #0: 778.886\n" + "Row #0: 636.935\n" + "Row #0: 937.842\n" + "Row #0: 767.332\n" + "Row #0: 920.707\n" + "Row #0: 1,007.764\n" + "Row #0: 820.808\n" + "Row #0: 792.167\n" + "Row #1: 8,383.446\n" + "Row #1: 4,851.406\n" + "Row #1: 5,353.188\n" + "Row #1: 6,061.829\n" + "Row #1: 6,039.282\n" + "Row #1: 5,259.242\n" + "Row #1: 6,902.01\n" + "Row #1: 5,790.772\n" + "Row #1: 8,167.053\n" + "Row #1: 6,188.732\n" + "Row #1: 5,344.845\n" + "Row #1: 5,025.744\n" + "Row #2: 2,040.396\n" + "Row #2: 1,269.816\n" + "Row #2: 1,460.686\n" + "Row #2: 1,696.757\n" + "Row #2: 1,397.035\n" + "Row #2: 1,578.136\n" + "Row #2: 1,671.046\n" + "Row #2: 1,609.447\n" + "Row #2: 2,059.617\n" + "Row #2: 1,617.493\n" + "Row #2: 1,909.713\n" + "Row #2: 1,382.364\n" + "Row #3: 1,763.693\n" + "Row #3: 1,158.102\n" + "Row #3: 952.584\n" + "Row #3: 1,237.444\n" + "Row #3: 1,557.773\n" + "Row #3: 1,273.87\n" + "Row #3: 1,875.685\n" + "Row #3: 1,534.665\n" + "Row #3: 1,841.414\n" + "Row #3: 2,015.528\n" + "Row #3: 1,641.615\n" + "Row #3: 1,584.334\n" + "Row #4: 1,058.216\n" + "Row #4: 752.766\n" + "Row #4: 666.809\n" + "Row #4: 989.955\n" + "Row #4: 1,635.661\n" + "Row #4: 1,528.644\n" + "Row #4: 2,438.39\n" + "Row #4: 1,764.865\n" + "Row #4: 1,749.343\n" + "Row #4: 1,511.646\n" + "Row #4: 1,149.13\n" + "Row #4: 950.601\n"); } /** * <p>Other techniques, such as the addition of member properties to the * Time or Product dimensions to support such calculations, are not as * flexible but are much more efficient. The primary drawback to using such * techniques is that the calculations are not easily altered for * speculative analysis purposes. For client applications, however, where * the calculations are static or slowly changing, using a member property * is an excellent way of supplying such functionality to clients while * keeping maintenance of calculation variables at the server level. The * same MDX query, for example, could be rewritten to use a member property * named [Dynamic Forecast Multiplier] as shown in the following MDX query. */ public void _testDc4dtp2() { assertQueryReturns( "WITH MEMBER [Product].[Drink Forecast - Standard] AS\n" + " '[Product].[All Products].[Drink] * 2'\n" + "MEMBER [Product].[Drink Forecast - Dynamic] AS \n" + " '[Product].[All Products].[Drink] * \n" + " [Time].CURRENTMEMBER.PROPERTIES(\"Dynamic Forecast Multiplier\")'\n" + "SELECT DESCENDANTS(Time.[1997], [Month], SELF) ON COLUMNS, \n" + " {[Product].CHILDREN, [Drink Forecast - Standard], [Drink Forecast - Dynamic]} ON ROWS\n" + "FROM Warehouse", ""); } public void _testWarehouseProfit() { assertQueryReturns( "select \n" + "{[Measures].[Warehouse Cost], [Measures].[Warehouse Sales], [Measures].[Warehouse Profit]}\n" + " ON COLUMNS from [Warehouse]", ""); } /** * <b>How Can I Compare Time Periods in MDX?</b> * * <p>To answer such a common business question, MDX provides a number of * functions specifically designed to navigate and aggregate information * across time periods. For example, year-to-date (YTD) totals are directly * supported through the YTD function in MDX. In combination with the MDX * ParallelPeriod function, you can create calculated members to support * direct comparison of totals across time periods. * * <p>For example, the following table represents a comparison of YTD unit * sales between 1997 and 1998, run against the Sales cube in the FoodMart * 2000 database. * * <p>The following MDX query uses three calculated members to illustrate * how to use the YTD and ParallelPeriod functions in combination to compare * time periods. */ public void _testYtdGrowth() { assertQueryReturns( // todo: implement "ParallelPeriod" "WITH MEMBER [Measures].[YTD Unit Sales] AS\n" + " 'COALESCEEMPTY(SUM(YTD(), [Measures].[Unit Sales]), 0)'\n" + "MEMBER [Measures].[Previous YTD Unit Sales] AS\n" + " '(Measures.[YTD Unit Sales], PARALLELPERIOD([Time].[Year]))'\n" + "MEMBER [Measures].[YTD Growth] AS\n" + " '[Measures].[YTD Unit Sales] - ([Measures].[Previous YTD Unit Sales])'\n" + "SELECT {[Time].[1998]} ON COLUMNS,\n" + " {[Measures].[YTD Unit Sales], [Measures].[Previous YTD Unit Sales], [Measures].[YTD Growth]} ON ROWS\n" + "FROM Sales ", ""); } /* * takes quite long */ public void dont_testParallelMutliple() { for (int i = 0; i < 5; i++) { runParallelQueries(1, 1, false); runParallelQueries(3, 2, false); runParallelQueries(4, 6, true); runParallelQueries(6, 10, false); } } public void dont_testParallelNot() { runParallelQueries(1, 1, false); } public void dont_testParallelSomewhat() { runParallelQueries(3, 2, false); } public void dont_testParallelFlushCache() { runParallelQueries(4, 6, true); } public void dont_testParallelVery() { runParallelQueries(6, 10, false); } private void runParallelQueries( final int threadCount, final int iterationCount, final boolean flush) { // 10 minute per query long timeoutMs = (long) threadCount * iterationCount * 600 * 1000; final int[] executeCount = new int[] {0}; final List<QueryAndResult> queries = new ArrayList<QueryAndResult>(); queries.addAll(Arrays.asList(sampleQueries)); queries.addAll(taglibQueries); TestCaseForker threaded = new TestCaseForker( this, timeoutMs, threadCount, new ChooseRunnable() { public void run(int i) { for (int j = 0; j < iterationCount; j++) { int queryIndex = (i * 2 + j) % queries.size(); try { QueryAndResult query = queries.get(queryIndex); assertQueryReturns(query.query, query.result); if (flush && i == 0) { getConnection().getCacheControl(null) .flushSchemaCache(); } synchronized (executeCount) { executeCount[0]++; } } catch (Throwable e) { e.printStackTrace(); throw Util.newInternal( e, "Thread #" + i + " failed while executing query #" + queryIndex); } } } }); threaded.run(); assertEquals( "number of executions", threadCount * iterationCount, executeCount[0]); } /** * Makes sure that the expression <code> * * [Measures].[Unit Sales] / ([Measures].[Unit Sales], [Product].[All * Products]) * * </code> depends on the current member of the Product dimension, although * [Product].[All Products] is referenced from the expression. */ public void testDependsOn() { assertQueryReturns( "with member [Customers].[my] as \n" + " 'Aggregate(Filter([Customers].[City].Members, (([Measures].[Unit Sales] / ([Measures].[Unit Sales], [Product].[All Products])) > 0.1)))' \n" + "select \n" + " {[Measures].[Unit Sales]} ON columns, \n" + " {[Product].[All Products].[Food].[Deli], [Product].[All Products].[Food].[Frozen Foods]} ON rows \n" + "from [Sales] \n" + "where ([Customers].[my], [Time].[1997])\n", "Axis #0:\n" + "{[Customers].[my], [Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "Row #0: 13\n" + "Row #1: 15,111\n"); } /** * Testcase for bug 1755778, "CrossJoin / Filter query returns null row in * result set" * * @throws Exception on error */ public void testFilterWithCrossJoin() throws Exception { String queryWithFilter = "WITH SET [#DataSet#] AS 'Filter(Crossjoin({[Store].[All Stores]}, {[Customers].[All Customers]}), " + "[Measures].[Unit Sales] > 5)' " + "MEMBER [Customers].[#GT#] as 'Aggregate({[#DataSet#]})' " + "MEMBER [Store].[#GT#] as 'Aggregate({[#DataSet#]})' " + "SET [#GrandTotalSet#] as 'Crossjoin({[Store].[#GT#]}, {[Customers].[#GT#]})' " + "SELECT {[Measures].[Unit Sales]} " + "on columns, Union([#GrandTotalSet#], Hierarchize({[#DataSet#]})) on rows FROM [Sales]"; String queryWithoutFilter = "WITH SET [#DataSet#] AS 'Crossjoin({[Store].[All Stores]}, {[Customers].[All Customers]})' " + "SET [#GrandTotalSet#] as 'Crossjoin({[Store].[All Stores]}, {[Customers].[All Customers]})' " + "SELECT {[Measures].[Unit Sales]} on columns, Union([#GrandTotalSet#], Hierarchize({[#DataSet#]})) " + "on rows FROM [Sales]"; String wrongResultWithFilter = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[#GT#], [Customers].[#GT#]}\n" + "Row #0: \n"; String expectedResultWithFilter = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[#GT#], [Customers].[#GT#]}\n" + "{[Store].[All Stores], [Customers].[All Customers]}\n" + "Row #0: 266,773\n" + "Row #1: 266,773\n"; String expectedResultWithoutFilter = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores], [Customers].[All Customers]}\n" + "Row #0: 266,773\n"; // With bug 1755778, the following test below fails because it returns // only row that have a null value (see "wrongResultWithFilter"). // It should return the "expectedResultWithFilter" value. assertQueryReturns(queryWithFilter, expectedResultWithFilter); // To see the test case return the correct result comment out the line // above and uncomment out the lines below following. If a similar // query without the filter is executed (queryWithoutFilter) prior to // running the query with the filter then the correct result set is // returned assertQueryReturns( queryWithoutFilter, expectedResultWithoutFilter); assertQueryReturns( queryWithFilter, expectedResultWithFilter); } /** * This resulted in {@link OutOfMemoryError} when the * BatchingCellReader did not know the values for the tuples that * were used in filters. */ public void testFilteredCrossJoin() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Measures].[Store Sales]} on columns,\n" + " NON EMPTY Crossjoin(\n" + " Filter([Customers].[Name].Members,\n" + " (([Measures].[Store Sales],\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]) > 5.0)),\n" + " Filter([Product].[Product Name].Members,\n" + " (([Measures].[Store Sales],\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]) > 5.0))\n" + " ) ON rows\n" + "from [Sales]\n" + "where (\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]\n" + ")\n"); // ok if no OutOfMemoryError occurs Axis a = result.getAxes()[1]; assertEquals(12, a.getPositions().size()); } /** * Tests a query with a CrossJoin so large that we run out of memory unless * we can push down evaluation to SQL. */ public void testNonEmptyCrossJoin() { if (!props.EnableNativeCrossJoin.get()) { // If we try to evaluate the crossjoin in memory we run out of // memory. return; } getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Measures].[Store Sales]} on columns,\n" + " NON EMPTY Crossjoin(\n" + " [Customers].[Name].Members,\n" + " [Product].[Product Name].Members\n" + " ) ON rows\n" + "from [Sales]\n" + "where (\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]\n" + ")\n"); // ok if no OutOfMemoryError occurs Axis a = result.getAxes()[1]; assertEquals(67, a.getPositions().size()); } /** * NonEmptyCrossJoin() is not the same as NON EMPTY CrossJoin() * because it's evaluated independently of the other axes. * (see http://blogs.msdn.com/bi_systems/articles/162841.aspx) */ public void testNonEmptyNonEmptyCrossJoin1() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " CrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(306, a.getPositions().size()); } public void testNonEmptyNonEmptyCrossJoin2() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " NonEmptyCrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(10, a.getPositions().size()); } public void testNonEmptyNonEmptyCrossJoin3() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " Non Empty CrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(1, a.getPositions().size()); } public void testNonEmptyNonEmptyCrossJoin4() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " Non Empty NonEmptyCrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(1, a.getPositions().size()); } /** * description of this testcase: * A calculated member is created on the time.month level. * On Hierarchize this member is compared to a month. * The month has a numeric key, while the calculated members * key type is string. * No exeception must be thrown. */ public void testHierDifferentKeyClass() { Result result = executeQuery( "with member [Time].[1997].[Q1].[xxx] as\n" + "'Aggregate({[Time].[1997].[Q1].[1], [Time].[1997].[Q1].[2]})'\n" + "select {[Measures].[Unit Sales], [Measures].[Store Cost],\n" + "[Measures].[Store Sales]} ON columns,\n" + "Hierarchize(Union(Union({[Time].[1997], [Time].[1998],\n" + "[Time].[1997].[Q1].[xxx]}, [Time].[1997].Children),\n" + "[Time].[1997].[Q1].Children)) ON rows from [Sales]"); Axis a = result.getAxes()[1]; assertEquals(10, a.getPositions().size()); } /** * Bug #1005995 - many totals of various dimensions */ public void testOverlappingCalculatedMembers() { assertQueryReturns( "WITH MEMBER [Store].[Total] AS 'SUM([Store].[Store Country].MEMBERS)' " + "MEMBER [Store Type].[Total] AS 'SUM([Store Type].[Store Type].MEMBERS)' " + "MEMBER [Gender].[Total] AS 'SUM([Gender].[Gender].MEMBERS)' " + "MEMBER [Measures].[x] AS '[Measures].[Store Sales]' " + "SELECT {[Measures].[x]} ON COLUMNS , " + "{ ([Store].[Total], [Store Type].[Total], [Gender].[Total]) } ON ROWS " + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[x]}\n" + "Axis #2:\n" + "{[Store].[Total], [Store Type].[Total], [Gender].[Total]}\n" + "Row #0: 565,238.13\n"); } /** * the following query raised a classcast exception because * an empty property evaluated as "NullMember" * note: Store "HQ" does not have a "Store Manager" */ public void testEmptyProperty() { assertQueryReturns( "select {[Measures].[Unit Sales]} on columns, " + "filter([Store].[Store Name].members," + "[Store].currentmember.properties(\"Store Manager\")=\"Smith\") on rows" + " from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "Row #0: 2,237\n"); } /** * This test modifies the Sales cube to contain both the regular usage * of the [Store] shared dimension, and another usage called [Other Store] * which is connected to the [Unit Sales] column */ public void _testCubeWhichUsesSameSharedDimTwice() { // Create a second usage of the "Store" shared dimension called "Other // Store". Attach it to the "unit_sales" column (which has values [1, // 6] whereas store has values [1, 24]. TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<DimensionUsage name=\"Other Store\" source=\"Store\" foreignKey=\"unit_sales\" />"); Axis axis = testContext.executeAxis("[Other Store].members"); assertEquals(63, axis.getPositions().size()); axis = testContext.executeAxis("[Store].members"); assertEquals(63, axis.getPositions().size()); final String q1 = "select {[Measures].[Unit Sales]} on columns,\n" + " NON EMPTY {[Other Store].members} on rows\n" + "from [Sales]"; testContext.assertQueryReturns( q1, "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Other Store].[All Other Stores]}\n" + "{[Other Store].[All Other Stores].[Mexico]}\n" + "{[Other Store].[All Other Stores].[USA]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas]}\n" + "{[Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Other Store].[All Other Stores].[USA].[WA]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero].[Acapulco]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco].[Guadalajara]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas].[Camacho]}\n" + "{[Other Store].[All Other Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bellingham]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bremerton]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero].[Acapulco].[Store 1]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco].[Guadalajara].[Store 5]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas].[Camacho].[Store 4]}\n" + "{[Other Store].[All Other Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "Row #0: 266,773\n" + "Row #1: 110,822\n" + "Row #2: 155,951\n" + "Row #3: 1,827\n" + "Row #4: 14,915\n" + "Row #5: 94,080\n" + "Row #6: 222\n" + "Row #7: 155,729\n" + "Row #8: 1,827\n" + "Row #9: 14,915\n" + "Row #10: 94,080\n" + "Row #11: 222\n" + "Row #12: 39,362\n" + "Row #13: 116,367\n" + "Row #14: 1,827\n" + "Row #15: 14,915\n" + "Row #16: 94,080\n" + "Row #17: 222\n" + "Row #18: 39,362\n" + "Row #19: 116,367\n"); final String q2 = "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin(\n" + " {[Store].[USA], [Store].[USA].[CA], [Store].[USA].[OR].[Portland]}, \n" + " {[Other Store].[USA], [Other Store].[USA].[CA], [Other Store].[USA].[OR].[Portland]}) on rows\n" + "from [Sales]"; testContext.assertQueryReturns( q2, "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "Row #0: 155,951\n" + "Row #1: 222\n" + "Row #2: \n" + "Row #3: 43,730\n" + "Row #4: 66\n" + "Row #5: \n" + "Row #6: 15,134\n" + "Row #7: 24\n" + "Row #8: \n"); Result result = executeQuery(q2); final Cell cell = result.getCell(new int[] {0, 0}); String sql = cell.getDrillThroughSQL(false); // the following replacement is for databases in ANSI mode // using '"' to quote identifiers sql = sql.replace('"', '`'); String tableQualifier = "as "; final Dialect dialect = getTestContext().getDialect(); if (dialect.getDatabaseProduct() == Dialect.DatabaseProduct.ORACLE) { // " + tableQualifier + " tableQualifier = ""; } assertEquals( "select `store`.`store_country` as `Store Country`," + " `time_by_day`.`the_year` as `Year`," + " `store_1`.`store_country` as `x0`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store` " + tableQualifier + "`store`," + " `sales_fact_1997` " + tableQualifier + "`sales_fact_1997`," + " `time_by_day` " + tableQualifier + "`time_by_day`," + " `store` " + tableQualifier + "`store_1` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id`" + " and `store`.`store_country` = 'USA'" + " and `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`unit_sales` = `store_1`.`store_id`" + " and `store_1`.`store_country` = 'USA'", sql); } public void testMemberVisibility() { String cubeName = "Sales_MemberVis"; TestContext testContext = TestContext.create( null, "<Cube name=\"" + cubeName + "\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"\n" + " formatString=\"#,###.00\"/>\n" + " <Measure name=\"Store Sales\" column=\"store_sales\" aggregator=\"sum\"\n" + " formatString=\"#,###.00\"/>\n" + " <Measure name=\"Sales Count\" column=\"product_id\" aggregator=\"count\"\n" + " formatString=\"#,###\"/>\n" + " <Measure name=\"Customer Count\" column=\"customer_id\"\n" + " aggregator=\"distinct-count\" formatString=\"#,###\"/>\n" + " <CalculatedMember\n" + " name=\"Profit\"\n" + " dimension=\"Measures\"\n" + " visible=\"false\"\n" + " formula=\"[Measures].[Store Sales]-[Measures].[Store Cost]\">\n" + " <CalculatedMemberProperty name=\"FORMAT_STRING\" value=\"$#,##0.00\"/>\n" + " </CalculatedMember>\n" + "</Cube>", null, null, null, null); SchemaReader scr = testContext.getConnection().getSchema().lookupCube( cubeName, true).getSchemaReader(null); Member member = scr.getMemberByUniqueName( Id.Segment.toList( "Measures", "Unit Sales"), true); Object visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.FALSE, visible); member = scr.getMemberByUniqueName( Id.Segment.toList( "Measures", "Store Cost"), true); visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.TRUE, visible); member = scr.getMemberByUniqueName( Id.Segment.toList( "Measures", "Profit"), true); visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.FALSE, visible); } public void testAllMemberCaption() { TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<Dimension name=\"Gender3\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\"\n" + " allMemberCaption=\"Frauen und Maenner\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>"); String mdx = "select {[Gender3].[All Gender]} on columns from Sales"; Result result = testContext.executeQuery(mdx); Axis axis0 = result.getAxes()[0]; Position pos0 = axis0.getPositions().get(0); Member allGender = pos0.get(0); String caption = allGender.getCaption(); Assert.assertEquals(caption, "Frauen und Maenner"); } public void testAllLevelName() { TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<Dimension name=\"Gender4\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\"\n" + " allLevelName=\"GenderLevel\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>"); String mdx = "select {[Gender4].[All Gender]} on columns from Sales"; Result result = testContext.executeQuery(mdx); Axis axis0 = result.getAxes()[0]; Position pos0 = axis0.getPositions().get(0); Member allGender = pos0.get(0); String caption = allGender.getLevel().getName(); Assert.assertEquals(caption, "GenderLevel"); } /** * Bug 1250080 caused a dimension with no 'all' member to be constrained * twice. */ public void testDimWithoutAll() { // Create a test context with a new ""Sales_DimWithoutAll" cube, and // which evaluates expressions against that cube. TestContext testContext = new TestContext() { public Util.PropertyList getFoodMartConnectionProperties() { final String schema = getFoodMartSchema( null, "<Cube name=\"Sales_DimWithoutAll\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <Dimension name=\"Product\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"false\" primaryKey=\"product_id\" primaryKeyTable=\"product\">\n" + " <Join leftKey=\"product_class_id\" rightKey=\"product_class_id\">\n" + " <Table name=\"product\"/>\n" + " <Table name=\"product_class\"/>\n" + " </Join>\n" + " <Level name=\"Product Family\" table=\"product_class\" column=\"product_family\"\n" + " uniqueMembers=\"true\"/>\n" + " <Level name=\"Product Department\" table=\"product_class\" column=\"product_department\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Category\" table=\"product_class\" column=\"product_category\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Subcategory\" table=\"product_class\" column=\"product_subcategory\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\"\n" + " uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Gender\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"false\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"\n" + " formatString=\"#,###.00\"/>\n" + "</Cube>", null, null, null, null); Util.PropertyList properties = super.getFoodMartConnectionProperties(); properties.put( RolapConnectionProperties.CatalogContent.name(), schema); return properties; } public String getDefaultCubeName() { return "Sales_DimWithoutAll"; } }; // the default member of the Gender dimension is the first member testContext.assertExprReturns("[Gender].CurrentMember.Name", "F"); testContext.assertExprReturns("[Product].CurrentMember.Name", "Drink"); // There is no all member. testContext.assertExprThrows( "([Gender].[All Gender], [Measures].[Unit Sales])", "MDX object '[Gender].[All Gender]' not found in cube 'Sales_DimWithoutAll'"); testContext.assertExprThrows( "([Gender].[All Genders], [Measures].[Unit Sales])", "MDX object '[Gender].[All Genders]' not found in cube 'Sales_DimWithoutAll'"); // evaluated in the default context: [Product].[Drink], [Gender].[F] testContext.assertExprReturns("[Measures].[Unit Sales]", "12,202"); // evaluated in the same context: [Product].[Drink], [Gender].[F] testContext.assertExprReturns( "([Gender].[F], [Measures].[Unit Sales])", "12,202"); // evaluated at in the context: [Product].[Drink], [Gender].[M] testContext.assertExprReturns( "([Gender].[M], [Measures].[Unit Sales])", "12,395"); // evaluated in the context: // [Product].[Food].[Canned Foods], [Gender].[F] testContext.assertExprReturns( "([Product].[Food].[Canned Foods], [Measures].[Unit Sales])", "9,407"); testContext.assertExprReturns( "([Product].[Food].[Dairy], [Measures].[Unit Sales])", "6,513"); testContext.assertExprReturns( "([Product].[Drink].[Dairy], [Measures].[Unit Sales])", "1,987"); } /** * If an axis expression is a member, implicitly convert it to a set. */ public void testMemberOnAxis() { assertQueryReturns( "select [Measures].[Sales Count] on 0, non empty [Store].[Store State].members on 1 from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Sales Count]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[OR]}\n" + "{[Store].[All Stores].[USA].[WA]}\n" + "Row #0: 24,442\n" + "Row #1: 21,611\n" + "Row #2: 40,784\n"); } public void testScalarOnAxisFails() { assertQueryThrows( "select [Measures].[Sales Count] + 1 on 0, non empty [Store].[Store State].members on 1 from [Sales]", "Axis 'COLUMNS' expression is not a set"); } /** * It is illegal for a query to have the same dimension on more than * one axis. */ public void testSameDimOnTwoAxesFails() { assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Measures].[Store Sales]} on rows\n" + "from [Sales]", "Hierarchy '[Measures]' appears in more than one independent axis"); // as part of a crossjoin assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin({[Product].members}," + " {[Measures].[Store Sales]}) on rows\n" + "from [Sales]", "Hierarchy '[Measures]' appears in more than one independent axis"); // as part of a tuple assertQueryThrows( "select CrossJoin(\n" + " {[Product].children},\n" + " {[Measures].[Unit Sales]}) on columns,\n" + " {([Product],\n" + " [Store].CurrentMember)} on rows\n" + "from [Sales]", "Hierarchy '[Product]' appears in more than one independent axis"); // clash between columns and slicer assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Store].Members} on rows\n" + "from [Sales]\n" + "where ([Time].[1997].[Q1], [Measures].[Store Sales])", "Hierarchy '[Measures]' appears in more than one independent axis"); // within aggregate is OK executeQuery( "with member [Measures].[West Coast Total] as " + " ' Aggregate({[Store].[USA].[CA], [Store].[USA].[OR], [Store].[USA].[WA]}) ' \n" + "select " + " {[Measures].[Store Sales], \n" + " [Measures].[Unit Sales]} on Columns,\n" + " CrossJoin(\n" + " {[Product].children},\n" + " {[Store].children}) on Rows\n" + "from [Sales]"); } public void _testSetArgToTupleFails() { assertQueryThrows( "select CrossJoin(\n" + " {[Product].children},\n" + " {[Measures].[Unit Sales]}) on columns,\n" + " {([Product],\n" + " [Store].members)} on rows\n" + "from [Sales]", "Dimension '[Product]' appears in more than one independent axis"); } public void _badArgsToTupleFails() { // clash within slicer assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Store].Members} on rows\n" + "from [Sales]\n" + "where ([Time].[1997].[Q1], [Product], [Time].[1997].[Q2])", "Dimension '[Time]' more than once in same tuple"); // ditto assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin({[Time].[1997].[Q1],\n" + " {[Product]},\n" + " {[Time].[1997].[Q2]}) on rows\n" + "from [Sales]", "Dimension '[Time]' more than once in same tuple"); } public void testNullMember() { if (isDefaultNullMemberRepresentation()) { assertQueryReturns( "SELECT \n" + "{[Measures].[Store Cost]} ON columns, \n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]} ON rows \n" + "FROM [Sales] \n" + "WHERE [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Store Cost]}\n" + "Axis #2:\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" + "Row #0: 33,307.69\n"); } } public void testNullMemberWithOneNonNull() { if (isDefaultNullMemberRepresentation()) { assertQueryReturns( "SELECT \n" + "{[Measures].[Store Cost]} ON columns, \n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]," + "[Store Size in SQFT].[ALL Store Size in SQFTs].[39696]} ON rows \n" + "FROM [Sales] \n" + "WHERE [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Store Cost]}\n" + "Axis #2:\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[39696]}\n" + "Row #0: 33,307.69\n" + "Row #1: 21,121.96\n"); } } /** * Tests whether the agg mgr behaves correctly if a cell request causes * a column to be constrained multiple times. This happens if two levels * map to the same column via the same join-path. If the constraints are * inconsistent, no data will be returned. */ public void testMultipleConstraintsOnSameColumn() { final String cubeName = "Sales_withCities"; TestContext testContext = TestContext.create( null, "<Cube name=\"" + cubeName + "\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Dimension name=\"Cities\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Cities\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/> \n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Customers\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Customers\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Country\" column=\"country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"State Province\" column=\"state_province\" uniqueMembers=\"true\"/>\n" + " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Name\" column=\"fullname\" uniqueMembers=\"true\">\n" + " <Property name=\"Gender\" column=\"gender\"/>\n" + " <Property name=\"Marital Status\" column=\"marital_status\"/>\n" + " <Property name=\"Education\" column=\"education\"/>\n" + " <Property name=\"Yearly Income\" column=\"yearly_income\"/>\n" + " </Level>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Gender\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Sales\" column=\"store_sales\" aggregator=\"sum\"\n" + " formatString=\"#,###.00\"/>\n" + "</Cube>", null, null, null, null); testContext.assertQueryReturns( "select {\n" + " [Customers].[All Customers].[USA],\n" + " [Customers].[All Customers].[USA].[OR],\n" + " [Customers].[All Customers].[USA].[CA],\n" + " [Customers].[All Customers].[USA].[CA].[Altadena],\n" + " [Customers].[All Customers].[USA].[CA].[Burbank],\n" + " [Customers].[All Customers].[USA].[CA].[Burbank].[Alma Son]} ON COLUMNS\n" + "from [" + cubeName + "] \n" + "where ([Cities].[All Cities].[Burbank], [Measures].[Store Sales])", "Axis #0:\n" + "{[Cities].[All Cities].[Burbank], [Measures].[Store Sales]}\n" + "Axis #1:\n" + "{[Customers].[All Customers].[USA]}\n" + "{[Customers].[All Customers].[USA].[OR]}\n" + "{[Customers].[All Customers].[USA].[CA]}\n" + "{[Customers].[All Customers].[USA].[CA].[Altadena]}\n" + "{[Customers].[All Customers].[USA].[CA].[Burbank]}\n" + "{[Customers].[All Customers].[USA].[CA].[Burbank].[Alma Son]}\n" + "Row #0: 6,577.33\n" + "Row #0: \n" + "Row #0: 6,577.33\n" + "Row #0: \n" + "Row #0: 6,577.33\n" + "Row #0: 36.50\n"); } public void testOverrideDimension() { assertQueryReturns( "with member [Gender].[test] as '\n" + " aggregate(\n" + " filter (crossjoin( [Gender].[Gender].members, [Time].[Time].members), \n" + " [time].[Time].CurrentMember = [Time].[1997].[Q1] AND\n" + "[measures].[unit sales] > 50) )\n" + "'\n" + "select \n" + " { [time].[year].members } on 0,\n" + " { [gender].[test] }\n" + " on 1 \n" + "from [sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997]}\n" + "{[Time].[1998]}\n" + "Axis #2:\n" + "{[Gender].[test]}\n" + "Row #0: 66,291\n" + "Row #0: 66,291\n"); } public void testBadMeasure1() { TestContext testContext = TestContext.create( null, "<Cube name=\"SalesWithBadMeasure\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Measure name=\"Bad Measure\" aggregator=\"sum\"\n" + " formatString=\"Standard\"/>\n" + "</Cube>", null, null, null, null); Throwable throwable = null; try { testContext.assertSimpleQuery(); } catch (Throwable e) { throwable = e; } // neither a source column or source expression specified TestContext.checkThrowable( throwable, "must contain either a source column or a source expression, but not both"); } public void testBadMeasure2() { TestContext testContext = TestContext.create( null, "<Cube name=\"SalesWithBadMeasure2\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Measure name=\"Bad Measure\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\">\n" + " <MeasureExpression>\n" + " <SQL dialect=\"generic\">\n" + " unit_sales\n" + " </SQL>\n" + " </MeasureExpression>\n" + " </Measure>\n" + "</Cube>", null, null, null, null); Throwable throwable = null; try { testContext.assertSimpleQuery(); } catch (Throwable e) { throwable = e; } // both a source column and source expression specified TestContext.checkThrowable( throwable, "must contain either a source column or a source expression, but not both"); } public void testInvalidMembersInQuery() { String mdx = "select {[Measures].[Unit Sales]} on columns,\n" + " {[Time].[1997].[Q1], [Time].[1997].[QTOO]} on rows\n" + "from [Sales]"; String mdx2 = "select {[Measures].[Unit Sales]} on columns,\n" + "nonemptycrossjoin(\n" + "{[Time].[1997].[Q1], [Time].[1997].[QTOO]},\n" + "[Customers].[All Customers].[USA].children) on rows\n" + "from [Sales]"; String mdx3 = "select {[Measures].[Unit Sales]} on columns\n" + "from [Sales]\n" + "where ([Time].[1997].[QTOO])"; // By default, reference to invalid member should cause // query failure. assertQueryThrows( mdx, "MDX object '[Time].[1997].[QTOO]' not found in cube 'Sales'"); assertQueryThrows( mdx3, "MDX object '[Time].[1997].[QTOO]' not found in cube 'Sales'"); // Now set property boolean savedInvalidProp = props.IgnoreInvalidMembersDuringQuery.get(); String savedAlertProp = props.AlertNativeEvaluationUnsupported.get(); try { props.IgnoreInvalidMembersDuringQuery.set(true); assertQueryReturns( mdx, "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1]}\n" + "Row #0: 66,291\n"); // Illegal member in slicer assertQueryReturns( mdx3, "Axis #0:\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Row #0: \n"); // Verify that invalid members in query do NOT prevent // usage of native NECJ (LER-5165). props.AlertNativeEvaluationUnsupported.set("ERROR"); assertQueryReturns( mdx2, "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1], [Customers].[All Customers].[USA].[CA]}\n" + "{[Time].[1997].[Q1], [Customers].[All Customers].[USA].[OR]}\n" + "{[Time].[1997].[Q1], [Customers].[All Customers].[USA].[WA]}\n" + "Row #0: 16,890\n" + "Row #1: 19,287\n" + "Row #2: 30,114\n"); } finally { props.IgnoreInvalidMembersDuringQuery.set(savedInvalidProp); props.AlertNativeEvaluationUnsupported.set(savedAlertProp); } } public void testMemberOrdinalCaching() { boolean saved = props.CompareSiblingsByOrderKey.get(); props.CompareSiblingsByOrderKey.set(true); Connection conn = null; try { // Use a fresh connection to make sure bad member ordinals haven't // been assigned by previous tests. conn = getTestContext().getFoodMartConnection(false); TestContext context = getTestContext(conn); tryMemberOrdinalCaching(context); } finally { props.CompareSiblingsByOrderKey.set(saved); if (conn != null) { conn.close(); } } } private void tryMemberOrdinalCaching(TestContext context) { // NOTE jvs 20-Feb-2007: If you change the calculated measure // definition below from zero to // [Customers].[Name].currentmember.Properties(\"MEMBER_ORDINAL\"), you // can see that the absolute ordinals returned are incorrect due to bug // 1660383 (http://tinyurl.com/3xb56f). For now, this test just // verifies that the member sorting is correct when using relative // order key rather than absolute ordinal value. If absolute ordinals // get fixed, replace zero with the MEMBER_ORDINAL property. context.assertQueryReturns( "with member [Measures].[o] as 0\n" + "set necj as nonemptycrossjoin(\n" + "[Store].[Store State].members, [Customers].[Name].members)\n" + "select tail(necj,5) on rows,\n" + "{[Measures].[o]} on columns\n" + "from [Sales]\n", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[o]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[Tracy Meyer]}\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[Vanessa Thompson]}\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[Velma Lykes]}\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[William Battaglia]}\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[Wilma Fink]}\n" + "Row #0: 0\n" + "Row #1: 0\n" + "Row #2: 0\n" + "Row #3: 0\n" + "Row #4: 0\n"); // The query above primed the cache with bad absolute ordinals; // verify that this doesn't interfere with subsequent queries. context.assertQueryReturns( "with member [Measures].[o] as 0\n" + "select tail([Customers].[Name].members, 5)\n" + "on rows,\n" + "{[Measures].[o]} on columns\n" + "from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[o]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[Tracy Meyer]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[Vanessa Thompson]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[Velma Lykes]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[William Battaglia]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[Wilma Fink]}\n" + "Row #0: 0\n" + "Row #1: 0\n" + "Row #2: 0\n" + "Row #3: 0\n" + "Row #4: 0\n"); } public void testCancel() { // the cancel is issued after 2 seconds so the test query needs to // run for at least that long; it will because the query references // a Udf that has a 1 ms sleep in it; and there are enough rows // in the result that the Udf should execute > 2000 times String query = "WITH \n" + " MEMBER [Measures].[Sleepy] \n" + " AS 'SleepUdf([Measures].[Unit Sales])' \n" + "SELECT {[Measures].[Sleepy]} ON COLUMNS,\n" + " {[Product].members} ON ROWS\n" + "FROM [Sales]"; executeAndCancel(query, 2000); } private void executeAndCancel(String queryString, int waitMillis) { final TestContext tc = TestContext.create( null, null, null, null, "<UserDefinedFunction name=\"SleepUdf\" className=\"" + SleepUdf.class.getName() + "\"/>", null); Connection connection = tc.getConnection(); final Query query = connection.parseQuery(queryString); if (waitMillis == 0) { // cancel immediately query.cancel(); } else { // Schedule timer to cancel after waitMillis Timer timer = new Timer(true); TimerTask task = new TimerTask() { public void run() { Thread thread = Thread.currentThread(); thread.setName("CancelThread"); try { query.cancel(); } catch (Exception ex) { Assert.fail( "Cancel request failed: " + ex.getMessage()); } } }; timer.schedule(task, waitMillis); } Throwable throwable = null; try { connection.execute(query); } catch (Throwable ex) { throwable = ex; } TestContext.checkThrowable(throwable, "canceled"); } public void testQueryTimeout() { // timeout is issued after 2 seconds so the test query needs to // run for at least that long; it will because the query references // a Udf that has a 1 ms sleep in it; and there are enough rows // in the result that the Udf should execute > 2000 times final TestContext tc = TestContext.create( null, null, null, null, "<UserDefinedFunction name=\"SleepUdf\" className=\"" + SleepUdf.class.getName() + "\"/>", null); String query = "WITH\n" + " MEMBER [Measures].[Sleepy]\n" + " AS 'SleepUdf([Measures].[Unit Sales])'\n" + "SELECT {[Measures].[Sleepy]} ON COLUMNS,\n" + " {[Product].members} ON ROWS\n" + "FROM [Sales]"; Throwable throwable = null; int origTimeout = props.QueryTimeout.get(); try { props.QueryTimeout.set(2); tc.executeQuery(query); } catch (Throwable ex) { throwable = ex; } finally { // reset the timeout back to the original value props.QueryTimeout.set(origTimeout); } TestContext.checkThrowable( throwable, "Query timeout of 2 seconds reached"); } public void testFormatInheritance() { assertQueryReturns( "with member measures.foo as 'measures.bar' " + "member measures.bar as " + "'measures.profit' select {measures.foo} on 0 from sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[foo]}\n" + "Row #0: $339,610.90\n"); } public void testFormatInheritanceWithIIF() { assertQueryReturns( "with member measures.foo as 'measures.bar' " + "member measures.bar as " + "'iif(not isempty(measures.profit),measures.profit,null)' " + "select from sales where measures.foo", "Axis #0:\n" + "{[Measures].[foo]}\n" + "$339,610.90"); } /** * For a calulated member picks up the format of first member that has a * format. In this particular case foo will use profit's format, i.e * neither [unit sales] nor [customer count] format is used. */ public void testFormatInheritanceWorksWithFirstFormatItFinds() { assertQueryReturns( "with member measures.foo as 'measures.bar' " + "member measures.bar as " + "'iif(measures.profit>3000,measures.[unit sales],measures.[Customer Count])' " + "select {[Store].[All Stores].[USA].[WA].children} on 0 " + "from sales where measures.foo", "Axis #0:\n" + "{[Measures].[foo]}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima]}\n" + "Row #0: $190.00\n" + "Row #0: $24,576.00\n" + "Row #0: $25,011.00\n" + "Row #0: $23,591.00\n" + "Row #0: $35,257.00\n" + "Row #0: $96.00\n" + "Row #0: $11,491.00\n"); } /** * This tests a fix for bug #1603653 */ public void testAvgCastProblem() { assertQueryReturns( "with member measures.bar as " + "'iif(measures.profit>3000,min([Education Level].[Education Level].Members),min([Education Level].[Education Level].Members))' " + "select {[Store].[All Stores].[USA].[WA].children} on 0 " + "from sales where measures.bar", "Axis #0:\n" + "{[Measures].[bar]}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima]}\n" + "Row #0: $95.00\n" + "Row #0: $1,835.00\n" + "Row #0: $1,277.00\n" + "Row #0: $1,434.00\n" + "Row #0: $1,084.00\n" + "Row #0: $129.00\n" + "Row #0: $958.00\n"); } /** * Test format inheritance to pickup format from second measure when the * first does not have one. */ public void testFormatInheritanceUseSecondIfFirstHasNoFormat() { assertQueryReturns( "with member measures.foo as 'measures.bar+measures.blah'" + " member measures.bar as '10'" + " member measures.blah as '20',format_string='$##.###.00' " + "select from sales where measures.foo", "Axis #0:\n" + "{[Measures].[foo]}\n" + "$30.00"); } /** * Tests format inheritance with complex expression to assert that the * format of the first member that has a valid format is used. */ public void testFormatInheritanceUseFirstValid() { assertQueryReturns( "with member measures.foo as '13+31*measures.[Unit Sales]/" + "iif(measures.profit>0,measures.profit,measures.[Customer Count])'" + " select {[Store].[All Stores].[USA].[CA].children} on 0 " + "from sales where measures.foo", "Axis #0:\n" + "{[Measures].[foo]}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "Row #0: 13\n" + "Row #0: 37\n" + "Row #0: 37\n" + "Row #0: 37\n" + "Row #0: 38\n"); } public void testQueryIterationLimit() { // Query will need to iterate 4*3 times to compute aggregates, // so set iteration limit to 11 String queryString = "With Set [*NATIVE_CJ_SET] as " + "'NonEmptyCrossJoin([*BASE_MEMBERS_Dates], [*BASE_MEMBERS_Stores])' " + "Set [*BASE_MEMBERS_Dates] as '{[Time].[1997].[Q1], [Time].[1997].[Q2], [Time].[1997].[Q3], [Time].[1997].[Q4]}' " + "Set [*GENERATED_MEMBERS_Dates] as 'Generate([*NATIVE_CJ_SET], {[Time].[Time].CurrentMember})' " + "Set [*GENERATED_MEMBERS_Measures] as '{[Measures].[*SUMMARY_METRIC_0]}' " + "Set [*BASE_MEMBERS_Stores] as '{[Store].[USA].[CA], [Store].[USA].[WA], [Store].[USA].[OR]}' " + "Set [*GENERATED_MEMBERS_Stores] as 'Generate([*NATIVE_CJ_SET], {[Store].CurrentMember})' " + "Member [Time].[*SM_CTX_SEL] as 'Aggregate([*GENERATED_MEMBERS_Dates])' " + "Member [Measures].[*SUMMARY_METRIC_0] as '[Measures].[Unit Sales]/([Measures].[Unit Sales],[Time].[*SM_CTX_SEL])' " + "Member [Time].[*SUBTOTAL_MEMBER_SEL~SUM] as 'sum([*GENERATED_MEMBERS_Dates])' " + "Member [Store].[*SUBTOTAL_MEMBER_SEL~SUM] as 'sum([*GENERATED_MEMBERS_Stores])' " + "select crossjoin({[Time].[*SUBTOTAL_MEMBER_SEL~SUM]}, {[Store].[*SUBTOTAL_MEMBER_SEL~SUM]}) " + "on columns from [Sales]"; Throwable throwable = null; int origLimit = props.IterationLimit.get(); try { props.IterationLimit.set(11); Connection connection = getConnection(); Query query = connection.parseQuery(queryString); query.setResultStyle(ResultStyle.LIST); connection.execute(query); } catch (Throwable ex) { throwable = ex; } finally { // reset the timeout back to the original value props.IterationLimit.set(origLimit); } TestContext.checkThrowable( throwable, "Number of iterations exceeded limit of 11"); // make sure the query runs without the limit set executeQuery(queryString); } public void testGetCaptionUsingMemberDotCaption() { assertQueryReturns( "SELECT Filter(Store.allmembers, " + "[store].currentMember.caption = \"USA\") on 0 FROM SALES", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA]}\n" + "Row #0: 266,773\n"); } public void testGetCaptionUsingMemberDotPropertiesCaption() { assertQueryReturns( "SELECT Filter(Store.allmembers, " + "[store].currentMember.properties(\"caption\") = \"USA\") " + "on 0 FROM SALES", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA]}\n" + "Row #0: 266,773\n"); } public void testDefaultMeasureInCube() { TestContext testContext = TestContext.create( null, "<Cube name=\"DefaultMeasureTesting\" defaultMeasure=\"Supply Time\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Store\" source=\"Store\" " + "foreignKey=\"store_id\"/>\n" + " <DimensionUsage name=\"Store Type\" source=\"Store Type\" " + "foreignKey=\"store_id\"/>\n" + " <Measure name=\"Store Invoice\" column=\"store_invoice\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Supply Time\" column=\"supply_time\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" " + "aggregator=\"sum\"/>\n" + "</Cube>", null, null, null, null); String queryWithoutFilter = "select store.members on 0 from " + "DefaultMeasureTesting"; String queryWithDeflaultMeasureFilter = "select store.members on 0 " + "from DefaultMeasureTesting where [measures].[Supply Time]"; assertQueriesReturnSimilarResults( queryWithoutFilter, queryWithDeflaultMeasureFilter, testContext); } public void testDefaultMeasureInCubeForIncorrectMeasureName() { TestContext testContext = TestContext.create( null, "<Cube name=\"DefaultMeasureTesting\" defaultMeasure=\"Supply Time Error\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Store\" source=\"Store\" " + "foreignKey=\"store_id\"/>\n" + " <DimensionUsage name=\"Store Type\" source=\"Store Type\" " + "foreignKey=\"store_id\"/>\n" + " <Measure name=\"Store Invoice\" column=\"store_invoice\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Supply Time\" column=\"supply_time\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" " + "aggregator=\"sum\"/>\n" + "</Cube>", null, null, null, null); String queryWithoutFilter = "select store.members on 0 from " + "DefaultMeasureTesting"; String queryWithFirstMeasure = "select store.members on 0 " + "from DefaultMeasureTesting where [measures].[Store Invoice]"; assertQueriesReturnSimilarResults( queryWithoutFilter, queryWithFirstMeasure, testContext); } public void testDefaultMeasureInCubeForCaseSensitivity() { TestContext testContext = TestContext.create( null, "<Cube name=\"DefaultMeasureTesting\" defaultMeasure=\"SUPPLY TIME\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Store\" source=\"Store\" " + "foreignKey=\"store_id\"/>\n" + " <DimensionUsage name=\"Store Type\" source=\"Store Type\" " + "foreignKey=\"store_id\"/>\n" + " <Measure name=\"Store Invoice\" column=\"store_invoice\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Supply Time\" column=\"supply_time\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" " + "aggregator=\"sum\"/>\n" + "</Cube>", null, null, null, null); String queryWithoutFilter = "select store.members on 0 from " + "DefaultMeasureTesting"; String queryWithFirstMeasure = "select store.members on 0 " + "from DefaultMeasureTesting where [measures].[Store Invoice]"; String queryWithDefaultMeasureFilter = "select store.members on 0 " + "from DefaultMeasureTesting where [measures].[Supply Time]"; if (props.CaseSensitive.get()) { assertQueriesReturnSimilarResults( queryWithoutFilter, queryWithFirstMeasure, testContext); } else { assertQueriesReturnSimilarResults( queryWithoutFilter, queryWithDefaultMeasureFilter, testContext); } } /** * This tests for bug #1706434, * the ability to convert numeric types to logical (boolean) types. */ public void testNumericToLogicalConversion() { assertQueryReturns( "select " + "{[Measures].[Unit Sales]} on columns, " + "Filter(Descendants(" + "[Product].[Food].[Baked Goods].[Bread]), " + "Count([Product].currentMember.children)) on Rows " + "from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Colony]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Fantastic]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Great]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Modell]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Sphinx]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Colony]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Fantastic]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Great]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Modell]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Sphinx]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Colony]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Fantastic]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Great]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Modell]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Sphinx]}\n" + "Row #0: 7,870\n" + "Row #1: 815\n" + "Row #2: 163\n" + "Row #3: 160\n" + "Row #4: 145\n" + "Row #5: 165\n" + "Row #6: 182\n" + "Row #7: 3,497\n" + "Row #8: 740\n" + "Row #9: 798\n" + "Row #10: 605\n" + "Row #11: 719\n" + "Row #12: 635\n" + "Row #13: 3,558\n" + "Row #14: 737\n" + "Row #15: 815\n" + "Row #16: 638\n" + "Row #17: 653\n" + "Row #18: 715\n"); } public void testRollupQuery() { assertQueryReturns( "SELECT {[Product].[Product Department].MEMBERS} ON AXIS(0),\n" + "{{[Gender].[Gender].MEMBERS}, {[Gender].[All Gender]}} ON AXIS(1)\n" + "FROM [Sales 2] WHERE {[Measures].[Unit Sales]}", "Axis #0:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #1:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "{[Product].[All Products].[Food].[Baked Goods]}\n" + "{[Product].[All Products].[Food].[Baking Goods]}\n" + "{[Product].[All Products].[Food].[Breakfast Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "{[Product].[All Products].[Food].[Canned Products]}\n" + "{[Product].[All Products].[Food].[Dairy]}\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Eggs]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Meat]}\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Seafood]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Snacks]}\n" + "{[Product].[All Products].[Food].[Starchy Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Carousel]}\n" + "{[Product].[All Products].[Non-Consumable].[Checkout]}\n" + "{[Product].[All Products].[Non-Consumable].[Health and Hygiene]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Non-Consumable].[Periodicals]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[All Gender]}\n" + "Row #0: 3,439\n" + "Row #0: 6,776\n" + "Row #0: 1,987\n" + "Row #0: 3,771\n" + "Row #0: 9,841\n" + "Row #0: 1,821\n" + "Row #0: 9,407\n" + "Row #0: 867\n" + "Row #0: 6,513\n" + "Row #0: 5,990\n" + "Row #0: 2,001\n" + "Row #0: 13,011\n" + "Row #0: 841\n" + "Row #0: 18,713\n" + "Row #0: 947\n" + "Row #0: 14,936\n" + "Row #0: 3,459\n" + "Row #0: 2,696\n" + "Row #0: 368\n" + "Row #0: 887\n" + "Row #0: 7,841\n" + "Row #0: 13,278\n" + "Row #0: 2,168\n" + "Row #1: 3,399\n" + "Row #1: 6,797\n" + "Row #1: 2,199\n" + "Row #1: 4,099\n" + "Row #1: 10,404\n" + "Row #1: 1,496\n" + "Row #1: 9,619\n" + "Row #1: 945\n" + "Row #1: 6,372\n" + "Row #1: 6,047\n" + "Row #1: 2,131\n" + "Row #1: 13,644\n" + "Row #1: 873\n" + "Row #1: 19,079\n" + "Row #1: 817\n" + "Row #1: 15,609\n" + "Row #1: 3,425\n" + "Row #1: 2,566\n" + "Row #1: 473\n" + "Row #1: 892\n" + "Row #1: 8,443\n" + "Row #1: 13,760\n" + "Row #1: 2,126\n" + "Row #2: 6,838\n" + "Row #2: 13,573\n" + "Row #2: 4,186\n" + "Row #2: 7,870\n" + "Row #2: 20,245\n" + "Row #2: 3,317\n" + "Row #2: 19,026\n" + "Row #2: 1,812\n" + "Row #2: 12,885\n" + "Row #2: 12,037\n" + "Row #2: 4,132\n" + "Row #2: 26,655\n" + "Row #2: 1,714\n" + "Row #2: 37,792\n" + "Row #2: 1,764\n" + "Row #2: 30,545\n" + "Row #2: 6,884\n" + "Row #2: 5,262\n" + "Row #2: 841\n" + "Row #2: 1,779\n" + "Row #2: 16,284\n" + "Row #2: 27,038\n" + "Row #2: 4,294\n"); } /** * Tests for bug #1630754. In Mondrian 2.2.2 the SqlTupleReader.readTuples * method would create a SQL having an in-clause with more that 1000 * entities under some circumstances. This exceeded the limit for Oracle * resulting in an ORA-01795 error. */ public void testBug1630754() { // In order to reproduce this bug a dimension with 2 levels with more // than 1000 member each was necessary. The customer_id column has more // than 1000 distinct members so it was used for this test. final TestContext testContext = TestContext.createSubstitutingCube( "Sales", " <Dimension name=\"Customer_2\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" " + "allMemberName=\"All Customers\" " + "primaryKey=\"customer_id\" " + " >\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Name1\" column=\"customer_id\" uniqueMembers=\"true\"/>" + " <Level name=\"Name2\" column=\"customer_id\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>"); Result result = testContext.executeQuery( "WITH SET [#DataSet#] AS " + " 'NonEmptyCrossjoin({Descendants([Customer_2].[All Customers], 2)}, " + " {[Product].[All Products]})' " + "SELECT {[Measures].[Unit Sales], [Measures].[Store Sales]} on columns, " + "Hierarchize({[#DataSet#]}) on rows FROM [Sales]"); final int rowCount = result.getAxes()[1].getPositions().size(); assertEquals(5581, rowCount); } /** * Tests a query which uses filter and crossjoin. This query caused * problems when the retrowoven version of mondrian was used in jdk1.5, * specifically a {@link ClassCastException} trying to cast a {@link List} * to a {@link Iterable}. */ public void testNonEmptyCrossjoinFilter() { String desiredResult = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products], [Time].[1997].[Q2].[5]}\n" + "Row #0: 21,081\n"; assertQueryReturns( "select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS,\n" + "NON EMPTY Crossjoin(" + " {Product.[All Products]},\n" + " Filter(" + " Descendants(Time.[Time], [Time].[Month]), " + " Time.[Time].CurrentMember.Name = '5')) ON ROWS\n" + "from [Sales] ", desiredResult); assertQueryReturns( "select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS,\n" + "NON EMPTY Filter(" + " Crossjoin(" + " {Product.[All Products]},\n" + " Descendants(Time.[Time], [Time].[Month]))," + " Time.[Time].CurrentMember.Name = '5') ON ROWS\n" + "from [Sales] ", desiredResult); } public void testDuplicateAxisFails() { assertQueryThrows( "select [Gender].Members on columns," + " [Measures].Members on columns " + "from [Sales]", "Duplicate axis name 'COLUMNS'."); } public void testInvalidAxisFails() { assertQueryThrows( "select [Gender].Members on 0," + " [Measures].Members on 10 " + "from [Sales]", "Axis numbers specified in a query must be sequentially specified," + " and cannot contain gaps. Axis 1 (ROWS) is missing."); assertQueryThrows( "select [Gender].Members on columns," + " [Measures].Members on foobar\n" + "from [Sales]", "Syntax error at line 1, column 59, token 'foobar'"); assertQueryThrows( "select [Gender].Members on columns," + " [Measures].Members on slicer\n" + "from [Sales]", "Syntax error at line 1, column 59, token 'slicer'"); assertQueryThrows( "select [Gender].Members on columns," + " [Measures].Members on filter\n" + "from [Sales]", "Syntax error at line 1, column 59, token 'filter'"); } /** * Tests various ways to sum the properties of the descendants of a member, * inspired by forum post * <a href="http://forums.pentaho.org/showthread.php?p=177135">summing * properties</a>. */ public void testSummingProperties() { final String expected = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 131,558\n" + "Row #0: 36,759\n" + "Row #1: 135,215\n" + "Row #1: 37,989\n"; assertQueryReturns( "with member [Measures].[Sum Sqft] as '" + "sum(" + " Descendants([Store].CurrentMember, [Store].Levels(5))," + " [Store].CurrentMember.Properties(\"Store Sqft\")) '\n" + "select {[Store].[USA], [Store].[USA].[CA]} on 0,\n" + " [Gender].Children on 1\n" + "from [Sales]", expected); // same query, except get level by name not ordinal, should give same // result assertQueryReturns( "with member [Measures].[Sum Sqft] as '" + "sum(" + " Descendants([Store].CurrentMember, [Store].Levels(\"Store Name\"))," + " [Store].CurrentMember.Properties(\"Store Sqft\")) '\n" + "select {[Store].[USA], [Store].[USA].[CA]} on 0,\n" + " [Gender].Children on 1\n" + "from [Sales]", expected); // same query, except level is hard-coded; same result again assertQueryReturns( "with member [Measures].[Sum Sqft] as '" + "sum(" + " Descendants([Store].CurrentMember, [Store].[Store Name])," + " [Store].CurrentMember.Properties(\"Store Sqft\")) '\n" + "select {[Store].[USA], [Store].[USA].[CA]} on 0,\n" + " [Gender].Children on 1\n" + "from [Sales]", expected); // same query, except using the level-less form of the DESCENDANTS // function; same result again assertQueryReturns( "with member [Measures].[Sum Sqft] as '" + "sum(" + " Descendants([Store].CurrentMember, , LEAVES)," + " [Store].CurrentMember.Properties(\"Store Sqft\")) '\n" + "select {[Store].[USA], [Store].[USA].[CA]} on 0,\n" + " [Gender].Children on 1\n" + "from [Sales]", expected); } public void testIifWithTupleFirstAndMemberNextWithMeasure() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(1=1, ([Gender].[All Gender],measures.[unit sales])," + "([Gender].[All Gender]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 266,773\n"); } public void testIifWithMemberFirstAndTupleNextWithMeasure() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(1=1, ([Gender].[All Gender])," + "([Gender].[All Gender],measures.[unit sales]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 266,773\n"); } public void testIifWithMemberFirstAndTupleNextWithoutMeasure() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(1=1, ([Gender].[All Gender])," + "([Gender].[All Gender],[Time].[1997]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 266,773\n"); } public void testIifWithTupleFirstAndMemberNextWithoutMeasure() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(1=1, " + "([Store].[All Stores].[USA], [Gender].[All Gender]), " + "([Gender].[All Gender]))', " + "SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{([Gender].agg)} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[agg]}\n" + "Row #0: 266,773\n"); } public void testIifWithTuplesOfUnequalSizes() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(Measures.currentMember is [Measures].[Unit Sales], " + "([Store].[All Stores],[Gender].[All Gender],measures.[unit sales])," + "([Store].[All Stores],[Gender].[All Gender]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 266,773\n"); } public void testIifWithTuplesOfUnequalSizesAndOrder() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(Measures.currentMember is [Measures].[Unit Sales], " + "([Store].[All Stores],[Gender].[M],measures.[unit sales])," + "([Gender].[M],[Store].[All Stores]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 135,215\n"); } public void testEmptyAggregationListDueToFilterDoesNotThrowException() { boolean ignoreMeasureForNonJoiningDimension = props.IgnoreMeasureForNonJoiningDimension.get(); props.IgnoreMeasureForNonJoiningDimension.set(true); try { assertQueryReturns( "WITH \n" + "MEMBER [GENDER].[AGG] " + "AS 'AGGREGATE(FILTER([S1], (NOT ISEMPTY([MEASURES].[STORE SALES]))))' " + "SET [S1] " + "AS 'CROSSJOIN({[GENDER].[GENDER].MEMBERS},{[STORE].[CANADA].CHILDREN})' " + "SELECT\n" + "{[MEASURES].[STORE SALES]} ON COLUMNS,\n" + "{[GENDER].[AGG]} ON ROWS\n" + "FROM [WAREHOUSE AND SALES]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Gender].[AGG]}\n" + "Row #0: \n"); } finally { props.IgnoreMeasureForNonJoiningDimension.set( ignoreMeasureForNonJoiningDimension); } } /** * Testcase for Pentaho bug * <a href="http://jira.pentaho.org/browse/BISERVER-1323">BISERVER-1323</a>, * empty SQL query generated when crossjoining more than two sets each * containing just the 'all' member. */ public void testEmptySqlBug() { final String expectedResult = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores], [Product].[All Products], [Customers].[All Customers]}\n" + "Row #0: 266,773\n"; assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin({[Store].[All Stores]}" + ", Crossjoin({[Product].[All Products]}, {[Customers].[All Customers]})) ON ROWS " + "from [Sales]", expectedResult); // without NON EMPTY assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + " Crossjoin({[Store].[All Stores]}" + ", Crossjoin({[Product].[All Products]}, {[Customers].[All Customers]})) ON ROWS " + "from [Sales]", expectedResult); // using * operator assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores] " + " * [Product].[All Products]" + " * [Customers].[All Customers] ON ROWS " + "from [Sales]", expectedResult); // combining tuple assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores] " + " * {([Product].[All Products]," + " [Customers].[All Customers])} ON ROWS " + "from [Sales]", expectedResult); // combining two members with tuple final String expectedResult4 = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores], [Product].[All Products], [Customers].[All Customers], [Gender].[All Gender]}\n" + "Row #0: 266,773\n"; assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores] " + " * [Product].[All Products]" + " * {([Customers].[All Customers], [Gender].[All Gender])} ON ROWS " + "from [Sales]", expectedResult4); assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores] " + " * {([Product].[All Products], [Customers].[All Customers])}" + " * [Gender].[All Gender] ON ROWS " + "from [Sales]", expectedResult4); assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY {([Store].[All Stores], [Product].[All Products])}" + " * [Customers].[All Customers]" + " * [Gender].[All Gender] ON ROWS " + "from [Sales]", expectedResult4); } /** * Tests bug <a href="http://jira.pentaho.com/browse/MONDRIAN-7">MONDRIAN-7, * "Heterogeneous axis gives wrong results"</a>. The bug is a misnomer; * heterogeneous axes should give an error. */ public void testHeterogeneousAxis() { // SSAS2005 gives error: // Query (1, 8) Two sets specified in the function have different // dimensionality. assertQueryThrows( "select {[Measures].[Unit Sales], [Gender].Members} on 0,\n" + " [Store].[USA].Children on 1\n" + "from [Sales]", "All arguments to function '{}' must have same hierarchy."); assertQueryThrows( "select {[Marital Status].Members, [Gender].Members} on 0,\n" + " [Store].[USA].Children on 1\n" + "from [Sales]", "All arguments to function '{}' must have same hierarchy."); } /** * Tests hierarchies of the same dimension on different axes. */ public void testHierarchiesOfSameDimensionOnDifferentAxes() { if (!MondrianProperties.instance().SsasCompatibleNaming.get()) { return; } assertQueryReturns( "select [Time].[Year].Members on columns,\n" + "[Time].[Weekly].[1997].[6].Children on rows\n" + "from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997]}\n" + "{[Time].[1998]}\n" + "Axis #2:\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[1]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[26]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[27]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[28]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[29]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[30]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[31]}\n" + "Row #0: 404\n" + "Row #0: \n" + "Row #1: 593\n" + "Row #1: \n" + "Row #2: 422\n" + "Row #2: \n" + "Row #3: 382\n" + "Row #3: \n" + "Row #4: 731\n" + "Row #4: \n" + "Row #5: \n" + "Row #5: \n" + "Row #6: \n" + "Row #6: \n"); } /** * A simple user-defined function which adds one to its argument, but * sleeps 1 ms before doing so. */ public static class SleepUdf implements UserDefinedFunction { public String getName() { return "SleepUdf"; } public String getDescription() { return "Returns its argument plus one but sleeps 1 ms first"; } public Syntax getSyntax() { return Syntax.Function; } public Type getReturnType(Type[] parameterTypes) { return new NumericType(); } public Type[] getParameterTypes() { return new Type[] {new NumericType()}; } public Object execute(Evaluator evaluator, Argument[] arguments) { final Object argValue = arguments[0].evaluateScalar(evaluator); if (argValue instanceof Number) { try { Thread.sleep(1); } catch (Exception ex) { return null; } return ((Number) argValue).doubleValue() + 1; } else { // Argument might be a RuntimeException indicating that // the cache does not yet have the required cell value. The // function will be called again when the cache is loaded. return null; } } public String[] getReservedWords() { return null; } } /** * This unit test would cause connection leaks without a fix for bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-571">MONDRIAN-571, * "HighCardSqlTupleReader does not close SQL Connections"</a>. * It would be better if there was a way to verify that no leaks occurred in * the data source. */ public void testHighCardSqlTupleReaderLeakingConnections() { assertQueryReturns( "WITH MEMBER [Measures].[NegativeSales] AS '- [Measures].[Store Sales]' " + "MEMBER [Product].[SameName] AS 'Aggregate(Filter(" + "[Product].[Product Name].members,([Measures].[Store Sales] > 0)))' " + "MEMBER [Measures].[SameName] AS " + "'([Measures].[Store Sales],[Product].[SameName])' " + "select {[Measures].[Store Sales], [Measures].[NegativeSales], " + "[Measures].[SameName]} ON COLUMNS, " + "[Store].[Store Country].members ON ROWS " + "from [Sales] " + "where [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[NegativeSales]}\n" + "{[Measures].[SameName]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[Canada]}\n" + "{[Store].[All Stores].[Mexico]}\n" + "{[Store].[All Stores].[USA]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #2: 565,238.13\n" + "Row #2: -565,238.13\n" + "Row #2: 565,238.13\n"); } } // End BasicQueryTest.java
testsrc/main/mondrian/test/BasicQueryTest.java
/* // $Id$ // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // Copyright (C) 2003-2009 Julian Hyde // All Rights Reserved. // You must accept the terms of that agreement to use this software. // // jhyde, Feb 14, 2003 */ package mondrian.test; import mondrian.olap.*; import mondrian.olap.type.NumericType; import mondrian.olap.type.Type; import mondrian.rolap.RolapConnectionProperties; import mondrian.spi.UserDefinedFunction; import mondrian.spi.Dialect; import mondrian.util.Bug; import mondrian.calc.ResultStyle; import java.util.regex.Pattern; import java.util.*; import junit.framework.Assert; /** * <code>BasicQueryTest</code> is a test case which tests simple queries * against the FoodMart database. * * @author jhyde * @since Feb 14, 2003 * @version $Id$ */ public class BasicQueryTest extends FoodMartTestCase { static final String EmptyResult = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "Axis #2:\n"; private static final String timeWeekly = TestContext.hierarchyName("Time", "Weekly"); private MondrianProperties props = MondrianProperties.instance(); public BasicQueryTest() { super(); } public BasicQueryTest(String name) { super(name); } private static final QueryAndResult[] sampleQueries = { // 0 new QueryAndResult( "select {[Measures].[Unit Sales]} on columns\n" + " from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Row #0: 266,773\n"), // 1 new QueryAndResult( "select\n" + " {[Measures].[Unit Sales]} on columns,\n" + " order(except([Promotion Media].[Media Type].members,{[Promotion Media].[Media Type].[No Media]}),[Measures].[Unit Sales],DESC) on rows\n" + "from Sales ", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Promotion Media].[All Media].[Daily Paper, Radio, TV]}\n" + "{[Promotion Media].[All Media].[Daily Paper]}\n" + "{[Promotion Media].[All Media].[Product Attachment]}\n" + "{[Promotion Media].[All Media].[Daily Paper, Radio]}\n" + "{[Promotion Media].[All Media].[Cash Register Handout]}\n" + "{[Promotion Media].[All Media].[Sunday Paper, Radio]}\n" + "{[Promotion Media].[All Media].[Street Handout]}\n" + "{[Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Promotion Media].[All Media].[Bulk Mail]}\n" + "{[Promotion Media].[All Media].[In-Store Coupon]}\n" + "{[Promotion Media].[All Media].[TV]}\n" + "{[Promotion Media].[All Media].[Sunday Paper, Radio, TV]}\n" + "{[Promotion Media].[All Media].[Radio]}\n" + "Row #0: 9,513\n" + "Row #1: 7,738\n" + "Row #2: 7,544\n" + "Row #3: 6,891\n" + "Row #4: 6,697\n" + "Row #5: 5,945\n" + "Row #6: 5,753\n" + "Row #7: 4,339\n" + "Row #8: 4,320\n" + "Row #9: 3,798\n" + "Row #10: 3,607\n" + "Row #11: 2,726\n" + "Row #12: 2,454\n"), // 2 new QueryAndResult( "select\n" + " { [Measures].[Units Shipped], [Measures].[Units Ordered] } on columns,\n" + " NON EMPTY [Store].[Store Name].members on rows\n" + "from Warehouse", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Units Shipped]}\n" + "{[Measures].[Units Ordered]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Row #0: 10759.0\n" + "Row #0: 11699.0\n" + "Row #1: 24587.0\n" + "Row #1: 26463.0\n" + "Row #2: 23835.0\n" + "Row #2: 26270.0\n" + "Row #3: 1696.0\n" + "Row #3: 1875.0\n" + "Row #4: 8515.0\n" + "Row #4: 9109.0\n" + "Row #5: 32393.0\n" + "Row #5: 35797.0\n" + "Row #6: 2348.0\n" + "Row #6: 2454.0\n" + "Row #7: 22734.0\n" + "Row #7: 24610.0\n" + "Row #8: 24110.0\n" + "Row #8: 26703.0\n" + "Row #9: 11889.0\n" + "Row #9: 12828.0\n" + "Row #10: 32411.0\n" + "Row #10: 35930.0\n" + "Row #11: 1860.0\n" + "Row #11: 2074.0\n" + "Row #12: 10589.0\n" + "Row #12: 11426.0\n"), // 3 new QueryAndResult( "with member [Measures].[Store Sales Last Period] as " + " '([Measures].[Store Sales], Time.[Time].PrevMember)',\n" + " format='#,###.00'\n" + "select\n" + " {[Measures].[Store Sales Last Period]} on columns,\n" + " {TopCount([Product].[Product Department].members,5, [Measures].[Store Sales Last Period])} on rows\n" + "from Sales\n" + "where ([Time].[1998])", "Axis #0:\n" + "{[Time].[1998]}\n" + "Axis #1:\n" + "{[Measures].[Store Sales Last Period]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "Row #0: 82,248.42\n" + "Row #1: 67,609.82\n" + "Row #2: 60,469.89\n" + "Row #3: 55,207.50\n" + "Row #4: 39,774.34\n"), // 4 new QueryAndResult( "with member [Measures].[Total Store Sales] as 'Sum(YTD(),[Measures].[Store Sales])', format_string='#.00'\n" + "select\n" + " {[Measures].[Total Store Sales]} on columns,\n" + " {TopCount([Product].[Product Department].members,5, [Measures].[Total Store Sales])} on rows\n" + "from Sales\n" + "where ([Time].[1997].[Q2].[4])", "Axis #0:\n" + "{[Time].[1997].[Q2].[4]}\n" + "Axis #1:\n" + "{[Measures].[Total Store Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "Row #0: 26526.67\n" + "Row #1: 21897.10\n" + "Row #2: 19980.90\n" + "Row #3: 17882.63\n" + "Row #4: 12963.23\n"), // 5 new QueryAndResult( "with member [Measures].[Store Profit Rate] as '([Measures].[Store Sales]-[Measures].[Store Cost])/[Measures].[Store Cost]', format = '#.00%'\n" + "select\n" + " {[Measures].[Store Cost],[Measures].[Store Sales],[Measures].[Store Profit Rate]} on columns,\n" + " Order([Product].[Product Department].members, [Measures].[Store Profit Rate], BDESC) on rows\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[Store Profit Rate]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Breakfast Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Carousel]}\n" + "{[Product].[All Products].[Food].[Canned Products]}\n" + "{[Product].[All Products].[Food].[Baking Goods]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Non-Consumable].[Health and Hygiene]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Baked Goods]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Periodicals]}\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Seafood]}\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Meat]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Starchy Foods]}\n" + "{[Product].[All Products].[Food].[Eggs]}\n" + "{[Product].[All Products].[Food].[Snacks]}\n" + "{[Product].[All Products].[Food].[Dairy]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "{[Product].[All Products].[Non-Consumable].[Checkout]}\n" + "Row #0: 2,756.80\n" + "Row #0: 6,941.46\n" + "Row #0: 151.79%\n" + "Row #1: 595.97\n" + "Row #1: 1,500.11\n" + "Row #1: 151.71%\n" + "Row #2: 1,317.13\n" + "Row #2: 3,314.52\n" + "Row #2: 151.65%\n" + "Row #3: 15,370.61\n" + "Row #3: 38,670.41\n" + "Row #3: 151.59%\n" + "Row #4: 5,576.79\n" + "Row #4: 14,029.08\n" + "Row #4: 151.56%\n" + "Row #5: 12,972.99\n" + "Row #5: 32,571.86\n" + "Row #5: 151.07%\n" + "Row #6: 26,963.34\n" + "Row #6: 67,609.82\n" + "Row #6: 150.75%\n" + "Row #7: 6,564.09\n" + "Row #7: 16,455.43\n" + "Row #7: 150.69%\n" + "Row #8: 11,069.53\n" + "Row #8: 27,748.53\n" + "Row #8: 150.67%\n" + "Row #9: 22,030.66\n" + "Row #9: 55,207.50\n" + "Row #9: 150.59%\n" + "Row #10: 3,614.55\n" + "Row #10: 9,056.76\n" + "Row #10: 150.56%\n" + "Row #11: 32,831.33\n" + "Row #11: 82,248.42\n" + "Row #11: 150.52%\n" + "Row #12: 1,520.70\n" + "Row #12: 3,809.14\n" + "Row #12: 150.49%\n" + "Row #13: 10,108.87\n" + "Row #13: 25,318.93\n" + "Row #13: 150.46%\n" + "Row #14: 1,465.42\n" + "Row #14: 3,669.89\n" + "Row #14: 150.43%\n" + "Row #15: 15,894.53\n" + "Row #15: 39,774.34\n" + "Row #15: 150.24%\n" + "Row #16: 24,170.73\n" + "Row #16: 60,469.89\n" + "Row #16: 150.18%\n" + "Row #17: 4,705.91\n" + "Row #17: 11,756.07\n" + "Row #17: 149.82%\n" + "Row #18: 3,684.90\n" + "Row #18: 9,200.76\n" + "Row #18: 149.69%\n" + "Row #19: 5,827.58\n" + "Row #19: 14,550.05\n" + "Row #19: 149.68%\n" + "Row #20: 12,228.85\n" + "Row #20: 30,508.85\n" + "Row #20: 149.48%\n" + "Row #21: 2,830.92\n" + "Row #21: 7,058.60\n" + "Row #21: 149.34%\n" + "Row #22: 1,525.04\n" + "Row #22: 3,767.71\n" + "Row #22: 147.06%\n"), // 6 new QueryAndResult( "with\n" + " member [Product].[All Products].[Drink].[Percent of Alcoholic Drinks] as '[Product].[All Products].[Drink].[Alcoholic Beverages]/[Product].[All Products].[Drink]',\n" + " format_string = '#.00%'\n" + "select\n" + " { [Product].[All Products].[Drink].[Percent of Alcoholic Drinks] } on columns,\n" + " order([Customers].[All Customers].[USA].[WA].Children, [Product].[All Products].[Drink].[Percent of Alcoholic Drinks],BDESC) on rows\n" + "from Sales\n" + "where ([Measures].[Unit Sales])", "Axis #0:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #1:\n" + "{[Product].[All Products].[Drink].[Percent of Alcoholic Drinks]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "Row #0: 44.05%\n" + "Row #1: 34.41%\n" + "Row #2: 34.20%\n" + "Row #3: 32.93%\n" + "Row #4: 31.05%\n" + "Row #5: 30.84%\n" + "Row #6: 30.69%\n" + "Row #7: 29.81%\n" + "Row #8: 28.82%\n" + "Row #9: 28.70%\n" + "Row #10: 28.37%\n" + "Row #11: 26.67%\n" + "Row #12: 26.60%\n" + "Row #13: 26.47%\n" + "Row #14: 26.42%\n" + "Row #15: 26.28%\n" + "Row #16: 25.96%\n" + "Row #17: 24.70%\n" + "Row #18: 21.89%\n" + "Row #19: 21.47%\n" + "Row #20: 17.47%\n" + "Row #21: 13.79%\n"), // 7 new QueryAndResult( "with member [Measures].[Accumulated Sales] as 'Sum(YTD(),[Measures].[Store Sales])'\n" + "select\n" + " {[Measures].[Store Sales],[Measures].[Accumulated Sales]} on columns,\n" + " {Descendants([Time].[1997],[Time].[Month])} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[Accumulated Sales]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1].[1]}\n" + "{[Time].[1997].[Q1].[2]}\n" + "{[Time].[1997].[Q1].[3]}\n" + "{[Time].[1997].[Q2].[4]}\n" + "{[Time].[1997].[Q2].[5]}\n" + "{[Time].[1997].[Q2].[6]}\n" + "{[Time].[1997].[Q3].[7]}\n" + "{[Time].[1997].[Q3].[8]}\n" + "{[Time].[1997].[Q3].[9]}\n" + "{[Time].[1997].[Q4].[10]}\n" + "{[Time].[1997].[Q4].[11]}\n" + "{[Time].[1997].[Q4].[12]}\n" + "Row #0: 45,539.69\n" + "Row #0: 45,539.69\n" + "Row #1: 44,058.79\n" + "Row #1: 89,598.48\n" + "Row #2: 50,029.87\n" + "Row #2: 139,628.35\n" + "Row #3: 42,878.25\n" + "Row #3: 182,506.60\n" + "Row #4: 44,456.29\n" + "Row #4: 226,962.89\n" + "Row #5: 45,331.73\n" + "Row #5: 272,294.62\n" + "Row #6: 50,246.88\n" + "Row #6: 322,541.50\n" + "Row #7: 46,199.04\n" + "Row #7: 368,740.54\n" + "Row #8: 43,825.97\n" + "Row #8: 412,566.51\n" + "Row #9: 42,342.27\n" + "Row #9: 454,908.78\n" + "Row #10: 53,363.71\n" + "Row #10: 508,272.49\n" + "Row #11: 56,965.64\n" + "Row #11: 565,238.13\n"), // 8 new QueryAndResult( "select {[Measures].[Promotion Sales]} on columns\n" + " from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Promotion Sales]}\n" + "Row #0: 151,211.21\n"), }; public void testSample0() { assertQueryReturns(sampleQueries[0].query, sampleQueries[0].result); } public void testSample1() { assertQueryReturns(sampleQueries[1].query, sampleQueries[1].result); } public void testSample2() { assertQueryReturns(sampleQueries[2].query, sampleQueries[2].result); } public void testSample3() { assertQueryReturns(sampleQueries[3].query, sampleQueries[3].result); } public void testSample4() { assertQueryReturns(sampleQueries[4].query, sampleQueries[4].result); } public void testSample5() { assertQueryReturns(sampleQueries[5].query, sampleQueries[5].result); } public void testSample6() { assertQueryReturns(sampleQueries[6].query, sampleQueries[6].result); } public void testSample7() { assertQueryReturns(sampleQueries[7].query, sampleQueries[7].result); } public void testSample8() { if (TestContext.instance().getDialect().getDatabaseProduct() == Dialect.DatabaseProduct.INFOBRIGHT) { // Skip this test on Infobright, because [Promotion Sales] is // defined wrong. return; } assertQueryReturns(sampleQueries[8].query, sampleQueries[8].result); } public void testGoodComments() { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]/* trailing comment*/", EmptyResult); String[] comments = { "-- a basic comment\n", "// another basic comment\n", "/* yet another basic comment */", "-- a more complicated comment test\n", "-- to make it more intesting, -- we'll nest this comment\n", "-- also, \"we can put a string in the comment\"\n", "-- also, 'even a single quote string'\n", "---- and, the comment delimiter is looong\n", "/*\n" + " * next, how about a comment block?\n" + " * with several lines.\n" + " * also, \"we can put a string in the comment\"\n" + " * also, 'even a single quote string'\n" + " * also, -- another style comment is happy\n" + " */\n", "/* a simple /* nested */ comment */", "/*\n" + " * a multiline /* nested */ comment\n" + "*/", "/*\n" + " * a multiline\n" + " * /* multiline\n" + " * * nested comment\n" + " * */\n" + "*/", "/*\n" + " * a multiline\n" + " * /* multiline\n" + " * /* deeply\n" + " * /* really /* deeply */\n" + " * * nested comment\n" + " * */\n" + " * */\n" + " * */\n" + "*/", "-- single-line comment containing /* multiline */ comment\n", "/* multi-line comment containing -- single-line comment */", }; List<String> allCommentList = new ArrayList<String>(); for (String comment : comments) { allCommentList.add(comment); if (comment.indexOf("\n") >= 0) { allCommentList.add(comment.replaceAll("\n", "\r\n")); allCommentList.add(comment.replaceAll("\n", "\n\r")); allCommentList.add(comment.replaceAll("\n", " \n \n ")); } } allCommentList.add(""); final String[] allComments = allCommentList.toArray(new String[allCommentList.size()]); // The last element of the array is the concatenation of all other // comments. StringBuilder buf = new StringBuilder(); for (String allComment : allComments) { buf.append(allComment); } allComments[allComments.length - 1] = buf.toString(); // Comment at start of query. for (String comment : allComments) { assertQueryReturns( comment + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment after SELECT. for (String comment : allComments) { assertQueryReturns( "SELECT" + comment + "{} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment within braces. for (String comment : allComments) { assertQueryReturns( "SELECT {" + comment + "} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment after axis name. for (String comment : allComments) { assertQueryReturns( "SELECT {} ON ROWS" + comment + ", {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment before slicer. for (String comment : allComments) { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales] WHERE" + comment + "([Gender].[F])", "Axis #0:\n" + "{[Gender].[All Gender].[F]}\n" + "Axis #1:\n" + "Axis #2:\n"); } // Comment after query. for (String comment : allComments) { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]" + comment, EmptyResult); } assertQueryReturns( "-- a comment test with carriage returns at the end of the lines\r\n" + "-- first, more than one single-line comment in a row\r\n" + "-- and, to make it more intesting, -- we'll nest this comment\r\n" + "-- also, \"we can put a string in the comment\"\r\n" + "-- also, 'even a single quote string'\r\n" + "---- and, the comment delimiter is looong\r\n" + "/*\r\n" + " * next, now about a comment block?\r\n" + " * with several lines.\r\n" + " * also, \"we can put a string in the comment\"\r\n" + " * also, 'even a single quote comment'\r\n" + " * also, -- another style comment is heppy\r\n" + " * also, // another style comment is heppy\r\n" + " */\r\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]\r", EmptyResult); assertQueryReturns( "/* a simple /* nested */ comment */\n" + "/*\n" + " * a multiline /* nested */ comment\n" + "*/\n" + "/*\n" + " * a multiline\n" + " * /* multiline\n" + " * * nested comment\n" + " * */\n" + "*/\n" + "/*\n" + " * a multiline\n" + " * /* multiline\n" + " * /* deeply\n" + " * /* really /* deeply */\n" + " * * nested comment\n" + " * */\n" + " * */\n" + " * */\n" + "*/\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); assertQueryReturns( "-- an entire select statement commented out\n" + "-- SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];\n" + "/*SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];*/\n" + "// SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); assertQueryReturns( "// now for some comments in a larger command\n" + "with // create calculate measure [Product].[All Products].[Drink].[Percent of Alcoholic Drinks]\n" + " member [Product].[All Products].[Drink].[Percent of Alcoholic Drinks]/*the measure name*/as ' // begin the definition of the measure next\n" + " [Product]./****this is crazy****/[All Products].[Drink].[Alcoholic Beverages]/[Product].[All Products].[Drink]', // divide number of alcoholic drinks by total # of drinks\n" + " format_string = '#.00%' // a custom format for our measure\n" + "select\n" + " { [Product]/**** still crazy ****/.[All Products].[Drink].[Percent of Alcoholic Drinks] } on columns,\n" + " order(/****do not put a comment inside square brackets****/[Customers].[All Customers].[USA].[WA].Children, [Product].[All Products].[Drink].[Percent of Alcoholic Drinks],BDESC) on rows\n" + "from Sales\n" + "where ([Measures].[Unit Sales] /****,[Time].[1997]****/) -- a comment at the end of the command", "Axis #0:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #1:\n" + "{[Product].[All Products].[Drink].[Percent of Alcoholic Drinks]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "Row #0: 44.05%\n" + "Row #1: 34.41%\n" + "Row #2: 34.20%\n" + "Row #3: 32.93%\n" + "Row #4: 31.05%\n" + "Row #5: 30.84%\n" + "Row #6: 30.69%\n" + "Row #7: 29.81%\n" + "Row #8: 28.82%\n" + "Row #9: 28.70%\n" + "Row #10: 28.37%\n" + "Row #11: 26.67%\n" + "Row #12: 26.60%\n" + "Row #13: 26.47%\n" + "Row #14: 26.42%\n" + "Row #15: 26.28%\n" + "Row #16: 25.96%\n" + "Row #17: 24.70%\n" + "Row #18: 21.89%\n" + "Row #19: 21.47%\n" + "Row #20: 17.47%\n" + "Row #21: 13.79%\n"); } public void testBadComments() { // Comments cannot appear inside identifiers. assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[/***an illegal comment****/Marital Status].[S]}", "Failed to parse query"); // Nested comments must be closed. assertQueryThrows( "/* a simple /* nested * comment */\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", "Failed to parse query"); // We do NOT support \r as a line-end delimiter. (Too bad, Mac users.) assertQueryThrows( "SELECT {} ON COLUMNS -- comment terminated by CR only\r, {} ON ROWS FROM [Sales]", "Failed to parse query"); } /** * Tests that a query whose axes are empty works; bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-52">MONDRIAN-52</a>. */ public void testBothAxesEmpty() { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); // expression which evaluates to empty set assertQueryReturns( "SELECT Filter({[Gender].MEMBERS}, 1 = 0) ON COLUMNS, \n" + "{} ON ROWS\n" + "FROM [Sales]", EmptyResult); // with slicer assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS \n" + "FROM [Sales] WHERE ([Gender].[F])", "Axis #0:\n" + "{[Gender].[All Gender].[F]}\n" + "Axis #1:\n" + "Axis #2:\n"); } /** * Tests that a slicer with multiple values gives an error; bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-96">MONDRIAN-96</a>. */ public void testCompoundSlicerFails() { // two tuples assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {([Marital Status].[S]),\n" + " ([Marital Status].[M])}", "Axis #0:\n" + "{[Marital Status].[All Marital Status].[S]}\n" + "{[Marital Status].[All Marital Status].[M]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n"); // set with incompatible members assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[Marital Status].[S],\n" + " [Product]}", "All arguments to function '{}' must have same hierarchy."); // expression which evaluates to a set with zero members used to be an // error - now it's ok; cells are null because they are aggregating over // nothing assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, 1 = 0)", "Axis #0:\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: \n" + "Row #1: \n" + "Row #2: \n"); // expression which evaluates to a not-null member is ok assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE ({Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] = 266773)}.Item(0))", "Axis #0:\n" + "{[Marital Status].[All Marital Status]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n"); // Expression which evaluates to a null member used to be an error; now // it is an unsatisfiable condition, so cells come out empty. // Confirmed with SSAS 2005. assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE [Marital Status].Parent", "Axis #0:\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: \n" + "Row #1: \n" + "Row #2: \n"); // expression which evaluates to a set with one member is ok assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] = 266773)", "Axis #0:\n" + "{[Marital Status].[All Marital Status]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n"); // slicer expression which evaluates to three tuples is not ok assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] <= 266773)", "Axis #0:\n" + "{[Marital Status].[All Marital Status]}\n" + "{[Marital Status].[All Marital Status].[M]}\n" + "{[Marital Status].[All Marital Status].[S]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n"); // set with incompatible members assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[Marital Status].[S],\n" + " [Product]}", "All arguments to function '{}' must have same hierarchy."); // two members of same dimension in columns and rows assertQueryThrows( "SELECT CrossJoin(\n" + " {[Measures].[Unit Sales]},\n" + " {[Gender].[M]}) ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]", "Hierarchy '[Gender]' appears in more than one independent axis."); // two members of same dimension in rows and filter assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Marital Status].[S], [Gender].[F])", "Hierarchy '[Gender]' appears in more than one independent axis."); // members of different hierarchies of the same dimension in rows and // filter assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Time].[1997].Children} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Marital Status].[S], " + timeWeekly + ".[1997].[20])", "Axis #0:\n" + "{[Marital Status].[All Marital Status].[S], [Time].[Weekly].[All Weeklys].[1997].[20]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: \n" + "Row #1: 3,523\n" + "Row #2: \n" + "Row #3: \n"); // two members of same dimension in slicer tuple assertQueryThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Marital Status].[S], [Marital Status].[M])", "Tuple contains more than one member of hierarchy '[Marital Status]'."); // two members of different hierarchies of the same dimension in the // slicer tuple assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Time].[1997].[Q1], " + timeWeekly + ".[1997].[4])", "Axis #0:\n" + "{[Time].[1997].[Q1], [Time].[Weekly].[All Weeklys].[1997].[4]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 4,908\n" + "Row #1: 2,354\n" + "Row #2: 2,554\n"); // testcase for bug MONDRIAN-68, "Member appears in slicer and other // axis should be illegal" assertQueryThrows( "select\n" + "{[Measures].[Unit Sales]} on columns,\n" + "{([Product].[All Products], [Time].[1997])} ON rows\n" + "from Sales\n" + "where ([Time].[1997])", "Hierarchy '[Time]' appears in more than one independent axis."); // different hierarchies of same dimension on slicer and other axis assertQueryReturns( "select\n" + "{[Measures].[Unit Sales]} on columns,\n" + "{([Product].[All Products], " + timeWeekly + ".[1997])} ON rows\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products], [Time].[Weekly].[All Weeklys].[1997]}\n" + "Row #0: 266,773\n"); } public void testEmptyTupleSlicerFails() { assertQueryThrows( "select [Measures].[Unit Sales] on 0,\n" + "[Product].Children on 1\n" + "from [Warehouse and Sales]\n" + "where ()", "Syntax error at line 4, column 10, token ')'"); } /** * Requires the use of a sparse segment, because the product dimension * has 6 atttributes, the product of whose cardinalities is ~8M. If we * use a dense segment, we run out of memory trying to allocate a huge * array. */ public void testBigQuery() { Result result = executeQuery( "SELECT {[Measures].[Unit Sales]} on columns,\n" + " {[Product].members} on rows\n" + "from Sales"); final int rowCount = result.getAxes()[1].getPositions().size(); assertEquals(2256, rowCount); assertEquals( "152", result.getCell( new int[]{ 0, rowCount - 1 }).getFormattedValue()); } public void testNonEmpty1() { assertSize( "select\n" + " NON EMPTY CrossJoin({[Product].[All Products].[Drink].Children},\n" + " {[Customers].[All Customers].[USA].[WA].[Bellingham]}) on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", 8, 2); } public void testNonEmpty2() { assertSize( "select\n" + " NON EMPTY CrossJoin(\n" + " {[Product].[All Products].Children},\n" + " {[Customers].[All Customers].[USA].[WA].[Bellingham]}) on rows,\n" + " NON EMPTY CrossJoin(\n" + " {[Measures].[Unit Sales]},\n" + " { [Promotion Media].[All Media].[Cash Register Handout],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", 2, 2); } public void testOneDimensionalQueryWithTupleAsSlicer() { Result result = executeQuery( "select\n" + " [Product].[All Products].[Drink].children on columns\n" + "from Sales\n" + "where ([Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997])"); assertTrue(result.getAxes().length == 1); assertTrue(result.getAxes()[0].getPositions().size() == 3); assertTrue(result.getSlicerAxis().getPositions().size() == 1); assertTrue(result.getSlicerAxis().getPositions().get(0).size() == 3); } public void testSlicerIsEvaluatedBeforeAxes() { // about 10 products exceeded 20000 units in 1997, only 2 for Q1 assertSize( "SELECT {[Measures].[Unit Sales]} on columns,\n" + " filter({[Product].members}, [Measures].[Unit Sales] > 20000) on rows\n" + "FROM Sales\n" + "WHERE [Time].[1997].[Q1]", 1, 2); } public void testSlicerWithCalculatedMembers() { assertSize( "WITH MEMBER [Time].[1997].[H1] as ' Aggregate({[Time].[1997].[Q1], [Time].[1997].[Q2]})' \n" + " MEMBER [Measures].[Store Margin] as '[Measures].[Store Sales] - [Measures].[Store Cost]'\n" + "SELECT {[Gender].children} on columns,\n" + " filter({[Product].members}, [Gender].[F] > 10000) on rows\n" + "FROM Sales\n" + "WHERE ([Time].[1997].[H1], [Measures].[Store Margin])", 2, 6); } public void _testEver() { assertQueryReturns( "select\n" + " {[Measures].[Unit Sales], [Measures].[Ever]} on columns,\n" + " [Gender].members on rows\n" + "from Sales", "xxx"); } public void _testDairy() { assertQueryReturns( "with\n" + " member [Product].[Non dairy] as '[Product].[All Products] - [Product].[Food].[Dairy]'\n" + " member [Measures].[Dairy ever] as 'sum([Time].members, ([Measures].[Unit Sales],[Product].[Food].[Dairy]))'\n" + " set [Customers who never bought dairy] as 'filter([Customers].members, [Measures].[Dairy ever] = 0)'\n" + "select\n" + " {[Measures].[Unit Sales], [Measures].[Dairy ever]} on columns,\n" + " [Customers who never bought dairy] on rows\n" + "from Sales", "xxx"); } public void testSolveOrder() { assertQueryReturns( "WITH\n" + " MEMBER [Measures].[StoreType] AS \n" + " '[Store].CurrentMember.Properties(\"Store Type\")',\n" + " SOLVE_ORDER = 2\n" + " MEMBER [Measures].[ProfitPct] AS \n" + " '(Measures.[Store Sales] - Measures.[Store Cost]) / Measures.[Store Sales]',\n" + " SOLVE_ORDER = 1, FORMAT_STRING = '##.00%'\n" + "SELECT\n" + " { Descendants([Store].[USA], [Store].[Store Name])} ON COLUMNS,\n" + " { [Measures].[Store Sales], [Measures].[Store Cost], [Measures].[StoreType],\n" + " [Measures].[ProfitPct] } ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[CA].[Alameda].[HQ]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Axis #2:\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[StoreType]}\n" + "{[Measures].[ProfitPct]}\n" + "Row #0: \n" + "Row #0: 45,750.24\n" + "Row #0: 54,545.28\n" + "Row #0: 54,431.14\n" + "Row #0: 4,441.18\n" + "Row #0: 55,058.79\n" + "Row #0: 87,218.28\n" + "Row #0: 4,739.23\n" + "Row #0: 52,896.30\n" + "Row #0: 52,644.07\n" + "Row #0: 49,634.46\n" + "Row #0: 74,843.96\n" + "Row #0: 4,705.97\n" + "Row #0: 24,329.23\n" + "Row #1: \n" + "Row #1: 18,266.44\n" + "Row #1: 21,771.54\n" + "Row #1: 21,713.53\n" + "Row #1: 1,778.92\n" + "Row #1: 21,948.94\n" + "Row #1: 34,823.56\n" + "Row #1: 1,896.62\n" + "Row #1: 21,121.96\n" + "Row #1: 20,956.80\n" + "Row #1: 19,795.49\n" + "Row #1: 29,959.28\n" + "Row #1: 1,880.34\n" + "Row #1: 9,713.81\n" + "Row #2: HeadQuarters\n" + "Row #2: Gourmet Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Supermarket\n" + "Row #2: Deluxe Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Deluxe Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Mid-Size Grocery\n" + "Row #3: \n" + "Row #3: 60.07%\n" + "Row #3: 60.09%\n" + "Row #3: 60.11%\n" + "Row #3: 59.94%\n" + "Row #3: 60.14%\n" + "Row #3: 60.07%\n" + "Row #3: 59.98%\n" + "Row #3: 60.07%\n" + "Row #3: 60.19%\n" + "Row #3: 60.12%\n" + "Row #3: 59.97%\n" + "Row #3: 60.04%\n" + "Row #3: 60.07%\n"); } public void testSolveOrderNonMeasure() { assertQueryReturns( "WITH\n" + " MEMBER [Product].[ProdCalc] as '1', SOLVE_ORDER=1\n" + " MEMBER [Measures].[MeasuresCalc] as '2', SOLVE_ORDER=2\n" + " MEMBER [Time].[TimeCalc] as '3', SOLVE_ORDER=3\n" + "SELECT\n" + " { [Product].[ProdCalc] } ON columns,\n" + " {([Time].[TimeCalc], [Measures].[MeasuresCalc])} ON rows\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Product].[ProdCalc]}\n" + "Axis #2:\n" + "{[Time].[TimeCalc], [Measures].[MeasuresCalc]}\n" + "Row #0: 3\n"); } public void testSolveOrderNonMeasure2() { assertQueryReturns( "WITH\n" + " MEMBER [Store].[StoreCalc] as '0', SOLVE_ORDER=0\n" + " MEMBER [Product].[ProdCalc] as '1', SOLVE_ORDER=1\n" + "SELECT\n" + " { [Product].[ProdCalc] } ON columns,\n" + " { [Store].[StoreCalc] } ON rows\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Product].[ProdCalc]}\n" + "Axis #2:\n" + "{[Store].[StoreCalc]}\n" + "Row #0: 1\n"); } /** * Test what happens when the solve orders are the same. According to * http://msdn.microsoft.com/library/en-us/olapdmad/agmdxadvanced_6jn7.asp * if solve orders are the same then the dimension specified first * when defining the cube wins. * * <p>In the first test, the answer should be 1 because Promotions * comes before Customers in the FoodMart.xml schema. */ public void testSolveOrderAmbiguous1() { assertQueryReturns( "WITH\n" + " MEMBER [Promotions].[Calc] AS '1'\n" + " MEMBER [Customers].[Calc] AS '2'\n" + "SELECT\n" + " { [Promotions].[Calc] } ON COLUMNS,\n" + " { [Customers].[Calc] } ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Promotions].[Calc]}\n" + "Axis #2:\n" + "{[Customers].[Calc]}\n" + "Row #0: 1\n"); } /** * In the second test, the answer should be 2 because Product comes before * Promotions in the FoodMart.xml schema. */ public void testSolveOrderAmbiguous2() { assertQueryReturns( "WITH\n" + " MEMBER [Promotions].[Calc] AS '1'\n" + " MEMBER [Product].[Calc] AS '2'\n" + "SELECT\n" + " { [Promotions].[Calc] } ON COLUMNS,\n" + " { [Product].[Calc] } ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Promotions].[Calc]}\n" + "Axis #2:\n" + "{[Product].[Calc]}\n" + "Row #0: 2\n"); } public void testCalculatedMemberWhichIsNotAMeasure() { assertQueryReturns( "WITH MEMBER [Product].[BigSeller] AS\n" + " 'IIf([Product].[Drink].[Alcoholic Beverages].[Beer and Wine] > 100, \"Yes\",\"No\")'\n" + "SELECT {[Product].[BigSeller],[Product].children} ON COLUMNS,\n" + " {[Store].[All Stores].[USA].[CA].children} ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Product].[BigSeller]}\n" + "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "Row #0: No\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n" + "Row #1: Yes\n" + "Row #1: 1,945\n" + "Row #1: 15,438\n" + "Row #1: 3,950\n" + "Row #2: Yes\n" + "Row #2: 2,422\n" + "Row #2: 18,294\n" + "Row #2: 4,947\n" + "Row #3: Yes\n" + "Row #3: 2,560\n" + "Row #3: 18,369\n" + "Row #3: 4,706\n" + "Row #4: No\n" + "Row #4: 175\n" + "Row #4: 1,555\n" + "Row #4: 387\n"); } public void testMultipleCalculatedMembersWhichAreNotMeasures() { assertQueryReturns( "WITH\n" + " MEMBER [Store].[x] AS '1'\n" + " MEMBER [Product].[x] AS '1'\n" + "SELECT {[Store].[x]} ON COLUMNS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[x]}\n" + "Row #0: 1\n"); } /** * There used to be something wrong with non-measure calculated members * where the ordering of the WITH MEMBER would determine whether or not * the member would be found in the cube. This test would fail but the * previous one would work ok. (see sf#1084651) */ public void testMultipleCalculatedMembersWhichAreNotMeasures2() { assertQueryReturns( "WITH\n" + " MEMBER [Product].[x] AS '1'\n" + " MEMBER [Store].[x] AS '1'\n" + "SELECT {[Store].[x]} ON COLUMNS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[x]}\n" + "Row #0: 1\n"); } /** * This one had the same problem. It wouldn't find the * [Store].[All Stores].[x] member because it has the same leaf * name as [Product].[All Products].[x]. (see sf#1084651) */ public void testMultipleCalculatedMembersWhichAreNotMeasures3() { assertQueryReturns( "WITH\n" + " MEMBER [Product].[All Products].[x] AS '1'\n" + " MEMBER [Store].[All Stores].[x] AS '1'\n" + "SELECT {[Store].[All Stores].[x]} ON COLUMNS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[x]}\n" + "Row #0: 1\n"); } public void testConstantString() { String s = executeExpr(" \"a string\" "); assertEquals("a string", s); } public void testConstantNumber() { String s = executeExpr(" 1234 "); assertEquals("1,234", s); } public void testCyclicalCalculatedMembers() { Util.discard( executeQuery( "WITH\n" + " MEMBER [Product].[X] AS '[Product].[Y]'\n" + " MEMBER [Product].[Y] AS '[Product].[X]'\n" + "SELECT\n" + " {[Product].[X]} ON COLUMNS,\n" + " {Store.[Store Name].Members} ON ROWS\n" + "FROM Sales")); } /** * Disabled test. It used throw an 'infinite loop' error (which is what * Plato does). But now we revert to the context of the default member when * calculating calculated members (we used to stay in the context of the * calculated member), and we get a result. */ public void testCycle() { if (false) { assertExprThrows("[Time].[1997].[Q4]", "infinite loop"); } else { String s = executeExpr("[Time].[1997].[Q4]"); assertEquals("72,024", s); } } public void testHalfYears() { Util.discard( executeQuery( "WITH MEMBER [Measures].[ProfitPercent] AS\n" + " '([Measures].[Store Sales]-[Measures].[Store Cost])/([Measures].[Store Cost])',\n" + " FORMAT_STRING = '#.00%', SOLVE_ORDER = 1\n" + " MEMBER [Time].[First Half 97] AS '[Time].[1997].[Q1] + [Time].[1997].[Q2]'\n" + " MEMBER [Time].[Second Half 97] AS '[Time].[1997].[Q3] + [Time].[1997].[Q4]'\n" + " SELECT {[Time].[First Half 97],\n" + " [Time].[Second Half 97],\n" + " [Time].[1997].CHILDREN} ON COLUMNS,\n" + " {[Store].[Store Country].[USA].CHILDREN} ON ROWS\n" + " FROM [Sales]\n" + " WHERE ([Measures].[ProfitPercent])")); } public void _testHalfYearsTrickyCase() { Util.discard( executeQuery( "WITH MEMBER MEASURES.ProfitPercent AS\n" + " '([Measures].[Store Sales]-[Measures].[Store Cost])/([Measures].[Store Cost])',\n" + " FORMAT_STRING = '#.00%', SOLVE_ORDER = 1\n" + " MEMBER [Time].[First Half 97] AS '[Time].[1997].[Q1] + [Time].[1997].[Q2]'\n" + " MEMBER [Time].[Second Half 97] AS '[Time].[1997].[Q3] + [Time].[1997].[Q4]'\n" + " SELECT {[Time].[First Half 97],\n" + " [Time].[Second Half 97],\n" + " [Time].[1997].CHILDREN} ON COLUMNS,\n" + " {[Store].[Store Country].[USA].CHILDREN} ON ROWS\n" + " FROM [Sales]\n" + " WHERE (MEASURES.ProfitPercent)")); } public void testAsSample7ButUsingVirtualCube() { Util.discard( executeQuery( "with member [Measures].[Accumulated Sales] as 'Sum(YTD(),[Measures].[Store Sales])'\n" + "select\n" + " {[Measures].[Store Sales],[Measures].[Accumulated Sales]} on columns,\n" + " {Descendants([Time].[1997],[Time].[Month])} on rows\n" + "from [Warehouse and Sales]")); } public void testVirtualCube() { assertQueryReturns( // Note that Unit Sales is independent of Warehouse. "select CrossJoin(\n" + " {[Warehouse].DefaultMember, [Warehouse].[USA].children},\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales], [Measures].[Units Shipped]}) on columns,\n" + " [Time].[Time].children on rows\n" + "from [Warehouse and Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Warehouse].[All Warehouses], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Units Shipped]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 66,291\n" + "Row #0: 139,628.35\n" + "Row #0: 50951.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 8539.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 7994.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 34418.0\n" + "Row #1: 62,610\n" + "Row #1: 132,666.27\n" + "Row #1: 49187.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 15726.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 7575.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 25886.0\n" + "Row #2: 65,848\n" + "Row #2: 140,271.89\n" + "Row #2: 57789.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 20821.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 8673.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 28295.0\n" + "Row #3: 72,024\n" + "Row #3: 152,671.62\n" + "Row #3: 49799.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 15791.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 16666.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 17342.0\n"); } public void testUseDimensionAsShorthandForMember() { Util.discard( executeQuery( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Store], [Store].children} on rows\n" + "from [Sales]")); } public void _testMembersFunction() { Util.discard( executeQuery( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Customers].members(0)} on rows\n" + "from [Sales]")); } public void _testProduct2() { final Axis axis = getTestContext().executeAxis("{[Product2].members}"); System.out.println(TestContext.toString(axis.getPositions())); } private static final List<QueryAndResult> taglibQueries = Arrays.asList( // 0 new QueryAndResult( "select\n" + " {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} on columns,\n" + " CrossJoin(\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] },\n" + " [Product].[All Products].[Drink].children) on rows\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75\n" + "Row #0: 70.40\n" + "Row #0: 168.62\n" + "Row #1: 97\n" + "Row #1: 75.70\n" + "Row #1: 186.03\n" + "Row #2: 54\n" + "Row #2: 36.75\n" + "Row #2: 89.03\n" + "Row #3: 76\n" + "Row #3: 70.99\n" + "Row #3: 182.38\n" + "Row #4: 188\n" + "Row #4: 167.00\n" + "Row #4: 419.14\n" + "Row #5: 68\n" + "Row #5: 45.19\n" + "Row #5: 119.55\n" + "Row #6: 148\n" + "Row #6: 128.97\n" + "Row #6: 316.88\n" + "Row #7: 197\n" + "Row #7: 161.81\n" + "Row #7: 399.58\n" + "Row #8: 85\n" + "Row #8: 54.75\n" + "Row #8: 140.27\n" + "Row #9: 158\n" + "Row #9: 121.14\n" + "Row #9: 294.55\n" + "Row #10: 270\n" + "Row #10: 201.28\n" + "Row #10: 520.55\n" + "Row #11: 84\n" + "Row #11: 50.26\n" + "Row #11: 128.32\n"), // 1 new QueryAndResult( "select\n" + " [Product].[All Products].[Drink].children on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75\n" + "Row #0: 76\n" + "Row #0: 148\n" + "Row #0: 158\n" + "Row #0: 168.62\n" + "Row #0: 182.38\n" + "Row #0: 316.88\n" + "Row #0: 294.55\n" + "Row #1: 97\n" + "Row #1: 188\n" + "Row #1: 197\n" + "Row #1: 270\n" + "Row #1: 186.03\n" + "Row #1: 419.14\n" + "Row #1: 399.58\n" + "Row #1: 520.55\n" + "Row #2: 54\n" + "Row #2: 68\n" + "Row #2: 85\n" + "Row #2: 84\n" + "Row #2: 89.03\n" + "Row #2: 119.55\n" + "Row #2: 140.27\n" + "Row #2: 128.32\n"), // 2 new QueryAndResult( "select\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]} on columns,\n" + " Order([Product].[Product Department].members, [Measures].[Store Sales], DESC) on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "{[Product].[All Products].[Food].[Baking Goods]}\n" + "{[Product].[All Products].[Food].[Dairy]}\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Baked Goods]}\n" + "{[Product].[All Products].[Food].[Snacks]}\n" + "{[Product].[All Products].[Food].[Starchy Foods]}\n" + "{[Product].[All Products].[Food].[Eggs]}\n" + "{[Product].[All Products].[Food].[Breakfast Foods]}\n" + "{[Product].[All Products].[Food].[Seafood]}\n" + "{[Product].[All Products].[Food].[Meat]}\n" + "{[Product].[All Products].[Food].[Canned Products]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Non-Consumable].[Health and Hygiene]}\n" + "{[Product].[All Products].[Non-Consumable].[Periodicals]}\n" + "{[Product].[All Products].[Non-Consumable].[Checkout]}\n" + "{[Product].[All Products].[Non-Consumable].[Carousel]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 37,792\n" + "Row #0: 82,248.42\n" + "Row #1: 30,545\n" + "Row #1: 67,609.82\n" + "Row #2: 26,655\n" + "Row #2: 55,207.50\n" + "Row #3: 19,026\n" + "Row #3: 39,774.34\n" + "Row #4: 20,245\n" + "Row #4: 38,670.41\n" + "Row #5: 12,885\n" + "Row #5: 30,508.85\n" + "Row #6: 12,037\n" + "Row #6: 25,318.93\n" + "Row #7: 7,870\n" + "Row #7: 16,455.43\n" + "Row #8: 6,884\n" + "Row #8: 14,550.05\n" + "Row #9: 5,262\n" + "Row #9: 11,756.07\n" + "Row #10: 4,132\n" + "Row #10: 9,200.76\n" + "Row #11: 3,317\n" + "Row #11: 6,941.46\n" + "Row #12: 1,764\n" + "Row #12: 3,809.14\n" + "Row #13: 1,714\n" + "Row #13: 3,669.89\n" + "Row #14: 1,812\n" + "Row #14: 3,314.52\n" + "Row #15: 27,038\n" + "Row #15: 60,469.89\n" + "Row #16: 16,284\n" + "Row #16: 32,571.86\n" + "Row #17: 4,294\n" + "Row #17: 9,056.76\n" + "Row #18: 1,779\n" + "Row #18: 3,767.71\n" + "Row #19: 841\n" + "Row #19: 1,500.11\n" + "Row #20: 13,573\n" + "Row #20: 27,748.53\n" + "Row #21: 6,838\n" + "Row #21: 14,029.08\n" + "Row #22: 4,186\n" + "Row #22: 7,058.60\n"), // 3 new QueryAndResult( "select\n" + " [Product].[All Products].[Drink].children on columns\n" + "from Sales\n" + "where ([Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997])", "Axis #0:\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997]}\n" + "Axis #1:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 158\n" + "Row #0: 270\n" + "Row #0: 84\n"), // 4 new QueryAndResult( "select\n" + " NON EMPTY CrossJoin([Product].[All Products].[Drink].children, [Customers].[All Customers].[USA].[WA].Children) on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "Row #0: \n" + "Row #0: 2\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 1.14\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 4\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 4\n" + "Row #1: 10.40\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 2.16\n" + "Row #2: \n" + "Row #2: 1\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 2.37\n" + "Row #2: \n" + "Row #2: \n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 24\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 46.09\n" + "Row #3: \n" + "Row #4: 3\n" + "Row #4: \n" + "Row #4: \n" + "Row #4: 8\n" + "Row #4: 2.10\n" + "Row #4: \n" + "Row #4: \n" + "Row #4: 9.63\n" + "Row #5: 6\n" + "Row #5: \n" + "Row #5: \n" + "Row #5: 5\n" + "Row #5: 8.06\n" + "Row #5: \n" + "Row #5: \n" + "Row #5: 6.21\n" + "Row #6: 3\n" + "Row #6: \n" + "Row #6: \n" + "Row #6: 7\n" + "Row #6: 7.80\n" + "Row #6: \n" + "Row #6: \n" + "Row #6: 15.00\n" + "Row #7: 14\n" + "Row #7: \n" + "Row #7: \n" + "Row #7: \n" + "Row #7: 36.10\n" + "Row #7: \n" + "Row #7: \n" + "Row #7: \n" + "Row #8: 3\n" + "Row #8: \n" + "Row #8: \n" + "Row #8: 16\n" + "Row #8: 10.29\n" + "Row #8: \n" + "Row #8: \n" + "Row #8: 32.20\n" + "Row #9: 3\n" + "Row #9: \n" + "Row #9: \n" + "Row #9: \n" + "Row #9: 10.56\n" + "Row #9: \n" + "Row #9: \n" + "Row #9: \n" + "Row #10: \n" + "Row #10: \n" + "Row #10: 15\n" + "Row #10: 11\n" + "Row #10: \n" + "Row #10: \n" + "Row #10: 34.79\n" + "Row #10: 15.67\n" + "Row #11: \n" + "Row #11: \n" + "Row #11: 7\n" + "Row #11: \n" + "Row #11: \n" + "Row #11: \n" + "Row #11: 17.44\n" + "Row #11: \n" + "Row #12: \n" + "Row #12: \n" + "Row #12: 22\n" + "Row #12: 9\n" + "Row #12: \n" + "Row #12: \n" + "Row #12: 32.35\n" + "Row #12: 17.43\n" + "Row #13: 7\n" + "Row #13: \n" + "Row #13: \n" + "Row #13: 4\n" + "Row #13: 4.77\n" + "Row #13: \n" + "Row #13: \n" + "Row #13: 15.16\n" + "Row #14: 4\n" + "Row #14: \n" + "Row #14: \n" + "Row #14: 4\n" + "Row #14: 3.64\n" + "Row #14: \n" + "Row #14: \n" + "Row #14: 9.64\n" + "Row #15: 2\n" + "Row #15: \n" + "Row #15: \n" + "Row #15: 7\n" + "Row #15: 6.86\n" + "Row #15: \n" + "Row #15: \n" + "Row #15: 8.38\n" + "Row #16: \n" + "Row #16: \n" + "Row #16: \n" + "Row #16: 28\n" + "Row #16: \n" + "Row #16: \n" + "Row #16: \n" + "Row #16: 61.98\n" + "Row #17: \n" + "Row #17: \n" + "Row #17: 3\n" + "Row #17: 4\n" + "Row #17: \n" + "Row #17: \n" + "Row #17: 10.56\n" + "Row #17: 8.96\n" + "Row #18: 6\n" + "Row #18: \n" + "Row #18: \n" + "Row #18: 3\n" + "Row #18: 7.16\n" + "Row #18: \n" + "Row #18: \n" + "Row #18: 8.10\n" + "Row #19: 7\n" + "Row #19: \n" + "Row #19: \n" + "Row #19: \n" + "Row #19: 15.63\n" + "Row #19: \n" + "Row #19: \n" + "Row #19: \n" + "Row #20: 3\n" + "Row #20: \n" + "Row #20: \n" + "Row #20: 13\n" + "Row #20: 6.96\n" + "Row #20: \n" + "Row #20: \n" + "Row #20: 12.22\n" + "Row #21: \n" + "Row #21: \n" + "Row #21: 16\n" + "Row #21: \n" + "Row #21: \n" + "Row #21: \n" + "Row #21: 45.08\n" + "Row #21: \n" + "Row #22: 3\n" + "Row #22: \n" + "Row #22: \n" + "Row #22: 18\n" + "Row #22: 6.39\n" + "Row #22: \n" + "Row #22: \n" + "Row #22: 21.08\n" + "Row #23: \n" + "Row #23: \n" + "Row #23: \n" + "Row #23: 21\n" + "Row #23: \n" + "Row #23: \n" + "Row #23: \n" + "Row #23: 33.22\n" + "Row #24: \n" + "Row #24: \n" + "Row #24: \n" + "Row #24: 9\n" + "Row #24: \n" + "Row #24: \n" + "Row #24: \n" + "Row #24: 22.65\n" + "Row #25: 2\n" + "Row #25: \n" + "Row #25: \n" + "Row #25: 9\n" + "Row #25: 6.80\n" + "Row #25: \n" + "Row #25: \n" + "Row #25: 18.90\n" + "Row #26: 3\n" + "Row #26: \n" + "Row #26: \n" + "Row #26: 9\n" + "Row #26: 1.50\n" + "Row #26: \n" + "Row #26: \n" + "Row #26: 23.01\n" + "Row #27: \n" + "Row #27: \n" + "Row #27: \n" + "Row #27: 22\n" + "Row #27: \n" + "Row #27: \n" + "Row #27: \n" + "Row #27: 50.71\n" + "Row #28: 4\n" + "Row #28: \n" + "Row #28: \n" + "Row #28: \n" + "Row #28: 5.16\n" + "Row #28: \n" + "Row #28: \n" + "Row #28: \n" + "Row #29: \n" + "Row #29: \n" + "Row #29: 20\n" + "Row #29: 14\n" + "Row #29: \n" + "Row #29: \n" + "Row #29: 48.02\n" + "Row #29: 28.80\n" + "Row #30: \n" + "Row #30: \n" + "Row #30: 14\n" + "Row #30: \n" + "Row #30: \n" + "Row #30: \n" + "Row #30: 19.96\n" + "Row #30: \n" + "Row #31: \n" + "Row #31: \n" + "Row #31: 10\n" + "Row #31: 40\n" + "Row #31: \n" + "Row #31: \n" + "Row #31: 26.36\n" + "Row #31: 74.49\n" + "Row #32: 6\n" + "Row #32: \n" + "Row #32: \n" + "Row #32: \n" + "Row #32: 17.01\n" + "Row #32: \n" + "Row #32: \n" + "Row #32: \n" + "Row #33: 4\n" + "Row #33: \n" + "Row #33: \n" + "Row #33: \n" + "Row #33: 2.80\n" + "Row #33: \n" + "Row #33: \n" + "Row #33: \n" + "Row #34: 4\n" + "Row #34: \n" + "Row #34: \n" + "Row #34: \n" + "Row #34: 7.98\n" + "Row #34: \n" + "Row #34: \n" + "Row #34: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: 46\n" + "Row #35: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: 81.71\n" + "Row #36: \n" + "Row #36: \n" + "Row #36: 21\n" + "Row #36: 6\n" + "Row #36: \n" + "Row #36: \n" + "Row #36: 37.93\n" + "Row #36: 14.73\n" + "Row #37: \n" + "Row #37: \n" + "Row #37: 3\n" + "Row #37: \n" + "Row #37: \n" + "Row #37: \n" + "Row #37: 7.92\n" + "Row #37: \n" + "Row #38: 25\n" + "Row #38: \n" + "Row #38: \n" + "Row #38: 3\n" + "Row #38: 51.65\n" + "Row #38: \n" + "Row #38: \n" + "Row #38: 2.34\n" + "Row #39: 3\n" + "Row #39: \n" + "Row #39: \n" + "Row #39: 4\n" + "Row #39: 4.47\n" + "Row #39: \n" + "Row #39: \n" + "Row #39: 9.20\n" + "Row #40: \n" + "Row #40: 1\n" + "Row #40: \n" + "Row #40: \n" + "Row #40: \n" + "Row #40: 1.47\n" + "Row #40: \n" + "Row #40: \n" + "Row #41: \n" + "Row #41: \n" + "Row #41: 15\n" + "Row #41: \n" + "Row #41: \n" + "Row #41: \n" + "Row #41: 18.88\n" + "Row #41: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: 3\n" + "Row #42: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: 3.75\n" + "Row #43: 9\n" + "Row #43: \n" + "Row #43: \n" + "Row #43: 10\n" + "Row #43: 31.41\n" + "Row #43: \n" + "Row #43: \n" + "Row #43: 15.12\n" + "Row #44: 3\n" + "Row #44: \n" + "Row #44: \n" + "Row #44: 3\n" + "Row #44: 7.41\n" + "Row #44: \n" + "Row #44: \n" + "Row #44: 2.55\n" + "Row #45: 3\n" + "Row #45: \n" + "Row #45: \n" + "Row #45: \n" + "Row #45: 1.71\n" + "Row #45: \n" + "Row #45: \n" + "Row #45: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: 7\n" + "Row #46: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: 11.86\n" + "Row #47: \n" + "Row #47: \n" + "Row #47: \n" + "Row #47: 3\n" + "Row #47: \n" + "Row #47: \n" + "Row #47: \n" + "Row #47: 2.76\n" + "Row #48: \n" + "Row #48: \n" + "Row #48: 4\n" + "Row #48: 5\n" + "Row #48: \n" + "Row #48: \n" + "Row #48: 4.50\n" + "Row #48: 7.27\n" + "Row #49: \n" + "Row #49: \n" + "Row #49: 7\n" + "Row #49: \n" + "Row #49: \n" + "Row #49: \n" + "Row #49: 10.01\n" + "Row #49: \n" + "Row #50: \n" + "Row #50: \n" + "Row #50: 5\n" + "Row #50: 4\n" + "Row #50: \n" + "Row #50: \n" + "Row #50: 12.88\n" + "Row #50: 5.28\n" + "Row #51: 2\n" + "Row #51: \n" + "Row #51: \n" + "Row #51: \n" + "Row #51: 2.64\n" + "Row #51: \n" + "Row #51: \n" + "Row #51: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: 5\n" + "Row #52: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: 12.34\n" + "Row #53: \n" + "Row #53: \n" + "Row #53: \n" + "Row #53: 5\n" + "Row #53: \n" + "Row #53: \n" + "Row #53: \n" + "Row #53: 3.41\n" + "Row #54: \n" + "Row #54: \n" + "Row #54: \n" + "Row #54: 4\n" + "Row #54: \n" + "Row #54: \n" + "Row #54: \n" + "Row #54: 2.44\n" + "Row #55: \n" + "Row #55: \n" + "Row #55: 2\n" + "Row #55: \n" + "Row #55: \n" + "Row #55: \n" + "Row #55: 6.92\n" + "Row #55: \n" + "Row #56: 13\n" + "Row #56: \n" + "Row #56: \n" + "Row #56: 7\n" + "Row #56: 23.69\n" + "Row #56: \n" + "Row #56: \n" + "Row #56: 7.07\n"), // 5 new QueryAndResult( "select from Sales\n" + "where ([Measures].[Store Sales], [Time].[1997], [Promotion Media].[All Media].[TV])", "Axis #0:\n" + "{[Measures].[Store Sales], [Time].[1997], [Promotion Media].[All Media].[TV]}\n" + "7,786.21")); public void testTaglib0() { assertQueryReturns( taglibQueries.get(0).query, taglibQueries.get(0).result); } public void testTaglib1() { assertQueryReturns( taglibQueries.get(1).query, taglibQueries.get(1).result); } public void testTaglib2() { assertQueryReturns( taglibQueries.get(2).query, taglibQueries.get(2).result); } public void testTaglib3() { assertQueryReturns( taglibQueries.get(3).query, taglibQueries.get(3).result); } public void testTaglib4() { assertQueryReturns( taglibQueries.get(4).query, taglibQueries.get(4).result); } public void testTaglib5() { assertQueryReturns( taglibQueries.get(5).query, taglibQueries.get(5).result); } public void testCellValue() { Result result = executeQuery( "select {[Measures].[Unit Sales],[Measures].[Store Sales]} on columns,\n" + " {[Gender].[M]} on rows\n" + "from Sales"); Cell cell = result.getCell(new int[]{0, 0}); Object value = cell.getValue(); assertTrue(value instanceof Number); assertEquals(135215, ((Number) value).intValue()); cell = result.getCell(new int[]{1, 0}); value = cell.getValue(); assertTrue(value instanceof Number); // Plato give 285011.12, Oracle gives 285011, MySQL gives 285964 (bug!) assertEquals(285011, ((Number) value).intValue()); } public void testDynamicFormat() { assertQueryReturns( "with member [Measures].[USales] as [Measures].[Unit Sales],\n" + " format_string = iif([Measures].[Unit Sales] > 50000, \"\\<b\\>#.00\\<\\/b\\>\", \"\\<i\\>#.00\\<\\/i\\>\")\n" + "select \n" + " {[Measures].[USales]} on columns,\n" + " {[Store Type].members} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[USales]}\n" + "Axis #2:\n" + "{[Store Type].[All Store Types]}\n" + "{[Store Type].[All Store Types].[Deluxe Supermarket]}\n" + "{[Store Type].[All Store Types].[Gourmet Supermarket]}\n" + "{[Store Type].[All Store Types].[HeadQuarters]}\n" + "{[Store Type].[All Store Types].[Mid-Size Grocery]}\n" + "{[Store Type].[All Store Types].[Small Grocery]}\n" + "{[Store Type].[All Store Types].[Supermarket]}\n" + "Row #0: <b>266773.00</b>\n" + "Row #1: <b>76837.00</b>\n" + "Row #2: <i>21333.00</i>\n" + "Row #3: \n" + "Row #4: <i>11491.00</i>\n" + "Row #5: <i>6557.00</i>\n" + "Row #6: <b>150555.00</b>\n"); } public void testFormatOfNulls() { assertQueryReturns( "with member [Measures].[Foo] as '([Measures].[Store Sales])',\n" + " format_string = '$#,##0.00;($#,##0.00);ZERO;NULL;Nil'\n" + "select\n" + " {[Measures].[Foo]} on columns,\n" + " {[Customers].[Country].members} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Foo]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[Canada]}\n" + "{[Customers].[All Customers].[Mexico]}\n" + "{[Customers].[All Customers].[USA]}\n" + "Row #0: NULL\n" + "Row #1: NULL\n" + "Row #2: $565,238.13\n"); } /** * If a measure (in this case, <code>[Measures].[Sales Count]</code>) * occurs only within a format expression, bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-14">MONDRIAN-14</a>. * causes an internal * error ("value not found") when the cell's formatted value is retrieved. */ public void testBugMondrian14() { assertQueryReturns( "with member [Measures].[USales] as '[Measures].[Unit Sales]',\n" + " format_string = iif([Measures].[Sales Count] > 30, \"#.00 good\",\"#.00 bad\")\n" + "select {[Measures].[USales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns,\n" + " Crossjoin({[Promotion Media].[All Media].[Radio], [Promotion Media].[All Media].[TV], [Promotion Media]. [All Media].[Sunday Paper], [Promotion Media].[All Media].[Street Handout]}, [Product].[All Products].[Drink].Children) ON rows\n" + "from [Sales] where ([Time].[1997])", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[USales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75.00 bad\n" + "Row #0: 70.40\n" + "Row #0: 168.62\n" + "Row #1: 97.00 good\n" + "Row #1: 75.70\n" + "Row #1: 186.03\n" + "Row #2: 54.00 bad\n" + "Row #2: 36.75\n" + "Row #2: 89.03\n" + "Row #3: 76.00 bad\n" + "Row #3: 70.99\n" + "Row #3: 182.38\n" + "Row #4: 188.00 good\n" + "Row #4: 167.00\n" + "Row #4: 419.14\n" + "Row #5: 68.00 bad\n" + "Row #5: 45.19\n" + "Row #5: 119.55\n" + "Row #6: 148.00 good\n" + "Row #6: 128.97\n" + "Row #6: 316.88\n" + "Row #7: 197.00 good\n" + "Row #7: 161.81\n" + "Row #7: 399.58\n" + "Row #8: 85.00 bad\n" + "Row #8: 54.75\n" + "Row #8: 140.27\n" + "Row #9: 158.00 good\n" + "Row #9: 121.14\n" + "Row #9: 294.55\n" + "Row #10: 270.00 good\n" + "Row #10: 201.28\n" + "Row #10: 520.55\n" + "Row #11: 84.00 bad\n" + "Row #11: 50.26\n" + "Row #11: 128.32\n"); } /** * This bug causes all of the format strings to be the same, because the * required expression [Measures].[Unit Sales] is not in the cache; bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-34">MONDRIAN-34</a>. */ public void testBugMondrian34() { assertQueryReturns( "with member [Measures].[xxx] as '[Measures].[Store Sales]',\n" + " format_string = IIf([Measures].[Unit Sales] > 100000, \"AAA######.00\",\"BBB###.00\")\n" + "select {[Measures].[xxx]} ON columns,\n" + " {[Product].[All Products].children} ON rows\n" + "from [Sales] where [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[xxx]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "Row #0: BBB48836.21\n" + "Row #1: AAA409035.59\n" + "Row #2: BBB107366.33\n"); } /** * Tuple as slicer causes {@link ClassCastException}; bug * <a href="http://jira.pentaho.com/browse/MONDRIAN-36">MONDRIAN-36</a>. */ public void testBugMondrian36() { assertQueryReturns( "select {[Measures].[Unit Sales]} ON columns,\n" + " {[Gender].Children} ON rows\n" + "from [Sales]\n" + "where ([Time].[1997], [Customers])", "Axis #0:\n" + "{[Time].[1997], [Customers].[All Customers]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n"); } /** * Query with distinct-count measure and no other measures gives * {@link ArrayIndexOutOfBoundsException}; * <a href="http://jira.pentaho.com/browse/MONDRIAN-46">MONDRIAN-46</a>. */ public void testBugMondrian46() { getConnection().getCacheControl(null).flushSchemaCache(); assertQueryReturns( "select {[Measures].[Customer Count]} ON columns,\n" + " {([Promotion Media].[All Media], [Product].[All Products])} ON rows\n" + "from [Sales]\n" + "where [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Customer Count]}\n" + "Axis #2:\n" + "{[Promotion Media].[All Media], [Product].[All Products]}\n" + "Row #0: 5,581\n"); } /** Make sure that the "Store" cube is working. */ public void testStoreCube() { assertQueryReturns( "select {[Measures].members} on columns,\n" + " {[Store Type].members} on rows\n" + "from [Store]" + "where [Store].[USA].[CA]", "Axis #0:\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "Axis #1:\n" + "{[Measures].[Store Sqft]}\n" + "{[Measures].[Grocery Sqft]}\n" + "Axis #2:\n" + "{[Store Type].[All Store Types]}\n" + "{[Store Type].[All Store Types].[Deluxe Supermarket]}\n" + "{[Store Type].[All Store Types].[Gourmet Supermarket]}\n" + "{[Store Type].[All Store Types].[HeadQuarters]}\n" + "{[Store Type].[All Store Types].[Mid-Size Grocery]}\n" + "{[Store Type].[All Store Types].[Small Grocery]}\n" + "{[Store Type].[All Store Types].[Supermarket]}\n" + "Row #0: 69,764\n" + "Row #0: 44,868\n" + "Row #1: \n" + "Row #1: \n" + "Row #2: 23,688\n" + "Row #2: 15,337\n" + "Row #3: \n" + "Row #3: \n" + "Row #4: \n" + "Row #4: \n" + "Row #5: 22,478\n" + "Row #5: 15,321\n" + "Row #6: 23,598\n" + "Row #6: 14,210\n"); } public void testSchemaLevelTableIsBad() { // todo: <Level table="nonexistentTable"> } public void testSchemaLevelTableInAnotherHierarchy() { // todo: // <Cube> // <Hierarchy name="h1"><Table name="t1"/></Hierarchy> // <Hierarchy name="h2"> // <Table name="t2"/> // <Level tableName="t1"/> // </Hierarchy> // </Cube> } public void testSchemaLevelWithViewSpecifiesTable() { // todo: // <Hierarchy> // <View><SQL dialect="generic">select * from emp</SQL></View> // <Level tableName="emp"/> // </hierarchy> // Should get error that tablename is not allowed } public void testSchemaLevelOrdinalInOtherTable() { // todo: // Hierarchy is based upon a join. // Level's name expression is in a different table than its ordinal. } public void testSchemaTopLevelNotUnique() { // todo: // Should get error if the top level of a hierarchy does not have // uniqueNames="true" } /** * Bug 645744 happens when getting the children of a member crosses a table * boundary. The symptom */ public void testBug645744() { // minimal test case assertQueryReturns( "select {[Measures].[Unit Sales]} ON columns,\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].children} ON rows\n" + "from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Excellent]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Fabulous]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Skinner]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Token]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Washington]}\n" + "Row #0: 468\n" + "Row #1: 469\n" + "Row #2: 506\n" + "Row #3: 466\n" + "Row #4: 560\n"); // shorter test case executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns," + "ToggleDrillState({" + "([Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks])" + "}, {[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks]}) ON rows " + "from [Sales] where ([Time].[1997])"); } /** * The bug happened when a cell which was in cache was compared with a cell * which was not in cache. The compare method could not deal with the * {@link RuntimeException} which indicates that the cell is not in cache. */ public void testBug636687() { executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost],[Measures].[Store Sales]} ON columns, " + "Order(" + "{([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Beverages]), " + "Crossjoin({[Store].[All Stores].[USA].[CA].Children}, {[Product].[All Products].[Drink].[Beverages]}), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Dairy])}, " + "[Measures].[Store Cost], BDESC) ON rows " + "from [Sales] " + "where ([Time].[1997])"); executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns, " + "Order(" + "{([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[CA].[San Diego], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA].[Los Angeles], [Product].[All Products].[Drink].[Beverages]), " + "Crossjoin({[Store].[All Stores].[USA].[CA].[Los Angeles]}, {[Product].[All Products].[Drink].[Beverages].Children}), " + "([Store].[All Stores].[USA].[CA].[Beverly Hills], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[CA].[San Francisco], [Product].[All Products].[Drink].[Beverages])}, " + "[Measures].[Store Cost], BDESC) ON rows " + "from [Sales] " + "where ([Time].[1997])"); } /** * Bug 769114: Internal error ("not found") when executing * Order(TopCount). */ public void testBug769114() { assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns,\n" + " Order(TopCount({[Product].[Product Category].Members}, 10.0, [Measures].[Unit Sales]), [Measures].[Store Sales], ASC) ON rows\n" + "from [Sales]\n" + "where [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread]}\n" + "{[Product].[All Products].[Food].[Deli].[Meat]}\n" + "{[Product].[All Products].[Food].[Dairy].[Dairy]}\n" + "{[Product].[All Products].[Food].[Baking Goods].[Baking Goods]}\n" + "{[Product].[All Products].[Food].[Baking Goods].[Jams and Jellies]}\n" + "{[Product].[All Products].[Food].[Canned Foods].[Canned Soup]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Vegetables]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Produce].[Fruit]}\n" + "{[Product].[All Products].[Food].[Produce].[Vegetables]}\n" + "Row #0: 7,870\n" + "Row #0: 6,564.09\n" + "Row #0: 16,455.43\n" + "Row #1: 9,433\n" + "Row #1: 8,215.81\n" + "Row #1: 20,616.29\n" + "Row #2: 12,885\n" + "Row #2: 12,228.85\n" + "Row #2: 30,508.85\n" + "Row #3: 8,357\n" + "Row #3: 6,123.32\n" + "Row #3: 15,446.69\n" + "Row #4: 11,888\n" + "Row #4: 9,247.29\n" + "Row #4: 23,223.72\n" + "Row #5: 8,006\n" + "Row #5: 6,408.29\n" + "Row #5: 15,966.10\n" + "Row #6: 6,984\n" + "Row #6: 5,885.05\n" + "Row #6: 14,769.82\n" + "Row #7: 30,545\n" + "Row #7: 26,963.34\n" + "Row #7: 67,609.82\n" + "Row #8: 11,767\n" + "Row #8: 10,312.77\n" + "Row #8: 25,816.13\n" + "Row #9: 20,739\n" + "Row #9: 18,048.81\n" + "Row #9: 45,185.41\n"); } /** * Bug 793616: Deeply nested UNION function takes forever to validate. * (Problem was that each argument of a function was validated twice, hence * the validation time was <code>O(2 ^ depth)</code>.) */ public void _testBug793616() { if (props.TestExpDependencies.get() > 0) { // Don't run this test if dependency-checking is enabled. // Dependency checking will hugely slow down evaluation, and give // the false impression that the validation performance bug has // returned. return; } final long start = System.currentTimeMillis(); Connection connection = getTestContext().getFoodMartConnection(); final String queryString = "select {[Measures].[Unit Sales],\n" + " [Measures].[Store Cost],\n" + " [Measures].[Store Sales]} ON columns,\n" + "Hierarchize(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union\n" + "({([Gender].[All Gender],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers],\n" + " [Product].[All Products])},\n" + " Crossjoin ([Gender].[All Gender].Children,\n" + " {([Marital Status].[All Marital Status],\n" + " [Customers].[All Customers],\n" + " [Product].[All Products])})),\n" + " Crossjoin(Crossjoin({[Gender].[All Gender].[F]},\n" + " [Marital Status].[All Marital Status].Children),\n" + " {([Customers].[All Customers],\n" + " [Product].[All Products])})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[M])},\n" + " [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[M])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin(\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[S])}, [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status])},\n" + " [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children))) ON rows from [Sales] where [Time].[1997]"; Query query = connection.parseQuery(queryString); // If this call took longer than 10 seconds, the performance bug has // probably resurfaced again. final long afterParseMillis = System.currentTimeMillis(); final long afterParseNonDbMillis = afterParseMillis - Util.dbTimeMillis(); final long parseMillis = afterParseMillis - start; assertTrue( "performance problem: parse took " + parseMillis + " milliseconds", parseMillis <= 10000); Result result = connection.execute(query); assertEquals(59, result.getAxes()[1].getPositions().size()); // If this call took longer than 10 seconds, // or 2 seconds exclusing db access, // the performance bug has // probably resurfaced again. final long afterExecMillis = System.currentTimeMillis(); final long afterExecNonDbMillis = afterExecMillis - Util.dbTimeMillis(); final long execNonDbMillis = afterExecNonDbMillis - afterParseNonDbMillis; final long execMillis = (afterExecMillis - afterParseMillis); assertTrue( "performance problem: execute took " + execMillis + " milliseconds, " + execNonDbMillis + " milliseconds excluding db", execNonDbMillis <= 2000 && execMillis <= 30000); } public void testCatalogHierarchyBasedOnView() { // Don't run this test if aggregates are enabled: two levels mapped to // the "gender" column confuse the agg engine. if (props.ReadAggregates.get()) { return; } TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<Dimension name=\"Gender2\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\" primaryKey=\"customer_id\">\n" + " <View alias=\"gender2\">\n" + " <SQL dialect=\"generic\">\n" + " <![CDATA[SELECT * FROM customer]]>\n" + " </SQL>\n" + " <SQL dialect=\"oracle\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"derby\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"luciddb\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"db2\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"netezza\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " </View>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>", null); if (!testContext.getDialect().allowsFromQuery()) { return; } testContext.assertAxisReturns( "[Gender2].members", "[Gender2].[All Gender]\n" + "[Gender2].[All Gender].[F]\n" + "[Gender2].[All Gender].[M]"); } /** * Run a query against a large hierarchy, to make sure that we can generate * joins correctly. This probably won't work in MySQL. */ public void testCatalogHierarchyBasedOnView2() { // Don't run this test if aggregates are enabled: two levels mapped to // the "gender" column confuse the agg engine. if (props.ReadAggregates.get()) { return; } if (getTestContext().getDialect().allowsFromQuery()) { return; } TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<Dimension name=\"ProductView\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\" primaryKeyTable=\"productView\">\n" + " <View alias=\"productView\">\n" + " <SQL dialect=\"db2\"><![CDATA[\n" + "SELECT *\n" + "FROM \"product\", \"product_class\"\n" + "WHERE \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\"\n" + "]]>\n" + " </SQL>\n" + " <SQL dialect=\"mssql\"><![CDATA[\n" + "SELECT \"product\".\"product_id\",\n" + "\"product\".\"brand_name\",\n" + "\"product\".\"product_name\",\n" + "\"product\".\"SKU\",\n" + "\"product\".\"SRP\",\n" + "\"product\".\"gross_weight\",\n" + "\"product\".\"net_weight\",\n" + "\"product\".\"recyclable_package\",\n" + "\"product\".\"low_fat\",\n" + "\"product\".\"units_per_case\",\n" + "\"product\".\"cases_per_pallet\",\n" + "\"product\".\"shelf_width\",\n" + "\"product\".\"shelf_height\",\n" + "\"product\".\"shelf_depth\",\n" + "\"product_class\".\"product_class_id\",\n" + "\"product_class\".\"product_subcategory\",\n" + "\"product_class\".\"product_category\",\n" + "\"product_class\".\"product_department\",\n" + "\"product_class\".\"product_family\"\n" + "FROM \"product\" inner join \"product_class\"\n" + "ON \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\"\n" + "]]>\n" + " </SQL>\n" + " <SQL dialect=\"mysql\"><![CDATA[\n" + "SELECT `product`.`product_id`,\n" + "`product`.`brand_name`,\n" + "`product`.`product_name`,\n" + "`product`.`SKU`,\n" + "`product`.`SRP`,\n" + "`product`.`gross_weight`,\n" + "`product`.`net_weight`,\n" + "`product`.`recyclable_package`,\n" + "`product`.`low_fat`,\n" + "`product`.`units_per_case`,\n" + "`product`.`cases_per_pallet`,\n" + "`product`.`shelf_width`,\n" + "`product`.`shelf_height`,\n" + "`product`.`shelf_depth`,\n" + "`product_class`.`product_class_id`,\n" + "`product_class`.`product_family`,\n" + "`product_class`.`product_department`,\n" + "`product_class`.`product_category`,\n" + "`product_class`.`product_subcategory` \n" + "FROM `product`, `product_class`\n" + "WHERE `product`.`product_class_id` = `product_class`.`product_class_id`\n" + "]]>\n" + " </SQL>\n" + " <SQL dialect=\"generic\"><![CDATA[\n" + "SELECT *\n" + "FROM \"product\", \"product_class\"\n" + "WHERE \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\"\n" + "]]>\n" + " </SQL>\n" + " </View>\n" + " <Level name=\"Product Family\" column=\"product_family\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Product Department\" column=\"product_department\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Category\" column=\"product_category\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Subcategory\" column=\"product_subcategory\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Brand Name\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" column=\"product_name\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>"); testContext.assertQueryReturns( "select {[Measures].[Unit Sales]} on columns,\n" + " {[ProductView].[Drink].[Beverages].children} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Carbonated Beverages]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Drinks]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Hot Beverages]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Pure Juice Beverages]}\n" + "Row #0: 3,407\n" + "Row #1: 2,469\n" + "Row #2: 4,301\n" + "Row #3: 3,396\n"); } public void testCountDistinct() { assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on columns,\n" + " {[Gender].members} on rows\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Axis #2:\n" + "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #0: 5,581\n" + "Row #1: 131,558\n" + "Row #1: 2,755\n" + "Row #2: 135,215\n" + "Row #2: 2,826\n"); } /** * Turn off aggregate caching and run query with both use of aggregate * tables on and off - should result in the same answer. * Note that if the "mondrian.rolap.aggregates.Read" property is not true, * then no aggregate tables is be read in any event. */ public void testCountDistinctAgg() { boolean use_agg_orig = props.UseAggregates.get(); boolean do_caching_orig = props.DisableCaching.get(); // turn off caching props.DisableCaching.setString("true"); assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on rows,\n" + "NON EMPTY {[Time].[1997].[Q1].[1]} ON COLUMNS\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997].[Q1].[1]}\n" + "Axis #2:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Row #0: 21,628\n" + "Row #1: 1,396\n"); if (use_agg_orig) { props.UseAggregates.setString("false"); } else { props.UseAggregates.setString("true"); } assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on rows,\n" + "NON EMPTY {[Time].[1997].[Q1].[1]} ON COLUMNS\n" + "from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997].[Q1].[1]}\n" + "Axis #2:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Row #0: 21,628\n" + "Row #1: 1,396\n"); if (use_agg_orig) { props.UseAggregates.setString("true"); } else { props.UseAggregates.setString("false"); } if (do_caching_orig) { props.DisableCaching.setString("true"); } else { props.DisableCaching.setString("false"); } } /** * * There are cross database order issues in this test. * * MySQL and Access show the rows as: * * [Store Size in SQFT].[All Store Size in SQFTs] * [Store Size in SQFT].[All Store Size in SQFTs].[null] * [Store Size in SQFT].[All Store Size in SQFTs].[<each distinct store * size>] * * Postgres shows: * * [Store Size in SQFT].[All Store Size in SQFTs] * [Store Size in SQFT].[All Store Size in SQFTs].[<each distinct store * size>] * [Store Size in SQFT].[All Store Size in SQFTs].[null] * * The test failure is due to some inherent differences in the way * Postgres orders NULLs in a result set, * compared with MySQL and Access. * * From the MySQL 4.X manual: * * When doing an ORDER BY, NULL values are presented first if you do * ORDER BY ... ASC and last if you do ORDER BY ... DESC. * * From the Postgres 8.0 manual: * * The null value sorts higher than any other value. In other words, * with ascending sort order, null values sort at the end, and with * descending sort order, null values sort at the beginning. * * Oracle also sorts nulls high by default. * * So, this test has expected results that vary depending on whether * the database is being used sorts nulls high or low. * */ public void testMemberWithNullKey() { if (!isDefaultNullMemberRepresentation()) { return; } Result result = executeQuery( "select {[Measures].[Unit Sales]} on columns,\n" + "{[Store Size in SQFT].members} on rows\n" + "from Sales"); String resultString = TestContext.toString(result); resultString = Pattern.compile("\\.0\\]").matcher(resultString).replaceAll("]"); // The members function hierarchizes its results, so nulls should // sort high, regardless of DBMS. Note that Oracle's driver says that // NULLs sort low, but it's lying. final boolean nullsSortHigh = false; int row = 0; final String expected = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store Size in SQFT].[All Store Size in SQFTs]}\n" // null is at the start in order under DBMSs that sort null low + (!nullsSortHigh ? "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" : "") + "{[Store Size in SQFT].[All Store Size in SQFTs].[20319]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[21215]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[22478]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23112]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23593]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23598]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23688]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23759]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[24597]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[27694]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[28206]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30268]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30584]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30797]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[33858]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[34452]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[34791]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[36509]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[38382]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[39696]}\n" // null is at the end in order for DBMSs that sort nulls high + (nullsSortHigh ? "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" : "") + "Row #" + row++ + ": 266,773\n" + (!nullsSortHigh ? "Row #" + row++ + ": 39,329\n" : "") + "Row #" + row++ + ": 26,079\n" + "Row #" + row++ + ": 25,011\n" + "Row #" + row++ + ": 2,117\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 25,663\n" + "Row #" + row++ + ": 21,333\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 41,580\n" + "Row #" + row++ + ": 2,237\n" + "Row #" + row++ + ": 23,591\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 35,257\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 24,576\n" + (nullsSortHigh ? "Row #" + row++ + ": 39,329\n" : ""); TestContext.assertEqualsVerbose(expected, resultString); } /** * Slicer contains <code>[Promotion Media].[Daily Paper]</code>, but * filter expression is in terms of <code>[Promotion Media].[Radio]</code>. */ public void testSlicerOverride() { assertQueryReturns( "with member [Measures].[Radio Unit Sales] as \n" + " '([Measures].[Unit Sales], [Promotion Media].[Radio])'\n" + "select {[Measures].[Unit Sales], [Measures].[Radio Unit Sales]} on columns,\n" + " filter([Product].[Product Department].members, [Promotion Media].[Radio] > 50) on rows\n" + "from Sales\n" + "where ([Promotion Media].[Daily Paper], [Time].[1997].[Q1])", "Axis #0:\n" + "{[Promotion Media].[All Media].[Daily Paper], [Time].[1997].[Q1]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Radio Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "Row #0: 692\n" + "Row #0: 87\n" + "Row #1: 447\n" + "Row #1: 63\n"); } public void testMembersOfLargeDimensionTheHardWay() { // Avoid this test if memory is scarce. if (Bug.avoidMemoryOverflow(TestContext.instance().getDialect())) { return; } final Connection connection = TestContext.instance().getFoodMartConnection(); String queryString = "select {[Measures].[Unit Sales]} on columns,\n" + "{[Customers].members} on rows\n" + "from Sales"; Query query = connection.parseQuery(queryString); Result result = connection.execute(query); assertEquals(10407, result.getAxes()[1].getPositions().size()); } public void testUnparse() { Connection connection = getConnection(); Query query = connection.parseQuery( "with member [Measures].[Rendite] as \n" + " '(([Measures].[Store Sales] - [Measures].[Store Cost])) / [Measures].[Store Cost]',\n" + " format_string = iif(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost] * 100 > \n" + " Parameter (\"UpperLimit\", NUMERIC, 151, \"Obere Grenze\"), \n" + " \"|#.00%|arrow='up'\",\n" + " iif(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost] * 100 < \n" + " Parameter(\"LowerLimit\", NUMERIC, 150, \"Untere Grenze\"),\n" + " \"|#.00%|arrow='down'\",\n" + " \"|#.00%|arrow='right'\"))\n" + "select {[Measures].members} on columns\n" + "from Sales"); final String s = Util.unparse(query); // Parentheses are added to reflect operator precedence, but that's ok. // Note that the doubled parentheses in line #2 of the query have been // reduced to a single level. TestContext.assertEqualsVerbose( "with member [Measures].[Rendite] as '(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost])', " + "format_string = IIf((((([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost]) * 100.0) > Parameter(\"UpperLimit\", NUMERIC, 151.0, \"Obere Grenze\")), " + "\"|#.00%|arrow='up'\", " + "IIf((((([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost]) * 100.0) < Parameter(\"LowerLimit\", NUMERIC, 150.0, \"Untere Grenze\")), " + "\"|#.00%|arrow='down'\", \"|#.00%|arrow='right'\"))\n" + "select {[Measures].Members} ON COLUMNS\n" + "from [Sales]\n", s); } public void testUnparse2() { Connection connection = getConnection(); Query query = connection.parseQuery( "with member [Measures].[Foo] as '1', " + "format_string='##0.00', " + "funny=IIf(1=1,\"x\"\"y\",\"foo\") " + "select {[Measures].[Foo]} on columns from Sales"); final String s = query.toString(); // The "format_string" property, a string literal, is now delimited by // double-quotes. This won't work in MSOLAP, but for Mondrian it's // consistent with the fact that property values are expressions, // not enclosed in single-quotes. TestContext.assertEqualsVerbose( "with member [Measures].[Foo] as '1.0', " + "format_string = \"##0.00\", " + "funny = IIf((1.0 = 1.0), \"x\"\"y\", \"foo\")\n" + "select {[Measures].[Foo]} ON COLUMNS\n" + "from [Sales]\n", s); } /** * Basically, the LookupCube function can evaluate a single MDX statement * against a cube other than the cube currently indicated by query context * to retrieve a single string or numeric result. * * <p>For example, the Budget cube in the FoodMart 2000 database contains * budget information that can be displayed by store. The Sales cube in the * FoodMart 2000 database contains sales information that can be displayed * by store. Since no virtual cube exists in the FoodMart 2000 database that * joins the Sales and Budget cubes together, comparing the two sets of * figures would be difficult at best. * * <p><b>Note<b> In many situations a virtual cube can be used to integrate * data from multiple cubes, which will often provide a simpler and more * efficient solution than the LookupCube function. This example uses the * LookupCube function for purposes of illustration. * * <p>The following MDX query, however, uses the LookupCube function to * retrieve unit sales information for each store from the Sales cube, * presenting it side by side with the budget information from the Budget * cube. */ public void _testLookupCube() { assertQueryReturns( "WITH MEMBER Measures.[Store Unit Sales] AS \n" + " 'LookupCube(\"Sales\", \"(\" + MemberToStr(Store.CurrentMember) + \", Measures.[Unit Sales])\")'\n" + "SELECT\n" + " {Measures.Amount, Measures.[Store Unit Sales]} ON COLUMNS,\n" + " Store.CA.CHILDREN ON ROWS\n" + "FROM Budget", ""); } /** * <p>Basket analysis is a topic better suited to data mining discussions, * but some basic forms of basket analysis can be handled through the use of * MDX queries. * * <p>For example, one method of basket analysis groups customers based on * qualification. In the following example, a qualified customer is one who * has more than $10,000 in store sales or more than 10 unit sales. The * following table illustrates such a report, run against the Sales cube in * FoodMart 2000 with qualified customers grouped by the Country and State * Province levels of the Customers dimension. The count and store sales * total of qualified customers is represented by the Qualified Count and * Qualified Sales columns, respectively. * * <p>To accomplish this basic form of basket analysis, the following MDX * query constructs two calculated members. The first calculated member uses * the MDX Count, Filter, and Descendants functions to create the Qualified * Count column, while the second calculated member uses the MDX Sum, * Filter, and Descendants functions to create the Qualified Sales column. * * <p>The key to this MDX query is the use of Filter and Descendants * together to screen out non-qualified customers. Once screened out, the * Sum and Count MDX functions can then be used to provide aggregation data * only on qualified customers. */ public void testBasketAnalysis() { assertQueryReturns( "WITH MEMBER [Measures].[Qualified Count] AS\n" + " 'COUNT(FILTER(DESCENDANTS(Customers.CURRENTMEMBER, [Customers].[Name]),\n" + " ([Measures].[Store Sales]) > 10000 OR ([Measures].[Unit Sales]) > 10))'\n" + "MEMBER [Measures].[Qualified Sales] AS\n" + " 'SUM(FILTER(DESCENDANTS(Customers.CURRENTMEMBER, [Customers].[Name]),\n" + " ([Measures].[Store Sales]) > 10000 OR ([Measures].[Unit Sales]) > 10),\n" + " ([Measures].[Store Sales]))'\n" + "SELECT {[Measures].[Qualified Count], [Measures].[Qualified Sales]} ON COLUMNS,\n" + " DESCENDANTS([Customers].[All Customers], [State Province], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Qualified Count]}\n" + "{[Measures].[Qualified Sales]}\n" + "Axis #2:\n" + "{[Customers].[All Customers]}\n" + "{[Customers].[All Customers].[Canada]}\n" + "{[Customers].[All Customers].[Canada].[BC]}\n" + "{[Customers].[All Customers].[Mexico]}\n" + "{[Customers].[All Customers].[Mexico].[DF]}\n" + "{[Customers].[All Customers].[Mexico].[Guerrero]}\n" + "{[Customers].[All Customers].[Mexico].[Jalisco]}\n" + "{[Customers].[All Customers].[Mexico].[Mexico]}\n" + "{[Customers].[All Customers].[Mexico].[Oaxaca]}\n" + "{[Customers].[All Customers].[Mexico].[Sinaloa]}\n" + "{[Customers].[All Customers].[Mexico].[Veracruz]}\n" + "{[Customers].[All Customers].[Mexico].[Yucatan]}\n" + "{[Customers].[All Customers].[Mexico].[Zacatecas]}\n" + "{[Customers].[All Customers].[USA]}\n" + "{[Customers].[All Customers].[USA].[CA]}\n" + "{[Customers].[All Customers].[USA].[OR]}\n" + "{[Customers].[All Customers].[USA].[WA]}\n" + "Row #0: 4,719.00\n" + "Row #0: 553,587.77\n" + "Row #1: .00\n" + "Row #1: \n" + "Row #2: .00\n" + "Row #2: \n" + "Row #3: .00\n" + "Row #3: \n" + "Row #4: .00\n" + "Row #4: \n" + "Row #5: .00\n" + "Row #5: \n" + "Row #6: .00\n" + "Row #6: \n" + "Row #7: .00\n" + "Row #7: \n" + "Row #8: .00\n" + "Row #8: \n" + "Row #9: .00\n" + "Row #9: \n" + "Row #10: .00\n" + "Row #10: \n" + "Row #11: .00\n" + "Row #11: \n" + "Row #12: .00\n" + "Row #12: \n" + "Row #13: 4,719.00\n" + "Row #13: 553,587.77\n" + "Row #14: 2,149.00\n" + "Row #14: 151,509.69\n" + "Row #15: 1,008.00\n" + "Row #15: 141,899.84\n" + "Row #16: 1,562.00\n" + "Row #16: 260,178.24\n"); } /** * Flushes the cache then runs {@link #testBasketAnalysis}, because this * test has been known to fail when run standalone. */ public void testBasketAnalysisAfterFlush() { getConnection().getCacheControl(null).flushSchemaCache(); testBasketAnalysis(); } /** * <b>How Can I Perform Complex String Comparisons?</b> * * <p>MDX can handle basic string comparisons, but does not include complex * string comparison and manipulation functions, for example, for finding * substrings in strings or for supporting case-insensitive string * comparisons. However, since MDX can take advantage of external function * libraries, this question is easily resolved using string manipulation * and comparison functions from the Microsoft Visual Basic for * Applications (VBA) external function library. * * <p>For example, you want to report the unit sales of all fruit-based * products -- not only the sales of fruit, but canned fruit, fruit snacks, * fruit juices, and so on. By using the LCase and InStr VBA functions, the * following results are easily accomplished in a single MDX query, without * complex set construction or explicit member names within the query. * * <p>The following MDX query demonstrates how to achieve the results * displayed in the previous table. For each member in the Product * dimension, the name of the member is converted to lowercase using the * LCase VBA function. Then, the InStr VBA function is used to discover * whether or not the name contains the word "fruit". This information is * used to then construct a set, using the Filter MDX function, from only * those members from the Product dimension that contain the substring * "fruit" in their names. */ public void testStringComparisons() { assertQueryReturns( "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " FILTER([Product].[Product Name].MEMBERS,\n" + " INSTR(LCASE([Product].CURRENTMEMBER.NAME), \"fruit\") <> 0) ON ROWS \n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Applause].[Applause Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Big City].[Big City Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Green Ribbon].[Green Ribbon Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Swell].[Swell Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Canned Products].[Fruit].[Canned Fruit].[Toucan].[Toucan Canned Mixed Fruit]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Best Choice].[Best Choice Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Best Choice].[Best Choice Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Best Choice].[Best Choice Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Best Choice].[Best Choice Strawberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Strawberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fort West].[Fort West Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fort West].[Fort West Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fort West].[Fort West Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fort West].[Fort West Strawberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Horatio].[Horatio Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Horatio].[Horatio Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Horatio].[Horatio Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Horatio].[Horatio Strawberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Nationeel].[Nationeel Apple Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Nationeel].[Nationeel Grape Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Nationeel].[Nationeel Raspberry Fruit Roll]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Nationeel].[Nationeel Strawberry Fruit Roll]}\n" + "Row #0: 205\n" + "Row #1: 204\n" + "Row #2: 142\n" + "Row #3: 204\n" + "Row #4: 187\n" + "Row #5: 174\n" + "Row #6: 114\n" + "Row #7: 110\n" + "Row #8: 150\n" + "Row #9: 149\n" + "Row #10: 173\n" + "Row #11: 163\n" + "Row #12: 154\n" + "Row #13: 181\n" + "Row #14: 178\n" + "Row #15: 210\n" + "Row #16: 189\n" + "Row #17: 177\n" + "Row #18: 191\n" + "Row #19: 149\n" + "Row #20: 169\n" + "Row #21: 185\n" + "Row #22: 216\n" + "Row #23: 167\n" + "Row #24: 138\n"); } /** * Test case for * <a href="http://jira.pentaho.com/browse/MONDRIAN-539">MONDRIAN-539, * "Problem with the MID function getting last character in a string."</a>. */ public void testMid() { assertQueryReturns( "with\n" + "member measures.x as 'Mid(\"yahoo\",5, 1)'\n" + "select {measures.x} ON COLUMNS from [Sales] ", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[x]}\n" + "Row #0: o\n"); } /** * <b>How Can I Show Percentages as Measures?</b> * * <p>Another common business question easily answered through MDX is the * display of percent values created as available measures. * * <p>For example, the Sales cube in the FoodMart 2000 database contains * unit sales for each store in a given city, state, and country, organized * along the Sales dimension. A report is requested to show, for * California, the percentage of total unit sales attained by each city * with a store. The results are illustrated in the following table. * * <p>Because the parent of a member is typically another, aggregated * member in a regular dimension, this is easily achieved by the * construction of a calculated member, as demonstrated in the following MDX * query, using the CurrentMember and Parent MDX functions. */ public void testPercentagesAsMeasures() { assertQueryReturns( // todo: "Store.[USA].[CA]" should be "Store.CA" "WITH MEMBER Measures.[Unit Sales Percent] AS\n" + " '((Store.CURRENTMEMBER, Measures.[Unit Sales]) /\n" + " (Store.CURRENTMEMBER.PARENT, Measures.[Unit Sales])) ',\n" + " FORMAT_STRING = 'Percent'\n" + "SELECT {Measures.[Unit Sales], Measures.[Unit Sales Percent]} ON COLUMNS,\n" + " ORDER(DESCENDANTS(Store.[USA].[CA], Store.[Store City], SELF), \n" + " [Measures].[Unit Sales], ASC) ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Unit Sales Percent]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 2,117\n" + "Row #1: 2.83%\n" + "Row #2: 21,333\n" + "Row #2: 28.54%\n" + "Row #3: 25,635\n" + "Row #3: 34.30%\n" + "Row #4: 25,663\n" + "Row #4: 34.33%\n"); } /** * <b>How Can I Show Cumulative Sums as Measures?</b> * * <p>Another common business request, cumulative sums, is useful for * business reporting purposes. However, since aggregations are handled in a * hierarchical fashion, cumulative sums present some unique challenges in * Analysis Services. * * <p>The best way to create a cumulative sum is as a calculated measure in * MDX, using the Rank, Head, Order, and Sum MDX functions together. * * <p>For example, the following table illustrates a report that shows two * views of employee count in all stores and cities in California, sorted * by employee count. The first column shows the aggregated counts for each * store and city, while the second column shows aggregated counts for each * store, but cumulative counts for each city. * * <p>The cumulative number of employees for San Diego represents the value * of both Los Angeles and San Diego, the value for Beverly Hills represents * the cumulative total of Los Angeles, San Diego, and Beverly Hills, and so * on. * * <p>Since the members within the state of California have been ordered * from highest to lowest number of employees, this form of cumulative sum * measure provides a form of pareto analysis within each state. * * <p>To support this, the Order function is first used to reorder members * accordingly for both the Rank and Head functions. Once reordered, the * Rank function is used to supply the ranking of each tuple within the * reordered set of members, progressing as each member in the Store * dimension is examined. The value is then used to determine the number of * tuples to retrieve from the set of reordered members using the Head * function. Finally, the retrieved members are then added together using * the Sum function to obtain a cumulative sum. The following MDX query * demonstrates how all of this works in concert to provide cumulative * sums. * * <p>As an aside, a named set cannot be used in this situation to replace * the duplicate Order function calls. Named sets are evaluated once, when * a query is parsed -- since the set can change based on the fact that the * set can be different for each store member because the set is evaluated * for the children of multiple parents, the set does not change with * respect to its use in the Sum function. Since the named set is only * evaluated once, it would not satisfy the needs of this query. */ public void _testCumlativeSums() { assertQueryReturns( // todo: "[Store].[USA].[CA]" should be "Store.CA"; implement "AS" "WITH MEMBER Measures.[Cumulative No of Employees] AS\n" + " 'SUM(HEAD(ORDER({[Store].Siblings}, [Measures].[Number of Employees], BDESC) AS OrderedSiblings,\n" + " RANK([Store], OrderedSiblings)),\n" + " [Measures].[Number of Employees])'\n" + "SELECT {[Measures].[Number of Employees], [Measures].[Cumulative No of Employees]} ON COLUMNS,\n" + " ORDER(DESCENDANTS([Store].[USA].[CA], [Store State], AFTER), \n" + " [Measures].[Number of Employees], BDESC) ON ROWS\n" + "FROM HR", ""); } /** * <b>How Can I Implement a Logical AND or OR Condition in a WHERE * Clause?</b> * * <p>For SQL users, the use of AND and OR logical operators in the WHERE * clause of a SQL statement is an essential tool for constructing business * queries. However, the WHERE clause of an MDX statement serves a * slightly different purpose, and understanding how the WHERE clause is * used in MDX can assist in constructing such business queries. * * <p>The WHERE clause in MDX is used to further restrict the results of * an MDX query, in effect providing another dimension on which the results * of the query are further sliced. As such, only expressions that resolve * to a single tuple are allowed. The WHERE clause implicitly supports a * logical AND operation involving members across different dimensions, by * including the members as part of a tuple. To support logical AND * operations involving members within a single dimensions, as well as * logical OR operations, a calculated member needs to be defined in * addition to the use of the WHERE clause. * * <p>For example, the following MDX query illustrates the use of a * calculated member to support a logical OR. The query returns unit sales * by quarter and year for all food and drink related products sold in 1997, * run against the Sales cube in the FoodMart 2000 database. * * <p>The calculated member simply adds the values of the Unit Sales * measure for the Food and the Drink levels of the Product dimension * together. The WHERE clause is then used to restrict return of * information only to the calculated member, effectively implementing a * logical OR to return information for all time periods that contain unit * sales values for either food, drink, or both types of products. * * <p>You can use the Aggregate function in similar situations where all * measures are not aggregated by summing. To return the same results in the * above example using the Aggregate function, replace the definition for * the calculated member with this definition: * * <blockquote> * <code>'Aggregate({[Product].[Food], [Product].[Drink]})'</code> * </blockquote> */ public void testLogicalOps() { assertQueryReturns( "WITH MEMBER [Product].[Food OR Drink] AS\n" + " '([Product].[Food], Measures.[Unit Sales]) + ([Product].[Drink], Measures.[Unit Sales])'\n" + "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " DESCENDANTS(Time.[1997], [Quarter], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales\n" + "WHERE [Product].[Food OR Drink]", "Axis #0:\n" + "{[Product].[Food OR Drink]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997]}\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 216,537\n" + "Row #1: 53,785\n" + "Row #2: 50,720\n" + "Row #3: 53,505\n" + "Row #4: 58,527\n"); } /** * <p>A logical AND, by contrast, can be supported by using two different * techniques. If the members used to construct the logical AND reside on * different dimensions, all that is required is a WHERE clause that uses * a tuple representing all involved members. The following MDX query uses a * WHERE clause that effectively restricts the query to retrieve unit * sales for drink products in the USA, shown by quarter and year for 1997. */ public void testLogicalAnd() { assertQueryReturns( "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " DESCENDANTS([Time].[1997], [Quarter], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales\n" + "WHERE ([Product].[Drink], [Store].USA)", "Axis #0:\n" + "{[Product].[All Products].[Drink], [Store].[All Stores].[USA]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997]}\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 24,597\n" + "Row #1: 5,976\n" + "Row #2: 5,895\n" + "Row #3: 6,065\n" + "Row #4: 6,661\n"); } /** * <p>The WHERE clause in the previous MDX query effectively provides a * logical AND operator, in which all unit sales for 1997 are returned only * for drink products and only for those sold in stores in the USA. * * <p>If the members used to construct the logical AND condition reside on * the same dimension, you can use a calculated member or a named set to * filter out the unwanted members, as demonstrated in the following MDX * query. * * <p>The named set, [Good AND Pearl Stores], restricts the displayed unit * sales totals only to those stores that have sold both Good products and * Pearl products. */ public void _testSet() { assertQueryReturns( "WITH SET [Good AND Pearl Stores] AS\n" + " 'FILTER(Store.Members,\n" + " ([Product].[Good], Measures.[Unit Sales]) > 0 AND \n" + " ([Product].[Pearl], Measures.[Unit Sales]) > 0)'\n" + "SELECT DESCENDANTS([Time].[1997], [Quarter], SELF_AND_BEFORE) ON COLUMNS,\n" + " [Good AND Pearl Stores] ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Can I Use Custom Member Properties in MDX?</b> * * <p>Member properties are a good way of adding secondary business * information to members in a dimension. However, getting that information * out can be confusing -- member properties are not readily apparent in a * typical MDX query. * * <p>Member properties can be retrieved in one of two ways. The easiest * and most used method of retrieving member properties is to use the * DIMENSION PROPERTIES MDX statement when constructing an axis in an MDX * query. * * <p>For example, a member property in the Store dimension in the FoodMart * 2000 database details the total square feet for each store. The following * MDX query can retrieve this member property as part of the returned * cellset. */ public void testCustomMemberProperties() { assertQueryReturns( "SELECT {[Measures].[Units Shipped], [Measures].[Units Ordered]} ON COLUMNS,\n" + " NON EMPTY [Store].[Store Name].MEMBERS\n" + " DIMENSION PROPERTIES [Store].[Store Name].[Store Sqft] ON ROWS\n" + "FROM Warehouse", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Units Shipped]}\n" + "{[Measures].[Units Ordered]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Row #0: 10759.0\n" + "Row #0: 11699.0\n" + "Row #1: 24587.0\n" + "Row #1: 26463.0\n" + "Row #2: 23835.0\n" + "Row #2: 26270.0\n" + "Row #3: 1696.0\n" + "Row #3: 1875.0\n" + "Row #4: 8515.0\n" + "Row #4: 9109.0\n" + "Row #5: 32393.0\n" + "Row #5: 35797.0\n" + "Row #6: 2348.0\n" + "Row #6: 2454.0\n" + "Row #7: 22734.0\n" + "Row #7: 24610.0\n" + "Row #8: 24110.0\n" + "Row #8: 26703.0\n" + "Row #9: 11889.0\n" + "Row #9: 12828.0\n" + "Row #10: 32411.0\n" + "Row #10: 35930.0\n" + "Row #11: 1860.0\n" + "Row #11: 2074.0\n" + "Row #12: 10589.0\n" + "Row #12: 11426.0\n"); } /** * <p>The drawback to using the DIMENSION PROPERTIES statement is that, * for most client applications, the member property is not readily * apparent. If the previous MDX query is executed in the MDX sample * application shipped with SQL Server 2000 Analysis Services, for example, * you must double-click the name of the member in the grid to open the * Member Properties dialog box, which displays all of the member properties * shipped as part of the cellset, including the [Store].[Store Name].[Store * Sqft] member property. * * <p>The other method of retrieving member properties involves the creation * of a calculated member based on the member property. The following MDX * query brings back the total square feet for each store as a measure, * included in the COLUMNS axis. * * <p>The [Store SqFt] measure is constructed with the Properties MDX * function to retrieve the [Store SQFT] member property for each member in * the Store dimension. The benefit to this technique is that the calculated * member is readily apparent and easily accessible in client applications * that do not support member properties. */ public void _testMemberPropertyAsCalcMember() { assertQueryReturns( // todo: implement <member>.PROPERTIES "WITH MEMBER Measures.[Store SqFt] AS '[Store].CURRENTMEMBER.PROPERTIES(\"Store SQFT\")'\n" + "SELECT { [Measures].[Store SQFT], [Measures].[Units Shipped], [Measures].[Units Ordered] } ON COLUMNS,\n" + " [Store].[Store Name].MEMBERS ON ROWS\n" + "FROM Warehouse", ""); } /** * <b>How Can I Drill Down More Than One Level Deep, or Skip Levels When * Drilling Down?</b> * * <p>Drilling down is an essential ability for most OLAP products, and * Analysis Services is no exception. Several functions exist that support * drilling up and down the hierarchy of dimensions within a cube. * Typically, drilling up and down the hierarchy is done one level at a * time; think of this functionality as a zoom feature for OLAP data. * * <p>There are times, though, when the need to drill down more than one * level at the same time, or even skip levels when displaying information * about multiple levels, exists for a business scenario. * * <p>For example, you would like to show report results from a query of * the Sales cube in the FoodMart 2000 sample database showing sales totals * for individual cities and the subtotals for each country, as shown in the * following table. * * <p>The Customers dimension, however, has Country, State Province, and * City levels. In order to show the above report, you would have to show * the Country level and then drill down two levels to show the City * level, skipping the State Province level entirely. * * <p>However, the MDX ToggleDrillState and DrillDownMember functions * provide drill down functionality only one level below a specified set. To * drill down more than one level below a specified set, you need to use a * combination of MDX functions, including Descendants, Generate, and * Except. This technique essentially constructs a large set that includes * all levels between both upper and lower desired levels, then uses a * smaller set representing the undesired level or levels to remove the * appropriate members from the larger set. * * <p>The MDX Descendants function is used to construct a set consisting of * the descendants of each member in the Customers dimension. The * descendants are determined using the MDX Descendants function, with the * descendants of the City level and the level above, the State Province * level, for each member of the Customers dimension being added to the * set. * * <p>The MDX Generate function now creates a set consisting of all members * at the Country level as well as the members of the set generated by the * MDX Descendants function. Then, the MDX Except function is used to * exclude all members at the State Province level, so the returned set * contains members at the Country and City levels. * * <p>Note, however, that the previous MDX query will still order the * members according to their hierarchy. Although the returned set contains * members at the Country and City levels, the Country, State Province, * and City levels determine the order of the members. */ public void _testDrillingDownMoreThanOneLevel() { assertQueryReturns( // todo: implement "GENERATE" "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " EXCEPT(GENERATE([Customers].[Country].MEMBERS,\n" + " {DESCENDANTS([Customers].CURRENTMEMBER, [Customers].[City], SELF_AND_BEFORE)}),\n" + " {[Customers].[State Province].MEMBERS}) ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Do I Get the Topmost Members of a Level Broken Out by an Ancestor * Level?</b> * * <p>This type of MDX query is common when only the facts for the lowest * level of a dimension within a cube are needed, but information about * other levels within the same dimension may also be required to satisfy a * specific business scenario. * * <p>For example, a report that shows the unit sales for the store with * the highest unit sales from each country is needed for marketing * purposes. The following table provides an example of this report, run * against the Sales cube in the FoodMart 2000 sample database. * * <p>This looks simple enough, but the Country Name column provides * unexpected difficulty. The values for the Store Country column are taken * from the Store Country level of the Store dimension, so the Store * Country column is constructed as a calculated member as part of the MDX * query, using the MDX Ancestor and Name functions to return the country * names for each store. * * <p>A combination of the MDX Generate, TopCount, and Descendants * functions are used to create a set containing the top stores in unit * sales for each country. */ public void _testTopmost() { assertQueryReturns( // todo: implement "GENERATE" "WITH MEMBER Measures.[Country Name] AS \n" + " 'Ancestor(Store.CurrentMember, [Store Country]).Name'\n" + "SELECT {Measures.[Country Name], Measures.[Unit Sales]} ON COLUMNS,\n" + " GENERATE([Store Country].MEMBERS, \n" + " TOPCOUNT(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]),\n" + " 1, [Measures].[Unit Sales])) ON ROWS\n" + "FROM Sales", ""); } /** * <p>The MDX Descendants function is used to construct a set consisting of * only those members at the Store Name level in the Store dimension. Then, * the MDX TopCount function is used to return only the topmost store based * on the Unit Sales measure. The MDX Generate function then constructs a * set based on the topmost stores, following the hierarchy of the Store * dimension. * * <p>Alternate techniques, such as using the MDX Crossjoin function, may * not provide the desired results because non-related joins can occur. * Since the Store Country and Store Name levels are within the same * dimension, they cannot be cross-joined. Another dimension that provides * the same regional hierarchy structure, such as the Customers dimension, * can be employed with the Crossjoin function. But, using this technique * can cause non-related joins and return unexpected results. * * <p>For example, the following MDX query uses the Crossjoin function to * attempt to return the same desired results. * * <p>However, some unexpected surprises occur because the topmost member * in the Store dimension is cross-joined with all of the children of the * Customers dimension, as shown in the following table. * * <p>In this instance, the use of a calculated member to provide store * country names is easier to understand and debug than attempting to * cross-join across unrelated members */ public void testTopmost2() { assertQueryReturns( "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " CROSSJOIN(Customers.CHILDREN,\n" + " TOPCOUNT(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]),\n" + " 1, [Measures].[Unit Sales])) ON ROWS\n" + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[Canada], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Customers].[All Customers].[Mexico], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Customers].[All Customers].[USA], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "Row #0: \n" + "Row #1: \n" + "Row #2: 41,580\n"); } /** * <b>How Can I Rank or Reorder Members?</b> * * <p>One of the issues commonly encountered in business scenarios is the * need to rank the members of a dimension according to their corresponding * measure values. The Order MDX function allows you to order a set based on * a string or numeric expression evaluated against the members of a set. * Combined with other MDX functions, the Order function can support * several different types of ranking. * * <p>For example, the Sales cube in the FoodMart 2000 database can be used * to show unit sales for each store. However, the business scenario * requires a report that ranks the stores from highest to lowest unit * sales, individually, of nonconsumable products. * * <p>Because of the requirement that stores be sorted individually, the * hierarchy must be broken (in other words, ignored) for the purpose of * ranking the stores. The Order function is capable of sorting within the * hierarchy, based on the topmost level represented in the set to be * sorted, or, by breaking the hierarchy, sorting all of the members of the * set as if they existed on the same level, with the same parent. * * <p>The following MDX query illustrates the use of the Order function to * rank the members according to unit sales. */ public void testRank() { assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS, \n" + " ORDER([Store].[Store Name].MEMBERS, (Measures.[Unit Sales]), BDESC) ON ROWS\n" + "FROM Sales\n" + "WHERE [Product].[Non-Consumable]", "Axis #0:\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[Canada].[BC].[Vancouver].[Store 19]}\n" + "{[Store].[All Stores].[Canada].[BC].[Victoria].[Store 20]}\n" + "{[Store].[All Stores].[Mexico].[DF].[Mexico City].[Store 9]}\n" + "{[Store].[All Stores].[Mexico].[DF].[San Andres].[Store 21]}\n" + "{[Store].[All Stores].[Mexico].[Guerrero].[Acapulco].[Store 1]}\n" + "{[Store].[All Stores].[Mexico].[Jalisco].[Guadalajara].[Store 5]}\n" + "{[Store].[All Stores].[Mexico].[Veracruz].[Orizaba].[Store 10]}\n" + "{[Store].[All Stores].[Mexico].[Yucatan].[Merida].[Store 8]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Camacho].[Store 4]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Hidalgo].[Store 12]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Hidalgo].[Store 18]}\n" + "{[Store].[All Stores].[USA].[CA].[Alameda].[HQ]}\n" + "Row #0: 7,940\n" + "Row #1: 6,712\n" + "Row #2: 5,076\n" + "Row #3: 4,947\n" + "Row #4: 4,706\n" + "Row #5: 4,639\n" + "Row #6: 4,479\n" + "Row #7: 4,428\n" + "Row #8: 3,950\n" + "Row #9: 2,140\n" + "Row #10: 442\n" + "Row #11: 390\n" + "Row #12: 387\n" + "Row #13: \n" + "Row #14: \n" + "Row #15: \n" + "Row #16: \n" + "Row #17: \n" + "Row #18: \n" + "Row #19: \n" + "Row #20: \n" + "Row #21: \n" + "Row #22: \n" + "Row #23: \n" + "Row #24: \n"); } /** * <b>How Can I Use Different Calculations for Different Levels in a * Dimension?</b> * * <p>This type of MDX query frequently occurs when different aggregations * are needed at different levels in a dimension. One easy way to support * such functionality is through the use of a calculated measure, created as * part of the query, which uses the MDX Descendants function in conjunction * with one of the MDX aggregation functions to provide results. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * supplies the [Units Ordered] measure, aggregated through the Sum * function. But, you would also like to see the average number of units * ordered per store. The following table demonstrates the desired results. * * <p>By using the following MDX query, the desired results can be * achieved. The calculated measure, [Average Units Ordered], supplies the * average number of ordered units per store by using the Avg, * CurrentMember, and Descendants MDX functions. */ public void testDifferentCalculationsForDifferentLevels() { assertQueryReturns( "WITH MEMBER Measures.[Average Units Ordered] AS\n" + " 'AVG(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]), [Measures].[Units Ordered])',\n" + " FORMAT_STRING='#.00'\n" + "SELECT {[Measures].[Units ordered], Measures.[Average Units Ordered]} ON COLUMNS,\n" + " [Store].[Store State].MEMBERS ON ROWS\n" + "FROM Warehouse", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Units Ordered]}\n" + "{[Measures].[Average Units Ordered]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[Canada].[BC]}\n" + "{[Store].[All Stores].[Mexico].[DF]}\n" + "{[Store].[All Stores].[Mexico].[Guerrero]}\n" + "{[Store].[All Stores].[Mexico].[Jalisco]}\n" + "{[Store].[All Stores].[Mexico].[Veracruz]}\n" + "{[Store].[All Stores].[Mexico].[Yucatan]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas]}\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[OR]}\n" + "{[Store].[All Stores].[USA].[WA]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: \n" + "Row #1: \n" + "Row #2: \n" + "Row #2: \n" + "Row #3: \n" + "Row #3: \n" + "Row #4: \n" + "Row #4: \n" + "Row #5: \n" + "Row #5: \n" + "Row #6: \n" + "Row #6: \n" + "Row #7: 66307.0\n" + "Row #7: 16576.75\n" + "Row #8: 44906.0\n" + "Row #8: 22453.00\n" + "Row #9: 116025.0\n" + "Row #9: 16575.00\n"); } /** * <p>This calculated measure is more powerful than it seems; if, for * example, you then want to see the average number of units ordered for * beer products in all of the stores in the California area, the following * MDX query can be executed with the same calculated measure. */ public void testDifferentCalculations2() { assertQueryReturns( // todo: "[Store].[USA].[CA]" should be "[Store].CA", // "[Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer]" // should be "[Product].[Beer]" "WITH MEMBER Measures.[Average Units Ordered] AS\n" + " 'AVG(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]), [Measures].[Units Ordered])'\n" + "SELECT {[Measures].[Units ordered], Measures.[Average Units Ordered]} ON COLUMNS,\n" + " [Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].CHILDREN ON ROWS\n" + "FROM Warehouse\n" + "WHERE [Store].[USA].[CA]", "Axis #0:\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "Axis #1:\n" + "{[Measures].[Units Ordered]}\n" + "{[Measures].[Average Units Ordered]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Good]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Pearl]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Top Measure]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Walrus]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 151.0\n" + "Row #1: 75.5\n" + "Row #2: 95.0\n" + "Row #2: 95.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #4: 211.0\n" + "Row #4: 105.5\n"); } /** * <b>How Can I Use Different Calculations for Different Dimensions?</b> * * <p>Each measure in a cube uses the same aggregation function across all * dimensions. However, there are times where a different aggregation * function may be needed to represent a measure for reporting purposes. Two * basic cases involve aggregating a single dimension using a different * aggregation function than the one used for other dimensions.<ul> * * <li>Aggregating minimums, maximums, or averages along a time * dimension</li> * * <li>Aggregating opening and closing period values along a time * dimension</li></ul> * * <p>The first case involves some knowledge of the behavior of the time * dimension specified in the cube. For instance, to create a calculated * measure that contains the average, along a time dimension, of measures * aggregated as sums along other dimensions, the average of the aggregated * measures must be taken over the set of averaging time periods, * constructed through the use of the Descendants MDX function. Minimum and * maximum values are more easily calculated through the use of the Min and * Max MDX functions, also combined with the Descendants function. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * contains information on ordered and shipped inventory; from it, a report * is requested to show the average number of units shipped, by product, to * each store. Information on units shipped is added on a monthly basis, so * the aggregated measure [Units Shipped] is divided by the count of * descendants, at the Month level, of the current member in the Time * dimension. This calculation provides a measure representing the average * number of units shipped per month, as demonstrated in the following MDX * query. */ public void _testDifferentCalculationsForDifferentDimensions() { assertQueryReturns( // todo: implement "NONEMPTYCROSSJOIN" "WITH MEMBER [Measures].[Avg Units Shipped] AS\n" + " '[Measures].[Units Shipped] / \n" + " COUNT(DESCENDANTS([Time].CURRENTMEMBER, [Time].[Month], SELF))'\n" + "SELECT {Measures.[Units Shipped], Measures.[Avg Units Shipped]} ON COLUMNS,\n" + "NONEMPTYCROSSJOIN(Store.CA.Children, Product.MEMBERS) ON ROWS\n" + "FROM Warehouse", ""); } /** * <p>The second case is easier to resolve, because MDX provides the * OpeningPeriod and ClosingPeriod MDX functions specifically to support * opening and closing period values. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * contains information on ordered and shipped inventory; from it, a report * is requested to show on-hand inventory at the end of every month. Because * the inventory on hand should equal ordered inventory minus shipped * inventory, the ClosingPeriod MDX function can be used to create a * calculated measure to supply the value of inventory on hand, as * demonstrated in the following MDX query. */ public void _testDifferentCalculationsForDifferentDimensions2() { assertQueryReturns( "WITH MEMBER Measures.[Closing Balance] AS\n" + " '([Measures].[Units Ordered], \n" + " CLOSINGPERIOD([Time].[Month], [Time].CURRENTMEMBER)) -\n" + " ([Measures].[Units Shipped], \n" + " CLOSINGPERIOD([Time].[Month], [Time].CURRENTMEMBER))'\n" + "SELECT {[Measures].[Closing Balance]} ON COLUMNS,\n" + " Product.MEMBERS ON ROWS\n" + "FROM Warehouse", ""); } /** * <b>How Can I Use Date Ranges in MDX?</b> * * <p>Date ranges are a frequently encountered problem. Business questions * use ranges of dates, but OLAP objects provide aggregated information in * date levels. * * <p>Using the technique described here, you can establish date ranges in * MDX queries at the level of granularity provided by a time dimension. * Date ranges cannot be established below the granularity of the dimension * without additional information. For example, if the lowest level of a * time dimension represents months, you will not be able to establish a * two-week date range without other information. Member properties can be * added to supply specific dates for members; using such member properties, * you can take advantage of the date and time functions provided by VBA and * Excel external function libraries to establish date ranges. * * <p>The easiest way to specify a static date range is by using the colon * (:) operator. This operator creates a naturally ordered set, using the * members specified on either side of the operator as the endpoints for the * ordered set. For example, to specify the first six months of 1998 from * the Time dimension in FoodMart 2000, the MDX syntax would resemble: * * <blockquote><pre>[Time].[1998].[1]:[Time].[1998].[6]</pre></blockquote> * * <p>For example, the Sales cube uses a time dimension that supports Year, * Quarter, and Month levels. To add a six-month and nine-month total, two * calculated members are created in the following MDX query. */ public void _testDateRange() { assertQueryReturns( // todo: implement "AddCalculatedMembers" "WITH MEMBER [Time].[1997].[Six Month] AS\n" + " 'SUM([Time].[1]:[Time].[6])'\n" + "MEMBER [Time].[1997].[Nine Month] AS\n" + " 'SUM([Time].[1]:[Time].[9])'\n" + "SELECT AddCalculatedMembers([Time].[1997].Children) ON COLUMNS,\n" + " [Product].Children ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Can I Use Rolling Date Ranges in MDX?</b> * * <p>There are several techniques that can be used in MDX to support * rolling date ranges. All of these techniques tend to fall into two * groups. The first group involves the use of relative hierarchical * functions to construct named sets or calculated members, and the second * group involves the use of absolute date functions from external function * libraries to construct named sets or calculated members. Both groups are * applicable in different business scenarios. * * <p>In the first group of techniques, typically a named set is * constructed which contains a number of periods from a time dimension. For * example, the following table illustrates a 12-month rolling period, in * which the figures for unit sales of the previous 12 months are shown. * * <p>The following MDX query accomplishes this by using a number of MDX * functions, including LastPeriods, Tail, Filter, Members, and Item, to * construct a named set containing only those members across all other * dimensions that share data with the time dimension at the Month level. * The example assumes that there is at least one measure, such as [Unit * Sales], with a value greater than zero in the current period. The Filter * function creates a set of months with unit sales greater than zero, while * the Tail function returns the last month in this set, the current month. * The LastPeriods function, finally, is then used to retrieve the last 12 * periods at this level, including the current period. */ public void _testRolling() { assertQueryReturns( "WITH SET Rolling12 AS\n" + " 'LASTPERIODS(12, TAIL(FILTER([Time].[Month].MEMBERS, \n" + " ([Customers].[All Customers], \n" + " [Education Level].[All Education Level],\n" + " [Gender].[All Gender],\n" + " [Marital Status].[All Marital Status],\n" + " [Product].[All Products], \n" + " [Promotion Media].[All Media],\n" + " [Promotions].[All Promotions],\n" + " [Store].[All Stores],\n" + " [Store Size in SQFT].[All Store Size in SQFT],\n" + " [Store Type].[All Store Type],\n" + " [Yearly Income].[All Yearly Income],\n" + " Measures.[Unit Sales]) >0),\n" + " 1).ITEM(0).ITEM(0))'\n" + "SELECT {[Measures].[Unit Sales]} ON COLUMNS, \n" + " Rolling12 ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Can I Use Different Calculations for Different Time Periods?</b> * * <p>A few techniques can be used, depending on the structure of the cube * being queried, to support different calculations for members depending * on the time period. The following example includes the MDX IIf function, * and is easy to use but difficult to maintain. This example works well for * ad hoc queries, but is not the ideal technique for client applications in * a production environment. * * <p>For example, the following table illustrates a standard and dynamic * forecast of warehouse sales, from the Warehouse cube in the FoodMart 2000 * database, for drink products. The standard forecast is double the * warehouse sales of the previous year, while the dynamic forecast varies * from month to month -- the forecast for January is 120 percent of * previous sales, while the forecast for July is 260 percent of previous * sales. * * <p>The most flexible way of handling this type of report is the use of * nested MDX IIf functions to return a multiplier to be used on the members * of the Products dimension, at the Drinks level. The following MDX query * demonstrates this technique. */ public void testDifferentCalcsForDifferentTimePeriods() { assertQueryReturns( // note: "[Product].[Drink Forecast - Standard]" // was "[Drink Forecast - Standard]" "WITH MEMBER [Product].[Drink Forecast - Standard] AS\n" + " '[Product].[All Products].[Drink] * 2'\n" + "MEMBER [Product].[Drink Forecast - Dynamic] AS \n" + " '[Product].[All Products].[Drink] * \n" + " IIF([Time].[Time].CurrentMember.Name = \"1\", 1.2,\n" + " IIF([Time].[Time].CurrentMember.Name = \"2\", 1.3,\n" + " IIF([Time].[Time].CurrentMember.Name = \"3\", 1.4,\n" + " IIF([Time].[Time].CurrentMember.Name = \"4\", 1.6,\n" + " IIF([Time].[Time].CurrentMember.Name = \"5\", 2.1,\n" + " IIF([Time].[Time].CurrentMember.Name = \"6\", 2.4,\n" + " IIF([Time].[Time].CurrentMember.Name = \"7\", 2.6,\n" + " IIF([Time].[Time].CurrentMember.Name = \"8\", 2.3,\n" + " IIF([Time].[Time].CurrentMember.Name = \"9\", 1.9,\n" + " IIF([Time].[Time].CurrentMember.Name = \"10\", 1.5,\n" + " IIF([Time].[Time].CurrentMember.Name = \"11\", 1.4,\n" + " IIF([Time].[Time].CurrentMember.Name = \"12\", 1.2, 1.0))))))))))))'\n" + "SELECT DESCENDANTS(Time.[1997], [Month], SELF) ON COLUMNS, \n" + " {[Product].CHILDREN, [Product].[Drink Forecast - Standard], [Product].[Drink Forecast - Dynamic]} ON ROWS\n" + "FROM Warehouse", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997].[Q1].[1]}\n" + "{[Time].[1997].[Q1].[2]}\n" + "{[Time].[1997].[Q1].[3]}\n" + "{[Time].[1997].[Q2].[4]}\n" + "{[Time].[1997].[Q2].[5]}\n" + "{[Time].[1997].[Q2].[6]}\n" + "{[Time].[1997].[Q3].[7]}\n" + "{[Time].[1997].[Q3].[8]}\n" + "{[Time].[1997].[Q3].[9]}\n" + "{[Time].[1997].[Q4].[10]}\n" + "{[Time].[1997].[Q4].[11]}\n" + "{[Time].[1997].[Q4].[12]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "{[Product].[Drink Forecast - Standard]}\n" + "{[Product].[Drink Forecast - Dynamic]}\n" + "Row #0: 881.847\n" + "Row #0: 579.051\n" + "Row #0: 476.292\n" + "Row #0: 618.722\n" + "Row #0: 778.886\n" + "Row #0: 636.935\n" + "Row #0: 937.842\n" + "Row #0: 767.332\n" + "Row #0: 920.707\n" + "Row #0: 1,007.764\n" + "Row #0: 820.808\n" + "Row #0: 792.167\n" + "Row #1: 8,383.446\n" + "Row #1: 4,851.406\n" + "Row #1: 5,353.188\n" + "Row #1: 6,061.829\n" + "Row #1: 6,039.282\n" + "Row #1: 5,259.242\n" + "Row #1: 6,902.01\n" + "Row #1: 5,790.772\n" + "Row #1: 8,167.053\n" + "Row #1: 6,188.732\n" + "Row #1: 5,344.845\n" + "Row #1: 5,025.744\n" + "Row #2: 2,040.396\n" + "Row #2: 1,269.816\n" + "Row #2: 1,460.686\n" + "Row #2: 1,696.757\n" + "Row #2: 1,397.035\n" + "Row #2: 1,578.136\n" + "Row #2: 1,671.046\n" + "Row #2: 1,609.447\n" + "Row #2: 2,059.617\n" + "Row #2: 1,617.493\n" + "Row #2: 1,909.713\n" + "Row #2: 1,382.364\n" + "Row #3: 1,763.693\n" + "Row #3: 1,158.102\n" + "Row #3: 952.584\n" + "Row #3: 1,237.444\n" + "Row #3: 1,557.773\n" + "Row #3: 1,273.87\n" + "Row #3: 1,875.685\n" + "Row #3: 1,534.665\n" + "Row #3: 1,841.414\n" + "Row #3: 2,015.528\n" + "Row #3: 1,641.615\n" + "Row #3: 1,584.334\n" + "Row #4: 1,058.216\n" + "Row #4: 752.766\n" + "Row #4: 666.809\n" + "Row #4: 989.955\n" + "Row #4: 1,635.661\n" + "Row #4: 1,528.644\n" + "Row #4: 2,438.39\n" + "Row #4: 1,764.865\n" + "Row #4: 1,749.343\n" + "Row #4: 1,511.646\n" + "Row #4: 1,149.13\n" + "Row #4: 950.601\n"); } /** * <p>Other techniques, such as the addition of member properties to the * Time or Product dimensions to support such calculations, are not as * flexible but are much more efficient. The primary drawback to using such * techniques is that the calculations are not easily altered for * speculative analysis purposes. For client applications, however, where * the calculations are static or slowly changing, using a member property * is an excellent way of supplying such functionality to clients while * keeping maintenance of calculation variables at the server level. The * same MDX query, for example, could be rewritten to use a member property * named [Dynamic Forecast Multiplier] as shown in the following MDX query. */ public void _testDc4dtp2() { assertQueryReturns( "WITH MEMBER [Product].[Drink Forecast - Standard] AS\n" + " '[Product].[All Products].[Drink] * 2'\n" + "MEMBER [Product].[Drink Forecast - Dynamic] AS \n" + " '[Product].[All Products].[Drink] * \n" + " [Time].CURRENTMEMBER.PROPERTIES(\"Dynamic Forecast Multiplier\")'\n" + "SELECT DESCENDANTS(Time.[1997], [Month], SELF) ON COLUMNS, \n" + " {[Product].CHILDREN, [Drink Forecast - Standard], [Drink Forecast - Dynamic]} ON ROWS\n" + "FROM Warehouse", ""); } public void _testWarehouseProfit() { assertQueryReturns( "select \n" + "{[Measures].[Warehouse Cost], [Measures].[Warehouse Sales], [Measures].[Warehouse Profit]}\n" + " ON COLUMNS from [Warehouse]", ""); } /** * <b>How Can I Compare Time Periods in MDX?</b> * * <p>To answer such a common business question, MDX provides a number of * functions specifically designed to navigate and aggregate information * across time periods. For example, year-to-date (YTD) totals are directly * supported through the YTD function in MDX. In combination with the MDX * ParallelPeriod function, you can create calculated members to support * direct comparison of totals across time periods. * * <p>For example, the following table represents a comparison of YTD unit * sales between 1997 and 1998, run against the Sales cube in the FoodMart * 2000 database. * * <p>The following MDX query uses three calculated members to illustrate * how to use the YTD and ParallelPeriod functions in combination to compare * time periods. */ public void _testYtdGrowth() { assertQueryReturns( // todo: implement "ParallelPeriod" "WITH MEMBER [Measures].[YTD Unit Sales] AS\n" + " 'COALESCEEMPTY(SUM(YTD(), [Measures].[Unit Sales]), 0)'\n" + "MEMBER [Measures].[Previous YTD Unit Sales] AS\n" + " '(Measures.[YTD Unit Sales], PARALLELPERIOD([Time].[Year]))'\n" + "MEMBER [Measures].[YTD Growth] AS\n" + " '[Measures].[YTD Unit Sales] - ([Measures].[Previous YTD Unit Sales])'\n" + "SELECT {[Time].[1998]} ON COLUMNS,\n" + " {[Measures].[YTD Unit Sales], [Measures].[Previous YTD Unit Sales], [Measures].[YTD Growth]} ON ROWS\n" + "FROM Sales ", ""); } /* * takes quite long */ public void dont_testParallelMutliple() { for (int i = 0; i < 5; i++) { runParallelQueries(1, 1, false); runParallelQueries(3, 2, false); runParallelQueries(4, 6, true); runParallelQueries(6, 10, false); } } public void dont_testParallelNot() { runParallelQueries(1, 1, false); } public void dont_testParallelSomewhat() { runParallelQueries(3, 2, false); } public void dont_testParallelFlushCache() { runParallelQueries(4, 6, true); } public void dont_testParallelVery() { runParallelQueries(6, 10, false); } private void runParallelQueries( final int threadCount, final int iterationCount, final boolean flush) { // 10 minute per query long timeoutMs = (long) threadCount * iterationCount * 600 * 1000; final int[] executeCount = new int[] {0}; final List<QueryAndResult> queries = new ArrayList<QueryAndResult>(); queries.addAll(Arrays.asList(sampleQueries)); queries.addAll(taglibQueries); TestCaseForker threaded = new TestCaseForker( this, timeoutMs, threadCount, new ChooseRunnable() { public void run(int i) { for (int j = 0; j < iterationCount; j++) { int queryIndex = (i * 2 + j) % queries.size(); try { QueryAndResult query = queries.get(queryIndex); assertQueryReturns(query.query, query.result); if (flush && i == 0) { getConnection().getCacheControl(null) .flushSchemaCache(); } synchronized (executeCount) { executeCount[0]++; } } catch (Throwable e) { e.printStackTrace(); throw Util.newInternal( e, "Thread #" + i + " failed while executing query #" + queryIndex); } } } }); threaded.run(); assertEquals( "number of executions", threadCount * iterationCount, executeCount[0]); } /** * Makes sure that the expression <code> * * [Measures].[Unit Sales] / ([Measures].[Unit Sales], [Product].[All * Products]) * * </code> depends on the current member of the Product dimension, although * [Product].[All Products] is referenced from the expression. */ public void testDependsOn() { assertQueryReturns( "with member [Customers].[my] as \n" + " 'Aggregate(Filter([Customers].[City].Members, (([Measures].[Unit Sales] / ([Measures].[Unit Sales], [Product].[All Products])) > 0.1)))' \n" + "select \n" + " {[Measures].[Unit Sales]} ON columns, \n" + " {[Product].[All Products].[Food].[Deli], [Product].[All Products].[Food].[Frozen Foods]} ON rows \n" + "from [Sales] \n" + "where ([Customers].[my], [Time].[1997])\n", "Axis #0:\n" + "{[Customers].[my], [Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "Row #0: 13\n" + "Row #1: 15,111\n"); } /** * Testcase for bug 1755778, "CrossJoin / Filter query returns null row in * result set" * * @throws Exception on error */ public void testFilterWithCrossJoin() throws Exception { String queryWithFilter = "WITH SET [#DataSet#] AS 'Filter(Crossjoin({[Store].[All Stores]}, {[Customers].[All Customers]}), " + "[Measures].[Unit Sales] > 5)' " + "MEMBER [Customers].[#GT#] as 'Aggregate({[#DataSet#]})' " + "MEMBER [Store].[#GT#] as 'Aggregate({[#DataSet#]})' " + "SET [#GrandTotalSet#] as 'Crossjoin({[Store].[#GT#]}, {[Customers].[#GT#]})' " + "SELECT {[Measures].[Unit Sales]} " + "on columns, Union([#GrandTotalSet#], Hierarchize({[#DataSet#]})) on rows FROM [Sales]"; String queryWithoutFilter = "WITH SET [#DataSet#] AS 'Crossjoin({[Store].[All Stores]}, {[Customers].[All Customers]})' " + "SET [#GrandTotalSet#] as 'Crossjoin({[Store].[All Stores]}, {[Customers].[All Customers]})' " + "SELECT {[Measures].[Unit Sales]} on columns, Union([#GrandTotalSet#], Hierarchize({[#DataSet#]})) " + "on rows FROM [Sales]"; String wrongResultWithFilter = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[#GT#], [Customers].[#GT#]}\n" + "Row #0: \n"; String expectedResultWithFilter = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[#GT#], [Customers].[#GT#]}\n" + "{[Store].[All Stores], [Customers].[All Customers]}\n" + "Row #0: 266,773\n" + "Row #1: 266,773\n"; String expectedResultWithoutFilter = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores], [Customers].[All Customers]}\n" + "Row #0: 266,773\n"; // With bug 1755778, the following test below fails because it returns // only row that have a null value (see "wrongResultWithFilter"). // It should return the "expectedResultWithFilter" value. assertQueryReturns(queryWithFilter, expectedResultWithFilter); // To see the test case return the correct result comment out the line // above and uncomment out the lines below following. If a similar // query without the filter is executed (queryWithoutFilter) prior to // running the query with the filter then the correct result set is // returned assertQueryReturns( queryWithoutFilter, expectedResultWithoutFilter); assertQueryReturns( queryWithFilter, expectedResultWithFilter); } /** * This resulted in {@link OutOfMemoryError} when the * BatchingCellReader did not know the values for the tuples that * were used in filters. */ public void testFilteredCrossJoin() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Measures].[Store Sales]} on columns,\n" + " NON EMPTY Crossjoin(\n" + " Filter([Customers].[Name].Members,\n" + " (([Measures].[Store Sales],\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]) > 5.0)),\n" + " Filter([Product].[Product Name].Members,\n" + " (([Measures].[Store Sales],\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]) > 5.0))\n" + " ) ON rows\n" + "from [Sales]\n" + "where (\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]\n" + ")\n"); // ok if no OutOfMemoryError occurs Axis a = result.getAxes()[1]; assertEquals(12, a.getPositions().size()); } /** * Tests a query with a CrossJoin so large that we run out of memory unless * we can push down evaluation to SQL. */ public void testNonEmptyCrossJoin() { if (!props.EnableNativeCrossJoin.get()) { // If we try to evaluate the crossjoin in memory we run out of // memory. return; } getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Measures].[Store Sales]} on columns,\n" + " NON EMPTY Crossjoin(\n" + " [Customers].[Name].Members,\n" + " [Product].[Product Name].Members\n" + " ) ON rows\n" + "from [Sales]\n" + "where (\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]\n" + ")\n"); // ok if no OutOfMemoryError occurs Axis a = result.getAxes()[1]; assertEquals(67, a.getPositions().size()); } /** * NonEmptyCrossJoin() is not the same as NON EMPTY CrossJoin() * because it's evaluated independently of the other axes. * (see http://blogs.msdn.com/bi_systems/articles/162841.aspx) */ public void testNonEmptyNonEmptyCrossJoin1() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " CrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(306, a.getPositions().size()); } public void testNonEmptyNonEmptyCrossJoin2() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " NonEmptyCrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(10, a.getPositions().size()); } public void testNonEmptyNonEmptyCrossJoin3() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " Non Empty CrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(1, a.getPositions().size()); } public void testNonEmptyNonEmptyCrossJoin4() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " Non Empty NonEmptyCrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(1, a.getPositions().size()); } /** * description of this testcase: * A calculated member is created on the time.month level. * On Hierarchize this member is compared to a month. * The month has a numeric key, while the calculated members * key type is string. * No exeception must be thrown. */ public void testHierDifferentKeyClass() { Result result = executeQuery( "with member [Time].[1997].[Q1].[xxx] as\n" + "'Aggregate({[Time].[1997].[Q1].[1], [Time].[1997].[Q1].[2]})'\n" + "select {[Measures].[Unit Sales], [Measures].[Store Cost],\n" + "[Measures].[Store Sales]} ON columns,\n" + "Hierarchize(Union(Union({[Time].[1997], [Time].[1998],\n" + "[Time].[1997].[Q1].[xxx]}, [Time].[1997].Children),\n" + "[Time].[1997].[Q1].Children)) ON rows from [Sales]"); Axis a = result.getAxes()[1]; assertEquals(10, a.getPositions().size()); } /** * Bug #1005995 - many totals of various dimensions */ public void testOverlappingCalculatedMembers() { assertQueryReturns( "WITH MEMBER [Store].[Total] AS 'SUM([Store].[Store Country].MEMBERS)' " + "MEMBER [Store Type].[Total] AS 'SUM([Store Type].[Store Type].MEMBERS)' " + "MEMBER [Gender].[Total] AS 'SUM([Gender].[Gender].MEMBERS)' " + "MEMBER [Measures].[x] AS '[Measures].[Store Sales]' " + "SELECT {[Measures].[x]} ON COLUMNS , " + "{ ([Store].[Total], [Store Type].[Total], [Gender].[Total]) } ON ROWS " + "FROM Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[x]}\n" + "Axis #2:\n" + "{[Store].[Total], [Store Type].[Total], [Gender].[Total]}\n" + "Row #0: 565,238.13\n"); } /** * the following query raised a classcast exception because * an empty property evaluated as "NullMember" * note: Store "HQ" does not have a "Store Manager" */ public void testEmptyProperty() { assertQueryReturns( "select {[Measures].[Unit Sales]} on columns, " + "filter([Store].[Store Name].members," + "[Store].currentmember.properties(\"Store Manager\")=\"Smith\") on rows" + " from Sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "Row #0: 2,237\n"); } /** * This test modifies the Sales cube to contain both the regular usage * of the [Store] shared dimension, and another usage called [Other Store] * which is connected to the [Unit Sales] column */ public void _testCubeWhichUsesSameSharedDimTwice() { // Create a second usage of the "Store" shared dimension called "Other // Store". Attach it to the "unit_sales" column (which has values [1, // 6] whereas store has values [1, 24]. TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<DimensionUsage name=\"Other Store\" source=\"Store\" foreignKey=\"unit_sales\" />"); Axis axis = testContext.executeAxis("[Other Store].members"); assertEquals(63, axis.getPositions().size()); axis = testContext.executeAxis("[Store].members"); assertEquals(63, axis.getPositions().size()); final String q1 = "select {[Measures].[Unit Sales]} on columns,\n" + " NON EMPTY {[Other Store].members} on rows\n" + "from [Sales]"; testContext.assertQueryReturns( q1, "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Other Store].[All Other Stores]}\n" + "{[Other Store].[All Other Stores].[Mexico]}\n" + "{[Other Store].[All Other Stores].[USA]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas]}\n" + "{[Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Other Store].[All Other Stores].[USA].[WA]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero].[Acapulco]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco].[Guadalajara]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas].[Camacho]}\n" + "{[Other Store].[All Other Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bellingham]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bremerton]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero].[Acapulco].[Store 1]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco].[Guadalajara].[Store 5]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas].[Camacho].[Store 4]}\n" + "{[Other Store].[All Other Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "Row #0: 266,773\n" + "Row #1: 110,822\n" + "Row #2: 155,951\n" + "Row #3: 1,827\n" + "Row #4: 14,915\n" + "Row #5: 94,080\n" + "Row #6: 222\n" + "Row #7: 155,729\n" + "Row #8: 1,827\n" + "Row #9: 14,915\n" + "Row #10: 94,080\n" + "Row #11: 222\n" + "Row #12: 39,362\n" + "Row #13: 116,367\n" + "Row #14: 1,827\n" + "Row #15: 14,915\n" + "Row #16: 94,080\n" + "Row #17: 222\n" + "Row #18: 39,362\n" + "Row #19: 116,367\n"); final String q2 = "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin(\n" + " {[Store].[USA], [Store].[USA].[CA], [Store].[USA].[OR].[Portland]}, \n" + " {[Other Store].[USA], [Other Store].[USA].[CA], [Other Store].[USA].[OR].[Portland]}) on rows\n" + "from [Sales]"; testContext.assertQueryReturns( q2, "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "Row #0: 155,951\n" + "Row #1: 222\n" + "Row #2: \n" + "Row #3: 43,730\n" + "Row #4: 66\n" + "Row #5: \n" + "Row #6: 15,134\n" + "Row #7: 24\n" + "Row #8: \n"); Result result = executeQuery(q2); final Cell cell = result.getCell(new int[] {0, 0}); String sql = cell.getDrillThroughSQL(false); // the following replacement is for databases in ANSI mode // using '"' to quote identifiers sql = sql.replace('"', '`'); String tableQualifier = "as "; final Dialect dialect = getTestContext().getDialect(); if (dialect.getDatabaseProduct() == Dialect.DatabaseProduct.ORACLE) { // " + tableQualifier + " tableQualifier = ""; } assertEquals( "select `store`.`store_country` as `Store Country`," + " `time_by_day`.`the_year` as `Year`," + " `store_1`.`store_country` as `x0`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store` " + tableQualifier + "`store`," + " `sales_fact_1997` " + tableQualifier + "`sales_fact_1997`," + " `time_by_day` " + tableQualifier + "`time_by_day`," + " `store` " + tableQualifier + "`store_1` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id`" + " and `store`.`store_country` = 'USA'" + " and `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`unit_sales` = `store_1`.`store_id`" + " and `store_1`.`store_country` = 'USA'", sql); } public void testMemberVisibility() { String cubeName = "Sales_MemberVis"; TestContext testContext = TestContext.create( null, "<Cube name=\"" + cubeName + "\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"\n" + " formatString=\"#,###.00\"/>\n" + " <Measure name=\"Store Sales\" column=\"store_sales\" aggregator=\"sum\"\n" + " formatString=\"#,###.00\"/>\n" + " <Measure name=\"Sales Count\" column=\"product_id\" aggregator=\"count\"\n" + " formatString=\"#,###\"/>\n" + " <Measure name=\"Customer Count\" column=\"customer_id\"\n" + " aggregator=\"distinct-count\" formatString=\"#,###\"/>\n" + " <CalculatedMember\n" + " name=\"Profit\"\n" + " dimension=\"Measures\"\n" + " visible=\"false\"\n" + " formula=\"[Measures].[Store Sales]-[Measures].[Store Cost]\">\n" + " <CalculatedMemberProperty name=\"FORMAT_STRING\" value=\"$#,##0.00\"/>\n" + " </CalculatedMember>\n" + "</Cube>", null, null, null, null); SchemaReader scr = testContext.getConnection().getSchema().lookupCube( cubeName, true).getSchemaReader(null); Member member = scr.getMemberByUniqueName( Id.Segment.toList( "Measures", "Unit Sales"), true); Object visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.FALSE, visible); member = scr.getMemberByUniqueName( Id.Segment.toList( "Measures", "Store Cost"), true); visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.TRUE, visible); member = scr.getMemberByUniqueName( Id.Segment.toList( "Measures", "Profit"), true); visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.FALSE, visible); } public void testAllMemberCaption() { TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<Dimension name=\"Gender3\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\"\n" + " allMemberCaption=\"Frauen und Maenner\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>"); String mdx = "select {[Gender3].[All Gender]} on columns from Sales"; Result result = testContext.executeQuery(mdx); Axis axis0 = result.getAxes()[0]; Position pos0 = axis0.getPositions().get(0); Member allGender = pos0.get(0); String caption = allGender.getCaption(); Assert.assertEquals(caption, "Frauen und Maenner"); } public void testAllLevelName() { TestContext testContext = TestContext.createSubstitutingCube( "Sales", "<Dimension name=\"Gender4\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\"\n" + " allLevelName=\"GenderLevel\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>"); String mdx = "select {[Gender4].[All Gender]} on columns from Sales"; Result result = testContext.executeQuery(mdx); Axis axis0 = result.getAxes()[0]; Position pos0 = axis0.getPositions().get(0); Member allGender = pos0.get(0); String caption = allGender.getLevel().getName(); Assert.assertEquals(caption, "GenderLevel"); } /** * Bug 1250080 caused a dimension with no 'all' member to be constrained * twice. */ public void testDimWithoutAll() { // Create a test context with a new ""Sales_DimWithoutAll" cube, and // which evaluates expressions against that cube. TestContext testContext = new TestContext() { public Util.PropertyList getFoodMartConnectionProperties() { final String schema = getFoodMartSchema( null, "<Cube name=\"Sales_DimWithoutAll\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <Dimension name=\"Product\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"false\" primaryKey=\"product_id\" primaryKeyTable=\"product\">\n" + " <Join leftKey=\"product_class_id\" rightKey=\"product_class_id\">\n" + " <Table name=\"product\"/>\n" + " <Table name=\"product_class\"/>\n" + " </Join>\n" + " <Level name=\"Product Family\" table=\"product_class\" column=\"product_family\"\n" + " uniqueMembers=\"true\"/>\n" + " <Level name=\"Product Department\" table=\"product_class\" column=\"product_department\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Category\" table=\"product_class\" column=\"product_category\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Subcategory\" table=\"product_class\" column=\"product_subcategory\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\"\n" + " uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Gender\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"false\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"\n" + " formatString=\"#,###.00\"/>\n" + "</Cube>", null, null, null, null); Util.PropertyList properties = super.getFoodMartConnectionProperties(); properties.put( RolapConnectionProperties.CatalogContent.name(), schema); return properties; } public String getDefaultCubeName() { return "Sales_DimWithoutAll"; } }; // the default member of the Gender dimension is the first member testContext.assertExprReturns("[Gender].CurrentMember.Name", "F"); testContext.assertExprReturns("[Product].CurrentMember.Name", "Drink"); // There is no all member. testContext.assertExprThrows( "([Gender].[All Gender], [Measures].[Unit Sales])", "MDX object '[Gender].[All Gender]' not found in cube 'Sales_DimWithoutAll'"); testContext.assertExprThrows( "([Gender].[All Genders], [Measures].[Unit Sales])", "MDX object '[Gender].[All Genders]' not found in cube 'Sales_DimWithoutAll'"); // evaluated in the default context: [Product].[Drink], [Gender].[F] testContext.assertExprReturns("[Measures].[Unit Sales]", "12,202"); // evaluated in the same context: [Product].[Drink], [Gender].[F] testContext.assertExprReturns( "([Gender].[F], [Measures].[Unit Sales])", "12,202"); // evaluated at in the context: [Product].[Drink], [Gender].[M] testContext.assertExprReturns( "([Gender].[M], [Measures].[Unit Sales])", "12,395"); // evaluated in the context: // [Product].[Food].[Canned Foods], [Gender].[F] testContext.assertExprReturns( "([Product].[Food].[Canned Foods], [Measures].[Unit Sales])", "9,407"); testContext.assertExprReturns( "([Product].[Food].[Dairy], [Measures].[Unit Sales])", "6,513"); testContext.assertExprReturns( "([Product].[Drink].[Dairy], [Measures].[Unit Sales])", "1,987"); } /** * If an axis expression is a member, implicitly convert it to a set. */ public void testMemberOnAxis() { assertQueryReturns( "select [Measures].[Sales Count] on 0, non empty [Store].[Store State].members on 1 from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Sales Count]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[OR]}\n" + "{[Store].[All Stores].[USA].[WA]}\n" + "Row #0: 24,442\n" + "Row #1: 21,611\n" + "Row #2: 40,784\n"); } public void testScalarOnAxisFails() { assertQueryThrows( "select [Measures].[Sales Count] + 1 on 0, non empty [Store].[Store State].members on 1 from [Sales]", "Axis 'COLUMNS' expression is not a set"); } /** * It is illegal for a query to have the same dimension on more than * one axis. */ public void testSameDimOnTwoAxesFails() { assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Measures].[Store Sales]} on rows\n" + "from [Sales]", "Hierarchy '[Measures]' appears in more than one independent axis"); // as part of a crossjoin assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin({[Product].members}," + " {[Measures].[Store Sales]}) on rows\n" + "from [Sales]", "Hierarchy '[Measures]' appears in more than one independent axis"); // as part of a tuple assertQueryThrows( "select CrossJoin(\n" + " {[Product].children},\n" + " {[Measures].[Unit Sales]}) on columns,\n" + " {([Product],\n" + " [Store].CurrentMember)} on rows\n" + "from [Sales]", "Hierarchy '[Product]' appears in more than one independent axis"); // clash between columns and slicer assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Store].Members} on rows\n" + "from [Sales]\n" + "where ([Time].[1997].[Q1], [Measures].[Store Sales])", "Hierarchy '[Measures]' appears in more than one independent axis"); // within aggregate is OK executeQuery( "with member [Measures].[West Coast Total] as " + " ' Aggregate({[Store].[USA].[CA], [Store].[USA].[OR], [Store].[USA].[WA]}) ' \n" + "select " + " {[Measures].[Store Sales], \n" + " [Measures].[Unit Sales]} on Columns,\n" + " CrossJoin(\n" + " {[Product].children},\n" + " {[Store].children}) on Rows\n" + "from [Sales]"); } public void _testSetArgToTupleFails() { assertQueryThrows( "select CrossJoin(\n" + " {[Product].children},\n" + " {[Measures].[Unit Sales]}) on columns,\n" + " {([Product],\n" + " [Store].members)} on rows\n" + "from [Sales]", "Dimension '[Product]' appears in more than one independent axis"); } public void _badArgsToTupleFails() { // clash within slicer assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Store].Members} on rows\n" + "from [Sales]\n" + "where ([Time].[1997].[Q1], [Product], [Time].[1997].[Q2])", "Dimension '[Time]' more than once in same tuple"); // ditto assertQueryThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin({[Time].[1997].[Q1],\n" + " {[Product]},\n" + " {[Time].[1997].[Q2]}) on rows\n" + "from [Sales]", "Dimension '[Time]' more than once in same tuple"); } public void testNullMember() { if (isDefaultNullMemberRepresentation()) { assertQueryReturns( "SELECT \n" + "{[Measures].[Store Cost]} ON columns, \n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]} ON rows \n" + "FROM [Sales] \n" + "WHERE [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Store Cost]}\n" + "Axis #2:\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" + "Row #0: 33,307.69\n"); } } public void testNullMemberWithOneNonNull() { if (isDefaultNullMemberRepresentation()) { assertQueryReturns( "SELECT \n" + "{[Measures].[Store Cost]} ON columns, \n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]," + "[Store Size in SQFT].[ALL Store Size in SQFTs].[39696]} ON rows \n" + "FROM [Sales] \n" + "WHERE [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Store Cost]}\n" + "Axis #2:\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[39696]}\n" + "Row #0: 33,307.69\n" + "Row #1: 21,121.96\n"); } } /** * Tests whether the agg mgr behaves correctly if a cell request causes * a column to be constrained multiple times. This happens if two levels * map to the same column via the same join-path. If the constraints are * inconsistent, no data will be returned. */ public void testMultipleConstraintsOnSameColumn() { final String cubeName = "Sales_withCities"; TestContext testContext = TestContext.create( null, "<Cube name=\"" + cubeName + "\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Dimension name=\"Cities\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Cities\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/> \n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Customers\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Customers\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Country\" column=\"country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"State Province\" column=\"state_province\" uniqueMembers=\"true\"/>\n" + " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Name\" column=\"fullname\" uniqueMembers=\"true\">\n" + " <Property name=\"Gender\" column=\"gender\"/>\n" + " <Property name=\"Marital Status\" column=\"marital_status\"/>\n" + " <Property name=\"Education\" column=\"education\"/>\n" + " <Property name=\"Yearly Income\" column=\"yearly_income\"/>\n" + " </Level>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Gender\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Sales\" column=\"store_sales\" aggregator=\"sum\"\n" + " formatString=\"#,###.00\"/>\n" + "</Cube>", null, null, null, null); testContext.assertQueryReturns( "select {\n" + " [Customers].[All Customers].[USA],\n" + " [Customers].[All Customers].[USA].[OR],\n" + " [Customers].[All Customers].[USA].[CA],\n" + " [Customers].[All Customers].[USA].[CA].[Altadena],\n" + " [Customers].[All Customers].[USA].[CA].[Burbank],\n" + " [Customers].[All Customers].[USA].[CA].[Burbank].[Alma Son]} ON COLUMNS\n" + "from [" + cubeName + "] \n" + "where ([Cities].[All Cities].[Burbank], [Measures].[Store Sales])", "Axis #0:\n" + "{[Cities].[All Cities].[Burbank], [Measures].[Store Sales]}\n" + "Axis #1:\n" + "{[Customers].[All Customers].[USA]}\n" + "{[Customers].[All Customers].[USA].[OR]}\n" + "{[Customers].[All Customers].[USA].[CA]}\n" + "{[Customers].[All Customers].[USA].[CA].[Altadena]}\n" + "{[Customers].[All Customers].[USA].[CA].[Burbank]}\n" + "{[Customers].[All Customers].[USA].[CA].[Burbank].[Alma Son]}\n" + "Row #0: 6,577.33\n" + "Row #0: \n" + "Row #0: 6,577.33\n" + "Row #0: \n" + "Row #0: 6,577.33\n" + "Row #0: 36.50\n"); } public void testOverrideDimension() { assertQueryReturns( "with member [Gender].[test] as '\n" + " aggregate(\n" + " filter (crossjoin( [Gender].[Gender].members, [Time].[Time].members), \n" + " [time].[Time].CurrentMember = [Time].[1997].[Q1] AND\n" + "[measures].[unit sales] > 50) )\n" + "'\n" + "select \n" + " { [time].[year].members } on 0,\n" + " { [gender].[test] }\n" + " on 1 \n" + "from [sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997]}\n" + "{[Time].[1998]}\n" + "Axis #2:\n" + "{[Gender].[test]}\n" + "Row #0: 66,291\n" + "Row #0: 66,291\n"); } public void testBadMeasure1() { TestContext testContext = TestContext.create( null, "<Cube name=\"SalesWithBadMeasure\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Measure name=\"Bad Measure\" aggregator=\"sum\"\n" + " formatString=\"Standard\"/>\n" + "</Cube>", null, null, null, null); Throwable throwable = null; try { testContext.assertSimpleQuery(); } catch (Throwable e) { throwable = e; } // neither a source column or source expression specified TestContext.checkThrowable( throwable, "must contain either a source column or a source expression, but not both"); } public void testBadMeasure2() { TestContext testContext = TestContext.create( null, "<Cube name=\"SalesWithBadMeasure2\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Measure name=\"Bad Measure\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\">\n" + " <MeasureExpression>\n" + " <SQL dialect=\"generic\">\n" + " unit_sales\n" + " </SQL>\n" + " </MeasureExpression>\n" + " </Measure>\n" + "</Cube>", null, null, null, null); Throwable throwable = null; try { testContext.assertSimpleQuery(); } catch (Throwable e) { throwable = e; } // both a source column and source expression specified TestContext.checkThrowable( throwable, "must contain either a source column or a source expression, but not both"); } public void testInvalidMembersInQuery() { String mdx = "select {[Measures].[Unit Sales]} on columns,\n" + " {[Time].[1997].[Q1], [Time].[1997].[QTOO]} on rows\n" + "from [Sales]"; String mdx2 = "select {[Measures].[Unit Sales]} on columns,\n" + "nonemptycrossjoin(\n" + "{[Time].[1997].[Q1], [Time].[1997].[QTOO]},\n" + "[Customers].[All Customers].[USA].children) on rows\n" + "from [Sales]"; String mdx3 = "select {[Measures].[Unit Sales]} on columns\n" + "from [Sales]\n" + "where ([Time].[1997].[QTOO])"; // By default, reference to invalid member should cause // query failure. assertQueryThrows( mdx, "MDX object '[Time].[1997].[QTOO]' not found in cube 'Sales'"); assertQueryThrows( mdx3, "MDX object '[Time].[1997].[QTOO]' not found in cube 'Sales'"); // Now set property boolean savedInvalidProp = props.IgnoreInvalidMembersDuringQuery.get(); String savedAlertProp = props.AlertNativeEvaluationUnsupported.get(); try { props.IgnoreInvalidMembersDuringQuery.set(true); assertQueryReturns( mdx, "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1]}\n" + "Row #0: 66,291\n"); // Illegal member in slicer assertQueryReturns( mdx3, "Axis #0:\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Row #0: \n"); // Verify that invalid members in query do NOT prevent // usage of native NECJ (LER-5165). props.AlertNativeEvaluationUnsupported.set("ERROR"); assertQueryReturns( mdx2, "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Time].[1997].[Q1], [Customers].[All Customers].[USA].[CA]}\n" + "{[Time].[1997].[Q1], [Customers].[All Customers].[USA].[OR]}\n" + "{[Time].[1997].[Q1], [Customers].[All Customers].[USA].[WA]}\n" + "Row #0: 16,890\n" + "Row #1: 19,287\n" + "Row #2: 30,114\n"); } finally { props.IgnoreInvalidMembersDuringQuery.set(savedInvalidProp); props.AlertNativeEvaluationUnsupported.set(savedAlertProp); } } public void testMemberOrdinalCaching() { boolean saved = props.CompareSiblingsByOrderKey.get(); props.CompareSiblingsByOrderKey.set(true); Connection conn = null; try { // Use a fresh connection to make sure bad member ordinals haven't // been assigned by previous tests. conn = getTestContext().getFoodMartConnection(false); TestContext context = getTestContext(conn); tryMemberOrdinalCaching(context); } finally { props.CompareSiblingsByOrderKey.set(saved); if (conn != null) { conn.close(); } } } private void tryMemberOrdinalCaching(TestContext context) { // NOTE jvs 20-Feb-2007: If you change the calculated measure // definition below from zero to // [Customers].[Name].currentmember.Properties(\"MEMBER_ORDINAL\"), you // can see that the absolute ordinals returned are incorrect due to bug // 1660383 (http://tinyurl.com/3xb56f). For now, this test just // verifies that the member sorting is correct when using relative // order key rather than absolute ordinal value. If absolute ordinals // get fixed, replace zero with the MEMBER_ORDINAL property. context.assertQueryReturns( "with member [Measures].[o] as 0\n" + "set necj as nonemptycrossjoin(\n" + "[Store].[Store State].members, [Customers].[Name].members)\n" + "select tail(necj,5) on rows,\n" + "{[Measures].[o]} on columns\n" + "from [Sales]\n", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[o]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[Tracy Meyer]}\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[Vanessa Thompson]}\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[Velma Lykes]}\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[William Battaglia]}\n" + "{[Store].[All Stores].[USA].[WA], [Customers].[All Customers].[USA].[WA].[Yakima].[Wilma Fink]}\n" + "Row #0: 0\n" + "Row #1: 0\n" + "Row #2: 0\n" + "Row #3: 0\n" + "Row #4: 0\n"); // The query above primed the cache with bad absolute ordinals; // verify that this doesn't interfere with subsequent queries. context.assertQueryReturns( "with member [Measures].[o] as 0\n" + "select tail([Customers].[Name].members, 5)\n" + "on rows,\n" + "{[Measures].[o]} on columns\n" + "from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[o]}\n" + "Axis #2:\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[Tracy Meyer]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[Vanessa Thompson]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[Velma Lykes]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[William Battaglia]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima].[Wilma Fink]}\n" + "Row #0: 0\n" + "Row #1: 0\n" + "Row #2: 0\n" + "Row #3: 0\n" + "Row #4: 0\n"); } public void testCancel() { // the cancel is issued after 2 seconds so the test query needs to // run for at least that long; it will because the query references // a Udf that has a 1 ms sleep in it; and there are enough rows // in the result that the Udf should execute > 2000 times String query = "WITH \n" + " MEMBER [Measures].[Sleepy] \n" + " AS 'SleepUdf([Measures].[Unit Sales])' \n" + "SELECT {[Measures].[Sleepy]} ON COLUMNS,\n" + " {[Product].members} ON ROWS\n" + "FROM [Sales]"; executeAndCancel(query, 2000); } private void executeAndCancel(String queryString, int waitMillis) { final TestContext tc = TestContext.create( null, null, null, null, "<UserDefinedFunction name=\"SleepUdf\" className=\"" + SleepUdf.class.getName() + "\"/>", null); Connection connection = tc.getConnection(); final Query query = connection.parseQuery(queryString); if (waitMillis == 0) { // cancel immediately query.cancel(); } else { // Schedule timer to cancel after waitMillis Timer timer = new Timer(true); TimerTask task = new TimerTask() { public void run() { Thread thread = Thread.currentThread(); thread.setName("CancelThread"); try { query.cancel(); } catch (Exception ex) { Assert.fail( "Cancel request failed: " + ex.getMessage()); } } }; timer.schedule(task, waitMillis); } Throwable throwable = null; try { connection.execute(query); } catch (Throwable ex) { throwable = ex; } TestContext.checkThrowable(throwable, "canceled"); } public void testQueryTimeout() { // timeout is issued after 2 seconds so the test query needs to // run for at least that long; it will because the query references // a Udf that has a 1 ms sleep in it; and there are enough rows // in the result that the Udf should execute > 2000 times final TestContext tc = TestContext.create( null, null, null, null, "<UserDefinedFunction name=\"SleepUdf\" className=\"" + SleepUdf.class.getName() + "\"/>", null); String query = "WITH\n" + " MEMBER [Measures].[Sleepy]\n" + " AS 'SleepUdf([Measures].[Unit Sales])'\n" + "SELECT {[Measures].[Sleepy]} ON COLUMNS,\n" + " {[Product].members} ON ROWS\n" + "FROM [Sales]"; Throwable throwable = null; int origTimeout = props.QueryTimeout.get(); try { props.QueryTimeout.set(2); tc.executeQuery(query); } catch (Throwable ex) { throwable = ex; } finally { // reset the timeout back to the original value props.QueryTimeout.set(origTimeout); } TestContext.checkThrowable( throwable, "Query timeout of 2 seconds reached"); } public void testFormatInheritance() { assertQueryReturns( "with member measures.foo as 'measures.bar' " + "member measures.bar as " + "'measures.profit' select {measures.foo} on 0 from sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[foo]}\n" + "Row #0: $339,610.90\n"); } public void testFormatInheritanceWithIIF() { assertQueryReturns( "with member measures.foo as 'measures.bar' " + "member measures.bar as " + "'iif(not isempty(measures.profit),measures.profit,null)' " + "select from sales where measures.foo", "Axis #0:\n" + "{[Measures].[foo]}\n" + "$339,610.90"); } /** * For a calulated member picks up the format of first member that has a * format. In this particular case foo will use profit's format, i.e * neither [unit sales] nor [customer count] format is used. */ public void testFormatInheritanceWorksWithFirstFormatItFinds() { assertQueryReturns( "with member measures.foo as 'measures.bar' " + "member measures.bar as " + "'iif(measures.profit>3000,measures.[unit sales],measures.[Customer Count])' " + "select {[Store].[All Stores].[USA].[WA].children} on 0 " + "from sales where measures.foo", "Axis #0:\n" + "{[Measures].[foo]}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima]}\n" + "Row #0: $190.00\n" + "Row #0: $24,576.00\n" + "Row #0: $25,011.00\n" + "Row #0: $23,591.00\n" + "Row #0: $35,257.00\n" + "Row #0: $96.00\n" + "Row #0: $11,491.00\n"); } /** * This tests a fix for bug #1603653 */ public void testAvgCastProblem() { assertQueryReturns( "with member measures.bar as " + "'iif(measures.profit>3000,min([Education Level].[Education Level].Members),min([Education Level].[Education Level].Members))' " + "select {[Store].[All Stores].[USA].[WA].children} on 0 " + "from sales where measures.bar", "Axis #0:\n" + "{[Measures].[bar]}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima]}\n" + "Row #0: $95.00\n" + "Row #0: $1,835.00\n" + "Row #0: $1,277.00\n" + "Row #0: $1,434.00\n" + "Row #0: $1,084.00\n" + "Row #0: $129.00\n" + "Row #0: $958.00\n"); } /** * Test format inheritance to pickup format from second measure when the * first does not have one. */ public void testFormatInheritanceUseSecondIfFirstHasNoFormat() { assertQueryReturns( "with member measures.foo as 'measures.bar+measures.blah'" + " member measures.bar as '10'" + " member measures.blah as '20',format_string='$##.###.00' " + "select from sales where measures.foo", "Axis #0:\n" + "{[Measures].[foo]}\n" + "$30.00"); } /** * Tests format inheritance with complex expression to assert that the * format of the first member that has a valid format is used. */ public void testFormatInheritanceUseFirstValid() { assertQueryReturns( "with member measures.foo as '13+31*measures.[Unit Sales]/" + "iif(measures.profit>0,measures.profit,measures.[Customer Count])'" + " select {[Store].[All Stores].[USA].[CA].children} on 0 " + "from sales where measures.foo", "Axis #0:\n" + "{[Measures].[foo]}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "Row #0: 13\n" + "Row #0: 37\n" + "Row #0: 37\n" + "Row #0: 37\n" + "Row #0: 38\n"); } public void testQueryIterationLimit() { // Query will need to iterate 4*3 times to compute aggregates, // so set iteration limit to 11 String queryString = "With Set [*NATIVE_CJ_SET] as " + "'NonEmptyCrossJoin([*BASE_MEMBERS_Dates], [*BASE_MEMBERS_Stores])' " + "Set [*BASE_MEMBERS_Dates] as '{[Time].[1997].[Q1], [Time].[1997].[Q2], [Time].[1997].[Q3], [Time].[1997].[Q4]}' " + "Set [*GENERATED_MEMBERS_Dates] as 'Generate([*NATIVE_CJ_SET], {[Time].[Time].CurrentMember})' " + "Set [*GENERATED_MEMBERS_Measures] as '{[Measures].[*SUMMARY_METRIC_0]}' " + "Set [*BASE_MEMBERS_Stores] as '{[Store].[USA].[CA], [Store].[USA].[WA], [Store].[USA].[OR]}' " + "Set [*GENERATED_MEMBERS_Stores] as 'Generate([*NATIVE_CJ_SET], {[Store].CurrentMember})' " + "Member [Time].[*SM_CTX_SEL] as 'Aggregate([*GENERATED_MEMBERS_Dates])' " + "Member [Measures].[*SUMMARY_METRIC_0] as '[Measures].[Unit Sales]/([Measures].[Unit Sales],[Time].[*SM_CTX_SEL])' " + "Member [Time].[*SUBTOTAL_MEMBER_SEL~SUM] as 'sum([*GENERATED_MEMBERS_Dates])' " + "Member [Store].[*SUBTOTAL_MEMBER_SEL~SUM] as 'sum([*GENERATED_MEMBERS_Stores])' " + "select crossjoin({[Time].[*SUBTOTAL_MEMBER_SEL~SUM]}, {[Store].[*SUBTOTAL_MEMBER_SEL~SUM]}) " + "on columns from [Sales]"; Throwable throwable = null; int origLimit = props.IterationLimit.get(); try { props.IterationLimit.set(11); Connection connection = getConnection(); Query query = connection.parseQuery(queryString); query.setResultStyle(ResultStyle.LIST); connection.execute(query); } catch (Throwable ex) { throwable = ex; } finally { // reset the timeout back to the original value props.IterationLimit.set(origLimit); } TestContext.checkThrowable( throwable, "Number of iterations exceeded limit of 11"); // make sure the query runs without the limit set executeQuery(queryString); } public void testGetCaptionUsingMemberDotCaption() { assertQueryReturns( "SELECT Filter(Store.allmembers, " + "[store].currentMember.caption = \"USA\") on 0 FROM SALES", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA]}\n" + "Row #0: 266,773\n"); } public void testGetCaptionUsingMemberDotPropertiesCaption() { assertQueryReturns( "SELECT Filter(Store.allmembers, " + "[store].currentMember.properties(\"caption\") = \"USA\") " + "on 0 FROM SALES", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA]}\n" + "Row #0: 266,773\n"); } public void testDefaultMeasureInCube() { TestContext testContext = TestContext.create( null, "<Cube name=\"DefaultMeasureTesting\" defaultMeasure=\"Supply Time\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Store\" source=\"Store\" " + "foreignKey=\"store_id\"/>\n" + " <DimensionUsage name=\"Store Type\" source=\"Store Type\" " + "foreignKey=\"store_id\"/>\n" + " <Measure name=\"Store Invoice\" column=\"store_invoice\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Supply Time\" column=\"supply_time\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" " + "aggregator=\"sum\"/>\n" + "</Cube>", null, null, null, null); String queryWithoutFilter = "select store.members on 0 from " + "DefaultMeasureTesting"; String queryWithDeflaultMeasureFilter = "select store.members on 0 " + "from DefaultMeasureTesting where [measures].[Supply Time]"; assertQueriesReturnSimilarResults( queryWithoutFilter, queryWithDeflaultMeasureFilter, testContext); } public void testDefaultMeasureInCubeForIncorrectMeasureName() { TestContext testContext = TestContext.create( null, "<Cube name=\"DefaultMeasureTesting\" defaultMeasure=\"Supply Time Error\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Store\" source=\"Store\" " + "foreignKey=\"store_id\"/>\n" + " <DimensionUsage name=\"Store Type\" source=\"Store Type\" " + "foreignKey=\"store_id\"/>\n" + " <Measure name=\"Store Invoice\" column=\"store_invoice\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Supply Time\" column=\"supply_time\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" " + "aggregator=\"sum\"/>\n" + "</Cube>", null, null, null, null); String queryWithoutFilter = "select store.members on 0 from " + "DefaultMeasureTesting"; String queryWithFirstMeasure = "select store.members on 0 " + "from DefaultMeasureTesting where [measures].[Store Invoice]"; assertQueriesReturnSimilarResults( queryWithoutFilter, queryWithFirstMeasure, testContext); } public void testDefaultMeasureInCubeForCaseSensitivity() { TestContext testContext = TestContext.create( null, "<Cube name=\"DefaultMeasureTesting\" defaultMeasure=\"SUPPLY TIME\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Store\" source=\"Store\" " + "foreignKey=\"store_id\"/>\n" + " <DimensionUsage name=\"Store Type\" source=\"Store Type\" " + "foreignKey=\"store_id\"/>\n" + " <Measure name=\"Store Invoice\" column=\"store_invoice\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Supply Time\" column=\"supply_time\" " + "aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" " + "aggregator=\"sum\"/>\n" + "</Cube>", null, null, null, null); String queryWithoutFilter = "select store.members on 0 from " + "DefaultMeasureTesting"; String queryWithFirstMeasure = "select store.members on 0 " + "from DefaultMeasureTesting where [measures].[Store Invoice]"; String queryWithDefaultMeasureFilter = "select store.members on 0 " + "from DefaultMeasureTesting where [measures].[Supply Time]"; if (props.CaseSensitive.get()) { assertQueriesReturnSimilarResults( queryWithoutFilter, queryWithFirstMeasure, testContext); } else { assertQueriesReturnSimilarResults( queryWithoutFilter, queryWithDefaultMeasureFilter, testContext); } } /** * This tests for bug #1706434, * the ability to convert numeric types to logical (boolean) types. */ public void testNumericToLogicalConversion() { assertQueryReturns( "select " + "{[Measures].[Unit Sales]} on columns, " + "Filter(Descendants(" + "[Product].[Food].[Baked Goods].[Bread]), " + "Count([Product].currentMember.children)) on Rows " + "from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Colony]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Fantastic]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Great]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Modell]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Bagels].[Sphinx]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Colony]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Fantastic]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Great]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Modell]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Muffins].[Sphinx]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Colony]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Fantastic]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Great]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Modell]}\n" + "{[Product].[All Products].[Food].[Baked Goods].[Bread].[Sliced Bread].[Sphinx]}\n" + "Row #0: 7,870\n" + "Row #1: 815\n" + "Row #2: 163\n" + "Row #3: 160\n" + "Row #4: 145\n" + "Row #5: 165\n" + "Row #6: 182\n" + "Row #7: 3,497\n" + "Row #8: 740\n" + "Row #9: 798\n" + "Row #10: 605\n" + "Row #11: 719\n" + "Row #12: 635\n" + "Row #13: 3,558\n" + "Row #14: 737\n" + "Row #15: 815\n" + "Row #16: 638\n" + "Row #17: 653\n" + "Row #18: 715\n"); } public void testRollupQuery() { assertQueryReturns( "SELECT {[Product].[Product Department].MEMBERS} ON AXIS(0),\n" + "{{[Gender].[Gender].MEMBERS}, {[Gender].[All Gender]}} ON AXIS(1)\n" + "FROM [Sales 2] WHERE {[Measures].[Unit Sales]}", "Axis #0:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #1:\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "{[Product].[All Products].[Food].[Baked Goods]}\n" + "{[Product].[All Products].[Food].[Baking Goods]}\n" + "{[Product].[All Products].[Food].[Breakfast Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "{[Product].[All Products].[Food].[Canned Products]}\n" + "{[Product].[All Products].[Food].[Dairy]}\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Eggs]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Meat]}\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Seafood]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Snacks]}\n" + "{[Product].[All Products].[Food].[Starchy Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Carousel]}\n" + "{[Product].[All Products].[Non-Consumable].[Checkout]}\n" + "{[Product].[All Products].[Non-Consumable].[Health and Hygiene]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Non-Consumable].[Periodicals]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[All Gender]}\n" + "Row #0: 3,439\n" + "Row #0: 6,776\n" + "Row #0: 1,987\n" + "Row #0: 3,771\n" + "Row #0: 9,841\n" + "Row #0: 1,821\n" + "Row #0: 9,407\n" + "Row #0: 867\n" + "Row #0: 6,513\n" + "Row #0: 5,990\n" + "Row #0: 2,001\n" + "Row #0: 13,011\n" + "Row #0: 841\n" + "Row #0: 18,713\n" + "Row #0: 947\n" + "Row #0: 14,936\n" + "Row #0: 3,459\n" + "Row #0: 2,696\n" + "Row #0: 368\n" + "Row #0: 887\n" + "Row #0: 7,841\n" + "Row #0: 13,278\n" + "Row #0: 2,168\n" + "Row #1: 3,399\n" + "Row #1: 6,797\n" + "Row #1: 2,199\n" + "Row #1: 4,099\n" + "Row #1: 10,404\n" + "Row #1: 1,496\n" + "Row #1: 9,619\n" + "Row #1: 945\n" + "Row #1: 6,372\n" + "Row #1: 6,047\n" + "Row #1: 2,131\n" + "Row #1: 13,644\n" + "Row #1: 873\n" + "Row #1: 19,079\n" + "Row #1: 817\n" + "Row #1: 15,609\n" + "Row #1: 3,425\n" + "Row #1: 2,566\n" + "Row #1: 473\n" + "Row #1: 892\n" + "Row #1: 8,443\n" + "Row #1: 13,760\n" + "Row #1: 2,126\n" + "Row #2: 6,838\n" + "Row #2: 13,573\n" + "Row #2: 4,186\n" + "Row #2: 7,870\n" + "Row #2: 20,245\n" + "Row #2: 3,317\n" + "Row #2: 19,026\n" + "Row #2: 1,812\n" + "Row #2: 12,885\n" + "Row #2: 12,037\n" + "Row #2: 4,132\n" + "Row #2: 26,655\n" + "Row #2: 1,714\n" + "Row #2: 37,792\n" + "Row #2: 1,764\n" + "Row #2: 30,545\n" + "Row #2: 6,884\n" + "Row #2: 5,262\n" + "Row #2: 841\n" + "Row #2: 1,779\n" + "Row #2: 16,284\n" + "Row #2: 27,038\n" + "Row #2: 4,294\n"); } /** * Tests for bug #1630754. In Mondrian 2.2.2 the SqlTupleReader.readTuples * method would create a SQL having an in-clause with more that 1000 * entities under some circumstances. This exceeded the limit for Oracle * resulting in an ORA-01795 error. */ public void testBug1630754() { // In order to reproduce this bug a dimension with 2 levels with more // than 1000 member each was necessary. The customer_id column has more // than 1000 distinct members so it was used for this test. final TestContext testContext = TestContext.createSubstitutingCube( "Sales", " <Dimension name=\"Customer_2\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" " + "allMemberName=\"All Customers\" " + "primaryKey=\"customer_id\" " + " >\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Name1\" column=\"customer_id\" uniqueMembers=\"true\"/>" + " <Level name=\"Name2\" column=\"customer_id\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>"); Result result = testContext.executeQuery( "WITH SET [#DataSet#] AS " + " 'NonEmptyCrossjoin({Descendants([Customer_2].[All Customers], 2)}, " + " {[Product].[All Products]})' " + "SELECT {[Measures].[Unit Sales], [Measures].[Store Sales]} on columns, " + "Hierarchize({[#DataSet#]}) on rows FROM [Sales]"); final int rowCount = result.getAxes()[1].getPositions().size(); assertEquals(5581, rowCount); } /** * Tests a query which uses filter and crossjoin. This query caused * problems when the retrowoven version of mondrian was used in jdk1.5, * specifically a {@link ClassCastException} trying to cast a {@link List} * to a {@link Iterable}. */ public void testNonEmptyCrossjoinFilter() { String desiredResult = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Product].[All Products], [Time].[1997].[Q2].[5]}\n" + "Row #0: 21,081\n"; assertQueryReturns( "select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS,\n" + "NON EMPTY Crossjoin(" + " {Product.[All Products]},\n" + " Filter(" + " Descendants(Time.[Time], [Time].[Month]), " + " Time.[Time].CurrentMember.Name = '5')) ON ROWS\n" + "from [Sales] ", desiredResult); assertQueryReturns( "select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS,\n" + "NON EMPTY Filter(" + " Crossjoin(" + " {Product.[All Products]},\n" + " Descendants(Time.[Time], [Time].[Month]))," + " Time.[Time].CurrentMember.Name = '5') ON ROWS\n" + "from [Sales] ", desiredResult); } public void testDuplicateAxisFails() { assertQueryThrows( "select [Gender].Members on columns," + " [Measures].Members on columns " + "from [Sales]", "Duplicate axis name 'COLUMNS'."); } public void testInvalidAxisFails() { assertQueryThrows( "select [Gender].Members on 0," + " [Measures].Members on 10 " + "from [Sales]", "Axis numbers specified in a query must be sequentially specified," + " and cannot contain gaps. Axis 1 (ROWS) is missing."); assertQueryThrows( "select [Gender].Members on columns," + " [Measures].Members on foobar\n" + "from [Sales]", "Syntax error at line 1, column 59, token 'foobar'"); assertQueryThrows( "select [Gender].Members on columns," + " [Measures].Members on slicer\n" + "from [Sales]", "Syntax error at line 1, column 59, token 'slicer'"); assertQueryThrows( "select [Gender].Members on columns," + " [Measures].Members on filter\n" + "from [Sales]", "Syntax error at line 1, column 59, token 'filter'"); } /** * Tests various ways to sum the properties of the descendants of a member, * inspired by forum post * <a href="http://forums.pentaho.org/showthread.php?p=177135">summing * properties</a>. */ public void testSummingProperties() { final String expected = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 131,558\n" + "Row #0: 36,759\n" + "Row #1: 135,215\n" + "Row #1: 37,989\n"; assertQueryReturns( "with member [Measures].[Sum Sqft] as '" + "sum(" + " Descendants([Store].CurrentMember, [Store].Levels(5))," + " [Store].CurrentMember.Properties(\"Store Sqft\")) '\n" + "select {[Store].[USA], [Store].[USA].[CA]} on 0,\n" + " [Gender].Children on 1\n" + "from [Sales]", expected); // same query, except get level by name not ordinal, should give same // result assertQueryReturns( "with member [Measures].[Sum Sqft] as '" + "sum(" + " Descendants([Store].CurrentMember, [Store].Levels(\"Store Name\"))," + " [Store].CurrentMember.Properties(\"Store Sqft\")) '\n" + "select {[Store].[USA], [Store].[USA].[CA]} on 0,\n" + " [Gender].Children on 1\n" + "from [Sales]", expected); // same query, except level is hard-coded; same result again assertQueryReturns( "with member [Measures].[Sum Sqft] as '" + "sum(" + " Descendants([Store].CurrentMember, [Store].[Store Name])," + " [Store].CurrentMember.Properties(\"Store Sqft\")) '\n" + "select {[Store].[USA], [Store].[USA].[CA]} on 0,\n" + " [Gender].Children on 1\n" + "from [Sales]", expected); // same query, except using the level-less form of the DESCENDANTS // function; same result again assertQueryReturns( "with member [Measures].[Sum Sqft] as '" + "sum(" + " Descendants([Store].CurrentMember, , LEAVES)," + " [Store].CurrentMember.Properties(\"Store Sqft\")) '\n" + "select {[Store].[USA], [Store].[USA].[CA]} on 0,\n" + " [Gender].Children on 1\n" + "from [Sales]", expected); } public void testIifWithTupleFirstAndMemberNextWithMeasure() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(1=1, ([Gender].[All Gender],measures.[unit sales])," + "([Gender].[All Gender]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 266,773\n"); } public void testIifWithMemberFirstAndTupleNextWithMeasure() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(1=1, ([Gender].[All Gender])," + "([Gender].[All Gender],measures.[unit sales]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 266,773\n"); } public void testIifWithMemberFirstAndTupleNextWithoutMeasure() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(1=1, ([Gender].[All Gender])," + "([Gender].[All Gender],[Time].[1997]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 266,773\n"); } public void testIifWithTupleFirstAndMemberNextWithoutMeasure() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(1=1, " + "([Store].[All Stores].[USA], [Gender].[All Gender]), " + "([Gender].[All Gender]))', " + "SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{([Gender].agg)} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[agg]}\n" + "Row #0: 266,773\n"); } public void testIifWithTuplesOfUnequalSizes() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(Measures.currentMember is [Measures].[Unit Sales], " + "([Store].[All Stores],[Gender].[All Gender],measures.[unit sales])," + "([Store].[All Stores],[Gender].[All Gender]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 266,773\n"); } public void testIifWithTuplesOfUnequalSizesAndOrder() { assertQueryReturns( "WITH\n" + "MEMBER [Gender].agg " + "AS 'IIF(Measures.currentMember is [Measures].[Unit Sales], " + "([Store].[All Stores],[Gender].[M],measures.[unit sales])," + "([Gender].[M],[Store].[All Stores]))', SOLVE_ORDER = 4 " + "SELECT {[Measures].[unit sales]} ON 0, " + "{{[Gender].[Gender].MEMBERS},{([Gender].agg)}} on 1 FROM sales", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "{[Gender].[agg]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n" + "Row #2: 135,215\n"); } public void testEmptyAggregationListDueToFilterDoesNotThrowException() { boolean ignoreMeasureForNonJoiningDimension = props.IgnoreMeasureForNonJoiningDimension.get(); props.IgnoreMeasureForNonJoiningDimension.set(true); try { assertQueryReturns( "WITH \n" + "MEMBER [GENDER].[AGG] " + "AS 'AGGREGATE(FILTER([S1], (NOT ISEMPTY([MEASURES].[STORE SALES]))))' " + "SET [S1] " + "AS 'CROSSJOIN({[GENDER].[GENDER].MEMBERS},{[STORE].[CANADA].CHILDREN})' " + "SELECT\n" + "{[MEASURES].[STORE SALES]} ON COLUMNS,\n" + "{[GENDER].[AGG]} ON ROWS\n" + "FROM [WAREHOUSE AND SALES]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Gender].[AGG]}\n" + "Row #0: \n"); } finally { props.IgnoreMeasureForNonJoiningDimension.set( ignoreMeasureForNonJoiningDimension); } } /** * Testcase for Pentaho bug * <a href="http://jira.pentaho.org/browse/BISERVER-1323">BISERVER-1323</a>, * empty SQL query generated when crossjoining more than two sets each * containing just the 'all' member. */ public void testEmptySqlBug() { final String expectedResult = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores], [Product].[All Products], [Customers].[All Customers]}\n" + "Row #0: 266,773\n"; assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin({[Store].[All Stores]}" + ", Crossjoin({[Product].[All Products]}, {[Customers].[All Customers]})) ON ROWS " + "from [Sales]", expectedResult); // without NON EMPTY assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + " Crossjoin({[Store].[All Stores]}" + ", Crossjoin({[Product].[All Products]}, {[Customers].[All Customers]})) ON ROWS " + "from [Sales]", expectedResult); // using * operator assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores] " + " * [Product].[All Products]" + " * [Customers].[All Customers] ON ROWS " + "from [Sales]", expectedResult); // combining tuple assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores] " + " * {([Product].[All Products]," + " [Customers].[All Customers])} ON ROWS " + "from [Sales]", expectedResult); // combining two members with tuple final String expectedResult4 = "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "Axis #2:\n" + "{[Store].[All Stores], [Product].[All Products], [Customers].[All Customers], [Gender].[All Gender]}\n" + "Row #0: 266,773\n"; assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores] " + " * [Product].[All Products]" + " * {([Customers].[All Customers], [Gender].[All Gender])} ON ROWS " + "from [Sales]", expectedResult4); assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores] " + " * {([Product].[All Products], [Customers].[All Customers])}" + " * [Gender].[All Gender] ON ROWS " + "from [Sales]", expectedResult4); assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY {([Store].[All Stores], [Product].[All Products])}" + " * [Customers].[All Customers]" + " * [Gender].[All Gender] ON ROWS " + "from [Sales]", expectedResult4); } /** * Tests bug <a href="http://jira.pentaho.com/browse/MONDRIAN-7">MONDRIAN-7, * "Heterogeneous axis gives wrong results"</a>. The bug is a misnomer; * heterogeneous axes should give an error. */ public void testHeterogeneousAxis() { // SSAS2005 gives error: // Query (1, 8) Two sets specified in the function have different // dimensionality. assertQueryThrows( "select {[Measures].[Unit Sales], [Gender].Members} on 0,\n" + " [Store].[USA].Children on 1\n" + "from [Sales]", "All arguments to function '{}' must have same hierarchy."); assertQueryThrows( "select {[Marital Status].Members, [Gender].Members} on 0,\n" + " [Store].[USA].Children on 1\n" + "from [Sales]", "All arguments to function '{}' must have same hierarchy."); } /** * Tests hierarchies of the same dimension on different axes. */ public void testHierarchiesOfSameDimensionOnDifferentAxes() { if (!MondrianProperties.instance().SsasCompatibleNaming.get()) { return; } assertQueryReturns( "select [Time].[Year].Members on columns,\n" + "[Time].[Weekly].[1997].[6].Children on rows\n" + "from [Sales]", "Axis #0:\n" + "{}\n" + "Axis #1:\n" + "{[Time].[1997]}\n" + "{[Time].[1998]}\n" + "Axis #2:\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[1]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[26]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[27]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[28]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[29]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[30]}\n" + "{[Time].[Weekly].[All Weeklys].[1997].[6].[31]}\n" + "Row #0: 404\n" + "Row #0: \n" + "Row #1: 593\n" + "Row #1: \n" + "Row #2: 422\n" + "Row #2: \n" + "Row #3: 382\n" + "Row #3: \n" + "Row #4: 731\n" + "Row #4: \n" + "Row #5: \n" + "Row #5: \n" + "Row #6: \n" + "Row #6: \n"); } /** * A simple user-defined function which adds one to its argument, but * sleeps 1 ms before doing so. */ public static class SleepUdf implements UserDefinedFunction { public String getName() { return "SleepUdf"; } public String getDescription() { return "Returns its argument plus one but sleeps 1 ms first"; } public Syntax getSyntax() { return Syntax.Function; } public Type getReturnType(Type[] parameterTypes) { return new NumericType(); } public Type[] getParameterTypes() { return new Type[] {new NumericType()}; } public Object execute(Evaluator evaluator, Argument[] arguments) { final Object argValue = arguments[0].evaluateScalar(evaluator); if (argValue instanceof Number) { try { Thread.sleep(1); } catch (Exception ex) { return null; } return ((Number) argValue).doubleValue() + 1; } else { // Argument might be a RuntimeException indicating that // the cache does not yet have the required cell value. The // function will be called again when the cache is loaded. return null; } } public String[] getReservedWords() { return null; } } /** * This unit test would cause connection leaks without a fix for MONDRIAN-571. * It would be better if there was a way to verify that no leaks occurred in * the data source. */ public void testHighCardSqlTupleReaderLeakingConnections() { assertQueryReturns( "WITH MEMBER [Measures].[NegativeSales] AS '- [Measures].[Store Sales]' " + "MEMBER [Product].[SameName] AS 'Aggregate(Filter(" + "[Product].[Product Name].members,([Measures].[Store Sales] > 0)))' " + "MEMBER [Measures].[SameName] AS " + "'([Measures].[Store Sales],[Product].[SameName])' " + "select {[Measures].[Store Sales], [Measures].[NegativeSales], " + "[Measures].[SameName]} ON COLUMNS, " + "[Store].[Store Country].members ON ROWS " + "from [Sales] " + "where [Time].[1997]", "Axis #0:\n" + "{[Time].[1997]}\n" + "Axis #1:\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[NegativeSales]}\n" + "{[Measures].[SameName]}\n" + "Axis #2:\n" + "{[Store].[All Stores].[Canada]}\n" + "{[Store].[All Stores].[Mexico]}\n" + "{[Store].[All Stores].[USA]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #2: 565,238.13\n" + "Row #2: -565,238.13\n" + "Row #2: 565,238.13\n"); } } // End BasicQueryTest.java
MONDRIAN: Fix line length; UTIL: Enforce line length 80 for all files, even if not --strict. [git-p4: depot-paths = "//open/mondrian/": change = 12998]
testsrc/main/mondrian/test/BasicQueryTest.java
MONDRIAN: Fix line length; UTIL: Enforce line length 80 for all files, even if not --strict.
Java
agpl-3.0
05e4914d6a23651cbeacb36a0b44e39ba04c6d7e
0
axiomsoftware/axiom-stack,axiomsoftware/axiom-stack,axiomsoftware/axiom-stack,axiomsoftware/axiom-stack,axiomsoftware/axiom-stack,axiomsoftware/axiom-stack
/* * Axiom Stack Web Application Framework * Copyright (C) 2008 Axiom Software Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Axiom Software Inc., 11480 Commerce Park Drive, Third Floor, Reston, VA 20191 USA * email: [email protected] */ package axiom.scripting.rhino; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Stack; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.RangeQuery; import org.apache.lucene.search.SimpleQueryFilter; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldDocs; import org.mozilla.javascript.Context; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Undefined; import axiom.framework.ErrorReporter; import axiom.framework.core.Application; import axiom.framework.core.Prototype; import axiom.framework.core.RequestEvaluator; import axiom.framework.core.TypeManager; import axiom.objectmodel.INode; import axiom.objectmodel.IProperty; import axiom.objectmodel.db.DbKey; import axiom.objectmodel.db.DbMapping; import axiom.objectmodel.db.Key; import axiom.objectmodel.db.Node; import axiom.objectmodel.db.NodeManager; import axiom.objectmodel.dom.LuceneDataFormatter; import axiom.objectmodel.dom.LuceneManager; import axiom.scripting.rhino.extensions.filter.AndFilterObject; import axiom.scripting.rhino.extensions.filter.FilterObject; import axiom.scripting.rhino.extensions.filter.IFilter; import axiom.scripting.rhino.extensions.filter.NativeFilterObject; import axiom.scripting.rhino.extensions.filter.NotFilterObject; import axiom.scripting.rhino.extensions.filter.OpFilterObject; import axiom.scripting.rhino.extensions.filter.OrFilterObject; import axiom.scripting.rhino.extensions.filter.QuerySortField; import axiom.scripting.rhino.extensions.filter.RangeFilterObject; import axiom.scripting.rhino.extensions.filter.SearchFilterObject; import axiom.scripting.rhino.extensions.filter.SortObject; import axiom.scripting.rhino.extensions.filter.SearchFilterObject.SearchProfile; import axiom.util.ResourceProperties; public class LuceneQueryDispatcher extends QueryDispatcher { public static final String PATH_FIELD = "path"; static final String POLYMORPHIC_FIELD = "polymorphic"; static final String RECURSE_PATH_MARKER = "**"; public LuceneQueryDispatcher(){ super(); } public LuceneQueryDispatcher(Application app, String name) throws Exception { super(app, name); } public ArrayList executeQuery(ArrayList prototypes, IFilter filter, Object options) throws Exception { SortObject sort = getSortObject((Scriptable)options); ArrayList opaths = getPaths((Scriptable)options); int _layer = getLayer((Scriptable) options); boolean ext = extendPrototypes((Scriptable) options); if (ext) { prototypes = getAllPrototypes(prototypes); } ArrayList results = new ArrayList(); IndexSearcher searcher = null; try { int maxResults = getMaxResults(options); boolean unique = getUnique(options); String field = getField(options); searcher = this.lmgr.getIndexSearcher(); Object hits = this.luceneHits(prototypes, filter, sort, maxResults, opaths, searcher, null, _layer); if (hits == null || hits instanceof Boolean) { return results; } HashSet idSet = null; final int opaths_size; if ((opaths_size = opaths.size()) > 0) { for (int i = 0; i < opaths_size; i++) { String path = (String) opaths.get(i); ArrayList ids; if (path.endsWith("/*")) { path = path.substring(0, path.length() - 1); INode n = (INode) AxiomObject.traverse(path, this.app); ids = this.lmgr.getChildrenIds(n); } else { if (path.endsWith("/**")) { path = path.substring(0, path.length() - 2); } RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); int layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } ids = this.pindxr.getIds(path, layer); } if (idSet == null) { idSet = new HashSet(ids); } else { idSet.addAll(ids); } } } if (field == null) { if (hits instanceof Hits) { luceneResultsToNodes((Hits) hits, results, maxResults, idSet, _layer); } else if (hits instanceof TopDocs) { luceneResultsToNodes((TopDocs) hits, searcher, results, maxResults, idSet, _layer); } } else { if (hits instanceof Hits) { luceneResultsToFields((Hits) hits, results, maxResults, idSet, field, unique, _layer); } else if (hits instanceof TopDocs) { luceneResultsToFields((TopDocs) hits, searcher, results, maxResults, idSet, field, unique, _layer); } } } catch (Exception ex) { results.clear(); app.logError(ErrorReporter.errorMsg(this.getClass(), "executeQuery"), ex); } finally { this.lmgr.releaseIndexSearcher(searcher); } return results; } private Object luceneHits(ArrayList prototypes, IFilter filter, SortObject sort, int maxResults, ArrayList opaths, IndexSearcher searcher, LuceneQueryParams params, int _layer) throws Exception { long start = System.currentTimeMillis(); BooleanQuery primary = new BooleanQuery(); final String PROTO = LuceneManager.PROTOTYPE; final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD; final BooleanClause.Occur MUST = BooleanClause.Occur.MUST; final TypeManager tmgr = this.app.typemgr; final ResourceProperties combined_props = new ResourceProperties(); Sort lsort = null; final int length; if (prototypes != null && (length = prototypes.size()) > 0) { BooleanQuery proto_query = new BooleanQuery(); for (int i = 0; i < length; i++) { String prototype = (String) prototypes.get(i); proto_query.add(new TermQuery(new Term(PROTO, prototype)), SHOULD); Prototype proto = tmgr.getPrototype(prototype); Stack protos = new Stack(); while (proto != null) { protos.push(proto); proto = proto.getParentPrototype(); } final int protoChainSize = protos.size(); for (int j = 0; j < protoChainSize; j++) { proto = (Prototype) protos.pop(); combined_props.putAll(proto.getTypeProperties()); } } primary.add(proto_query, MUST); } else { ArrayList protoarr = app.getSearchablePrototypes(); BooleanQuery proto_query = new BooleanQuery(); for (int i = protoarr.size() - 1; i > -1; i--) { String protoName = (String) protoarr.get(i); proto_query.add(new TermQuery(new Term(PROTO, protoName)), SHOULD); Prototype proto = tmgr.getPrototype(protoName); Stack protos = new Stack(); while (proto != null) { protos.push(proto); proto = proto.getParentPrototype(); } final int protoChainSize = protos.size(); for (int j = 0; j < protoChainSize; j++) { proto = (Prototype) protos.pop(); combined_props.putAll(proto.getTypeProperties()); } } primary.add(proto_query, MUST); } parseFilterIntoQuery(filter, primary, combined_props); RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); int layer = _layer; if (layer == -1) { layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } } BooleanQuery layerQuery = new BooleanQuery(); for (int i = 0; i <= layer; i++) { layerQuery.add(new TermQuery(new Term(LuceneManager.LAYER_OF_SAVE, i + "")), BooleanClause.Occur.SHOULD); } primary.add(layerQuery, BooleanClause.Occur.MUST); BooleanClause[] clauses = primary.getClauses(); if (clauses == null || clauses.length == 0) { throw new Exception( "QueryBean.executeQuery(): The lucene query doesn't have any clauses!"); } if (filter.isCached()) { SimpleQueryFilter sqf = (SimpleQueryFilter) this.cache.get(primary); if (sqf == null) { sqf = new SimpleQueryFilter(primary); this.cache.put(primary, sqf); } } Object ret = null; int sizeOfResults = 0; try { if (app.debug()){ app.logEvent("running query "+primary+" with maxResults "+maxResults+ " and sort "+(sort == null ? "null" : getLuceneSort(sort))); } if (sort != null && (lsort = getLuceneSort(sort)) != null) { if (maxResults == -1 || opaths.size() > 0) { Hits h = searcher.search(primary, lsort); sizeOfResults = h.length(); ret = h; } else { TopFieldDocs tfd = searcher.search(primary, null, maxResults, lsort); sizeOfResults = tfd.totalHits; ret = tfd; } } else { if (maxResults == -1 || opaths.size() > 0) { Hits h = searcher.search(primary); sizeOfResults = h.length(); ret = h; } else { TopDocs td = searcher.search(primary, null, maxResults); sizeOfResults = td.totalHits; ret = td; } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "luceneHits") + "Occured on query = " + primary, ex); } if (ret == null) { ret = (maxResults == -1 || opaths.size() > 0) ? new Boolean(true) : new Boolean(false); } if (params != null) { params.query = primary; params.max_results = maxResults; params.sort = lsort; params.rprops = combined_props; } if(app.debug()){ long time = System.currentTimeMillis() - start; app.logEvent("... took "+(time/1000.0)+" seconds\n ------"); } return ret; } private Object luceneHits(ArrayList prototypes, IFilter ifilter, LuceneQueryParams params) throws Exception { long start = System.currentTimeMillis(); BooleanQuery primary = new BooleanQuery(); final String PROTO = LuceneManager.PROTOTYPE; final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD; final BooleanClause.Occur MUST = BooleanClause.Occur.MUST; final TypeManager tmgr = this.app.typemgr; final ResourceProperties combined_props = new ResourceProperties(); final int length; if (prototypes != null && (length = prototypes.size()) > 0) { BooleanQuery proto_query = new BooleanQuery(); for (int i = 0; i < length; i++) { String prototype = (String) prototypes.get(i); proto_query.add(new TermQuery(new Term(PROTO, prototype)), SHOULD); Prototype p = tmgr.getPrototype(prototype); if (p != null) { combined_props.putAll(p.getTypeProperties()); } } primary.add(proto_query, MUST); } Query mergedQuery; BooleanClause[] clauses = primary.getClauses(); if (clauses.length == 0) { mergedQuery = params.query; } else { BooleanQuery tmpQuery = new BooleanQuery(); tmpQuery.add(params.query, MUST); tmpQuery.add(primary, MUST); mergedQuery = tmpQuery; } if (params.rprops != null) { combined_props.putAll(params.rprops); } Filter filter = this.getQueryFilter(ifilter, combined_props); SimpleQueryFilter sqf = (SimpleQueryFilter) this.cache.get(mergedQuery); if (sqf != null) { mergedQuery = new TermQuery(new Term("_d", "1")); IndexReader reader = params.searcher.getIndexReader(); filter = new SimpleQueryFilter(filter.bits(reader), sqf.bits(reader)); } Object ret = null; int sizeOfResults = 0; try { if(app.debug()){ app.logEvent("running query "+primary); } IndexSearcher searcher = params.searcher; if (params.sort != null) { if (params.max_results == -1) { Hits h = searcher.search(mergedQuery, filter, params.sort); sizeOfResults = h.length(); ret = h; } else { TopFieldDocs tfd = searcher.search(mergedQuery, filter, params.max_results, params.sort); sizeOfResults = tfd.totalHits; ret = tfd; } } else { if (params.max_results == -1) { Hits h = searcher.search(mergedQuery, filter); sizeOfResults = h.length(); ret = h; } else { TopDocs td = searcher.search(mergedQuery, filter, params.max_results); sizeOfResults = td.totalHits; ret = td; } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "luceneHits") + "Occured on query = " + primary, ex); } if (app.debug()){ long time = System.currentTimeMillis() - start; app.logEvent("... took "+(time/1000.0)+" seconds\n ------"); } return ret; } public void luceneResultsToNodes(Hits hits, ArrayList results, int maxResults, HashSet ids, int _layer) throws Exception { int hitslen = hits.length(); if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final GlobalObject global = this.core != null ? this.core.global : null; final Application app = this.app; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } final String ID = LuceneManager.ID; HashSet retrieved = new HashSet(); NodeManager nmgr = this.app.getNodeManager(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document doc = hits.doc(i); String id = doc.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } Key key = new DbKey(this.app.getDbMapping(doc.get(LuceneManager.PROTOTYPE)), id, mode); Node node = nmgr.getNode(key); if (node != null) { if (global != null) { results.add(Context.toObject(node, global)); } else { results.add(node); } retrieved.add(id); count++; } } } } public int luceneResultsToNodesLength(Hits hits, int maxResults, HashSet ids, int _layer) throws Exception { int length = 0; int hitslen = hits.length(); if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final Application app = this.app; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } final String ID = LuceneManager.ID; HashSet retrieved = new HashSet(); NodeManager nmgr = this.app.getNodeManager(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document doc = hits.doc(i); String id = doc.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } retrieved.add(id); count++; length++; } } return length; } public int determineResultsLength(Hits hits) throws IOException { int count = 0; final String ID = LuceneManager.ID; HashSet retrieved = new HashSet(); final int length = hits.length(); for (int i = 0; i < length; i++) { Document d = hits.doc(i); String id = d.get(ID); if (id == null || retrieved.contains(id)) { continue; } count++; retrieved.add(id); } return count; } public int determineResultsLength(TopDocs hits) throws IOException { return hits.totalHits; } public void luceneResultsToNodes(TopDocs docs, IndexSearcher searcher, ArrayList results, int maxResults, HashSet ids, int _layer) throws Exception { int hitslen = docs.scoreDocs.length; if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final GlobalObject global = this.core != null ? this.core.global : null; final Application app = this.app; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } final String ID = LuceneManager.ID; NodeManager nmgr = this.app.getNodeManager(); HashSet retrieved = new HashSet(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document doc = searcher.doc(docs.scoreDocs[i].doc); String id = doc.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } Key key = new DbKey(this.app.getDbMapping(doc.get(LuceneManager.PROTOTYPE)), id, mode); Node node = nmgr.getNode(key); if (node != null) { if (global != null) { results.add(Context.toObject(node, global)); } else { results.add(node); } retrieved.add(id); count++; } } } } public int luceneResultsToNodesLength(TopDocs docs, IndexSearcher searcher, int maxResults, HashSet ids, int _layer) throws Exception { int length = 0; int hitslen = docs.scoreDocs.length; if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final Application app = this.app; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } final String ID = LuceneManager.ID; NodeManager nmgr = this.app.getNodeManager(); HashSet retrieved = new HashSet(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document doc = searcher.doc(docs.scoreDocs[i].doc); String id = doc.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } retrieved.add(id); count++; length++; } } return length; } public void luceneResultsToFields(Hits hits, ArrayList results, int maxResults, HashSet ids, String field, boolean unique, int _layer) throws Exception { int hitslen = hits.length(); if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final String ID = LuceneManager.ID; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } NodeManager nmgr = this.app.getNodeManager(); HashSet retrieved = new HashSet(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document d = hits.doc(i); String id = d.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } DbMapping dbmap = this.app.getDbMapping(d.getField(LuceneManager.PROTOTYPE).stringValue()); Key key = new DbKey(dbmap, d.getField(LuceneManager.ID).stringValue(), mode); INode node = nmgr.getNode(key); String f = null; if (node != null) { f = node.getString(field); } if (f == null) { f = d.getField(field).stringValue(); } if (unique) { if (!results.contains(f)) { results.add(f); retrieved.add(id); count++; } } else { results.add(f); retrieved.add(id); count++; } } } } public void luceneResultsToFields(TopDocs docs, IndexSearcher searcher, ArrayList results, int maxResults, HashSet ids, String field, boolean unique, int _layer) throws Exception { int hitslen = docs.scoreDocs.length; if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final String ID = LuceneManager.ID; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } NodeManager nmgr = this.app.getNodeManager(); HashSet retrieved = new HashSet(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document d = searcher.doc(docs.scoreDocs[i].doc); String id = d.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } DbMapping dbmap = this.app.getDbMapping(d.getField(LuceneManager.PROTOTYPE).stringValue()); Key key = new DbKey(dbmap, d.getField(LuceneManager.ID).stringValue(), mode); INode node = nmgr.getNode(key); String f = null; if (node != null) { f = node.getString(field); } if (f == null) { f = d.getField(field).stringValue(); } if (unique) { if (!results.contains(f)) { results.add(f); retrieved.add(id); count++; } } else { results.add(f); retrieved.add(id); count++; } } } } private void parseFilterIntoQuery(IFilter filter, BooleanQuery primary, ResourceProperties combined_props) throws Exception { if (filter instanceof FilterObject) { FilterObject fobj = (FilterObject) filter; Query filter_query = getFilterQuery(fobj, combined_props); String analyzer = filter.jsFunction_getAnalyzer(); if (analyzer != null) { QueryParser qp = new QueryParser(LuceneManager.ID, LuceneManager.getAnalyzer(analyzer)); filter_query = qp.parse(filter_query.toString()); qp = null; } if (filter_query != null) { primary.add(filter_query, BooleanClause.Occur.MUST); } } else if (filter instanceof NativeFilterObject) { NativeFilterObject nfobj = (NativeFilterObject) filter; Query native_query = getNativeQuery(nfobj); if (native_query != null) { primary.add(native_query, BooleanClause.Occur.MUST); } } else if (filter instanceof OpFilterObject) { Query q = parseOpFilter((OpFilterObject) filter, combined_props); String analyzer = filter.jsFunction_getAnalyzer(); if (analyzer != null) { QueryParser qp = new QueryParser(LuceneManager.ID, LuceneManager.getAnalyzer(analyzer)); q = qp.parse(q.toString()); qp = null; } if (q != null) { primary.add(q, BooleanClause.Occur.MUST); } } else if (filter instanceof RangeFilterObject){ RangeFilterObject rfobj = (RangeFilterObject)filter; Query q = getRangeQuery(rfobj, combined_props); if (q != null) { primary.add(q, BooleanClause.Occur.MUST); } } else if (filter instanceof SearchFilterObject){ SearchFilterObject sfobj = (SearchFilterObject) filter; Query q = getSearchFilterQuery(sfobj, combined_props); if (q != null) { primary.add(q, BooleanClause.Occur.MUST); } } } private Query getRangeQuery(RangeFilterObject rfobj, ResourceProperties combined_props) throws Exception { Query query = null; try{ String field = rfobj.getField(); if(combined_props.containsKey(field)){ String range_begin = new String(); String range_end = new String(); Object begin = rfobj.getBegin(); Object end = rfobj.getEnd(); LuceneDataFormatter ldf = lmgr.getDataFormatter(); String type = combined_props.getProperty(field + ".type") == null ? LuceneManager.STRING_FIELD : combined_props.getProperty(field + ".type"); if(type.equalsIgnoreCase(LuceneManager.DATE_FIELD)){ range_begin = ldf.formatDate(new Date((long) ScriptRuntime.toNumber(begin))); range_end = ldf.formatDate(new Date((long) ScriptRuntime.toNumber(end))); } else if(type.equalsIgnoreCase(LuceneManager.TIME_FIELD)){ range_begin = ldf.formatTime(new Date((long) ScriptRuntime.toNumber(begin))); range_end = ldf.formatTime(new Date((long) ScriptRuntime.toNumber(end))); } else if(type.equalsIgnoreCase(LuceneManager.TIMESTAMP_FIELD)){ range_begin = ldf.formatTimestamp(new Date((long) ScriptRuntime.toNumber(begin))); range_end = ldf.formatTimestamp(new Date((long) ScriptRuntime.toNumber(end))); } else if(type.equalsIgnoreCase(LuceneManager.FLOAT_FIELD)){ range_begin = ldf.formatFloat(((Number)begin).doubleValue()); range_end = ldf.formatFloat(((Number)end).doubleValue()); } else if(type.equalsIgnoreCase(LuceneManager.SMALL_FLOAT_FIELD)){ range_begin = ldf.formatSmallFloat(((Number)begin).doubleValue()); range_end = ldf.formatSmallFloat(((Number)end).doubleValue()); } else if(type.equalsIgnoreCase(LuceneManager.SMALL_INT_FIELD)){ range_begin = ldf.formatSmallInt(((Number)begin).longValue()); range_end = ldf.formatSmallInt(((Number)end).longValue()); } else if(type.equalsIgnoreCase(LuceneManager.INTEGER_FIELD)){ range_begin = ldf.formatInt(((Number)begin).longValue()); range_end = ldf.formatInt(((Number)end).longValue()); } else if(type.equalsIgnoreCase(LuceneManager.NUMBER_FIELD)){ range_begin = ldf.formatFloat(((Number)begin).doubleValue()); range_end = ldf.formatFloat(((Number)end).doubleValue()); } else if(type.equalsIgnoreCase(LuceneManager.STRING_FIELD)){ range_begin = begin.toString(); range_end = end.toString(); } else { throw new Exception("Cannot use RangeFilter on fields of type " + type); } Term tbegin = new Term(field, range_begin); Term tend = new Term(field, range_end); query = new RangeQuery(tbegin, tend, rfobj.isInclusive()); } } catch(Exception e){ throw e; } return query; } private Sort getLuceneSort(SortObject sort) { if (sort == null) { return null; } QuerySortField[] fields = sort.getSortFields(); if (fields == null) { return null; } final int length = fields.length; SortField[] sortFields = new SortField[length]; for (int i = 0; i < length; i++) { String s = fields[i].getField(); if (s == null) { return null; } sortFields[i] = new SortField(s, SortField.STRING, !fields[i].isAscending()); } return new Sort(sortFields); } public Object luceneDocumentToNode(Object d, Scriptable global, final int mode, final boolean executedInTransactor) throws Exception { Document doc = (Document)d; NodeManager nmgr = app.getNodeManager(); DbMapping dbmap = this.app.getDbMapping(doc.getField(LuceneManager.PROTOTYPE).stringValue()); Key key = new DbKey(dbmap, doc.getField(LuceneManager.ID).stringValue(), mode); axiom.objectmodel.db.Node node = null; if (executedInTransactor) { node = nmgr.getNodeFromTransaction(key); } if (node == null) { node = nmgr.getNodeFromCache(key); if (node == null) { node = nmgr.getNode(key); if (executedInTransactor) { node = nmgr.conditionalCacheUpdate(node); } } if (executedInTransactor) { nmgr.conditionalNodeVisit(key, node); } } Object ret = null; if (node != null) { if (global != null) { ret = Context.toObject(node, global); } else { ret = node; } } return ret; } private Query getFilterQuery(FilterObject fobj, ResourceProperties props) throws Exception { final LuceneManager lmgr = this.lmgr; final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD; final BooleanClause.Occur MUST = BooleanClause.Occur.MUST; Query query = null; try { BooleanQuery primary = null; Iterator<String> iter = fobj.getKeys().iterator(); while (iter.hasNext()) { if (primary == null) { primary = new BooleanQuery(); } BooleanQuery sub_query = new BooleanQuery(); String key = iter.next().toString(); Object[] values = (Object[]) fobj.getValueForKey(key); final int vallen = values.length; if (vallen > 1) { for (int i = 0; i < vallen; i++) { Query q = createLuceneQuery(key, values[i], lmgr, props); sub_query.add(q, SHOULD); } primary.add(sub_query, MUST); } else if (vallen == 1) { primary.add(createLuceneQuery(key, values[0], lmgr, props), MUST); } } query = primary; } catch (Exception ex) { return null; } return query; } private Query getNativeQuery(NativeFilterObject nfobj) throws Exception { Query query = null; String qstr = nfobj.getNativeQuery(); Analyzer analyzer = nfobj.getAnalyzer(); try { if (analyzer != null) { QueryParser qp = new QueryParser(LuceneManager.ID, analyzer); query = qp.parse(qstr); qp = null; } else { synchronized (this.qparser) { query = this.qparser.parse(qstr); } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "getNativeQuery") + "Could not parse the input query.\n\t query = " + qstr, ex); throw ex; } return query; } private Query getSearchFilterQuery(SearchFilterObject sfobj, ResourceProperties props) throws Exception { BooleanQuery primary = null; Query query = null; Analyzer analyzer = sfobj.getAnalyzer(); SearchProfile profile = sfobj.getSearchProfile(); Object filter = sfobj.getFilter(); String qstr = filter instanceof String ? (String)filter : new String(); BooleanClause.Occur OCCUR = BooleanClause.Occur.MUST; if (profile.operator == null) { OCCUR = BooleanClause.Occur.MUST; } else if(profile.operator.equalsIgnoreCase("and")){ OCCUR = BooleanClause.Occur.MUST; } else if(profile.operator.equalsIgnoreCase("or")) { OCCUR = BooleanClause.Occur.SHOULD; } else if(profile.operator.equalsIgnoreCase("not")) { OCCUR = BooleanClause.Occur.MUST_NOT; } try { if (analyzer != null) { if (primary == null) { primary = new BooleanQuery(); } QueryParser qp = new QueryParser(LuceneManager.ID, analyzer); if(profile != null && !qstr.isEmpty()) { BooleanQuery sub_query = new BooleanQuery(); for (int i = 0; i < profile.fields.length; i++) { Query q = qp.parse(profile.fields[i] + ":" + qstr); q.setBoost(profile.boosts[i]); sub_query.add(q, BooleanClause.Occur.SHOULD); } primary.add(sub_query, BooleanClause.Occur.MUST); sub_query = null; } String profileFilter = profile.filter; if(profileFilter != null && profileFilter.startsWith("{") && profileFilter.endsWith("}")){ profileFilter = "new Filter(" + profileFilter + ")"; } Context cx = Context.getCurrentContext(); Object result = null; if (profileFilter != null) { result = cx.evaluateString(RhinoEngine.getRhinoCore(app).getGlobal(), profileFilter, "eval", 1, null); } IFilter spfilter = null; if (result != null) { spfilter = QueryBean.getFilterFromObject(result); } Query q = null; if (spfilter instanceof FilterObject) { q = getFilterQuery((FilterObject) spfilter, props); } else if (spfilter instanceof NativeFilterObject) { q = getNativeQuery((NativeFilterObject) spfilter); } else if (spfilter instanceof OpFilterObject) { q = parseOpFilter((OpFilterObject) spfilter, props); } else if (spfilter instanceof RangeFilterObject) { q = getRangeQuery((RangeFilterObject)spfilter, props); } else if (spfilter instanceof SearchFilterObject) { q = getSearchFilterQuery((SearchFilterObject)spfilter, props); } if(q != null){ primary.add(q, OCCUR); } query = primary; qp = null; } else { synchronized (this.qparser) { query = this.qparser.parse(qstr); } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "getSearchFilterQuery") + "Could not parse the input query.\n\t query = " + qstr, ex); throw ex; } return query; } private Query _getNativeQuery(String qstr, String analyzer) throws Exception { Query query = null; try { if (analyzer != null) { QueryParser qp = new QueryParser(LuceneManager.ID, this.lmgr.getAnalyzer(analyzer)); query = qp.parse(qstr); qp = null; } else { synchronized (this.qparser) { query = this.qparser.parse(qstr); } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "_getNativeQuery") + "Could not parse the input query.\n\t query = " + qstr, ex); throw ex; } return query; } private Query parseOpFilter(OpFilterObject opf, ResourceProperties props) throws Exception { IFilter[] filters = opf.getFilters(); //want to return all the results if no filters are specified if (filters == null || filters.length == 0) { return null; } BooleanQuery bq = new BooleanQuery(); BooleanClause.Occur OCCUR = BooleanClause.Occur.MUST; // default is AND if (opf instanceof AndFilterObject) { OCCUR = BooleanClause.Occur.MUST; } else if (opf instanceof OrFilterObject) { OCCUR = BooleanClause.Occur.SHOULD; } else if (opf instanceof NotFilterObject) { OCCUR = BooleanClause.Occur.MUST_NOT; } final int length = filters.length; for (int i = 0; i < length; i++) { Query q = null; if (filters[i] instanceof FilterObject) { try { q = getFilterQuery((FilterObject) filters[i], props); } catch (Exception ex) { q = null; } } else if (filters[i] instanceof NativeFilterObject) { q = getNativeQuery((NativeFilterObject) filters[i]); } else if (filters[i] instanceof OpFilterObject) { try { q = parseOpFilter((OpFilterObject) filters[i], props); } catch (Exception e) { q = null; } } else if (filters[i] instanceof RangeFilterObject) { q = getRangeQuery((RangeFilterObject)filters[i], props); } else if (filters[i] instanceof SearchFilterObject) { q = getSearchFilterQuery((SearchFilterObject)filters[i], props); } if (q != null) { if (OCCUR == BooleanClause.Occur.MUST_NOT) { // every NOT query in lucene must be proceeded with a MUST have query, // since every document in the index will have IDENTITY set to 1, we // precede the NOT query with something we know every document will have, // that is, IDENTITY set to 1. (its a hack, i know) bq.add(new TermQuery(new Term(LuceneManager.IDENTITY, "1")), BooleanClause.Occur.MUST); } bq.add(q, OCCUR); } } return bq; } private Query createLuceneQuery(final String key, final Object value, final LuceneManager lmgr, ResourceProperties props) throws Exception { final int type = LuceneManager.stringToType((String) props.get(key + ".type")); final String idx = props.getProperty(key + ".index"); Query q = null; if ((idx == null || LuceneManager.TOKENIZED_INDEX.equalsIgnoreCase(idx)) && type == IProperty.STRING && !key.startsWith("_")) { q = _getNativeQuery(key + ":\"" + (String) value + "\"", (String) props.getProperty(key + ".analyzer")); } else { q = _createLuceneQuery(key, value, lmgr, type); } return q; } private Query _createLuceneQuery(final String key, final Object value, final LuceneManager lmgr, final int type) throws Exception { if (value == null) { throw new Exception("QueryBean.createQuery(): The value specified to the query is null"); } String normalized_value = null; switch (type) { case IProperty.BOOLEAN: normalized_value = lmgr.serializeBoolean(Boolean.parseBoolean(value.toString())); break; case IProperty.DATE: if (value instanceof java.util.Date) { normalized_value = lmgr.serializeDate((java.util.Date) value); } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String class_name = s.getClassName(); if ("Date".equals(class_name)) { normalized_value = lmgr.serializeDate(new java.util.Date( (long) ScriptRuntime.toNumber(s))); } } break; case IProperty.TIME: if (value instanceof java.util.Date) { normalized_value = lmgr.serializeTime((java.util.Date) value); } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String class_name = s.getClassName(); if ("Date".equals(class_name)) { normalized_value = lmgr.serializeTime(new java.util.Date( (long) ScriptRuntime.toNumber(s))); } } break; case IProperty.TIMESTAMP: if (value instanceof java.util.Date) { normalized_value = lmgr .serializeTimestamp((java.util.Date) value); } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String class_name = s.getClassName(); if ("Date".equals(class_name)) { normalized_value = lmgr .serializeTimestamp(new java.util.Date( (long) ScriptRuntime.toNumber(s))); } } break; case IProperty.FLOAT: normalized_value = lmgr.serializeFloat(Double.parseDouble(value .toString())); break; case IProperty.SMALLFLOAT: normalized_value = lmgr.serializeSmallFloat(Double .parseDouble(value.toString())); break; case IProperty.INTEGER: normalized_value = lmgr.serializeInt(Long.parseLong(value .toString())); break; case IProperty.SMALLINT: normalized_value = lmgr.serializeSmallInt(Long.parseLong(value .toString())); break; case IProperty.STRING: if (value instanceof Number && key.equals(LuceneManager.ID)) { normalized_value = serializeNumber((Number) value); } else if (value instanceof String) { normalized_value = (String) value; } else if (value instanceof Scriptable && "String".equalsIgnoreCase(((Scriptable) value).getClassName())) { normalized_value = ScriptRuntime.toString(value); } break; case IProperty.REFERENCE: case IProperty.MULTI_VALUE: if (value instanceof String) { normalized_value = (String) value; } else if (value instanceof Scriptable && "String".equalsIgnoreCase(((Scriptable) value).getClassName())) { normalized_value = ScriptRuntime.toString(value); } else if (value instanceof AxiomObject) { normalized_value = ((AxiomObject) value).getNode().getID(); } else if (value instanceof INode) { normalized_value = ((INode) value).getID(); } break; default: break; } if (normalized_value == null) { throw new Exception("QueryBean.createQuery(): Unable to normalize the value " + value); } Query q = null; if (type == IProperty.STRING && (normalized_value.indexOf("*") > -1 || normalized_value .indexOf("?") > -1)) { // might be a wildcard query, so use the query parser to parse the query synchronized (this.qparser) { q = this.qparser.parse(key + ": " + normalized_value); } } else { q = new TermQuery(new Term(key, normalized_value)); } return q; } private String serializeNumber(Number number) { String str = null; if (number.doubleValue() - (double) number.longValue() != 0.0) { str = number.toString(); } else { Long l = new Long(number.longValue()); str = l.toString(); } return str; } private Filter getQueryFilter(IFilter filter, ResourceProperties props) { BooleanQuery query = new BooleanQuery(); try { this.parseFilterIntoQuery(filter, query, props); SimpleQueryFilter sqf = (SimpleQueryFilter) this.cache.get(query); if (sqf == null && filter.isCached()) { sqf = new SimpleQueryFilter(query); this.cache.put(query, sqf); } return sqf; } catch (Exception ex) { } return null; } public class LuceneQueryParams { public Query query; public Sort sort; public int max_results; public IndexSearcher searcher; public ResourceProperties rprops; } private ArrayList getPaths(Object options) throws Exception{ try { ArrayList opaths = new ArrayList(); if (options != null) { Object value = null; if (options instanceof Scriptable) { value = ((Scriptable) options).get(PATH_FIELD, (Scriptable) options); } else if (options instanceof Map) { value = ((Map) options).get(PATH_FIELD); } if (value != null) { if (value instanceof Scriptable) { String className = ((Scriptable) value).getClassName(); if (className.equals("String")) { opaths.add(ScriptRuntime.toString(value)); } else if (className.equals("Array")) { Scriptable arr = (Scriptable) value; final int arrlen = arr.getIds().length; for (int j = 0; j < arrlen; j++) { opaths.add(arr.get(j, arr)); } } } else if (value instanceof String) { opaths.add(value); } } } return opaths; } catch(Exception e){ throw e; } } private ArrayList<String> getAllPrototypes(ArrayList<String> prototypes) { ArrayList<String> newPrototypes = new ArrayList<String>(prototypes); for (Object p : prototypes) { String proto = p.toString(); newPrototypes.add(proto); newPrototypes.addAll(this.getSubPrototypes(proto)); } return newPrototypes; } private ArrayList<String> getSubPrototypes(String proto) { ArrayList<String> newPrototypes = new ArrayList<String>(); Prototype prototype = app.typemgr.getPrototype(proto); if (prototype != null) { for (Prototype subprototype : prototype.getChildPrototypes()) { String subproto = subprototype.getName(); newPrototypes.add(subproto); newPrototypes.addAll(this.getSubPrototypes(subproto)); } } return newPrototypes; } private boolean extendPrototypes(Object options) throws Exception { try { boolean ext = false; if (options != null) { Object value = null; if (options instanceof Scriptable) { value = ((Scriptable) options).get(POLYMORPHIC_FIELD, (Scriptable) options); } else if (options instanceof Map) { value = ((Map) options).get(POLYMORPHIC_FIELD); } if (value != null) { if (value instanceof Scriptable) { ext = ScriptRuntime.toBoolean(value); } else if (value instanceof Boolean) { ext = ((Boolean) value).booleanValue(); } else if (value instanceof String) { ext = Boolean.parseBoolean((String) value); } } } return ext; } catch (Exception e) { throw e; } } public Object hits(ArrayList prototypes, IFilter filter, Object options) throws Exception { Object results = null; int maxResults = getMaxResults((Scriptable)options); SortObject sort = getSortObject((Scriptable)options); int _layer = getLayer((Scriptable) options); boolean ext = extendPrototypes((Scriptable) options); if (ext) { prototypes = getAllPrototypes(prototypes); } ArrayList opaths = getPaths((Scriptable)options); IndexSearcher searcher = this.lmgr.getIndexSearcher(); LuceneQueryParams params = new LuceneQueryParams(); params.searcher = searcher; Object hits = luceneHits(prototypes, filter, sort, maxResults, opaths, searcher, params, _layer); HashSet idSet = null; final int opaths_size; if ((opaths_size = opaths.size()) > 0) { for (int i = 0; i < opaths_size; i++) { String path = (String) opaths.get(i); ArrayList ids; if (path.endsWith("/*")) { path = path.substring(0, path.length() - 1); INode n = (INode) AxiomObject.traverse(path, this.app); ids = this.lmgr.getChildrenIds(n); } else { if (path.endsWith("/**")) { path = path.substring(0, path.length() - 2); } RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); int layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } ids = this.pindxr.getIds(path, layer); } if (idSet == null) { idSet = new HashSet(ids); } else { idSet.addAll(ids); } } } hits = hitsToKeys(hits, params, _layer, idSet); final Object[] args = { this.core, this, hits, params, this.lmgr }; results = Context.getCurrentContext().newObject(this.core.getScope(), "LuceneHits", args); return results; } public Object filterHits(Object prototype, Object filter, Object params) throws Exception { IFilter theFilter = QueryBean.getFilterFromObject(filter); LuceneQueryParams lparams = (LuceneQueryParams)params; if (theFilter == null) { throw new Exception("LuceneQueryDispatcher.filterHits(): Could not determine the query filter."); } Object results = null; ArrayList embeddedDbProtos = new ArrayList(); QueryBean.setPrototypeArrays(this.app, prototype, embeddedDbProtos, new ArrayList(), new HashMap<String, ArrayList>()); Object hits = luceneHits(embeddedDbProtos, theFilter, lparams); hits = hitsToKeys(hits, lparams, -1, null); final Object[] args = { this.core, this, hits, params, this.lmgr }; results = Context.getCurrentContext().newObject(this.core.getScope(), "LuceneHits", args); return results; } public Object documentToNode(Object d, Scriptable global, final int mode, final boolean executedInTransactor) throws Exception { return this.luceneDocumentToNode(d, global, mode, executedInTransactor); } public int filterHitsLength(Object prototype, Object filter, LuceneQueryParams params) throws Exception { IFilter theFilter = QueryBean.getFilterFromObject(filter); if (theFilter == null) { throw new Exception("LuceneQueryDispatcher.filterHits(): Could not determine the query filter."); } ArrayList embeddedDbProtos = new ArrayList(); QueryBean.setPrototypeArrays(this.app, prototype, embeddedDbProtos, new ArrayList(), new HashMap<String, ArrayList>()); Object hits = luceneHits(embeddedDbProtos, theFilter, params); return hitsToKeys(hits, params, -1, null).size(); } public Scriptable getReferences(ArrayList sources, ArrayList targets, final int mode) throws Exception { long start = System.currentTimeMillis(); final GlobalObject global = this.core != null ? this.core.global : null; final Application app = this.app; final String ID_FIELD = LuceneManager.ID; final String REF_LIST = LuceneManager.REF_LIST_FIELD; final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD; final BooleanClause.Occur MUST = BooleanClause.Occur.MUST; final int sources_size = sources.size(); final int targets_size = targets.size(); ArrayList results = new ArrayList(); BooleanQuery sub_query = new BooleanQuery(); for (int i = 0; i < sources_size; i++) { sub_query.add(new TermQuery(new Term(ID_FIELD, sources.get(i).toString())), SHOULD); } BooleanQuery primary = new BooleanQuery(); primary.add(sub_query, MUST); sub_query = new BooleanQuery(); for (int i = 0; i < targets_size; i++) { sub_query.add(new TermQuery(new Term(REF_LIST, targets.get(i).toString())), SHOULD); } primary.add(sub_query, MUST); IndexSearcher searcher = null; try { if (app.debug()){ app.logEvent("running query "+primary); } searcher = this.lmgr.getIndexSearcher(); Hits hits = searcher.search(primary); HashSet target_set = new HashSet(targets); luceneResultsToReferences(hits, results, target_set, mode); } catch (Exception ex) { results.clear(); app.logError(ErrorReporter.errorMsg(this.getClass(), "getReferences") + "Occured on query = " + primary, ex); } finally { this.lmgr.releaseIndexSearcher(searcher); } if(app.debug()){ long time = System.currentTimeMillis() - start; app.logEvent("... took "+(time/1000.0)+" seconds\n ------"); } return Context.getCurrentContext().newArray(global, results.toArray()); } private ArrayList hitsToKeys(Object hits, LuceneQueryParams params, int _layer, HashSet ids) throws IOException { ArrayList keys = new ArrayList(); RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); int layer; if (_layer != -1) { layer = _layer; } else { layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } } if (hits instanceof Hits) { Hits h = (Hits) hits; final int length = h.length(); HashSet retrieved = new HashSet(); for (int i = 0; i < length; i++) { Document doc = h.doc(i); String id = doc.get(LuceneManager.ID); String prototype = doc.get(LuceneManager.PROTOTYPE); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { // if (id == null || retrieved.contains(id)) { continue; } Key key = new DbKey(this.app.getDbMapping(prototype), id, layer); keys.add(key); retrieved.add(id); } } else if (hits instanceof TopDocs) { TopDocs td = (TopDocs) hits; final int length = td.scoreDocs.length; HashSet retrieved = new HashSet(); IndexSearcher searcher = params.searcher; for (int i = 0; i < length; i++) { Document doc = searcher.doc(td.scoreDocs[i].doc); String id = doc.get(LuceneManager.ID); String prototype = doc.get(LuceneManager.PROTOTYPE); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { // if (id == null || retrieved.contains(id)) { continue; } Key key = new DbKey(this.app.getDbMapping(prototype), id, layer); keys.add(key); retrieved.add(id); } } return keys; } private void luceneResultsToReferences(final Hits hits, final ArrayList results, final HashSet targets, final int mode) throws Exception { final int hitslen = hits.length(); final String ID = LuceneManager.ID; final String REF_FIELD = LuceneManager.REF_LIST_FIELD; final String DELIM = LuceneManager.NULL_DELIM; final Context cx = Context.getCurrentContext(); final GlobalObject global = this.core != null ? this.core.global : null; if (global == null) { return; } for (int i = 0; i < hitslen; i++) { Document d = hits.doc(i); Field f = d.getField(ID); if (f == null) { continue; } final String source_id = f.stringValue(); Field[] ref_fields = d.getFields(REF_FIELD); int ref_length = ref_fields != null ? ref_fields.length : 0; for (int j = 0; j < ref_length; j++) { String[] values = ref_fields[j].stringValue().split(DELIM); if (targets.contains(values[0])) { final Object[] args = { new DbKey(null, values[0], mode) }; Object o = cx.newObject(global, "Reference", args); Reference relobj = (Reference) o; relobj.setSourceKey(new DbKey(null, source_id, mode)); relobj.setSourceProperty(values[1]); if (values.length > 2) { relobj.setSourceIndex(Integer.parseInt(values[2])); if (values.length > 3) { relobj.setSourceXPath(values[3]); } } results.add(relobj); } } } } public Object getDirectionalNodesFor(Object o, int direction, Object prototypes, Object filter, Object options) throws Exception { final GlobalObject global = this.core != null ? this.core.global : null; final Application app = this.app; final LuceneManager lmgr = this.lmgr; INode node = null; int objLayer = -1; ArrayList objects = null; if (o instanceof AxiomObject) { objects = new ArrayList(); node = ((AxiomObject) o).node; if (node != null) { objects.add(node.getID()); if (node instanceof Node) { objLayer = ((Node) node).getLayer(); } } } else if (o instanceof INode) { objects = new ArrayList(); node = (INode) o; objects.add(node.getID()); if (node instanceof Node) { objLayer = ((Node) node).getLayer(); } } else if (o instanceof String) { objects = this.getNodesByPath((String) o); } final int size = objects == null ? 0 : objects.size(); if (size == 0) { if (global != null) { return Context.getCurrentContext().newArray(global, new Object[0]); } else { return new Object[0]; } } int _layer = getLayer(options); final int mode; if (_layer > -1) { mode = _layer; } else if (objLayer > -1) { mode = objLayer; } else { RequestEvaluator req_eval = app.getCurrentRequestEvaluator(); if (req_eval != null) { mode = req_eval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } int maxResults = Integer.MAX_VALUE; try { maxResults = getMaxResults(options); } catch (Exception e) { maxResults = Integer.MAX_VALUE; } if (maxResults < 0) { maxResults = Integer.MAX_VALUE; } ArrayList protos = new ArrayList(); if (prototypes != null && prototypes != Scriptable.NOT_FOUND) { QueryBean.setPrototypeArrays(this.app, prototypes, protos, new ArrayList(), new HashMap<String, ArrayList>()); } IFilter theFilter = QueryBean.getFilterFromObject(filter); BooleanQuery primary = new BooleanQuery(); ResourceProperties props = QueryBean.getResourceProperties(this.app, protos); parseFilterIntoQuery(theFilter, primary, props); NodeManager nmgr = app.getNodeManager(); ArrayList node_list = new ArrayList(); HashSet encountered_keys = new HashSet(); int list_count = 0; for (int i = 0; i < size; i++) { if (node_list.size() >= maxResults) { break; } Key[] node_keys = null; try { node_keys = (direction == 0 ? lmgr.getTargetNodeIds(objects.get(i).toString(), mode, protos, primary, getLuceneSort(getSortObject(options))) : lmgr.getSourceNodeIds(objects.get(i).toString(), mode, protos, primary, getLuceneSort(getSortObject(options)))); } catch (Exception ex) { node_keys = null; app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesFor") + "Could not retrieve " + (direction == 0 ? "target" : "source") + " nodes", ex); } if (node_keys == null) { continue; } int length = node_keys.length; for (int j = 0; j < length; j++) { if (encountered_keys.contains(node_keys[j])) { continue; } Node curr = null; try { curr = nmgr.getNode(node_keys[j]); } catch (Exception ex) { curr = null; app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesFor") + "Could not get node '" + node_keys[j].getID() + "'.", ex); } if (curr != null) { if (global != null) { node_list.add(Context.toObject(curr, global)); } else { node_list.add(curr); } if (node_list.size() >= maxResults) { break; } encountered_keys.add(node_keys[j]); } } } if (global != null) { return Context.getCurrentContext().newArray(core.global, node_list.toArray()); } else { return node_list.toArray(); } } public ArrayList getNodesByPath(String path) { ArrayList objects; int layer = DbKey.LIVE_LAYER; RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); if (reqeval != null) { layer = reqeval.getLayer(); } if (path.endsWith(RECURSE_PATH_MARKER)) { objects = this.pindxr.getIds(path.substring(0, path.indexOf(RECURSE_PATH_MARKER)), layer); } else { objects = new ArrayList(); objects.add(this.pindxr.getId(path, layer)); } return objects; } public int getDirectionalNodesForCount(Object o, int direction, Object prototypes, Object filter, Object options) throws Exception { final Application app = this.app; final LuceneManager lmgr = this.lmgr; INode node = null; int objLayer = -1; ArrayList objects = null; if (o instanceof AxiomObject) { objects = new ArrayList(); node = ((AxiomObject) o).node; if (node != null) { objects.add(node.getID()); if (node instanceof Node) { objLayer = ((Node) node).getLayer(); } } } else if (o instanceof INode) { objects = new ArrayList(); node = (INode) o; objects.add(node.getID()); if (node instanceof Node) { objLayer = ((Node) node).getLayer(); } } else if (o instanceof String) { objects = this.getNodesByPath((String) o); } final int size = objects == null ? 0 : objects.size(); if (size == 0) { return 0; } int _layer = getLayer((Scriptable) options); final int mode; if (_layer > -1) { mode = _layer; } else if (objLayer > -1) { mode = objLayer; } else { RequestEvaluator req_eval = app.getCurrentRequestEvaluator(); if (req_eval != null) { mode = req_eval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } int maxResults = Integer.MAX_VALUE; try { maxResults = getMaxResults(options); } catch (Exception e) { maxResults = Integer.MAX_VALUE; } if (maxResults < 0) { maxResults = Integer.MAX_VALUE; } ArrayList protos = new ArrayList(); if (prototypes != null && prototypes != Scriptable.NOT_FOUND) { QueryBean.setPrototypeArrays(this.app, prototypes, protos, new ArrayList(), new HashMap<String, ArrayList>()); } IFilter theFilter = QueryBean.getFilterFromObject(filter); BooleanQuery primary = new BooleanQuery(); ResourceProperties props = QueryBean.getResourceProperties(this.app, protos); parseFilterIntoQuery(theFilter, primary, props); int count = 0; for (int i = 0; i < size; i++) { Key[] node_keys = null; try { node_keys = (direction == 0 ? lmgr.getTargetNodeIds(objects.get(i).toString(), mode, protos, primary, getLuceneSort(getSortObject(options))) : lmgr.getSourceNodeIds(objects.get(i).toString(), mode, protos, primary, getLuceneSort(getSortObject(options)))); } catch (Exception ex) { ex.printStackTrace(); node_keys = null; app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesForCount") + "Could not retrieve " + (direction == 0 ? "target" : "source") + " nodes", ex); } if (node_keys == null) { continue; } count += node_keys.length; if (count >= maxResults) { count = maxResults; break; } } return count; } public int getHitCount(ArrayList prototypes, IFilter filter, Object options) throws Exception { ArrayList opaths = getPaths(options); IndexSearcher searcher = null; int count = 0; try { int maxResults = getMaxResults((Scriptable)options); boolean unique = getUnique((Scriptable)options); int _layer = getLayer((Scriptable) options); searcher = this.lmgr.getIndexSearcher(); Object hits = this.luceneHits(prototypes, filter, null, maxResults, opaths, searcher, null, _layer); if (hits == null || hits instanceof Boolean) { return 0; } HashSet idSet = null; final int opaths_size; if ((opaths_size = opaths.size()) > 0) { for (int i = 0; i < opaths_size; i++) { String path = (String) opaths.get(i); ArrayList ids; if (path.endsWith("/*")) { path = path.substring(0, path.length() - 1); INode n = (INode) AxiomObject.traverse(path, this.app); ids = this.lmgr.getChildrenIds(n); } else { if (path.endsWith("/**")) { path = path.substring(0, path.length() - 2); } int layer; if (_layer != -1) { layer = _layer; } else { RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } } ids = this.pindxr.getIds(path, layer); } if (idSet == null) { idSet = new HashSet(ids); } else { idSet.addAll(ids); } } } if (hits instanceof Hits) { count = luceneResultsToNodesLength((Hits) hits, maxResults, idSet, _layer); } else if (hits instanceof TopDocs) { count = luceneResultsToNodesLength((TopDocs) hits, searcher, maxResults, idSet, _layer); } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "getHitCount"), ex); } finally { this.lmgr.releaseIndexSearcher(searcher); } return count; } public ArrayList getVersionFields(Object obj, Object fields, ArrayList prototypes, IFilter filter, Object options) throws Exception{ String id = null; if (obj instanceof String) { id = (String) obj; } else if(obj instanceof INode) { id = ((INode)obj).getID(); } else if (obj instanceof Scriptable) { id = ScriptRuntime.toString(obj); } else { id = obj.toString(); } Scriptable idfilter = Context.getCurrentContext().newObject(this.core.getScope()); idfilter.put(LuceneManager.ID, idfilter, id); IFilter newFilter = AndFilterObject.filterObjCtor(null, new Object[]{filter, idfilter}, null, false); SortObject sort = getSortObject((Scriptable)options); ArrayList opaths = getPaths((Scriptable)options); int _layer = getLayer((Scriptable) options); RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); _layer = (_layer == -1) ? (reqeval != null) ? reqeval.getLayer() : DbKey.LIVE_LAYER : _layer; int maxResults = getMaxResults((Scriptable)options); IndexSearcher searcher = new IndexSearcher(this.lmgr.getDirectory(), true); Object hits = this.luceneHits(prototypes, newFilter, sort, maxResults, opaths, searcher, null, _layer); ArrayList<Scriptable> versions = new ArrayList<Scriptable>(); if(hits != null){ int hitslength = hits instanceof Hits ? ((Hits)hits).length() : ((TopDocs)hits).scoreDocs.length; if (hitslength > 0) { if (maxResults < 0) { maxResults = hitslength; } } for (int i = 0, count = 0; i < hitslength && count < maxResults; i++) { Document doc = hits instanceof Hits ? ((Hits)hits).doc(i) : searcher.doc(((TopDocs)hits).scoreDocs[i].doc); if(doc != null){ ArrayList<String> _fields = new ArrayList<String>(); if(fields instanceof String){ _fields.add((String)fields); } else if (fields instanceof Scriptable){ String className = ((Scriptable) fields).getClassName(); if (className.equals("String")) { _fields.add(fields.toString()); } else if (className.equals("Array")) { Scriptable arr = (Scriptable) fields; final int arrlen = arr.getIds().length; for (int j = 0; j < arrlen; j++) { _fields.add(arr.get(j, arr).toString()); } } else{ _fields.add(fields.toString()); } } Scriptable version = Context.getCurrentContext().newObject(this.core.getScope()); for(int j = 0; j < _fields.size(); j++){ String field = _fields.get(j); Object value = doc.get(field) != null ? doc.get(field): Undefined.instance; version.put(field, version, value); } count++; versions.add(version); } } } return versions; } }
src/java/axiom/scripting/rhino/LuceneQueryDispatcher.java
/* * Axiom Stack Web Application Framework * Copyright (C) 2008 Axiom Software Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Axiom Software Inc., 11480 Commerce Park Drive, Third Floor, Reston, VA 20191 USA * email: [email protected] */ package axiom.scripting.rhino; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Stack; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.RangeQuery; import org.apache.lucene.search.SimpleQueryFilter; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldDocs; import org.mozilla.javascript.Context; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Undefined; import axiom.framework.ErrorReporter; import axiom.framework.core.Application; import axiom.framework.core.Prototype; import axiom.framework.core.RequestEvaluator; import axiom.framework.core.TypeManager; import axiom.objectmodel.INode; import axiom.objectmodel.IProperty; import axiom.objectmodel.db.DbKey; import axiom.objectmodel.db.DbMapping; import axiom.objectmodel.db.Key; import axiom.objectmodel.db.Node; import axiom.objectmodel.db.NodeManager; import axiom.objectmodel.dom.LuceneDataFormatter; import axiom.objectmodel.dom.LuceneManager; import axiom.scripting.rhino.extensions.filter.AndFilterObject; import axiom.scripting.rhino.extensions.filter.FilterObject; import axiom.scripting.rhino.extensions.filter.IFilter; import axiom.scripting.rhino.extensions.filter.NativeFilterObject; import axiom.scripting.rhino.extensions.filter.NotFilterObject; import axiom.scripting.rhino.extensions.filter.OpFilterObject; import axiom.scripting.rhino.extensions.filter.OrFilterObject; import axiom.scripting.rhino.extensions.filter.QuerySortField; import axiom.scripting.rhino.extensions.filter.RangeFilterObject; import axiom.scripting.rhino.extensions.filter.SearchFilterObject; import axiom.scripting.rhino.extensions.filter.SortObject; import axiom.scripting.rhino.extensions.filter.SearchFilterObject.SearchProfile; import axiom.util.ResourceProperties; public class LuceneQueryDispatcher extends QueryDispatcher { public static final String PATH_FIELD = "path"; static final String POLYMORPHIC_FIELD = "polymorphic"; static final String RECURSE_PATH_MARKER = "**"; public LuceneQueryDispatcher(){ super(); } public LuceneQueryDispatcher(Application app, String name) throws Exception { super(app, name); } public ArrayList executeQuery(ArrayList prototypes, IFilter filter, Object options) throws Exception { SortObject sort = getSortObject((Scriptable)options); ArrayList opaths = getPaths((Scriptable)options); int _layer = getLayer((Scriptable) options); boolean ext = extendPrototypes((Scriptable) options); if (ext) { prototypes = getAllPrototypes(prototypes); } ArrayList results = new ArrayList(); IndexSearcher searcher = null; try { int maxResults = getMaxResults(options); boolean unique = getUnique(options); String field = getField(options); searcher = this.lmgr.getIndexSearcher(); Object hits = this.luceneHits(prototypes, filter, sort, maxResults, opaths, searcher, null, _layer); if (hits == null || hits instanceof Boolean) { return results; } HashSet idSet = null; final int opaths_size; if ((opaths_size = opaths.size()) > 0) { for (int i = 0; i < opaths_size; i++) { String path = (String) opaths.get(i); ArrayList ids; if (path.endsWith("/*")) { path = path.substring(0, path.length() - 1); INode n = (INode) AxiomObject.traverse(path, this.app); ids = this.lmgr.getChildrenIds(n); } else { if (path.endsWith("/**")) { path = path.substring(0, path.length() - 2); } RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); int layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } ids = this.pindxr.getIds(path, layer); } if (idSet == null) { idSet = new HashSet(ids); } else { idSet.addAll(ids); } } } if (field == null) { if (hits instanceof Hits) { luceneResultsToNodes((Hits) hits, results, maxResults, idSet, _layer); } else if (hits instanceof TopDocs) { luceneResultsToNodes((TopDocs) hits, searcher, results, maxResults, idSet, _layer); } } else { if (hits instanceof Hits) { luceneResultsToFields((Hits) hits, results, maxResults, idSet, field, unique, _layer); } else if (hits instanceof TopDocs) { luceneResultsToFields((TopDocs) hits, searcher, results, maxResults, idSet, field, unique, _layer); } } } catch (Exception ex) { results.clear(); app.logError(ErrorReporter.errorMsg(this.getClass(), "executeQuery"), ex); } finally { this.lmgr.releaseIndexSearcher(searcher); } return results; } private Object luceneHits(ArrayList prototypes, IFilter filter, SortObject sort, int maxResults, ArrayList opaths, IndexSearcher searcher, LuceneQueryParams params, int _layer) throws Exception { long start = System.currentTimeMillis(); BooleanQuery primary = new BooleanQuery(); final String PROTO = LuceneManager.PROTOTYPE; final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD; final BooleanClause.Occur MUST = BooleanClause.Occur.MUST; final TypeManager tmgr = this.app.typemgr; final ResourceProperties combined_props = new ResourceProperties(); Sort lsort = null; final int length; if (prototypes != null && (length = prototypes.size()) > 0) { BooleanQuery proto_query = new BooleanQuery(); for (int i = 0; i < length; i++) { String prototype = (String) prototypes.get(i); proto_query.add(new TermQuery(new Term(PROTO, prototype)), SHOULD); Prototype proto = tmgr.getPrototype(prototype); Stack protos = new Stack(); while (proto != null) { protos.push(proto); proto = proto.getParentPrototype(); } final int protoChainSize = protos.size(); for (int j = 0; j < protoChainSize; j++) { proto = (Prototype) protos.pop(); combined_props.putAll(proto.getTypeProperties()); } } primary.add(proto_query, MUST); } else { ArrayList protoarr = app.getSearchablePrototypes(); BooleanQuery proto_query = new BooleanQuery(); for (int i = protoarr.size() - 1; i > -1; i--) { String protoName = (String) protoarr.get(i); proto_query.add(new TermQuery(new Term(PROTO, protoName)), SHOULD); Prototype proto = tmgr.getPrototype(protoName); Stack protos = new Stack(); while (proto != null) { protos.push(proto); proto = proto.getParentPrototype(); } final int protoChainSize = protos.size(); for (int j = 0; j < protoChainSize; j++) { proto = (Prototype) protos.pop(); combined_props.putAll(proto.getTypeProperties()); } } primary.add(proto_query, MUST); } parseFilterIntoQuery(filter, primary, combined_props); RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); int layer = _layer; if (layer == -1) { layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } } BooleanQuery layerQuery = new BooleanQuery(); for (int i = 0; i <= layer; i++) { layerQuery.add(new TermQuery(new Term(LuceneManager.LAYER_OF_SAVE, i + "")), BooleanClause.Occur.SHOULD); } primary.add(layerQuery, BooleanClause.Occur.MUST); BooleanClause[] clauses = primary.getClauses(); if (clauses == null || clauses.length == 0) { throw new Exception( "QueryBean.executeQuery(): The lucene query doesn't have any clauses!"); } if (filter.isCached()) { SimpleQueryFilter sqf = (SimpleQueryFilter) this.cache.get(primary); if (sqf == null) { sqf = new SimpleQueryFilter(primary); this.cache.put(primary, sqf); } } Object ret = null; int sizeOfResults = 0; try { if (app.debug()){ app.logEvent("running query "+primary+" with maxResults "+maxResults+ " and sort "+(sort == null ? "null" : getLuceneSort(sort))); } if (sort != null && (lsort = getLuceneSort(sort)) != null) { if (maxResults == -1 || opaths.size() > 0) { Hits h = searcher.search(primary, lsort); sizeOfResults = h.length(); ret = h; } else { TopFieldDocs tfd = searcher.search(primary, null, maxResults, lsort); sizeOfResults = tfd.totalHits; ret = tfd; } } else { if (maxResults == -1 || opaths.size() > 0) { Hits h = searcher.search(primary); sizeOfResults = h.length(); ret = h; } else { TopDocs td = searcher.search(primary, null, maxResults); sizeOfResults = td.totalHits; ret = td; } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "luceneHits") + "Occured on query = " + primary, ex); } if (ret == null) { ret = (maxResults == -1 || opaths.size() > 0) ? new Boolean(true) : new Boolean(false); } if (params != null) { params.query = primary; params.max_results = maxResults; params.sort = lsort; params.rprops = combined_props; } if(app.debug()){ long time = System.currentTimeMillis() - start; app.logEvent("... took "+(time/1000.0)+" seconds\n ------"); } return ret; } private Object luceneHits(ArrayList prototypes, IFilter ifilter, LuceneQueryParams params) throws Exception { long start = System.currentTimeMillis(); BooleanQuery primary = new BooleanQuery(); final String PROTO = LuceneManager.PROTOTYPE; final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD; final BooleanClause.Occur MUST = BooleanClause.Occur.MUST; final TypeManager tmgr = this.app.typemgr; final ResourceProperties combined_props = new ResourceProperties(); final int length; if (prototypes != null && (length = prototypes.size()) > 0) { BooleanQuery proto_query = new BooleanQuery(); for (int i = 0; i < length; i++) { String prototype = (String) prototypes.get(i); proto_query.add(new TermQuery(new Term(PROTO, prototype)), SHOULD); Prototype p = tmgr.getPrototype(prototype); if (p != null) { combined_props.putAll(p.getTypeProperties()); } } primary.add(proto_query, MUST); } Query mergedQuery; BooleanClause[] clauses = primary.getClauses(); if (clauses.length == 0) { mergedQuery = params.query; } else { BooleanQuery tmpQuery = new BooleanQuery(); tmpQuery.add(params.query, MUST); tmpQuery.add(primary, MUST); mergedQuery = tmpQuery; } if (params.rprops != null) { combined_props.putAll(params.rprops); } Filter filter = this.getQueryFilter(ifilter, combined_props); SimpleQueryFilter sqf = (SimpleQueryFilter) this.cache.get(mergedQuery); if (sqf != null) { mergedQuery = new TermQuery(new Term("_d", "1")); IndexReader reader = params.searcher.getIndexReader(); filter = new SimpleQueryFilter(filter.bits(reader), sqf.bits(reader)); } Object ret = null; int sizeOfResults = 0; try { if(app.debug()){ app.logEvent("running query "+primary); } IndexSearcher searcher = params.searcher; if (params.sort != null) { if (params.max_results == -1) { Hits h = searcher.search(mergedQuery, filter, params.sort); sizeOfResults = h.length(); ret = h; } else { TopFieldDocs tfd = searcher.search(mergedQuery, filter, params.max_results, params.sort); sizeOfResults = tfd.totalHits; ret = tfd; } } else { if (params.max_results == -1) { Hits h = searcher.search(mergedQuery, filter); sizeOfResults = h.length(); ret = h; } else { TopDocs td = searcher.search(mergedQuery, filter, params.max_results); sizeOfResults = td.totalHits; ret = td; } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "luceneHits") + "Occured on query = " + primary, ex); } if (app.debug()){ long time = System.currentTimeMillis() - start; app.logEvent("... took "+(time/1000.0)+" seconds\n ------"); } return ret; } public void luceneResultsToNodes(Hits hits, ArrayList results, int maxResults, HashSet ids, int _layer) throws Exception { int hitslen = hits.length(); if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final GlobalObject global = this.core != null ? this.core.global : null; final Application app = this.app; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } final String ID = LuceneManager.ID; HashSet retrieved = new HashSet(); NodeManager nmgr = this.app.getNodeManager(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document doc = hits.doc(i); String id = doc.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } Key key = new DbKey(this.app.getDbMapping(doc.get(LuceneManager.PROTOTYPE)), id, mode); Node node = nmgr.getNode(key); if (node != null) { if (global != null) { results.add(Context.toObject(node, global)); } else { results.add(node); } retrieved.add(id); count++; } } } } public int luceneResultsToNodesLength(Hits hits, int maxResults, HashSet ids, int _layer) throws Exception { int length = 0; int hitslen = hits.length(); if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final Application app = this.app; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } final String ID = LuceneManager.ID; HashSet retrieved = new HashSet(); NodeManager nmgr = this.app.getNodeManager(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document doc = hits.doc(i); String id = doc.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } retrieved.add(id); count++; length++; } } return length; } public int determineResultsLength(Hits hits) throws IOException { int count = 0; final String ID = LuceneManager.ID; HashSet retrieved = new HashSet(); final int length = hits.length(); for (int i = 0; i < length; i++) { Document d = hits.doc(i); String id = d.get(ID); if (id == null || retrieved.contains(id)) { continue; } count++; retrieved.add(id); } return count; } public int determineResultsLength(TopDocs hits) throws IOException { return hits.totalHits; } public void luceneResultsToNodes(TopDocs docs, IndexSearcher searcher, ArrayList results, int maxResults, HashSet ids, int _layer) throws Exception { int hitslen = docs.scoreDocs.length; if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final GlobalObject global = this.core != null ? this.core.global : null; final Application app = this.app; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } final String ID = LuceneManager.ID; NodeManager nmgr = this.app.getNodeManager(); HashSet retrieved = new HashSet(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document doc = searcher.doc(docs.scoreDocs[i].doc); String id = doc.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } Key key = new DbKey(this.app.getDbMapping(doc.get(LuceneManager.PROTOTYPE)), id, mode); Node node = nmgr.getNode(key); if (node != null) { if (global != null) { results.add(Context.toObject(node, global)); } else { results.add(node); } retrieved.add(id); count++; } } } } public int luceneResultsToNodesLength(TopDocs docs, IndexSearcher searcher, int maxResults, HashSet ids, int _layer) throws Exception { int length = 0; int hitslen = docs.scoreDocs.length; if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final Application app = this.app; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } final String ID = LuceneManager.ID; NodeManager nmgr = this.app.getNodeManager(); HashSet retrieved = new HashSet(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document doc = searcher.doc(docs.scoreDocs[i].doc); String id = doc.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } retrieved.add(id); count++; length++; } } return length; } public void luceneResultsToFields(Hits hits, ArrayList results, int maxResults, HashSet ids, String field, boolean unique, int _layer) throws Exception { int hitslen = hits.length(); if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final String ID = LuceneManager.ID; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } NodeManager nmgr = this.app.getNodeManager(); HashSet retrieved = new HashSet(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document d = hits.doc(i); String id = d.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } DbMapping dbmap = this.app.getDbMapping(d.getField(LuceneManager.PROTOTYPE).stringValue()); Key key = new DbKey(dbmap, d.getField(LuceneManager.ID).stringValue(), mode); INode node = nmgr.getNode(key); String f = null; if (node != null) { f = node.getString(field); } if (f == null) { f = d.getField(field).stringValue(); } if (unique) { if (!results.contains(f)) { results.add(f); retrieved.add(id); count++; } } else { results.add(f); retrieved.add(id); count++; } } } } public void luceneResultsToFields(TopDocs docs, IndexSearcher searcher, ArrayList results, int maxResults, HashSet ids, String field, boolean unique, int _layer) throws Exception { int hitslen = docs.scoreDocs.length; if (hitslen > 0) { if (maxResults < 0) { maxResults = hitslen; } final String ID = LuceneManager.ID; final int mode; if (_layer != -1) { mode = _layer; } else { RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); if (reqeval != null) { mode = reqeval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } NodeManager nmgr = this.app.getNodeManager(); HashSet retrieved = new HashSet(); for (int i = 0, count = 0; i < hitslen && count < maxResults; i++) { Document d = searcher.doc(docs.scoreDocs[i].doc); String id = d.get(ID); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { continue; } DbMapping dbmap = this.app.getDbMapping(d.getField(LuceneManager.PROTOTYPE).stringValue()); Key key = new DbKey(dbmap, d.getField(LuceneManager.ID).stringValue(), mode); INode node = nmgr.getNode(key); String f = null; if (node != null) { f = node.getString(field); } if (f == null) { f = d.getField(field).stringValue(); } if (unique) { if (!results.contains(f)) { results.add(f); retrieved.add(id); count++; } } else { results.add(f); retrieved.add(id); count++; } } } } private void parseFilterIntoQuery(IFilter filter, BooleanQuery primary, ResourceProperties combined_props) throws Exception { if (filter instanceof FilterObject) { FilterObject fobj = (FilterObject) filter; Query filter_query = getFilterQuery(fobj, combined_props); String analyzer = fobj.jsFunction_getAnalyzer(); if (app.debug()) app.logEvent("analyzer: " + analyzer); if (app.debug() && filter_query != null) app.logEvent("filter_query.toString(): " + filter_query.toString()); if (analyzer != null) { QueryParser qp = new QueryParser(LuceneManager.ID, LuceneManager.getAnalyzer(analyzer)); filter_query = qp.parse(filter_query.toString()); qp = null; } if (filter_query != null) { primary.add(filter_query, BooleanClause.Occur.MUST); } } else if (filter instanceof NativeFilterObject) { NativeFilterObject nfobj = (NativeFilterObject) filter; Query native_query = getNativeQuery(nfobj); if (native_query != null) { primary.add(native_query, BooleanClause.Occur.MUST); } } else if (filter instanceof OpFilterObject) { Query q = parseOpFilter((OpFilterObject) filter, combined_props); String analyzer = filter.jsFunction_getAnalyzer(); if (analyzer != null) { QueryParser qp = new QueryParser(LuceneManager.ID, LuceneManager.getAnalyzer(analyzer)); q = qp.parse(q.toString()); qp = null; } if (q != null) { primary.add(q, BooleanClause.Occur.MUST); } } else if (filter instanceof RangeFilterObject){ RangeFilterObject rfobj = (RangeFilterObject)filter; Query q = getRangeQuery(rfobj, combined_props); if (q != null) { primary.add(q, BooleanClause.Occur.MUST); } } else if (filter instanceof SearchFilterObject){ SearchFilterObject sfobj = (SearchFilterObject) filter; Query q = getSearchFilterQuery(sfobj, combined_props); if (q != null) { primary.add(q, BooleanClause.Occur.MUST); } } } private Query getRangeQuery(RangeFilterObject rfobj, ResourceProperties combined_props) throws Exception { Query query = null; try{ String field = rfobj.getField(); if(combined_props.containsKey(field)){ String range_begin = new String(); String range_end = new String(); Object begin = rfobj.getBegin(); Object end = rfobj.getEnd(); LuceneDataFormatter ldf = lmgr.getDataFormatter(); String type = combined_props.getProperty(field + ".type") == null ? LuceneManager.STRING_FIELD : combined_props.getProperty(field + ".type"); if(type.equalsIgnoreCase(LuceneManager.DATE_FIELD)){ range_begin = ldf.formatDate(new Date((long) ScriptRuntime.toNumber(begin))); range_end = ldf.formatDate(new Date((long) ScriptRuntime.toNumber(end))); } else if(type.equalsIgnoreCase(LuceneManager.TIME_FIELD)){ range_begin = ldf.formatTime(new Date((long) ScriptRuntime.toNumber(begin))); range_end = ldf.formatTime(new Date((long) ScriptRuntime.toNumber(end))); } else if(type.equalsIgnoreCase(LuceneManager.TIMESTAMP_FIELD)){ range_begin = ldf.formatTimestamp(new Date((long) ScriptRuntime.toNumber(begin))); range_end = ldf.formatTimestamp(new Date((long) ScriptRuntime.toNumber(end))); } else if(type.equalsIgnoreCase(LuceneManager.FLOAT_FIELD)){ range_begin = ldf.formatFloat(((Number)begin).doubleValue()); range_end = ldf.formatFloat(((Number)end).doubleValue()); } else if(type.equalsIgnoreCase(LuceneManager.SMALL_FLOAT_FIELD)){ range_begin = ldf.formatSmallFloat(((Number)begin).doubleValue()); range_end = ldf.formatSmallFloat(((Number)end).doubleValue()); } else if(type.equalsIgnoreCase(LuceneManager.SMALL_INT_FIELD)){ range_begin = ldf.formatSmallInt(((Number)begin).longValue()); range_end = ldf.formatSmallInt(((Number)end).longValue()); } else if(type.equalsIgnoreCase(LuceneManager.INTEGER_FIELD)){ range_begin = ldf.formatInt(((Number)begin).longValue()); range_end = ldf.formatInt(((Number)end).longValue()); } else if(type.equalsIgnoreCase(LuceneManager.NUMBER_FIELD)){ range_begin = ldf.formatFloat(((Number)begin).doubleValue()); range_end = ldf.formatFloat(((Number)end).doubleValue()); } else if(type.equalsIgnoreCase(LuceneManager.STRING_FIELD)){ range_begin = begin.toString(); range_end = end.toString(); } else { throw new Exception("Cannot use RangeFilter on fields of type " + type); } Term tbegin = new Term(field, range_begin); Term tend = new Term(field, range_end); query = new RangeQuery(tbegin, tend, rfobj.isInclusive()); } } catch(Exception e){ throw e; } return query; } private Sort getLuceneSort(SortObject sort) { if (sort == null) { return null; } QuerySortField[] fields = sort.getSortFields(); if (fields == null) { return null; } final int length = fields.length; SortField[] sortFields = new SortField[length]; for (int i = 0; i < length; i++) { String s = fields[i].getField(); if (s == null) { return null; } sortFields[i] = new SortField(s, SortField.STRING, !fields[i].isAscending()); } return new Sort(sortFields); } public Object luceneDocumentToNode(Object d, Scriptable global, final int mode, final boolean executedInTransactor) throws Exception { Document doc = (Document)d; NodeManager nmgr = app.getNodeManager(); DbMapping dbmap = this.app.getDbMapping(doc.getField(LuceneManager.PROTOTYPE).stringValue()); Key key = new DbKey(dbmap, doc.getField(LuceneManager.ID).stringValue(), mode); axiom.objectmodel.db.Node node = null; if (executedInTransactor) { node = nmgr.getNodeFromTransaction(key); } if (node == null) { node = nmgr.getNodeFromCache(key); if (node == null) { node = nmgr.getNode(key); if (executedInTransactor) { node = nmgr.conditionalCacheUpdate(node); } } if (executedInTransactor) { nmgr.conditionalNodeVisit(key, node); } } Object ret = null; if (node != null) { if (global != null) { ret = Context.toObject(node, global); } else { ret = node; } } return ret; } private Query getFilterQuery(FilterObject fobj, ResourceProperties props) throws Exception { final LuceneManager lmgr = this.lmgr; final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD; final BooleanClause.Occur MUST = BooleanClause.Occur.MUST; Query query = null; try { BooleanQuery primary = null; Iterator<String> iter = fobj.getKeys().iterator(); while (iter.hasNext()) { if (primary == null) { primary = new BooleanQuery(); } BooleanQuery sub_query = new BooleanQuery(); String key = iter.next().toString(); Object[] values = (Object[]) fobj.getValueForKey(key); final int vallen = values.length; if (vallen > 1) { for (int i = 0; i < vallen; i++) { if (app.debug()) app.logEvent("key: " + key + ", value: " + QueryParser.escape((String)values[i])); Query q = createLuceneQuery(key, QueryParser.escape((String)values[i]), lmgr, props); if (app.debug()) app.logEvent("q.toString(): " + q.toString()); sub_query.add(q, SHOULD); } primary.add(sub_query, MUST); } else if (vallen == 1) { if (app.debug()) app.logEvent("key: " + key + ", value: " + QueryParser.escape((String)values[0])); Query q = createLuceneQuery(key, QueryParser.escape((String)values[0]), lmgr, props); if (app.debug()) app.logEvent("q.toString(): " + q.toString()); primary.add(q, MUST); } } query = primary; } catch (Exception ex) { return null; } return query; } private Query getNativeQuery(NativeFilterObject nfobj) throws Exception { Query query = null; String qstr = nfobj.getNativeQuery(); Analyzer analyzer = nfobj.getAnalyzer(); try { if (analyzer != null) { QueryParser qp = new QueryParser(LuceneManager.ID, analyzer); query = qp.parse(qstr); qp = null; } else { synchronized (this.qparser) { query = this.qparser.parse(qstr); } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "getNativeQuery") + "Could not parse the input query.\n\t query = " + qstr, ex); throw ex; } return query; } private Query getSearchFilterQuery(SearchFilterObject sfobj, ResourceProperties props) throws Exception { BooleanQuery primary = null; Query query = null; Analyzer analyzer = sfobj.getAnalyzer(); SearchProfile profile = sfobj.getSearchProfile(); Object filter = sfobj.getFilter(); String qstr = filter instanceof String ? (String)filter : new String(); BooleanClause.Occur OCCUR = BooleanClause.Occur.MUST; if (profile.operator == null) { OCCUR = BooleanClause.Occur.MUST; } else if(profile.operator.equalsIgnoreCase("and")){ OCCUR = BooleanClause.Occur.MUST; } else if(profile.operator.equalsIgnoreCase("or")) { OCCUR = BooleanClause.Occur.SHOULD; } else if(profile.operator.equalsIgnoreCase("not")) { OCCUR = BooleanClause.Occur.MUST_NOT; } try { if (analyzer != null) { if (primary == null) { primary = new BooleanQuery(); } QueryParser qp = new QueryParser(LuceneManager.ID, analyzer); if(profile != null && !qstr.isEmpty()) { BooleanQuery sub_query = new BooleanQuery(); for (int i = 0; i < profile.fields.length; i++) { Query q = qp.parse(profile.fields[i] + ":" + qstr); q.setBoost(profile.boosts[i]); sub_query.add(q, BooleanClause.Occur.SHOULD); } primary.add(sub_query, BooleanClause.Occur.MUST); sub_query = null; } String profileFilter = profile.filter; if(profileFilter != null && profileFilter.startsWith("{") && profileFilter.endsWith("}")){ profileFilter = "new Filter(" + profileFilter + ")"; } Context cx = Context.getCurrentContext(); Object result = null; if (profileFilter != null) { result = cx.evaluateString(RhinoEngine.getRhinoCore(app).getGlobal(), profileFilter, "eval", 1, null); } IFilter spfilter = null; if (result != null) { spfilter = QueryBean.getFilterFromObject(result); } Query q = null; if (spfilter instanceof FilterObject) { q = getFilterQuery((FilterObject) spfilter, props); } else if (spfilter instanceof NativeFilterObject) { q = getNativeQuery((NativeFilterObject) spfilter); } else if (spfilter instanceof OpFilterObject) { q = parseOpFilter((OpFilterObject) spfilter, props); } else if (spfilter instanceof RangeFilterObject) { q = getRangeQuery((RangeFilterObject)spfilter, props); } else if (spfilter instanceof SearchFilterObject) { q = getSearchFilterQuery((SearchFilterObject)spfilter, props); } if(q != null){ primary.add(q, OCCUR); } query = primary; qp = null; } else { synchronized (this.qparser) { query = this.qparser.parse(qstr); } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "getSearchFilterQuery") + "Could not parse the input query.\n\t query = " + qstr, ex); throw ex; } return query; } private Query _getNativeQuery(String qstr, String analyzer) throws Exception { Query query = null; try { if (analyzer != null) { QueryParser qp = new QueryParser(LuceneManager.ID, this.lmgr.getAnalyzer(analyzer)); query = qp.parse(qstr); qp = null; } else { synchronized (this.qparser) { query = this.qparser.parse(qstr); } } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "_getNativeQuery") + "Could not parse the input query.\n\t query = " + qstr, ex); throw ex; } return query; } private Query parseOpFilter(OpFilterObject opf, ResourceProperties props) throws Exception { IFilter[] filters = opf.getFilters(); //want to return all the results if no filters are specified if (filters == null || filters.length == 0) { return null; } BooleanQuery bq = new BooleanQuery(); BooleanClause.Occur OCCUR = BooleanClause.Occur.MUST; // default is AND if (opf instanceof AndFilterObject) { OCCUR = BooleanClause.Occur.MUST; } else if (opf instanceof OrFilterObject) { OCCUR = BooleanClause.Occur.SHOULD; } else if (opf instanceof NotFilterObject) { OCCUR = BooleanClause.Occur.MUST_NOT; } final int length = filters.length; for (int i = 0; i < length; i++) { Query q = null; if (filters[i] instanceof FilterObject) { try { q = getFilterQuery((FilterObject) filters[i], props); } catch (Exception ex) { q = null; } } else if (filters[i] instanceof NativeFilterObject) { q = getNativeQuery((NativeFilterObject) filters[i]); } else if (filters[i] instanceof OpFilterObject) { try { q = parseOpFilter((OpFilterObject) filters[i], props); } catch (Exception e) { q = null; } } else if (filters[i] instanceof RangeFilterObject) { q = getRangeQuery((RangeFilterObject)filters[i], props); } else if (filters[i] instanceof SearchFilterObject) { q = getSearchFilterQuery((SearchFilterObject)filters[i], props); } if (q != null) { if (OCCUR == BooleanClause.Occur.MUST_NOT) { // every NOT query in lucene must be proceeded with a MUST have query, // since every document in the index will have IDENTITY set to 1, we // precede the NOT query with something we know every document will have, // that is, IDENTITY set to 1. (its a hack, i know) bq.add(new TermQuery(new Term(LuceneManager.IDENTITY, "1")), BooleanClause.Occur.MUST); } bq.add(q, OCCUR); } } return bq; } private Query createLuceneQuery(final String key, final Object value, final LuceneManager lmgr, ResourceProperties props) throws Exception { final int type = LuceneManager.stringToType((String) props.get(key + ".type")); final String idx = props.getProperty(key + ".index"); Query q = null; if ((idx == null || LuceneManager.TOKENIZED_INDEX.equalsIgnoreCase(idx)) && type == IProperty.STRING && !key.startsWith("_")) { q = _getNativeQuery(key + ":\"" + (String) value + "\"", (String) props.getProperty(key + ".analyzer")); } else { q = _createLuceneQuery(key, value, lmgr, type); } return q; } private Query _createLuceneQuery(final String key, final Object value, final LuceneManager lmgr, final int type) throws Exception { if (value == null) { throw new Exception("QueryBean.createQuery(): The value specified to the query is null"); } String normalized_value = null; switch (type) { case IProperty.BOOLEAN: normalized_value = lmgr.serializeBoolean(Boolean.parseBoolean(value.toString())); break; case IProperty.DATE: if (value instanceof java.util.Date) { normalized_value = lmgr.serializeDate((java.util.Date) value); } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String class_name = s.getClassName(); if ("Date".equals(class_name)) { normalized_value = lmgr.serializeDate(new java.util.Date( (long) ScriptRuntime.toNumber(s))); } } break; case IProperty.TIME: if (value instanceof java.util.Date) { normalized_value = lmgr.serializeTime((java.util.Date) value); } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String class_name = s.getClassName(); if ("Date".equals(class_name)) { normalized_value = lmgr.serializeTime(new java.util.Date( (long) ScriptRuntime.toNumber(s))); } } break; case IProperty.TIMESTAMP: if (value instanceof java.util.Date) { normalized_value = lmgr .serializeTimestamp((java.util.Date) value); } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String class_name = s.getClassName(); if ("Date".equals(class_name)) { normalized_value = lmgr .serializeTimestamp(new java.util.Date( (long) ScriptRuntime.toNumber(s))); } } break; case IProperty.FLOAT: normalized_value = lmgr.serializeFloat(Double.parseDouble(value .toString())); break; case IProperty.SMALLFLOAT: normalized_value = lmgr.serializeSmallFloat(Double .parseDouble(value.toString())); break; case IProperty.INTEGER: normalized_value = lmgr.serializeInt(Long.parseLong(value .toString())); break; case IProperty.SMALLINT: normalized_value = lmgr.serializeSmallInt(Long.parseLong(value .toString())); break; case IProperty.STRING: if (value instanceof Number && key.equals(LuceneManager.ID)) { normalized_value = serializeNumber((Number) value); } else if (value instanceof String) { normalized_value = (String) value; } else if (value instanceof Scriptable && "String".equalsIgnoreCase(((Scriptable) value).getClassName())) { normalized_value = ScriptRuntime.toString(value); } break; case IProperty.REFERENCE: case IProperty.MULTI_VALUE: if (value instanceof String) { normalized_value = (String) value; } else if (value instanceof Scriptable && "String".equalsIgnoreCase(((Scriptable) value).getClassName())) { normalized_value = ScriptRuntime.toString(value); } else if (value instanceof AxiomObject) { normalized_value = ((AxiomObject) value).getNode().getID(); } else if (value instanceof INode) { normalized_value = ((INode) value).getID(); } break; default: break; } if (normalized_value == null) { throw new Exception("QueryBean.createQuery(): Unable to normalize the value " + value); } Query q = null; if (type == IProperty.STRING && (normalized_value.indexOf("*") > -1 || normalized_value .indexOf("?") > -1)) { // might be a wildcard query, so use the query parser to parse the query synchronized (this.qparser) { q = this.qparser.parse(key + ": " + normalized_value); } } else { q = new TermQuery(new Term(key, normalized_value)); } return q; } private String serializeNumber(Number number) { String str = null; if (number.doubleValue() - (double) number.longValue() != 0.0) { str = number.toString(); } else { Long l = new Long(number.longValue()); str = l.toString(); } return str; } private Filter getQueryFilter(IFilter filter, ResourceProperties props) { BooleanQuery query = new BooleanQuery(); try { this.parseFilterIntoQuery(filter, query, props); SimpleQueryFilter sqf = (SimpleQueryFilter) this.cache.get(query); if (sqf == null && filter.isCached()) { sqf = new SimpleQueryFilter(query); this.cache.put(query, sqf); } return sqf; } catch (Exception ex) { } return null; } public class LuceneQueryParams { public Query query; public Sort sort; public int max_results; public IndexSearcher searcher; public ResourceProperties rprops; } private ArrayList getPaths(Object options) throws Exception{ try { ArrayList opaths = new ArrayList(); if (options != null) { Object value = null; if (options instanceof Scriptable) { value = ((Scriptable) options).get(PATH_FIELD, (Scriptable) options); } else if (options instanceof Map) { value = ((Map) options).get(PATH_FIELD); } if (value != null) { if (value instanceof Scriptable) { String className = ((Scriptable) value).getClassName(); if (className.equals("String")) { opaths.add(ScriptRuntime.toString(value)); } else if (className.equals("Array")) { Scriptable arr = (Scriptable) value; final int arrlen = arr.getIds().length; for (int j = 0; j < arrlen; j++) { opaths.add(arr.get(j, arr)); } } } else if (value instanceof String) { opaths.add(value); } } } return opaths; } catch(Exception e){ throw e; } } private ArrayList<String> getAllPrototypes(ArrayList<String> prototypes) { ArrayList<String> newPrototypes = new ArrayList<String>(prototypes); for (Object p : prototypes) { String proto = p.toString(); newPrototypes.add(proto); newPrototypes.addAll(this.getSubPrototypes(proto)); } return newPrototypes; } private ArrayList<String> getSubPrototypes(String proto) { ArrayList<String> newPrototypes = new ArrayList<String>(); Prototype prototype = app.typemgr.getPrototype(proto); if (prototype != null) { for (Prototype subprototype : prototype.getChildPrototypes()) { String subproto = subprototype.getName(); newPrototypes.add(subproto); newPrototypes.addAll(this.getSubPrototypes(subproto)); } } return newPrototypes; } private boolean extendPrototypes(Object options) throws Exception { try { boolean ext = false; if (options != null) { Object value = null; if (options instanceof Scriptable) { value = ((Scriptable) options).get(POLYMORPHIC_FIELD, (Scriptable) options); } else if (options instanceof Map) { value = ((Map) options).get(POLYMORPHIC_FIELD); } if (value != null) { if (value instanceof Scriptable) { ext = ScriptRuntime.toBoolean(value); } else if (value instanceof Boolean) { ext = ((Boolean) value).booleanValue(); } else if (value instanceof String) { ext = Boolean.parseBoolean((String) value); } } } return ext; } catch (Exception e) { throw e; } } public Object hits(ArrayList prototypes, IFilter filter, Object options) throws Exception { Object results = null; int maxResults = getMaxResults((Scriptable)options); SortObject sort = getSortObject((Scriptable)options); int _layer = getLayer((Scriptable) options); boolean ext = extendPrototypes((Scriptable) options); if (ext) { prototypes = getAllPrototypes(prototypes); } ArrayList opaths = getPaths((Scriptable)options); IndexSearcher searcher = this.lmgr.getIndexSearcher(); LuceneQueryParams params = new LuceneQueryParams(); params.searcher = searcher; Object hits = luceneHits(prototypes, filter, sort, maxResults, opaths, searcher, params, _layer); HashSet idSet = null; final int opaths_size; if ((opaths_size = opaths.size()) > 0) { for (int i = 0; i < opaths_size; i++) { String path = (String) opaths.get(i); ArrayList ids; if (path.endsWith("/*")) { path = path.substring(0, path.length() - 1); INode n = (INode) AxiomObject.traverse(path, this.app); ids = this.lmgr.getChildrenIds(n); } else { if (path.endsWith("/**")) { path = path.substring(0, path.length() - 2); } RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); int layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } ids = this.pindxr.getIds(path, layer); } if (idSet == null) { idSet = new HashSet(ids); } else { idSet.addAll(ids); } } } hits = hitsToKeys(hits, params, _layer, idSet); final Object[] args = { this.core, this, hits, params, this.lmgr }; results = Context.getCurrentContext().newObject(this.core.getScope(), "LuceneHits", args); return results; } public Object filterHits(Object prototype, Object filter, Object params) throws Exception { IFilter theFilter = QueryBean.getFilterFromObject(filter); LuceneQueryParams lparams = (LuceneQueryParams)params; if (theFilter == null) { throw new Exception("LuceneQueryDispatcher.filterHits(): Could not determine the query filter."); } Object results = null; ArrayList embeddedDbProtos = new ArrayList(); QueryBean.setPrototypeArrays(this.app, prototype, embeddedDbProtos, new ArrayList(), new HashMap<String, ArrayList>()); Object hits = luceneHits(embeddedDbProtos, theFilter, lparams); hits = hitsToKeys(hits, lparams, -1, null); final Object[] args = { this.core, this, hits, params, this.lmgr }; results = Context.getCurrentContext().newObject(this.core.getScope(), "LuceneHits", args); return results; } public Object documentToNode(Object d, Scriptable global, final int mode, final boolean executedInTransactor) throws Exception { return this.luceneDocumentToNode(d, global, mode, executedInTransactor); } public int filterHitsLength(Object prototype, Object filter, LuceneQueryParams params) throws Exception { IFilter theFilter = QueryBean.getFilterFromObject(filter); if (theFilter == null) { throw new Exception("LuceneQueryDispatcher.filterHits(): Could not determine the query filter."); } ArrayList embeddedDbProtos = new ArrayList(); QueryBean.setPrototypeArrays(this.app, prototype, embeddedDbProtos, new ArrayList(), new HashMap<String, ArrayList>()); Object hits = luceneHits(embeddedDbProtos, theFilter, params); return hitsToKeys(hits, params, -1, null).size(); } public Scriptable getReferences(ArrayList sources, ArrayList targets, final int mode) throws Exception { long start = System.currentTimeMillis(); final GlobalObject global = this.core != null ? this.core.global : null; final Application app = this.app; final String ID_FIELD = LuceneManager.ID; final String REF_LIST = LuceneManager.REF_LIST_FIELD; final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD; final BooleanClause.Occur MUST = BooleanClause.Occur.MUST; final int sources_size = sources.size(); final int targets_size = targets.size(); ArrayList results = new ArrayList(); BooleanQuery sub_query = new BooleanQuery(); for (int i = 0; i < sources_size; i++) { sub_query.add(new TermQuery(new Term(ID_FIELD, sources.get(i).toString())), SHOULD); } BooleanQuery primary = new BooleanQuery(); primary.add(sub_query, MUST); sub_query = new BooleanQuery(); for (int i = 0; i < targets_size; i++) { sub_query.add(new TermQuery(new Term(REF_LIST, targets.get(i).toString())), SHOULD); } primary.add(sub_query, MUST); IndexSearcher searcher = null; try { if (app.debug()){ app.logEvent("running query "+primary); } searcher = this.lmgr.getIndexSearcher(); Hits hits = searcher.search(primary); HashSet target_set = new HashSet(targets); luceneResultsToReferences(hits, results, target_set, mode); } catch (Exception ex) { results.clear(); app.logError(ErrorReporter.errorMsg(this.getClass(), "getReferences") + "Occured on query = " + primary, ex); } finally { this.lmgr.releaseIndexSearcher(searcher); } if(app.debug()){ long time = System.currentTimeMillis() - start; app.logEvent("... took "+(time/1000.0)+" seconds\n ------"); } return Context.getCurrentContext().newArray(global, results.toArray()); } private ArrayList hitsToKeys(Object hits, LuceneQueryParams params, int _layer, HashSet ids) throws IOException { ArrayList keys = new ArrayList(); RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); int layer; if (_layer != -1) { layer = _layer; } else { layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } } if (hits instanceof Hits) { Hits h = (Hits) hits; final int length = h.length(); HashSet retrieved = new HashSet(); for (int i = 0; i < length; i++) { Document doc = h.doc(i); String id = doc.get(LuceneManager.ID); String prototype = doc.get(LuceneManager.PROTOTYPE); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { // if (id == null || retrieved.contains(id)) { continue; } Key key = new DbKey(this.app.getDbMapping(prototype), id, layer); keys.add(key); retrieved.add(id); } } else if (hits instanceof TopDocs) { TopDocs td = (TopDocs) hits; final int length = td.scoreDocs.length; HashSet retrieved = new HashSet(); IndexSearcher searcher = params.searcher; for (int i = 0; i < length; i++) { Document doc = searcher.doc(td.scoreDocs[i].doc); String id = doc.get(LuceneManager.ID); String prototype = doc.get(LuceneManager.PROTOTYPE); if (id == null || (ids != null && !ids.contains(id)) || retrieved.contains(id)) { // if (id == null || retrieved.contains(id)) { continue; } Key key = new DbKey(this.app.getDbMapping(prototype), id, layer); keys.add(key); retrieved.add(id); } } return keys; } private void luceneResultsToReferences(final Hits hits, final ArrayList results, final HashSet targets, final int mode) throws Exception { final int hitslen = hits.length(); final String ID = LuceneManager.ID; final String REF_FIELD = LuceneManager.REF_LIST_FIELD; final String DELIM = LuceneManager.NULL_DELIM; final Context cx = Context.getCurrentContext(); final GlobalObject global = this.core != null ? this.core.global : null; if (global == null) { return; } for (int i = 0; i < hitslen; i++) { Document d = hits.doc(i); Field f = d.getField(ID); if (f == null) { continue; } final String source_id = f.stringValue(); Field[] ref_fields = d.getFields(REF_FIELD); int ref_length = ref_fields != null ? ref_fields.length : 0; for (int j = 0; j < ref_length; j++) { String[] values = ref_fields[j].stringValue().split(DELIM); if (targets.contains(values[0])) { final Object[] args = { new DbKey(null, values[0], mode) }; Object o = cx.newObject(global, "Reference", args); Reference relobj = (Reference) o; relobj.setSourceKey(new DbKey(null, source_id, mode)); relobj.setSourceProperty(values[1]); if (values.length > 2) { relobj.setSourceIndex(Integer.parseInt(values[2])); if (values.length > 3) { relobj.setSourceXPath(values[3]); } } results.add(relobj); } } } } public Object getDirectionalNodesFor(Object o, int direction, Object prototypes, Object filter, Object options) throws Exception { final GlobalObject global = this.core != null ? this.core.global : null; final Application app = this.app; final LuceneManager lmgr = this.lmgr; INode node = null; int objLayer = -1; ArrayList objects = null; if (o instanceof AxiomObject) { objects = new ArrayList(); node = ((AxiomObject) o).node; if (node != null) { objects.add(node.getID()); if (node instanceof Node) { objLayer = ((Node) node).getLayer(); } } } else if (o instanceof INode) { objects = new ArrayList(); node = (INode) o; objects.add(node.getID()); if (node instanceof Node) { objLayer = ((Node) node).getLayer(); } } else if (o instanceof String) { objects = this.getNodesByPath((String) o); } final int size = objects == null ? 0 : objects.size(); if (size == 0) { if (global != null) { return Context.getCurrentContext().newArray(global, new Object[0]); } else { return new Object[0]; } } int _layer = getLayer(options); final int mode; if (_layer > -1) { mode = _layer; } else if (objLayer > -1) { mode = objLayer; } else { RequestEvaluator req_eval = app.getCurrentRequestEvaluator(); if (req_eval != null) { mode = req_eval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } int maxResults = Integer.MAX_VALUE; try { maxResults = getMaxResults(options); } catch (Exception e) { maxResults = Integer.MAX_VALUE; } if (maxResults < 0) { maxResults = Integer.MAX_VALUE; } ArrayList protos = new ArrayList(); if (prototypes != null && prototypes != Scriptable.NOT_FOUND) { QueryBean.setPrototypeArrays(this.app, prototypes, protos, new ArrayList(), new HashMap<String, ArrayList>()); } IFilter theFilter = QueryBean.getFilterFromObject(filter); BooleanQuery primary = new BooleanQuery(); ResourceProperties props = QueryBean.getResourceProperties(this.app, protos); parseFilterIntoQuery(theFilter, primary, props); NodeManager nmgr = app.getNodeManager(); ArrayList node_list = new ArrayList(); HashSet encountered_keys = new HashSet(); int list_count = 0; for (int i = 0; i < size; i++) { if (node_list.size() >= maxResults) { break; } Key[] node_keys = null; try { node_keys = (direction == 0 ? lmgr.getTargetNodeIds(objects.get(i).toString(), mode, protos, primary, getLuceneSort(getSortObject(options))) : lmgr.getSourceNodeIds(objects.get(i).toString(), mode, protos, primary, getLuceneSort(getSortObject(options)))); } catch (Exception ex) { node_keys = null; app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesFor") + "Could not retrieve " + (direction == 0 ? "target" : "source") + " nodes", ex); } if (node_keys == null) { continue; } int length = node_keys.length; for (int j = 0; j < length; j++) { if (encountered_keys.contains(node_keys[j])) { continue; } Node curr = null; try { curr = nmgr.getNode(node_keys[j]); } catch (Exception ex) { curr = null; app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesFor") + "Could not get node '" + node_keys[j].getID() + "'.", ex); } if (curr != null) { if (global != null) { node_list.add(Context.toObject(curr, global)); } else { node_list.add(curr); } if (node_list.size() >= maxResults) { break; } encountered_keys.add(node_keys[j]); } } } if (global != null) { return Context.getCurrentContext().newArray(core.global, node_list.toArray()); } else { return node_list.toArray(); } } public ArrayList getNodesByPath(String path) { ArrayList objects; int layer = DbKey.LIVE_LAYER; RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); if (reqeval != null) { layer = reqeval.getLayer(); } if (path.endsWith(RECURSE_PATH_MARKER)) { objects = this.pindxr.getIds(path.substring(0, path.indexOf(RECURSE_PATH_MARKER)), layer); } else { objects = new ArrayList(); objects.add(this.pindxr.getId(path, layer)); } return objects; } public int getDirectionalNodesForCount(Object o, int direction, Object prototypes, Object filter, Object options) throws Exception { final Application app = this.app; final LuceneManager lmgr = this.lmgr; INode node = null; int objLayer = -1; ArrayList objects = null; if (o instanceof AxiomObject) { objects = new ArrayList(); node = ((AxiomObject) o).node; if (node != null) { objects.add(node.getID()); if (node instanceof Node) { objLayer = ((Node) node).getLayer(); } } } else if (o instanceof INode) { objects = new ArrayList(); node = (INode) o; objects.add(node.getID()); if (node instanceof Node) { objLayer = ((Node) node).getLayer(); } } else if (o instanceof String) { objects = this.getNodesByPath((String) o); } final int size = objects == null ? 0 : objects.size(); if (size == 0) { return 0; } int _layer = getLayer((Scriptable) options); final int mode; if (_layer > -1) { mode = _layer; } else if (objLayer > -1) { mode = objLayer; } else { RequestEvaluator req_eval = app.getCurrentRequestEvaluator(); if (req_eval != null) { mode = req_eval.getLayer(); } else { mode = DbKey.LIVE_LAYER; } } int maxResults = Integer.MAX_VALUE; try { maxResults = getMaxResults(options); } catch (Exception e) { maxResults = Integer.MAX_VALUE; } if (maxResults < 0) { maxResults = Integer.MAX_VALUE; } ArrayList protos = new ArrayList(); if (prototypes != null && prototypes != Scriptable.NOT_FOUND) { QueryBean.setPrototypeArrays(this.app, prototypes, protos, new ArrayList(), new HashMap<String, ArrayList>()); } IFilter theFilter = QueryBean.getFilterFromObject(filter); BooleanQuery primary = new BooleanQuery(); ResourceProperties props = QueryBean.getResourceProperties(this.app, protos); parseFilterIntoQuery(theFilter, primary, props); int count = 0; for (int i = 0; i < size; i++) { Key[] node_keys = null; try { node_keys = (direction == 0 ? lmgr.getTargetNodeIds(objects.get(i).toString(), mode, protos, primary, getLuceneSort(getSortObject(options))) : lmgr.getSourceNodeIds(objects.get(i).toString(), mode, protos, primary, getLuceneSort(getSortObject(options)))); } catch (Exception ex) { ex.printStackTrace(); node_keys = null; app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesForCount") + "Could not retrieve " + (direction == 0 ? "target" : "source") + " nodes", ex); } if (node_keys == null) { continue; } count += node_keys.length; if (count >= maxResults) { count = maxResults; break; } } return count; } public int getHitCount(ArrayList prototypes, IFilter filter, Object options) throws Exception { ArrayList opaths = getPaths(options); IndexSearcher searcher = null; int count = 0; try { int maxResults = getMaxResults((Scriptable)options); boolean unique = getUnique((Scriptable)options); int _layer = getLayer((Scriptable) options); searcher = this.lmgr.getIndexSearcher(); Object hits = this.luceneHits(prototypes, filter, null, maxResults, opaths, searcher, null, _layer); if (hits == null || hits instanceof Boolean) { return 0; } HashSet idSet = null; final int opaths_size; if ((opaths_size = opaths.size()) > 0) { for (int i = 0; i < opaths_size; i++) { String path = (String) opaths.get(i); ArrayList ids; if (path.endsWith("/*")) { path = path.substring(0, path.length() - 1); INode n = (INode) AxiomObject.traverse(path, this.app); ids = this.lmgr.getChildrenIds(n); } else { if (path.endsWith("/**")) { path = path.substring(0, path.length() - 2); } int layer; if (_layer != -1) { layer = _layer; } else { RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); layer = DbKey.LIVE_LAYER; if (reqeval != null) { layer = reqeval.getLayer(); } } ids = this.pindxr.getIds(path, layer); } if (idSet == null) { idSet = new HashSet(ids); } else { idSet.addAll(ids); } } } if (hits instanceof Hits) { count = luceneResultsToNodesLength((Hits) hits, maxResults, idSet, _layer); } else if (hits instanceof TopDocs) { count = luceneResultsToNodesLength((TopDocs) hits, searcher, maxResults, idSet, _layer); } } catch (Exception ex) { app.logError(ErrorReporter.errorMsg(this.getClass(), "getHitCount"), ex); } finally { this.lmgr.releaseIndexSearcher(searcher); } return count; } public ArrayList getVersionFields(Object obj, Object fields, ArrayList prototypes, IFilter filter, Object options) throws Exception{ String id = null; if (obj instanceof String) { id = (String) obj; } else if(obj instanceof INode) { id = ((INode)obj).getID(); } else if (obj instanceof Scriptable) { id = ScriptRuntime.toString(obj); } else { id = obj.toString(); } Scriptable idfilter = Context.getCurrentContext().newObject(this.core.getScope()); idfilter.put(LuceneManager.ID, idfilter, id); IFilter newFilter = AndFilterObject.filterObjCtor(null, new Object[]{filter, idfilter}, null, false); SortObject sort = getSortObject((Scriptable)options); ArrayList opaths = getPaths((Scriptable)options); int _layer = getLayer((Scriptable) options); RequestEvaluator reqeval = this.app.getCurrentRequestEvaluator(); _layer = (_layer == -1) ? (reqeval != null) ? reqeval.getLayer() : DbKey.LIVE_LAYER : _layer; int maxResults = getMaxResults((Scriptable)options); IndexSearcher searcher = new IndexSearcher(this.lmgr.getDirectory(), true); Object hits = this.luceneHits(prototypes, newFilter, sort, maxResults, opaths, searcher, null, _layer); ArrayList<Scriptable> versions = new ArrayList<Scriptable>(); if(hits != null){ int hitslength = hits instanceof Hits ? ((Hits)hits).length() : ((TopDocs)hits).scoreDocs.length; if (hitslength > 0) { if (maxResults < 0) { maxResults = hitslength; } } for (int i = 0, count = 0; i < hitslength && count < maxResults; i++) { Document doc = hits instanceof Hits ? ((Hits)hits).doc(i) : searcher.doc(((TopDocs)hits).scoreDocs[i].doc); if(doc != null){ ArrayList<String> _fields = new ArrayList<String>(); if(fields instanceof String){ _fields.add((String)fields); } else if (fields instanceof Scriptable){ String className = ((Scriptable) fields).getClassName(); if (className.equals("String")) { _fields.add(fields.toString()); } else if (className.equals("Array")) { Scriptable arr = (Scriptable) fields; final int arrlen = arr.getIds().length; for (int j = 0; j < arrlen; j++) { _fields.add(arr.get(j, arr).toString()); } } else{ _fields.add(fields.toString()); } } Scriptable version = Context.getCurrentContext().newObject(this.core.getScope()); for(int j = 0; j < _fields.size(); j++){ String field = _fields.get(j); Object value = doc.get(field) != null ? doc.get(field): Undefined.instance; version.put(field, version, value); } count++; versions.add(version); } } } return versions; } }
Revert "Added some debugging to queries based on FilterObject. Also added escaping of the content from the query though still has the old behavior of stripping out those chars." This reverts commit 17d625bee73654d6303ae41fd1aa313c8ccd07c5.
src/java/axiom/scripting/rhino/LuceneQueryDispatcher.java
Revert "Added some debugging to queries based on FilterObject. Also added escaping of the content from the query though still has the old behavior of stripping out those chars."
Java
agpl-3.0
84c73f4ce45c15a7c77b37c5fb20b1a955e385c3
0
bisq-network/exchange,bisq-network/exchange,bitsquare/bitsquare,bitsquare/bitsquare
/* * This file is part of bisq. * * bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.desktop.components; import bisq.desktop.Navigation; import bisq.desktop.common.view.View; import com.jfoenix.controls.JFXButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.geometry.Pos; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; @Slf4j public class MenuItem extends JFXButton implements Toggle { private final Navigation navigation; private final ObjectProperty<ToggleGroup> toggleGroupProperty = new SimpleObjectProperty<>(); private final Class<? extends View> viewClass; private final List<Class<? extends View>> baseNavPath; private final BooleanProperty selectedProperty = new SimpleBooleanProperty(); private final ChangeListener<Toggle> listener; public MenuItem(Navigation navigation, ToggleGroup toggleGroup, String title, Class<? extends View> viewClass, List<Class<? extends View>> baseNavPath) { this.navigation = navigation; this.viewClass = viewClass; this.baseNavPath = baseNavPath; setLabelText(title); setPrefHeight(40); setPrefWidth(240); setAlignment(Pos.CENTER_LEFT); toggleGroupProperty.set(toggleGroup); toggleGroup.getToggles().add(this); setUserData(getUid()); listener = (observable, oldValue, newValue) -> { Object userData = newValue.getUserData(); String uid = getUid(); if (newValue.isSelected() && userData != null && userData.equals(uid)) { getStyleClass().add("action-button"); } else { getStyleClass().remove("action-button"); } }; } /////////////////////////////////////////////////////////////////////////////////////////// // Toggle implementation /////////////////////////////////////////////////////////////////////////////////////////// @Override public ToggleGroup getToggleGroup() { return toggleGroupProperty.get(); } @Override public void setToggleGroup(ToggleGroup toggleGroup) { toggleGroupProperty.set(toggleGroup); } @Override public ObjectProperty<ToggleGroup> toggleGroupProperty() { return toggleGroupProperty; } @Override public boolean isSelected() { return selectedProperty.get(); } @Override public BooleanProperty selectedProperty() { return selectedProperty; } @Override public void setSelected(boolean selected) { selectedProperty.set(selected); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// public void activate() { setOnAction((event) -> navigation.navigateTo(getNavPathClasses())); toggleGroupProperty.get().selectedToggleProperty().addListener(listener); } public void deactivate() { setOnAction(null); toggleGroupProperty.get().selectedToggleProperty().removeListener(listener); } public void setLabelText(String value) { setText(value.toUpperCase()); } /////////////////////////////////////////////////////////////////////////////////////////// // Private /////////////////////////////////////////////////////////////////////////////////////////// @NotNull private Class<? extends View>[] getNavPathClasses() { List<Class<? extends View>> list = new ArrayList<>(baseNavPath); list.add(viewClass); //noinspection unchecked Class<? extends View>[] array = new Class[list.size()]; list.toArray(array); return array; } private String getUid() { return viewClass.getName(); } }
desktop/src/main/java/bisq/desktop/components/MenuItem.java
/* * This file is part of bisq. * * bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.desktop.components; import bisq.desktop.Navigation; import bisq.desktop.common.view.View; import com.jfoenix.controls.JFXButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.geometry.Pos; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; @Slf4j public class MenuItem extends JFXButton implements Toggle { private final Navigation navigation; private final ObjectProperty<ToggleGroup> toggleGroupProperty = new SimpleObjectProperty<>(); private final Class<? extends View> viewClass; private final List<Class<? extends View>> baseNavPath; private final BooleanProperty selectedProperty = new SimpleBooleanProperty(); private final ChangeListener<Toggle> listener; public MenuItem(Navigation navigation, ToggleGroup toggleGroup, String title, Class<? extends View> viewClass, List<Class<? extends View>> baseNavPath) { this.navigation = navigation; this.viewClass = viewClass; this.baseNavPath = baseNavPath; setLabelText(title.toUpperCase()); setPrefHeight(40); setPrefWidth(240); setAlignment(Pos.CENTER_LEFT); toggleGroupProperty.set(toggleGroup); toggleGroup.getToggles().add(this); setUserData(getUid()); listener = (observable, oldValue, newValue) -> { Object userData = newValue.getUserData(); String uid = getUid(); if (newValue.isSelected() && userData != null && userData.equals(uid)) { getStyleClass().add("action-button"); } else { getStyleClass().remove("action-button"); } }; } /////////////////////////////////////////////////////////////////////////////////////////// // Toggle implementation /////////////////////////////////////////////////////////////////////////////////////////// @Override public ToggleGroup getToggleGroup() { return toggleGroupProperty.get(); } @Override public void setToggleGroup(ToggleGroup toggleGroup) { toggleGroupProperty.set(toggleGroup); } @Override public ObjectProperty<ToggleGroup> toggleGroupProperty() { return toggleGroupProperty; } @Override public boolean isSelected() { return selectedProperty.get(); } @Override public BooleanProperty selectedProperty() { return selectedProperty; } @Override public void setSelected(boolean selected) { selectedProperty.set(selected); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// public void activate() { setOnAction((event) -> navigation.navigateTo(getNavPathClasses())); toggleGroupProperty.get().selectedToggleProperty().addListener(listener); } public void deactivate() { setOnAction(null); toggleGroupProperty.get().selectedToggleProperty().removeListener(listener); } public void setLabelText(String value) { setText(value.toUpperCase()); } /////////////////////////////////////////////////////////////////////////////////////////// // Private /////////////////////////////////////////////////////////////////////////////////////////// @NotNull private Class<? extends View>[] getNavPathClasses() { List<Class<? extends View>> list = new ArrayList<>(baseNavPath); list.add(viewClass); //noinspection unchecked Class<? extends View>[] array = new Class[list.size()]; list.toArray(array); return array; } private String getUid() { return viewClass.getName(); } }
Remove unnecessary uppercase
desktop/src/main/java/bisq/desktop/components/MenuItem.java
Remove unnecessary uppercase
Java
lgpl-2.1
51863aa73f73c404659a4a1366d25b49d1a7eb85
0
alkacon/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,gallardo/opencms-core,victos/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,serrapos/opencms-core,MenZil/opencms-core,serrapos/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,victos/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,victos/opencms-core,serrapos/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,victos/opencms-core,ggiudetti/opencms-core,mediaworx/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/main/CmsShell.java,v $ * Date : $Date: 2005/06/10 15:14:24 $ * Version: $Revision: 1.37 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2002 - 2005 Alkacon Software (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.main; import org.opencms.db.CmsUserSettings; import org.opencms.file.CmsObject; import org.opencms.i18n.CmsLocaleManager; import org.opencms.util.CmsPropertyUtils; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.StreamTokenizer; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import org.apache.commons.collections.ExtendedProperties; /** * A commad line interface to access OpenCms functions which * is used for the initial setup and also can be used to directly access the OpenCms * repository without the Workplace.<p> * * The CmsShell has direct access to all methods in the "command objects". * Currently the following classes are used as command objects: * {@link org.opencms.main.CmsShellCommands}, * {@link org.opencms.file.CmsRequestContext} and * {@link org.opencms.file.CmsObject}.<p> * * Only public methods in the command objects that use just supported data types * as parameters can be called from the shell. Supported data types are: * <code>String, CmsUUID, boolean, int, long, double, float</code>.<p> * * If a method name is ambiguous, i.e. the method name with the same numer of parameter exist * in more then one of the command objects, the method is only executed on the first matching object.<p> * * @author Alexander Kandzior ([email protected]) * @version $Revision: 1.37 $ * * @see org.opencms.main.CmsShellCommands * @see org.opencms.file.CmsRequestContext * @see org.opencms.file.CmsObject */ public class CmsShell { /** * Command object class.<p> */ private class CmsCommandObject { // The list of methods private Map m_methods; // The object to execute the methods on private Object m_object; /** * Creates a new command object.<p> * * @param object the object to execute the methods on */ protected CmsCommandObject(Object object) { m_object = object; initShellMethods(); } /** * Tries to execute a method for the provided parameters on this command object.<p> * * If methods with the same name and number of parameters exist in this command object, * the given parameters are tried to be converted from String to matching types.<p> * * @param command the command entered by the user in the shell * @param parameters the parameters entered by the user in the shell * @return true if a method was executed, false otherwise */ protected boolean executeMethod(String command, List parameters) { // build the method lookup String lookup = buildMethodLookup(command, parameters.size()); // try to look up the methods of this command object List possibleMethods = (List)m_methods.get(lookup); if (possibleMethods == null) { return false; } // a match for the mehod name was found, now try to figure out if the parameters are ok Method onlyStringMethod = null; Method foundMethod = null; Object[] params = null; Iterator i; // first check if there is one method with only has String parameters, make this the fallback i = possibleMethods.iterator(); while (i.hasNext()) { Method method = (Method)i.next(); Class[] clazz = method.getParameterTypes(); boolean onlyString = true; for (int j = 0; j < clazz.length; j++) { if (!(clazz[j].equals(String.class))) { onlyString = false; break; } } if (onlyString) { onlyStringMethod = method; break; } } // now check a method matches the provided parameters // if so, use this method, else continue searching i = possibleMethods.iterator(); while (i.hasNext()) { Method method = (Method)i.next(); if (method == onlyStringMethod) { // skip the String only signature because this would always match continue; } // now try to convert the parameters to the required types Class[] clazz = method.getParameterTypes(); Object[] converted = new Object[clazz.length]; boolean match = true; for (int j = 0; j < clazz.length; j++) { String value = (String)parameters.get(j); if (clazz[j].equals(String.class)) { // no conversion required for String converted[j] = value; } else if (clazz[j].equals(boolean.class)) { // try to convert to boolean if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) { converted[j] = Boolean.valueOf(value); } else { match = false; } } else if (clazz[j].equals(CmsUUID.class)) { // try to convert to CmsUUID try { converted[j] = new CmsUUID(value); } catch (NumberFormatException e) { match = false; } } else if (clazz[j].equals(int.class)) { // try to convert to int try { converted[j] = Integer.valueOf(value); } catch (NumberFormatException e) { match = false; } } else if (clazz[j].equals(long.class)) { // try to convert to long try { converted[j] = Long.valueOf(value); } catch (NumberFormatException e) { match = false; } } else if (clazz[j].equals(float.class)) { // try to convert to float try { converted[j] = Float.valueOf(value); } catch (NumberFormatException e) { match = false; } } else if (clazz[j].equals(double.class)) { // try to convert to double try { converted[j] = Double.valueOf(value); } catch (NumberFormatException e) { match = false; } } if (!match) { break; } } if (match) { // we found a matching method signature params = converted; foundMethod = method; break; } } if ((foundMethod == null) && (onlyStringMethod != null)) { // no match found but String only signature available, use this params = parameters.toArray(); foundMethod = onlyStringMethod; } if (params == null) { // no match found at all return false; } // now try to invoke the method try { Object result = foundMethod.invoke(m_object, params); if (result != null) { if (result instanceof Collection) { Collection c = (Collection)result; System.out.println(c.getClass().getName() + " (size: " + c.size() + ")"); int count = 0; if (result instanceof Map) { Map m = (Map)result; Iterator j = m.keySet().iterator(); while (j.hasNext()) { Object key = j.next(); System.out.println(count++ + ": " + key + "= " + m.get(key)); } } else { Iterator j = c.iterator(); while (j.hasNext()) { System.out.println(count++ + ": " + j.next()); } } } else { System.out.println(result.toString()); } } } catch (InvocationTargetException ite) { System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_EXEC_METHOD_1, new Object[] {foundMethod.getName()})); ite.getTargetException().printStackTrace(System.out); } catch (Throwable t) { System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_EXEC_METHOD_1, new Object[] {foundMethod.getName()})); t.printStackTrace(System.out); } return true; } /** * Returns a signature overview of all methods containing the given search String.<p> * * If no method name matches the given search String, the empty String is returned.<p> * * @param searchString the String to search for, if null all methods are shown * @return a signature overview of all methods containing the given search String */ protected String getMethodHelp(String searchString) { StringBuffer buf = new StringBuffer(512); Iterator i = m_methods.keySet().iterator(); while (i.hasNext()) { List l = (List)m_methods.get(i.next()); Iterator j = l.iterator(); while (j.hasNext()) { Method method = (Method)j.next(); if ((searchString == null) || (method.getName().toLowerCase().indexOf(searchString.toLowerCase()) > -1)) { buf.append("* "); buf.append(method.getName()); buf.append("("); Class[] params = method.getParameterTypes(); for (int k = 0; k < params.length; k++) { String par = params[k].getName(); par = par.substring(par.lastIndexOf('.') + 1); if (k != 0) { buf.append(", "); } buf.append(par); } buf.append(")\n"); } } } return buf.toString(); } /** * Returns the object to execute the methods on.<p> * * @return the object to execute the methods on */ protected Object getObject() { return m_object; } /** * Builds a method lookup String.<p> * * @param methodName the name of the method * @param paramCount the parameter count of the method * @return a method lookup String */ private String buildMethodLookup(String methodName, int paramCount) { StringBuffer buf = new StringBuffer(32); buf.append(methodName.toLowerCase()); buf.append(" ["); buf.append(paramCount); buf.append("]"); return buf.toString(); } /** * Initilizes the map of accessible methods.<p> */ private void initShellMethods() { Map result = new TreeMap(); Method[] methods = m_object.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { // only public methods directly declared in the base class can be used in the shell if ((methods[i].getDeclaringClass() == m_object.getClass()) && (methods[i].getModifiers() == Modifier.PUBLIC)) { // check if the method signature only uses primitive data types boolean onlyPrimitive = true; Class[] clazz = methods[i].getParameterTypes(); for (int j = 0; j < clazz.length; j++) { if (!((clazz[j].equals(String.class)) || (clazz[j].equals(CmsUUID.class)) || (clazz[j].equals(boolean.class)) || (clazz[j].equals(int.class)) || (clazz[j].equals(long.class)) || (clazz[j].equals(double.class)) || (clazz[j].equals(float.class)))) { // complex data type methods can not be called from the shell onlyPrimitive = false; break; } } if (onlyPrimitive) { // add this method to the set of methods that can be called from the shell String lookup = buildMethodLookup(methods[i].getName(), methods[i].getParameterTypes().length); List l; if (result.containsKey(lookup)) { l = (List)result.get(lookup); } else { l = new ArrayList(1); } l.add(methods[i]); result.put(lookup, l); } } } m_methods = result; } } /** The OpenCms context object. */ protected CmsObject m_cms; /** Additional shell commands object. */ private I_CmsShellCommands m_additionaShellCommands; /** All shell callable objects. */ private List m_commandObjects; /** If set to true, all commands are echoed. */ private boolean m_echo; /** Indicates if the 'exit' command has been called. */ private boolean m_exitCalled; /** The OpenCms system object. */ private OpenCmsCore m_opencms; /** The shell prompt format. */ private String m_prompt; /** The current users settings. */ private CmsUserSettings m_settings; /** Internal shell command object. */ private I_CmsShellCommands m_shellCommands; /** * Creates a new CmsShell.<p> * * @param prompt the prompt format to set * @param additionalShellCommands optional object for additional shell commands, or null * @param webInfPath the path to the 'WEB-INF' folder of the OpenCms installation */ public CmsShell(String webInfPath, String prompt, I_CmsShellCommands additionalShellCommands) { setPrompt(prompt); try { // first initialize runlevel 1 m_opencms = OpenCmsCore.getInstance(); // Externalisation: get Locale: will be the System default since no CmsObject is up before // runlevel 2 Locale locale = getLocale(); // search for the WEB-INF folder if (CmsStringUtil.isEmpty(webInfPath)) { System.out.println(Messages.get().key(locale, Messages.GUI_SHELL_NO_HOME_FOLDER_SPECIFIED_0, null)); System.out.println(); webInfPath = m_opencms.searchWebInfFolder(System.getProperty("user.dir")); if (CmsStringUtil.isEmpty(webInfPath)) { System.err.println(Messages.get().key(Messages.GUI_SHELL_HR_0)); System.err.println(Messages.get().key(locale, Messages.GUI_SHELL_NO_HOME_FOLDER_FOUND_0, null)); System.err.println(); System.err.println(Messages.get().key(locale, Messages.GUI_SHELL_START_DIR_LINE1_0, null)); System.err.println(Messages.get().key(locale, Messages.GUI_SHELL_START_DIR_LINE2_0, null)); System.err.println(Messages.get().key(Messages.GUI_SHELL_HR_0)); return; } } System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_WEB_INF_PATH_1, new Object[] {webInfPath})); // set the path to the WEB-INF folder (the 2nd and 3rd parameters are just reasonable dummies) m_opencms.getSystemInfo().init(webInfPath, "/opencms/*", null, "ROOT"); // now read the configuration properties String propertyPath = m_opencms.getSystemInfo().getConfigurationFileRfsPath(); System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_CONFIG_FILE_1, new Object[] {propertyPath})); System.out.println(); ExtendedProperties configuration = CmsPropertyUtils.loadProperties(propertyPath); // now upgrade to runlevel 2 m_opencms = m_opencms.upgradeRunlevel(configuration); // create a context object with 'Guest' permissions m_cms = m_opencms.initCmsObject(m_opencms.getDefaultUsers().getUserGuest()); // initialize the settings of the user m_settings = initSettings(); // initialize shell command object m_shellCommands = new CmsShellCommands(); m_shellCommands.initShellCmsObject(m_cms, this); // initialize additional shell command object if (additionalShellCommands != null) { m_additionaShellCommands = additionalShellCommands; m_additionaShellCommands.initShellCmsObject(m_cms, null); m_additionaShellCommands.shellStart(); } else { m_shellCommands.shellStart(); } m_commandObjects = new ArrayList(); if (m_additionaShellCommands != null) { // get all shell callable methods from the the additionsl shell command object m_commandObjects.add(new CmsCommandObject(m_additionaShellCommands)); } // get all shell callable methods from the CmsShellCommands m_commandObjects.add(new CmsCommandObject(m_shellCommands)); // get all shell callable methods from the CmsRequestContext m_commandObjects.add(new CmsCommandObject(m_cms.getRequestContext())); // get all shell callable methods from the CmsObject m_commandObjects.add(new CmsCommandObject(m_cms)); } catch (Throwable t) { t.printStackTrace(System.err); } } /** * Main program entry point when started via the command line.<p> * * @param args parameters passed to the application via the command line */ public static void main(String[] args) { boolean wrongUsage = false; String webInfPath = null; String script = null; if (args.length > 2) { wrongUsage = true; } else { for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("-base=")) { webInfPath = arg.substring(6); } else if (arg.startsWith("-script=")) { script = arg.substring(8); } else { System.out.println(Messages.get().key(Messages.GUI_SHELL_WRONG_USAGE_0)); wrongUsage = true; } } } if (wrongUsage) { System.out.println(Messages.get().key(Messages.GUI_SHELL_USAGE_1, CmsShell.class.getName())); } else { FileInputStream stream = null; if (script != null) { try { stream = new FileInputStream(script); } catch (IOException exc) { System.out.println(Messages.get().key(Messages.GUI_SHELL_ERR_SCRIPTFILE_1, script)); } } if (stream == null) { // no script-file, use standard input stream stream = new FileInputStream(FileDescriptor.in); } CmsShell shell = new CmsShell(webInfPath, "${user}@${project}:${siteroot}|${uri}>", null); shell.start(stream); } } /** * Exits this shell and destroys the OpenCms instance.<p> */ public void exit() { if (m_exitCalled) { return; } m_exitCalled = true; try { if (m_additionaShellCommands != null) { m_additionaShellCommands.shellExit(); } else { m_shellCommands.shellExit(); } } catch (Throwable t) { t.printStackTrace(); } try { m_opencms.shutDown(); } catch (Throwable t) { t.printStackTrace(); } } /** * Private internal helper for localisation to the current user's locale * within OpenCms. <p> * * @return the current user's <code>Locale</code>. */ public Locale getLocale() { if (getSettings() == null) { return CmsLocaleManager.getDefaultLocale(); } return getSettings().getLocale(); } /** * Obtain the additional settings related to the current user. * * @return the additional settings related to the current user. */ public CmsUserSettings getSettings() { return m_settings; } /** * Prints the shell prompt.<p> */ public void printPrompt() { String prompt = m_prompt; prompt = CmsStringUtil.substitute(prompt, "${user}", m_cms.getRequestContext().currentUser().getName()); prompt = CmsStringUtil.substitute(prompt, "${siteroot}", m_cms.getRequestContext().getSiteRoot()); prompt = CmsStringUtil.substitute(prompt, "${project}", m_cms.getRequestContext().currentProject().getName()); prompt = CmsStringUtil.substitute(prompt, "${uri}", m_cms.getRequestContext().getUri()); System.out.print(prompt); } /** * Starts this CmsShell.<p> * * @param fileInputStream a (file) input stream from which commands are read */ public void start(FileInputStream fileInputStream) { try { // execute the commands from the input stream executeCommands(fileInputStream); } catch (Throwable t) { t.printStackTrace(System.err); } } /** * Shows the signature of all methods containing the given search String.<p> * * @param searchString the String to search for in the methods, if null all methods are shown */ protected void help(String searchString) { String commandList; boolean foundSomething = false; System.out.println(); Iterator i = m_commandObjects.iterator(); while (i.hasNext()) { CmsCommandObject cmdObj = (CmsCommandObject)i.next(); commandList = cmdObj.getMethodHelp(searchString); if (!CmsStringUtil.isEmpty(commandList)) { System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_AVAILABLE_METHODS_1, new Object[] {cmdObj.getObject().getClass().getName()})); System.out.println(commandList); foundSomething = true; } } if (!foundSomething) { System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_MATCH_SEARCHSTRING_1, new Object[] {searchString})); } } /** * Initializes the internal <code>CmsWorkplaceSettings</code> that contain (amongst other * information) important information additional information about the current user * (an instance of {@link CmsUserSettings}). <p> * * This step is performed within the <code>CmsShell</code> constructor directly after * switching to run-level 2 and obtaining the <code>CmsObject</code> for the guest user as * well as when invoking the <code>CmsShell command {@link CmsShellCommands#login(String, String)}</code>. * * @return the user settings for the current user. */ protected CmsUserSettings initSettings() { m_settings = new CmsUserSettings(m_cms.getRequestContext().currentUser()); return m_settings; } /** * Sets the echo status.<p> * * @param echo the echo status to set */ protected void setEcho(boolean echo) { m_echo = echo; } /** * Sets the current shell prompt.<p> * * To set the prompt, the following variables are available:<p> * * <code>$u</code> the current user name<br> * <code>$s</code> the current site root<br> * <code>$p</code> the current project name<p> * * @param prompt the prompt to set */ protected void setPrompt(String prompt) { m_prompt = prompt; } /** * Executes a shell command with a list of parameters.<p> * * @param command the command to execute * @param parameters the list of parameters for the command */ private void executeCommand(String command, List parameters) { if (m_echo) { // echo the command to STDOUT System.out.print(command); for (int i = 0; i < parameters.size(); i++) { System.out.print(" " + parameters.get(i)); } System.out.println(); } // prepare to lookup a method in CmsObject or CmsShellCommands boolean executed = false; Iterator i = m_commandObjects.iterator(); while (!executed && i.hasNext()) { CmsCommandObject cmdObj = (CmsCommandObject)i.next(); executed = cmdObj.executeMethod(command, parameters); } if (!executed) { // method not found System.out.println(); StringBuffer commandMsg = new StringBuffer(command).append("("); for (int j = 0; j < parameters.size(); j++) { commandMsg.append("value"); if (j < parameters.size() - 1) { commandMsg.append(", "); } } commandMsg.append(")"); System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_METHOD_NOT_FOUND_1, new Object[] {commandMsg.toString()})); System.out.println(Messages.get().key(Messages.GUI_SHELL_HR_0)); ((CmsShellCommands)m_shellCommands).help(); } } /** * Executes all commands read from the given input stream.<p> * * @param fileInputStream a file input stream from which the commands are read */ private void executeCommands(FileInputStream fileInputStream) { try { LineNumberReader lnr = new LineNumberReader(new InputStreamReader(fileInputStream)); while (!m_exitCalled) { printPrompt(); String line = lnr.readLine(); if (line == null) { // if null the file has been read to the end try { Thread.sleep(500); } catch (Throwable t) { // noop } break; } if ((line != null) && line.trim().startsWith("#")) { System.out.println(line); continue; } StringReader reader = new StringReader(line); StreamTokenizer st = new StreamTokenizer(reader); st.eolIsSignificant(true); // put all tokens into a List List parameters = new ArrayList(); while (st.nextToken() != StreamTokenizer.TT_EOF) { if (st.ttype == StreamTokenizer.TT_NUMBER) { parameters.add(Integer.toString(new Double(st.nval).intValue())); } else { parameters.add(st.sval); } } reader.close(); // extract command and arguments if ((parameters == null) || (parameters.size() == 0)) { if (m_echo) { System.out.println(); } continue; } String command = (String)parameters.get(0); parameters = parameters.subList(1, parameters.size()); // execute the command executeCommand(command, parameters); } } catch (Throwable t) { t.printStackTrace(System.err); } } }
src/org/opencms/main/CmsShell.java
/* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/main/CmsShell.java,v $ * Date : $Date: 2005/06/07 15:03:46 $ * Version: $Revision: 1.36 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2002 - 2005 Alkacon Software (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.main; import org.opencms.db.CmsUserSettings; import org.opencms.file.CmsObject; import org.opencms.i18n.CmsLocaleManager; import org.opencms.util.CmsPropertyUtils; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.StreamTokenizer; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import org.apache.commons.collections.ExtendedProperties; /** * A commad line interface to access OpenCms functions which * is used for the initial setup and also can be used to directly access the OpenCms * repository without the Workplace.<p> * * The CmsShell has direct access to all methods in the "command objects". * Currently the following classes are used as command objects: * {@link org.opencms.main.CmsShellCommands}, * {@link org.opencms.file.CmsRequestContext} and * {@link org.opencms.file.CmsObject}.<p> * * Only public methods in the command objects that use just supported data types * as parameters can be called from the shell. Supported data types are: * <code>String, CmsUUID, boolean, int, long, double, float</code>.<p> * * If a method name is ambiguous, i.e. the method name with the same numer of parameter exist * in more then one of the command objects, the method is only executed on the first matching object.<p> * * @author Alexander Kandzior ([email protected]) * @version $Revision: 1.36 $ * * @see org.opencms.main.CmsShellCommands * @see org.opencms.file.CmsRequestContext * @see org.opencms.file.CmsObject */ public class CmsShell { /** * Command object class.<p> */ private class CmsCommandObject { // The list of methods private Map m_methods; // The object to execute the methods on private Object m_object; /** * Creates a new command object.<p> * * @param object the object to execute the methods on */ protected CmsCommandObject(Object object) { m_object = object; initShellMethods(); } /** * Tries to execute a method for the provided parameters on this command object.<p> * * If methods with the same name and number of parameters exist in this command object, * the given parameters are tried to be converted from String to matching types.<p> * * @param command the command entered by the user in the shell * @param parameters the parameters entered by the user in the shell * @return true if a method was executed, false otherwise */ protected boolean executeMethod(String command, List parameters) { // build the method lookup String lookup = buildMethodLookup(command, parameters.size()); // try to look up the methods of this command object List possibleMethods = (List)m_methods.get(lookup); if (possibleMethods == null) { return false; } // a match for the mehod name was found, now try to figure out if the parameters are ok Method onlyStringMethod = null; Method foundMethod = null; Object[] params = null; Iterator i; // first check if there is one method with only has String parameters, make this the fallback i = possibleMethods.iterator(); while (i.hasNext()) { Method method = (Method)i.next(); Class[] clazz = method.getParameterTypes(); boolean onlyString = true; for (int j = 0; j < clazz.length; j++) { if (!(clazz[j].equals(String.class))) { onlyString = false; break; } } if (onlyString) { onlyStringMethod = method; break; } } // now check a method matches the provided parameters // if so, use this method, else continue searching i = possibleMethods.iterator(); while (i.hasNext()) { Method method = (Method)i.next(); if (method == onlyStringMethod) { // skip the String only signature because this would always match continue; } // now try to convert the parameters to the required types Class[] clazz = method.getParameterTypes(); Object[] converted = new Object[clazz.length]; boolean match = true; for (int j = 0; j < clazz.length; j++) { String value = (String)parameters.get(j); if (clazz[j].equals(String.class)) { // no conversion required for String converted[j] = value; } else if (clazz[j].equals(boolean.class)) { // try to convert to boolean if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) { converted[j] = Boolean.valueOf(value); } else { match = false; } } else if (clazz[j].equals(CmsUUID.class)) { // try to convert to CmsUUID try { converted[j] = new CmsUUID(value); } catch (NumberFormatException e) { match = false; } } else if (clazz[j].equals(int.class)) { // try to convert to int try { converted[j] = Integer.valueOf(value); } catch (NumberFormatException e) { match = false; } } else if (clazz[j].equals(long.class)) { // try to convert to long try { converted[j] = Long.valueOf(value); } catch (NumberFormatException e) { match = false; } } else if (clazz[j].equals(float.class)) { // try to convert to float try { converted[j] = Float.valueOf(value); } catch (NumberFormatException e) { match = false; } } else if (clazz[j].equals(double.class)) { // try to convert to double try { converted[j] = Double.valueOf(value); } catch (NumberFormatException e) { match = false; } } if (!match) { break; } } if (match) { // we found a matching method signature params = converted; foundMethod = method; break; } } if ((foundMethod == null) && (onlyStringMethod != null)) { // no match found but String only signature available, use this params = parameters.toArray(); foundMethod = onlyStringMethod; } if (params == null) { // no match found at all return false; } // now try to invoke the method try { Object result = foundMethod.invoke(m_object, params); if (result != null) { if (result instanceof Collection) { Collection c = (Collection)result; System.out.println(c.getClass().getName() + " (size: " + c.size() + ")"); int count = 0; if (result instanceof Map) { Map m = (Map)result; Iterator j = m.keySet().iterator(); while (j.hasNext()) { Object key = j.next(); System.out.println(count++ + ": " + key + "= " + m.get(key)); } } else { Iterator j = c.iterator(); while (j.hasNext()) { System.out.println(count++ + ": " + j.next()); } } } else { System.out.println(result.toString()); } } } catch (InvocationTargetException ite) { System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_EXEC_METHOD_1, new Object[] {foundMethod.getName()})); ite.getTargetException().printStackTrace(System.out); } catch (Throwable t) { System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_EXEC_METHOD_1, new Object[] {foundMethod.getName()})); t.printStackTrace(System.out); } return true; } /** * Returns a signature overview of all methods containing the given search String.<p> * * If no method name matches the given search String, the empty String is returned.<p> * * @param searchString the String to search for, if null all methods are shown * @return a signature overview of all methods containing the given search String */ protected String getMethodHelp(String searchString) { StringBuffer buf = new StringBuffer(512); Iterator i = m_methods.keySet().iterator(); while (i.hasNext()) { List l = (List)m_methods.get(i.next()); Iterator j = l.iterator(); while (j.hasNext()) { Method method = (Method)j.next(); if ((searchString == null) || (method.getName().toLowerCase().indexOf(searchString.toLowerCase()) > -1)) { buf.append("* "); buf.append(method.getName()); buf.append("("); Class[] params = method.getParameterTypes(); for (int k = 0; k < params.length; k++) { String par = params[k].getName(); par = par.substring(par.lastIndexOf('.') + 1); if (k != 0) { buf.append(", "); } buf.append(par); } buf.append(")\n"); } } } return buf.toString(); } /** * Returns the object to execute the methods on.<p> * * @return the object to execute the methods on */ protected Object getObject() { return m_object; } /** * Builds a method lookup String.<p> * * @param methodName the name of the method * @param paramCount the parameter count of the method * @return a method lookup String */ private String buildMethodLookup(String methodName, int paramCount) { StringBuffer buf = new StringBuffer(32); buf.append(methodName.toLowerCase()); buf.append(" ["); buf.append(paramCount); buf.append("]"); return buf.toString(); } /** * Initilizes the map of accessible methods.<p> */ private void initShellMethods() { Map result = new TreeMap(); Method[] methods = m_object.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { // only public methods directly declared in the base class can be used in the shell if ((methods[i].getDeclaringClass() == m_object.getClass()) && (methods[i].getModifiers() == Modifier.PUBLIC)) { // check if the method signature only uses primitive data types boolean onlyPrimitive = true; Class[] clazz = methods[i].getParameterTypes(); for (int j = 0; j < clazz.length; j++) { if (!((clazz[j].equals(String.class)) || (clazz[j].equals(CmsUUID.class)) || (clazz[j].equals(boolean.class)) || (clazz[j].equals(int.class)) || (clazz[j].equals(long.class)) || (clazz[j].equals(double.class)) || (clazz[j].equals(float.class)))) { // complex data type methods can not be called from the shell onlyPrimitive = false; break; } } if (onlyPrimitive) { // add this method to the set of methods that can be called from the shell String lookup = buildMethodLookup(methods[i].getName(), methods[i].getParameterTypes().length); List l; if (result.containsKey(lookup)) { l = (List)result.get(lookup); } else { l = new ArrayList(1); } l.add(methods[i]); result.put(lookup, l); } } } m_methods = result; } } /** The OpenCms context object. */ protected CmsObject m_cms; /** Additional shell commands object. */ private I_CmsShellCommands m_additionaShellCommands; /** All shell callable objects. */ private List m_commandObjects; /** If set to true, all commands are echoed. */ private boolean m_echo; /** Indicates if the 'exit' command has been called. */ private boolean m_exitCalled; /** The OpenCms system object. */ private OpenCmsCore m_opencms; /** The shell prompt format. */ private String m_prompt; /** The current users settings. */ private CmsUserSettings m_settings; /** Internal shell command object. */ private I_CmsShellCommands m_shellCommands; /** * Creates a new CmsShell.<p> * * @param prompt the prompt format to set * @param additionalShellCommands optional object for additional shell commands, or null * @param webInfPath the path to the 'WEB-INF' folder of the OpenCms installation */ public CmsShell(String webInfPath, String prompt, I_CmsShellCommands additionalShellCommands) { setPrompt(prompt); try { // first initialize runlevel 1 m_opencms = OpenCmsCore.getInstance(); // Externalisation: get Locale: will be the System default since no CmsObject is up before // runlevel 2 Locale locale = getLocale(); // search for the WEB-INF folder if (CmsStringUtil.isEmpty(webInfPath)) { System.out.println(Messages.get().key(locale, Messages.GUI_SHELL_NO_HOME_FOLDER_SPECIFIED_0, null)); System.out.println(); webInfPath = m_opencms.searchWebInfFolder(System.getProperty("user.dir")); if (CmsStringUtil.isEmpty(webInfPath)) { System.err.println(Messages.get().key(Messages.GUI_SHELL_HR_0)); System.err.println(Messages.get().key(locale, Messages.GUI_SHELL_NO_HOME_FOLDER_FOUND_0, null)); System.err.println(); System.err.println(Messages.get().key(locale, Messages.GUI_SHELL_START_DIR_LINE1_0, null)); System.err.println(Messages.get().key(locale, Messages.GUI_SHELL_START_DIR_LINE2_0, null)); System.err.println(Messages.get().key(Messages.GUI_SHELL_HR_0)); return; } } System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_WEB_INF_PATH_1, new Object[] {webInfPath})); // set the path to the WEB-INF folder (the 2nd and 3rd parameters are just reasonable dummies) m_opencms.getSystemInfo().init(webInfPath, "/opencms/*", null, "ROOT"); // now read the configuration properties String propertyPath = m_opencms.getSystemInfo().getConfigurationFileRfsPath(); System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_CONFIG_FILE_1, new Object[] {propertyPath})); System.out.println(); ExtendedProperties configuration = CmsPropertyUtils.loadProperties(propertyPath); // now upgrade to runlevel 2 m_opencms = m_opencms.upgradeRunlevel(configuration); // create a context object with 'Guest' permissions m_cms = m_opencms.initCmsObject(m_opencms.getDefaultUsers().getUserGuest()); // initialize the settings of the user m_settings = initSettings(); // initialize shell command object m_shellCommands = new CmsShellCommands(); m_shellCommands.initShellCmsObject(m_cms, this); // initialize additional shell command object if (additionalShellCommands != null) { m_additionaShellCommands = additionalShellCommands; m_additionaShellCommands.initShellCmsObject(m_cms, null); m_additionaShellCommands.shellStart(); } else { m_shellCommands.shellStart(); } m_commandObjects = new ArrayList(); if (m_additionaShellCommands != null) { // get all shell callable methods from the the additionsl shell command object m_commandObjects.add(new CmsCommandObject(m_additionaShellCommands)); } // get all shell callable methods from the CmsShellCommands m_commandObjects.add(new CmsCommandObject(m_shellCommands)); // get all shell callable methods from the CmsRequestContext m_commandObjects.add(new CmsCommandObject(m_cms.getRequestContext())); // get all shell callable methods from the CmsObject m_commandObjects.add(new CmsCommandObject(m_cms)); } catch (Throwable t) { t.printStackTrace(System.err); } } /** * Main program entry point when started via the command line.<p> * * @param args parameters passed to the application via the command line */ public static void main(String[] args) { boolean wrongUsage = false; String webInfPath = null; String script = null; if (args.length > 2) { wrongUsage = true; } else { for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("-base=")) { webInfPath = arg.substring(6); } else if (arg.startsWith("-script=")) { script = arg.substring(8); } else { System.out.println(Messages.get().key(Messages.GUI_SHELL_WRONG_USAGE_0)); wrongUsage = true; } } } if (wrongUsage) { System.out.println(Messages.get().key(Messages.GUI_SHELL_USAGE_1, CmsShell.class.getName())); } else { FileInputStream stream = null; if (script != null) { try { stream = new FileInputStream(script); } catch (IOException exc) { System.out.println(Messages.get().key(Messages.GUI_SHELL_ERR_SCRIPTFILE_1, script)); } } if (stream == null) { // no script-file, use standard input stream stream = new FileInputStream(FileDescriptor.in); } CmsShell shell = new CmsShell(webInfPath, "${user}@${project}:${siteroot}|${uri}>", null); shell.start(stream); } } /** * Exits this shell and destroys the OpenCms instance.<p> */ public void exit() { if (m_exitCalled) { return; } m_exitCalled = true; try { if (m_additionaShellCommands != null) { m_additionaShellCommands.shellExit(); } else { m_shellCommands.shellExit(); } } catch (Throwable t) { t.printStackTrace(); } try { m_opencms.shutDown(); } catch (Throwable t) { t.printStackTrace(); } } /** * Private internal helper for localisation to the current user's locale * within OpenCms. <p> * * @return the current user's <code>Locale</code>. */ public Locale getLocale() { if (getSettings() == null) { return CmsLocaleManager.getDefaultLocale(); } return getSettings().getLocale(); } /** * Obtain the additional settings related to the current user. * * @return the additional settings related to the current user. */ public CmsUserSettings getSettings() { return m_settings; } /** * Initializes the internal <code>CmsWorkplaceSettings</code> that contain (amongst other * information) important information additional information about the current user * (an instance of {@link CmsUserSettings}). <p> * * This step is performed within the <code>CmsShell</code> constructor directly after * switching to run-level 2 and obtaining the <code>CmsObject</code> for the guest user as * well as when invoking the <code>CmsShell command {@link CmsShellCommands#login(String, String)}</code>. * * @return the user settings for the current user. */ public CmsUserSettings initSettings() { m_settings = new CmsUserSettings(m_cms.getRequestContext().currentUser()); return m_settings; } /** * Prints the shell prompt.<p> */ public void printPrompt() { String prompt = m_prompt; prompt = CmsStringUtil.substitute(prompt, "${user}", m_cms.getRequestContext().currentUser().getName()); prompt = CmsStringUtil.substitute(prompt, "${siteroot}", m_cms.getRequestContext().getSiteRoot()); prompt = CmsStringUtil.substitute(prompt, "${project}", m_cms.getRequestContext().currentProject().getName()); prompt = CmsStringUtil.substitute(prompt, "${uri}", m_cms.getRequestContext().getUri()); System.out.print(prompt); } /** * Starts this CmsShell.<p> * * @param fileInputStream a (file) input stream from which commands are read */ public void start(FileInputStream fileInputStream) { try { // execute the commands from the input stream executeCommands(fileInputStream); } catch (Throwable t) { t.printStackTrace(System.err); } } /** * Shows the signature of all methods containing the given search String.<p> * * @param searchString the String to search for in the methods, if null all methods are shown */ protected void help(String searchString) { String commandList; boolean foundSomething = false; System.out.println(); Iterator i = m_commandObjects.iterator(); while (i.hasNext()) { CmsCommandObject cmdObj = (CmsCommandObject)i.next(); commandList = cmdObj.getMethodHelp(searchString); if (!CmsStringUtil.isEmpty(commandList)) { System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_AVAILABLE_METHODS_1, new Object[] {cmdObj.getObject().getClass().getName()})); System.out.println(commandList); foundSomething = true; } } if (!foundSomething) { System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_MATCH_SEARCHSTRING_1, new Object[] {searchString})); } } /** * Sets the echo status.<p> * * @param echo the echo status to set */ protected void setEcho(boolean echo) { m_echo = echo; } /** * Sets the current shell prompt.<p> * * To set the prompt, the following variables are available:<p> * * <code>$u</code> the current user name<br> * <code>$s</code> the current site root<br> * <code>$p</code> the current project name<p> * * @param prompt the prompt to set */ protected void setPrompt(String prompt) { m_prompt = prompt; } /** * Executes a shell command with a list of parameters.<p> * * @param command the command to execute * @param parameters the list of parameters for the command */ private void executeCommand(String command, List parameters) { if (m_echo) { // echo the command to STDOUT System.out.print(command); for (int i = 0; i < parameters.size(); i++) { System.out.print(" " + parameters.get(i)); } System.out.println(); } // prepare to lookup a method in CmsObject or CmsShellCommands boolean executed = false; Iterator i = m_commandObjects.iterator(); while (!executed && i.hasNext()) { CmsCommandObject cmdObj = (CmsCommandObject)i.next(); executed = cmdObj.executeMethod(command, parameters); } if (!executed) { // method not found System.out.println(); StringBuffer commandMsg = new StringBuffer(command).append("("); for (int j = 0; j < parameters.size(); j++) { commandMsg.append("value"); if (j < parameters.size() - 1) { commandMsg.append(", "); } } commandMsg.append(")"); System.out.println(Messages.get().key( getLocale(), Messages.GUI_SHELL_METHOD_NOT_FOUND_1, new Object[] {commandMsg.toString()})); System.out.println(Messages.get().key(Messages.GUI_SHELL_HR_0)); ((CmsShellCommands)m_shellCommands).help(); } } /** * Executes all commands read from the given input stream.<p> * * @param fileInputStream a file input stream from which the commands are read */ private void executeCommands(FileInputStream fileInputStream) { try { LineNumberReader lnr = new LineNumberReader(new InputStreamReader(fileInputStream)); while (!m_exitCalled) { printPrompt(); String line = lnr.readLine(); if (line == null) { // if null the file has been read to the end try { Thread.sleep(500); } catch (Throwable t) { // noop } break; } if ((line != null) && line.trim().startsWith("#")) { System.out.println(line); continue; } StringReader reader = new StringReader(line); StreamTokenizer st = new StreamTokenizer(reader); st.eolIsSignificant(true); // put all tokens into a List List parameters = new ArrayList(); while (st.nextToken() != StreamTokenizer.TT_EOF) { if (st.ttype == StreamTokenizer.TT_NUMBER) { parameters.add(Integer.toString(new Double(st.nval).intValue())); } else { parameters.add(st.sval); } } reader.close(); // extract command and arguments if ((parameters == null) || (parameters.size() == 0)) { if (m_echo) { System.out.println(); } continue; } String command = (String)parameters.get(0); parameters = parameters.subList(1, parameters.size()); // execute the command executeCommand(command, parameters); } } catch (Throwable t) { t.printStackTrace(System.err); } } }
Protected initSettings() Method
src/org/opencms/main/CmsShell.java
Protected initSettings() Method
Java
lgpl-2.1
94430cd4229bd7248135ec71aca003bde6d506e0
0
juanmjacobs/kettle,cwarden/kettle,ontometrics/ontokettle,cwarden/kettle,ontometrics/ontokettle,ontometrics/ontokettle,juanmjacobs/kettle,juanmjacobs/kettle,cwarden/kettle
/********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.core.value; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.math.BigDecimal; import java.text.DateFormatSymbols; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.w3c.dom.Node; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.XMLInterface; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleEOFException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleFileException; import be.ibridge.kettle.core.exception.KettleValueException; import be.ibridge.kettle.repository.Repository; /** * This class is one of the core classes of the Kettle framework. * It contains everything you need to manipulate atomic data (Values/Fields/...) * and to describe it in the form of meta-data. (name, length, precision, etc.) * * @author Matt * @since Beginning 2003 */ public class Value implements Cloneable, XMLInterface, Serializable { private static final long serialVersionUID = -6310073485210258622L; /** * Value type indicating that the value has no type set. */ public static final int VALUE_TYPE_NONE = 0; /** * Value type indicating that the value contains a floating point double precision number. */ public static final int VALUE_TYPE_NUMBER = 1; /** * Value type indicating that the value contains a text String. */ public static final int VALUE_TYPE_STRING = 2; /** * Value type indicating that the value contains a Date. */ public static final int VALUE_TYPE_DATE = 3; /** * Value type indicating that the value contains a boolean. */ public static final int VALUE_TYPE_BOOLEAN = 4; /** * Value type indicating that the value contains a long integer. */ public static final int VALUE_TYPE_INTEGER = 5; /** * Value type indicating that the value contains a floating point precision number with arbitrary precision. */ public static final int VALUE_TYPE_BIGNUMBER = 6; /** * Value type indicating that the value contains an Object. */ public static final int VALUE_TYPE_SERIALIZABLE = 7; /** * The descriptions of the value types. */ private static final String valueTypeCode[]= { "-", // $NON-NLS-1$ "Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable" // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$ $NON-NLS-5$ $NON-NLS-6$ }; private ValueInterface value; private String name; private String origin; private boolean NULL; /** * Constructs a new Value of type EMPTY * */ public Value() { clearValue(); } /** * Constructs a new Value with a name. * * @param name Sets the name of the Value */ public Value(String name) { clearValue(); setName(name); } /** * Constructs a new Value with a name and a type. * * @param name Sets the name of the Value * @param val_type Sets the type of the Value (Value.VALUE_TYPE_*) */ public Value(String name, int val_type) { clearValue(); newValue(val_type); setName(name); } /** * This method allocates a new value of the appropriate type.. * @param val_type The new type of value */ private void newValue(int val_type) { switch(val_type) { case VALUE_TYPE_NUMBER : value = new ValueNumber(); break; case VALUE_TYPE_STRING : value = new ValueString(); break; case VALUE_TYPE_DATE : value = new ValueDate(); break; case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(); break; case VALUE_TYPE_INTEGER : value = new ValueInteger(); break; case VALUE_TYPE_BIGNUMBER: value = new ValueBigNumber(); break; default: value = null; } } /** * Convert the value to another type. This only works if a value has been set previously. * That is the reason this method is private. Rather, use the public method setType(int type). * * @param valType The type to convert to. */ private void convertTo(int valType) { if (value!=null) { switch(valType) { case VALUE_TYPE_NUMBER : value = new ValueNumber(value.getNumber()); break; case VALUE_TYPE_STRING : value = new ValueString(value.getString()); break; case VALUE_TYPE_DATE : value = new ValueDate(value.getDate()); break; case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(value.getBoolean()); break; case VALUE_TYPE_INTEGER : value = new ValueInteger(value.getInteger()); break; case VALUE_TYPE_BIGNUMBER : value = new ValueBigNumber(value.getBigNumber()); break; default: value = null; } } } /** * Constructs a new Value with a name, a type, length and precision. * * @param name Sets the name of the Value * @param valType Sets the type of the Value (Value.VALUE_TYPE_*) * @param length The length of the value * @param precision The precision of the value */ public Value(String name, int valType, int length, int precision) { this(name, valType); setLength(length, precision); } /** * Constructs a new Value of Type VALUE_TYPE_BIGNUMBER, with a name, containing a BigDecimal number * * @param name Sets the name of the Value * @param bignum The number to store in this Value */ public Value(String name, BigDecimal bignum) { clearValue(); setValue(bignum); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_NUMBER, with a name, containing a number * * @param name Sets the name of the Value * @param num The number to store in this Value */ public Value(String name, double num) { clearValue(); setValue(num); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String * * @param name Sets the name of the Value * @param str The text to store in this Value */ public Value(String name, StringBuffer str) { this(name, str.toString()); } /** * Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String * * @param name Sets the name of the Value * @param str The text to store in this Value */ public Value(String name, String str) { clearValue(); setValue(str); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_DATE, with a name, containing a Date * * @param name Sets the name of the Value * @param dat The date to store in this Value */ public Value(String name, Date dat) { clearValue(); setValue(dat); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_BOOLEAN, with a name, containing a boolean value * * @param name Sets the name of the Value * @param bool The boolean to store in this Value */ public Value(String name, boolean bool) { clearValue(); setValue(bool); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_INTEGER, with a name, containing an integer number * * @param name Sets the name of the Value * @param l The integer to store in this Value */ public Value(String name, long l) { clearValue(); setValue(l); setName(name); } /** * Constructs a new Value as a copy of another value and renames it... * * @param name The new name of the copied Value * @param v The value to be copied */ public Value(String name, Value v) { this(v); setName(name); } /** * Constructs a new Value as a copy of another value * * @param v The Value to be copied */ public Value(Value v) { if (v!=null) { setType(v.getType()); value = v.getValueCopy(); setName(v.getName()); setLength(v.getLength(), v.getPrecision()); setNull(v.isNull()); setOrigin(v.origin); } else { clearValue(); setNull(true); } } public Object clone() { Value retval = null; try { retval = (Value)super.clone(); } catch(CloneNotSupportedException e) { retval=null; } return retval; } /** * Build a copy of this Value * @return a copy of another value * */ public Value Clone() { Value v = new Value(this); return v; } /** * Clears the content and name of a Value * */ public void clearValue() { value = null; name = null; NULL = false; origin = null; } private ValueInterface getValueCopy() { if (value==null) return null; return (ValueInterface)value.clone(); } /** * Sets the name of a Value * * @param name The new name of the value */ public void setName(String name) { this.name = name; } /** * Obtain the name of a Value * * @return The name of the Value */ public String getName() { return name; } /** * This method allows you to set the origin of the Value by means of the name of the originating step. * * @param step_of_origin The step of origin. */ public void setOrigin(String step_of_origin) { origin = step_of_origin; } /** * Obtain the origin of the step. * * @return The name of the originating step */ public String getOrigin() { return origin; } /** * Sets the value to a BigDecimal number value. * @param num The number value to set the value to */ public void setValue(BigDecimal num) { if (value==null || value.getType()!=VALUE_TYPE_BIGNUMBER) value = new ValueBigNumber(num); else value.setBigNumber(num); setNull(false); } /** * Sets the value to a double Number value. * @param num The number value to set the value to */ public void setValue(double num) { if (value==null || value.getType()!=VALUE_TYPE_NUMBER) value = new ValueNumber(num); else value.setNumber(num); setNull(false); } /** * Sets the Value to a String text * @param str The StringBuffer to get the text from */ public void setValue(StringBuffer str) { if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str.toString()); else value.setString(str.toString()); setNull(str==null); } /** * Sets the Value to a String text * @param str The String to get the text from */ public void setValue(String str) { if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str); else value.setString(str); setNull(str==null); } public void setSerializedValue(Serializable ser) { if (value==null || value.getType()!=VALUE_TYPE_SERIALIZABLE) value = new ValueSerializable(ser); else value.setSerializable(ser); setNull(ser==null); } /** * Sets the Value to a Date * @param dat The Date to set the Value to */ public void setValue(Date dat) { if (value==null || value.getType()!=VALUE_TYPE_DATE) value = new ValueDate(dat); else value.setDate(dat); setNull(dat==null); } /** * Sets the Value to a boolean * @param bool The boolean to set the Value to */ public void setValue(boolean bool) { if (value==null || value.getType()!=VALUE_TYPE_BOOLEAN) value = new ValueBoolean(bool); else value.setBoolean(bool); setNull(false); } /** * Sets the Value to a long integer * @param b The byte to convert to a long integer to which the Value is set. */ public void setValue(byte b) { setValue((long)b); } /** * Sets the Value to a long integer * @param i The integer to convert to a long integer to which the Value is set. */ public void setValue(int i) { setValue((long)i); } /** * Sets the Value to a long integer * @param l The long integer to which the Value is set. */ public void setValue(long l) { if (value==null || value.getType()!=VALUE_TYPE_INTEGER) value = new ValueInteger(l); else value.setInteger(l); setNull(false); } /** * Copy the Value from another Value. * It doesn't copy the name. * @param v The Value to copy the settings and value from */ public void setValue(Value v) { if (v!=null) { value = v.getValueCopy(); setNull(v.isNull()); setOrigin(v.origin); } else { clearValue(); } } /** * Get the BigDecimal number of this Value. * If the value is not of type BIG_NUMBER, a conversion is done first. * @return the double precision floating point number of this Value. */ public BigDecimal getBigNumber() { if (value==null || isNull()) return null; return value.getBigNumber(); } /** * Get the double precision floating point number of this Value. * If the value is not of type NUMBER, a conversion is done first. * @return the double precision floating point number of this Value. */ public double getNumber() { if (value==null || isNull()) return 0.0; return value.getNumber(); } /** * Get the String text representing this value. * If the value is not of type STRING, a conversion if done first. * @return the String text representing this value. */ public String getString() { if (value==null || isNull()) return null; return value.getString(); } /** * Get the length of the String representing this value. * @return the length of the String representing this value. */ public int getStringLength() { String s = getString(); if (s==null) return 0; return s.length(); } /** * Get the Date of this Value. * If the Value is not of type DATE, a conversion is done first. * @return the Date of this Value. */ public Date getDate() { if (value==null || isNull()) return null; return value.getDate(); } /** * Get the Serializable of this Value. * If the Value is not of type Serializable, it returns null. * @return the Serializable of this Value. */ public Serializable getSerializable() { if (value==null || isNull() || value.getType() != VALUE_TYPE_SERIALIZABLE) return null; return value.getSerializable(); } /** * Get the boolean value of this Value. * If the Value is not of type BOOLEAN, it will be converted. * <p>Strings: "YES", "Y", "TRUE" (case insensitive) to true, the rest false * <p>Number: 0.0 is false, the rest is true. * <p>Integer: 0 is false, the rest is true. * <p>Date: always false. * @return the boolean representation of this Value. */ public boolean getBoolean() { if (value==null || isNull()) return false; return value.getBoolean(); } /** * Get the long integer representation of this value. * If the Value is not of type INTEGER, it will be converted: * <p>String: try to convert to a long value, 0L if it didn't work. * <p>Number: round the double value and return the resulting long integer. * <p>Date: return the number of miliseconds after <code>1970:01:01 00:00:00</code> * <p>Date: always false. * * @return the long integer representation of this value. */ public long getInteger() { if (value==null || isNull()) return 0L; return value.getInteger(); } /** * Set the type of this Value * @param val_type The type to which the Value will be set. */ public void setType(int val_type) { if (value==null) newValue(val_type); else // Convert the value to the appropriate type... { convertTo(val_type); } } /** * Returns the type of this Value * @return the type of this Value */ public int getType() { if (value==null) return VALUE_TYPE_NONE; return value.getType(); } /** * Checks whether or not this Value is empty. * A value is empty if it has the type VALUE_TYPE_EMPTY * @return true if the value is empty. */ public boolean isEmpty() { if (value==null) return true; return false; } /** * Checks wheter or not the value is a String. * @return true if the value is a String. */ public boolean isString() { if (value==null) return false; return value.getType()==VALUE_TYPE_STRING; } /** * Checks whether or not this value is a Date * @return true if the value is a Date */ public boolean isDate() { if (value==null) return false; return value.getType()==VALUE_TYPE_DATE; } /** * Checks whether or not the value is a Big Number * @return true is this value is a big number */ public boolean isBigNumber() { if (value==null) return false; return value.getType()==VALUE_TYPE_BIGNUMBER; } /** * Checks whether or not the value is a Number * @return true is this value is a number */ public boolean isNumber() { if (value==null) return false; return value.getType()==VALUE_TYPE_NUMBER; } /** * Checks whether or not this value is a boolean * @return true if this value has type boolean. */ public boolean isBoolean() { if (value==null) return false; return value.getType()==VALUE_TYPE_BOOLEAN; } /** * Checks whether or not this value is of type Serializable * @retur true if this value has type Serializable */ public boolean isSerializableType() { if(value == null) { return false; } return value.getType() == VALUE_TYPE_SERIALIZABLE; } /** * Checks whether or not this value is an Integer * @return true if this value is an integer */ public boolean isInteger() { if (value==null) return false; return value.getType()==VALUE_TYPE_INTEGER; } /** * Checks whether or not this Value is Numeric * A Value is numeric if it is either of type Number or Integer * @return true if the value is either of type Number or Integer */ public boolean isNumeric() { return isInteger() || isNumber() || isBigNumber(); } /** * Checks whether or not the specified type is either Integer or Number * @param t the type to check * @return true if the type is Integer or Number */ public static final boolean isNumeric(int t) { return t==VALUE_TYPE_INTEGER || t==VALUE_TYPE_NUMBER || t==VALUE_TYPE_BIGNUMBER; } /** * Returns a padded to length String text representation of this Value * @return a padded to length String text representation of this Value */ public String toString() { return toString(true); } /** * a String text representation of this Value, optionally padded to the specified length * @param pad true if you want to pad the resulting String * @return a String text representation of this Value, optionally padded to the specified length */ public String toString(boolean pad) { String retval; switch(getType()) { case VALUE_TYPE_STRING : retval=toStringString(pad); break; case VALUE_TYPE_NUMBER : retval=toStringNumber(pad); break; case VALUE_TYPE_DATE : retval=toStringDate(); break; case VALUE_TYPE_BOOLEAN: retval=toStringBoolean(); break; case VALUE_TYPE_INTEGER: retval=toStringInteger(pad); break; case VALUE_TYPE_BIGNUMBER: retval=toStringBigNumber(pad); break; default: retval=""; break; } return retval; } /** * a String text representation of this Value, optionally padded to the specified length * @param pad true if you want to pad the resulting String * @return a String text representation of this Value, optionally padded to the specified length */ public String toStringMeta() { // We (Sven Boden) did explicit performance testing for this // part. The original version used Strings instead of StringBuffers, // performance between the 2 does not differ that much. A few milliseconds // on 100000 iterations in the advantage of StringBuffers. The // lessened creation of objects may be worth it in the long run. StringBuffer retval=new StringBuffer(getTypeDesc()); switch(getType()) { case VALUE_TYPE_STRING : if (getLength()>0) retval.append('(').append(getLength()).append(')'); break; case VALUE_TYPE_NUMBER : case VALUE_TYPE_BIGNUMBER : if (getLength()>0) { retval.append('(').append(getLength()); if (getPrecision()>0) { retval.append(", ").append(getPrecision()); } retval.append(')'); } break; case VALUE_TYPE_INTEGER: if (getLength()>0) { retval.append('(').append(getLength()).append(')'); } break; default: break; } return retval.toString(); } /** * Converts a String Value to String optionally padded to the specified length. * @param pad true if you want to pad the resulting string to length. * @return a String optionally padded to the specified length. */ private String toStringString(boolean pad) { String retval=null; if (value==null) return null; if (value.getLength()<=0) // No length specified! { if (isNull() || value.getString()==null) retval = Const.NULL_STRING; else retval = value.getString(); } else { StringBuffer ret; if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING); else ret=new StringBuffer(value.getString()); if (pad) { int length = value.getLength(); if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS. Const.rightPad(ret, length); } retval=ret.toString(); } return retval; } /** * Converts a Number value to a String, optionally padding the result to the specified length. * @param pad true if you want to pad the resulting string to length. * @return a String optionally padded to the specified length. */ private String toStringNumber(boolean pad) { String retval; if (value==null) return null; if (pad) { if (value.getLength()<1) { if (isNull()) retval=Const.NULL_NUMBER; else { DecimalFormat form= new DecimalFormat(); form.applyPattern(" ##########0.0########;-#########0.0########"); // System.out.println("local.pattern = ["+form.toLocalizedPattern()+"]"); retval=form.format(value.getNumber()); } } else { if (isNull()) { StringBuffer ret=new StringBuffer(Const.NULL_NUMBER); Const.rightPad(ret, value.getLength()); retval=ret.toString(); } else { StringBuffer fmt=new StringBuffer(); int i; DecimalFormat form; if (value.getNumber()>=0) fmt.append(' '); // to compensate for minus sign. if (value.getPrecision()<0) // Default: two decimals { if (value.getLength()<0) // format: 1234,56 (-1,-1) { fmt.append("0.00"); } else // format 0000001234,00 --> (10,-1) { for (i=0;i<value.getLength();i++) fmt.append('0'); fmt.append(".00"); // for the .00 } } else if (value.getLength()==0) // No decimals 0000001234 --> (10,0) { for (i=0;i<value.getLength();i++) fmt.append('0'); // all zeroes. } else // Floating point format 00001234,56 --> (12,2) { for (i=0;i<=value.getLength();i++) fmt.append('0'); // all zeroes. int pos = value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0); if (pos>=0 && pos <fmt.length()) { fmt.setCharAt(value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0), '.'); // one 'comma' } } form= new DecimalFormat(fmt.toString()); retval=form.format(value.getNumber()); } } } else { if (isNull()) retval=Const.NULL_NUMBER; else retval=""+value.getNumber(); } return retval; } /** * Converts a Date value to a String. * The date has format: <code>yyyy/MM/dd HH:mm:ss.SSS</code> * @return a String representing the Date Value. */ private String toStringDate() { String retval; if (value==null) return null; SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US); if (isNull() || value.getDate()==null) retval=Const.NULL_DATE; else { retval=df.format(value.getDate()).toString(); } /* This code was removed as TYPE_VALUE_DATE does not know "length", so this could never be called anyway else { StringBuffer ret; if (isNull() || value.getDate()==null) ret=new StringBuffer(Const.NULL_DATE); else ret=new StringBuffer(df.format(value.getDate()).toString()); Const.rightPad(ret, getLength()<=10?10:getLength()); retval=ret.toString(); } */ return retval; } /** * Returns a String representing the boolean value. * It will be either "true" or "false". * * @return a String representing the boolean value. */ private String toStringBoolean() { // Code was removed from this method as ValueBoolean // did not store length, so some parts could never be // called. String retval; if (value==null) return null; if (isNull()) { retval=Const.NULL_BOOLEAN; } else { retval=value.getBoolean()?"true":"false"; } return retval; } /** * Converts an Integer value to a String, optionally padding the result to the specified length. * @param pad true if you want to pad the resulting string to length. * @return a String optionally padded to the specified length. */ private String toStringInteger(boolean pad) { String retval; if (value==null) return null; if (getLength()<1) { if (isNull()) retval=Const.NULL_INTEGER; else { DecimalFormat form= new DecimalFormat(" ###############0;-###############0"); retval=form.format(value.getInteger()); } } else { if (isNull()) { StringBuffer ret=new StringBuffer(Const.NULL_INTEGER); Const.rightPad(ret, getLength()); retval=ret.toString(); } else { StringBuffer fmt=new StringBuffer(); int i; DecimalFormat form; if (value.getInteger()>=0) fmt.append(' '); // to compensate for minus sign. if (getPrecision()<0) // Default: two decimals { if (getLength()<0) // format: 1234,56 (-1,-1) { fmt.append("0.00"); } else // format 0000001234,00 --> (10,-1) { for (i=0;i<getLength();i++) fmt.append('0'); fmt.append(".00"); // for the .00 } } else if (getPrecision()==0) // No decimals 0000001234 --> (10,0) { for (i=0;i<getLength();i++) fmt.append('0'); // all zeroes. } else // Floating point format 00001234,56 --> (12,2) { for (i=0;i<=getLength();i++) fmt.append('0'); // all zeroes. fmt.setCharAt(getLength()-getPrecision()+1-(value.getInteger()<0?1:0), '.'); // one 'comma' } form= new DecimalFormat(fmt.toString()); retval=form.format(value.getInteger()); } } return retval; } /** * Converts a BigNumber value to a String, optionally padding the result to the specified length. // TODO: BigNumber padding * @param pad true if you want to pad the resulting string to length. * @return a String optionally padded to the specified length. */ private String toStringBigNumber(boolean pad) { if (value.getBigNumber()==null) return null; String retval = value.getString(); // Localise . to , if (Const.DEFAULT_DECIMAL_SEPARATOR!='.') { retval = retval.replace('.', Const.DEFAULT_DECIMAL_SEPARATOR); } return retval; } /** * Sets the length of the Number, Integer or String to the specified length * Note: no truncation of the value takes place, this is meta-data only! * @param l the length to which you want to set the Value. */ public void setLength(int l) { if (value==null) return; value.setLength(l); } /** * Sets the length and the precision of the Number, Integer or String to the specified length & precision * Note: no truncation of the value takes place, this is meta-data only! * @param l the length to which you want to set the Value. * @param p the precision to which you want to set this Value */ public void setLength(int l, int p) { if (value==null) return; value.setLength(l,p); } /** * Get the length of this Value. * @return the length of this Value. */ public int getLength() { if (value==null) return -1; return value.getLength(); } /** * get the precision of this Value * @return the precision of this Value. */ public int getPrecision() { if (value==null) return -1; return value.getPrecision(); } /** * Sets the precision of this Value * Note: no rounding or truncation takes place, this is meta-data only! * @param p the precision to which you want to set this Value. */ public void setPrecision(int p) { if (value==null) return; value.setPrecision(p); } /** * Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... * @return A String describing the type of value. */ public String getTypeDesc() { if (value==null) return "Unknown"; return value.getTypeDesc(); } /** * Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... given a certain integer type * @param t the type to convert to text. * @return A String describing the type of a certain value. */ public static final String getTypeDesc(int t) { return valueTypeCode[t]; } /** * Convert the String description of a type to an integer type. * @param desc The description of the type to convert * @return The integer type of the given String. (Value.VALUE_TYPE_...) */ public static final int getType(String desc) { int i; for (i=1;i<valueTypeCode.length;i++) { if (valueTypeCode[i].equalsIgnoreCase(desc)) { return i; } } return VALUE_TYPE_NONE; } /** * get an array of String describing the possible types a Value can have. * @return an array of String describing the possible types a Value can have. */ public static final String[] getTypes() { String retval[] = new String[valueTypeCode.length-1]; for (int i=1;i<valueTypeCode.length;i++) { retval[i-1]=valueTypeCode[i]; } return retval; } /** * get an array of String describing the possible types a Value can have. * @return an array of String describing the possible types a Value can have. */ public static final String[] getAllTypes() { String retval[] = new String[valueTypeCode.length]; System.arraycopy(valueTypeCode, 0, retval, 0, valueTypeCode.length); return retval; } /** * Sets the Value to null, no type is being changed. * */ public void setNull() { setNull(true); } /** * Sets or unsets a value to null, no type is being changed. * @param n true if you want the value to be null, false if you don't want this to be the case. */ public void setNull(boolean n) { NULL=n; } /** * Checks wheter or not a value is null. * @return true if the Value is null. */ public boolean isNull() { return NULL; } /** * Write the object to an ObjectOutputStream * @param out * @throws IOException */ private void writeObject(java.io.ObjectOutputStream out) throws IOException { writeObj(new DataOutputStream(out)); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { readObj(new DataInputStream(in)); } public void writeObj(DataOutputStream dos) throws IOException { int type=getType(); // Handle type dos.writeInt(getType()); // Handle name-length dos.writeInt(name.length()); // Write name dos.writeChars(name); // length & precision dos.writeInt(getLength()); dos.writeInt(getPrecision()); // NULL? dos.writeBoolean(isNull()); // Handle Content -- only when not NULL if (!isNull()) { switch(type) { case VALUE_TYPE_STRING : case VALUE_TYPE_BIGNUMBER: if (getString()!=null && getString().getBytes().length>0) { dos.writeInt(getString().getBytes("UTF-8").length); dos.writeUTF(getString()); } else { dos.writeInt(0); } break; case VALUE_TYPE_DATE : dos.writeBoolean(getDate()!=null); if (getDate()!=null) { dos.writeLong(getDate().getTime()); } break; case VALUE_TYPE_NUMBER : dos.writeDouble(getNumber()); break; case VALUE_TYPE_BOOLEAN: dos.writeBoolean(getBoolean()); break; case VALUE_TYPE_INTEGER: dos.writeLong(getInteger()); break; default: break; // nothing } } } /** * Write the value, including the meta-data to a DataOutputStream * @param outputStream the OutputStream to write to . * @throws KettleFileException if something goes wrong. */ public void write(OutputStream outputStream) throws KettleFileException { try { writeObj(new DataOutputStream(outputStream)); } catch(Exception e) { throw new KettleFileException("Unable to write value to output stream", e); } } public void readObj(DataInputStream dis) throws IOException { // type int theType = dis.readInt(); newValue(theType); // name-length int nameLength=dis.readInt(); // name StringBuffer nameBuffer=new StringBuffer(); for (int i=0;i<nameLength;i++) nameBuffer.append(dis.readChar()); setName(new String(nameBuffer)); // length & precision setLength(dis.readInt(), dis.readInt()); // Null? setNull(dis.readBoolean()); // Read the values if (!isNull()) { switch(getType()) { case VALUE_TYPE_STRING: case VALUE_TYPE_BIGNUMBER: // Handle lengths int dataLength=dis.readInt(); if (dataLength>0) { String string = dis.readUTF(); setValue(string); } if (theType==VALUE_TYPE_BIGNUMBER) { try { convertString(theType); } catch(KettleValueException e) { throw new IOException("Unable to convert String to BigNumber while reading from data input stream ["+getString()+"]"); } } break; case VALUE_TYPE_DATE: if (dis.readBoolean()) { setValue(new Date(dis.readLong())); } break; case VALUE_TYPE_NUMBER: setValue(dis.readDouble()); break; case VALUE_TYPE_INTEGER: setValue(dis.readLong()); break; case VALUE_TYPE_BOOLEAN: setValue(dis.readBoolean()); break; default: break; } } } /** * Read the Value, including meta-data from a DataInputStream * @param is The InputStream to read the value from * @throws KettleFileException when the Value couldn't be created by reading it from the DataInputStream. */ public Value(InputStream is) throws KettleFileException { try { readObj(new DataInputStream(is)); } catch(EOFException e) { throw new KettleEOFException("End of file reached", e); } catch(Exception e) { throw new KettleFileException("Error reading from data input stream", e); } } /** * Write the data of this Value, without the meta-data to a DataOutputStream * @param dos The DataOutputStream to write the data to * @return true if all went well, false if something went wrong. */ public boolean writeData(DataOutputStream dos) throws KettleFileException { try { // Is the value NULL? dos.writeBoolean(isNull()); // Handle Content -- only when not NULL if (!isNull()) { switch(getType()) { case VALUE_TYPE_STRING : case VALUE_TYPE_BIGNUMBER: if (getString()!=null && getString().getBytes().length>0) { dos.writeInt(getString().getBytes().length); dos.writeUTF(getString()); } else { dos.writeInt(0); } break; case VALUE_TYPE_DATE : dos.writeBoolean(getDate()!=null); if (getDate()!=null) { dos.writeLong(getDate().getTime()); } break; case VALUE_TYPE_NUMBER : dos.writeDouble(getNumber()); break; case VALUE_TYPE_BOOLEAN: dos.writeBoolean(getBoolean()); break; case VALUE_TYPE_INTEGER: dos.writeLong(getInteger()); break; default: break; // nothing } } } catch(IOException e) { throw new KettleFileException("Unable to write value data to output stream", e); } return true; } /** * Read the data of a Value from a DataInputStream, the meta-data of the value has to be set before calling this method! * @param dis the DataInputStream to read from * @throws KettleFileException when the value couldn't be read from the DataInputStream */ public Value(Value metaData, DataInputStream dis) throws KettleFileException { setValue(metaData); setName(metaData.getName()); try { // Is the value NULL? setNull(dis.readBoolean()); // Read the values if (!isNull()) { switch(getType()) { case VALUE_TYPE_STRING: case VALUE_TYPE_BIGNUMBER: // Handle lengths int dataLength=dis.readInt(); if (dataLength>0) { String string = dis.readUTF(); setValue(string); if (metaData.isBigNumber()) convertString(metaData.getType()); } break; case VALUE_TYPE_DATE: if (dis.readBoolean()) { setValue(new Date(dis.readLong())); } break; case VALUE_TYPE_NUMBER: setValue(dis.readDouble()); break; case VALUE_TYPE_INTEGER: setValue(dis.readLong()); break; case VALUE_TYPE_BOOLEAN: setValue(dis.readBoolean()); break; default: break; } } } catch(EOFException e) { throw new KettleEOFException("End of file reached", e); } catch(Exception e) { throw new KettleEOFException("Error reading value data from stream", e); } } /** * Compare 2 values of the same or different type! * The comparison of Strings is case insensitive * @param v the value to compare with. * @return -1 if The value was smaller, 1 bigger and 0 if both values are equal. */ public int compare(Value v) { return compare(v, true); } /** * Compare 2 values of the same or different type! * @param v the value to compare with. * @param caseInsensitive True if you want the comparison to be case insensitive * @return -1 if The value was smaller, 1 bigger and 0 if both values are equal. */ public int compare(Value v, boolean caseInsensitive) { boolean n1 = isNull() || (isString() && (getString()==null || getString().length()==0)) || (isDate() && getDate()==null) || (isBigNumber() && getBigNumber()==null); boolean n2 = v.isNull() || (v.isString() && (v.getString()==null || v.getString().length()==0)) || (v.isDate() && v.getDate()==null) || (v.isBigNumber() && v.getBigNumber()==null); // null is always smaller! if ( n1 && !n2) return -1; if (!n1 && n2) return 1; if ( n1 && n2) return 0; switch(getType()) { case VALUE_TYPE_BOOLEAN: { if (getBoolean() && v.getBoolean() || !getBoolean() && !v.getBoolean()) return 0; // true == true, false == false if (getBoolean() && !v.getBoolean()) return 1; // true > false return -1; // false < true } case VALUE_TYPE_DATE : { return Double.compare(getNumber(), v.getNumber()); } case VALUE_TYPE_NUMBER : { return Double.compare(getNumber(), v.getNumber()); } case VALUE_TYPE_STRING: { String one = Const.rtrim(getString()); String two = Const.rtrim(v.getString()); int cmp=0; if (caseInsensitive) { cmp = one.compareToIgnoreCase(two); } else { cmp = one.compareTo(two); } return cmp; } case VALUE_TYPE_INTEGER: { return Double.compare(getNumber(), v.getNumber()); } case VALUE_TYPE_BIGNUMBER: { return getBigNumber().compareTo(v.getBigNumber()); } } // Still here? Not possible! But hey, give back 0, mkay? return 0; } public boolean equals(Object v) { if (compare((Value)v)==0) return true; else return false; } /** * Check whether this value is equal to the String supplied. * @param string The string to check for equality * @return true if the String representation of the value is equal to string. (ignoring case) */ public boolean isEqualTo(String string) { return getString().equalsIgnoreCase(string); } /** * Check whether this value is equal to the BigDecimal supplied. * @param number The BigDecimal to check for equality * @return true if the BigDecimal representation of the value is equal to number. */ public boolean isEqualTo(BigDecimal number) { return getBigNumber().equals(number); } /** * Check whether this value is equal to the Number supplied. * @param number The Number to check for equality * @return true if the Number representation of the value is equal to number. */ public boolean isEqualTo(double number) { return getNumber() == number; } /** * Check whether this value is equal to the Integer supplied. * @param number The Integer to check for equality * @return true if the Integer representation of the value is equal to number. */ public boolean isEqualTo(long number) { return getInteger() == number; } /** * Check whether this value is equal to the Integer supplied. * @param number The Integer to check for equality * @return true if the Integer representation of the value is equal to number. */ public boolean isEqualTo(int number) { return getInteger() == number; } /** * Check whether this value is equal to the Integer supplied. * @param number The Integer to check for equality * @return true if the Integer representation of the value is equal to number. */ public boolean isEqualTo(byte number) { return getInteger() == number; } /** * Check whether this value is equal to the Date supplied. * @param date The Date to check for equality * @return true if the Date representation of the value is equal to date. */ public boolean isEqualTo(Date date) { return getDate() == date; } public int hashCode() { int hash=0; // name.hashCode(); -> Name shouldn't be part of hashCode()! if (isNull()) { switch(getType()) { case VALUE_TYPE_BOOLEAN : hash^= 1; break; case VALUE_TYPE_DATE : hash^= 2; break; case VALUE_TYPE_NUMBER : hash^= 4; break; case VALUE_TYPE_STRING : hash^= 8; break; case VALUE_TYPE_INTEGER : hash^=16; break; case VALUE_TYPE_BIGNUMBER : hash^=32; break; case VALUE_TYPE_NONE : break; default: break; } } else { switch(getType()) { case VALUE_TYPE_BOOLEAN : hash^=Boolean.valueOf(getBoolean()).hashCode(); break; case VALUE_TYPE_DATE : if (getDate()!=null) hash^=getDate().hashCode(); break; case VALUE_TYPE_INTEGER : case VALUE_TYPE_NUMBER : hash^=(new Double(getNumber())).hashCode(); break; case VALUE_TYPE_STRING : if (getString()!=null) hash^=getString().hashCode(); break; case VALUE_TYPE_BIGNUMBER : if (getBigNumber()!=null) hash^=getBigNumber().hashCode(); break; case VALUE_TYPE_NONE : break; default: break; } } return hash; } // OPERATORS & COMPARATORS public Value and(Value v) { long n1 = getInteger(); long n2 = v.getInteger(); long res = n1 & n2; setValue(res); return this; } public Value xor(Value v) { long n1 = getInteger(); long n2 = v.getInteger(); long res = n1 ^ n2; setValue(res); return this; } public Value or(Value v) { long n1 = getInteger(); long n2 = v.getInteger(); long res = n1 | n2; setValue(res); return this; } public Value bool_and(Value v) { boolean b1 = getBoolean(); boolean b2 = v.getBoolean(); boolean res = b1 && b2; setValue(res); return this; } public Value bool_or(Value v) { boolean b1 = getBoolean(); boolean b2 = v.getBoolean(); boolean res = b1 || b2; setValue(res); return this; } public Value bool_xor(Value v) { boolean b1 = getBoolean(); boolean b2 = v.getBoolean(); boolean res = b1&&b2 ? false : !b1&&!b2 ? false : true; setValue(res); return this; } public Value bool_not() { value.setBoolean(!getBoolean()); return this; } public Value greater_equal(Value v) { if (compare(v)>=0) setValue(true); else setValue(false); return this; } public Value smaller_equal(Value v) { if (compare(v)<=0) setValue(true); else setValue(false); return this; } public Value different(Value v) { if (compare(v)!=0) setValue(true); else setValue(false); return this; } public Value equal(Value v) { if (compare(v)==0) setValue(true); else setValue(false); return this; } public Value like(Value v) { String cmp=v.getString(); // Is cmp part of look? int idx=getString().indexOf(cmp); if (idx<0) setValue(false); else setValue(true); return this; } public Value greater(Value v) { if (compare(v)>0) setValue(true); else setValue(false); return this; } public Value smaller(Value v) { if (compare(v)<0) setValue(true); else setValue(false); return this; } public Value minus(BigDecimal v) throws KettleValueException { return minus(new Value("tmp", v)); } public Value minus(double v) throws KettleValueException { return minus(new Value("tmp", v)); } public Value minus(long v) throws KettleValueException { return minus(new Value("tmp", v)); } public Value minus(int v) throws KettleValueException { return minus(new Value("tmp", (long)v)); } public Value minus(byte v) throws KettleValueException { return minus(new Value("tmp", (long)v)); } public Value minus(Value v) throws KettleValueException { switch(getType()) { case VALUE_TYPE_BIGNUMBER : value.setBigNumber(getBigNumber().subtract(v.getBigNumber())); break; case VALUE_TYPE_NUMBER : value.setNumber(getNumber()-v.getNumber()); break; case VALUE_TYPE_INTEGER : value.setInteger(getInteger()-v.getInteger()); break; case VALUE_TYPE_BOOLEAN : case VALUE_TYPE_STRING : default: throw new KettleValueException("Subtraction can only be done with numbers!"); } return this; } public Value plus(BigDecimal v) { return plus(new Value("tmp", v)); } public Value plus(double v) { return plus(new Value("tmp", v)); } public Value plus(long v) { return plus(new Value("tmp", v)); } public Value plus(int v) { return plus(new Value("tmp", (long)v)); } public Value plus(byte v) { return plus(new Value("tmp", (long)v)); } public Value plus(Value v) { switch(getType()) { case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().add(v.getBigNumber())); break; case VALUE_TYPE_NUMBER : setValue(getNumber()+v.getNumber()); break; case VALUE_TYPE_INTEGER : setValue(getInteger()+v.getInteger()); break; case VALUE_TYPE_BOOLEAN : setValue(getBoolean()|v.getBoolean()); break; case VALUE_TYPE_STRING : setValue(getString()+v.getString()); break; default: break; } return this; } public Value divide(BigDecimal v) throws KettleValueException { return divide(new Value("tmp", v)); } public Value divide(double v) throws KettleValueException { return divide(new Value("tmp", v)); } public Value divide(long v) throws KettleValueException { return divide(new Value("tmp", v)); } public Value divide(int v) throws KettleValueException { return divide(new Value("tmp", (long)v)); } public Value divide(byte v) throws KettleValueException { return divide(new Value("tmp", (long)v)); } public Value divide(Value v) throws KettleValueException { if (isNull() || v.isNull()) { setNull(); } else { switch(getType()) { case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().divide(v.getBigNumber(), BigDecimal.ROUND_UP)); break; case VALUE_TYPE_NUMBER : setValue(getNumber()/v.getNumber()); break; case VALUE_TYPE_INTEGER : setValue(getInteger()/v.getInteger()); break; case VALUE_TYPE_BOOLEAN : case VALUE_TYPE_STRING : default: throw new KettleValueException("Division can only be done with numeric data!"); } } return this; } public Value multiply(BigDecimal v) throws KettleValueException { return multiply(new Value("tmp", v)); } public Value multiply(double v) throws KettleValueException { return multiply(new Value("tmp", v)); } public Value multiply(long v) throws KettleValueException { return multiply(new Value("tmp", v)); } public Value multiply(int v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); } public Value multiply(byte v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); } public Value multiply(Value v) throws KettleValueException { // a number and a string! if (isNull() || v.isNull()) { setNull(); return this; } if ((v.isString() && isNumeric()) || (v.isNumeric() && isString())) { StringBuffer s; String append=""; int n; if (v.isString()) { s=new StringBuffer(v.getString()); append=v.getString(); n=(int)getInteger(); } else { s=new StringBuffer(getString()); append=getString(); n=(int)v.getInteger(); } if (n==0) s.setLength(0); else for (int i=1;i<n;i++) s.append(append); setValue(s); } else // big numbers if (isBigNumber() || v.isBigNumber()) { setValue(getBigNumber().multiply(v.getBigNumber())); } else // numbers if (isNumber() || v.isNumber()) { setValue(getNumber()*v.getNumber()); } else // integers if (isInteger() || v.isInteger()) { setValue(getInteger()*v.getInteger()); } else { throw new KettleValueException("Multiplication can only be done with numbers or a number and a string!"); } return this; } // FUNCTIONS!! // implement the ABS function, arguments in args[] public Value abs() throws KettleValueException { if (isNull()) return this; if (isBigNumber()) { setValue(getBigNumber().abs()); } else if (isNumber()) { setValue(Math.abs(getNumber())); } else if (isInteger()) { setValue(Math.abs(getInteger())); } else { throw new KettleValueException("Function ABS only works with a number"); } return this; } // implement the ACOS function, arguments in args[] public Value acos() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.acos(getNumber())); } else { throw new KettleValueException("Function ACOS only works with numeric data"); } return this; } // implement the ASIN function, arguments in args[] public Value asin() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.asin(getNumber())); } else { throw new KettleValueException("Function ASIN only works with numeric data"); } return this; } // implement the ATAN function, arguments in args[] public Value atan() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.atan(getNumber())); } else { throw new KettleValueException("Function ATAN only works with numeric data"); } return this; } // implement the ATAN2 function, arguments in args[] public Value atan2(Value arg0) throws KettleValueException { return atan2(arg0.getNumber()); } public Value atan2(double arg0) throws KettleValueException { if (isNull()) { return this; } if (isNumeric()) { setValue(Math.atan2(getNumber(), arg0)); } else { throw new KettleValueException("Function ATAN2 only works with numbers"); } return this; } // implement the CEIL function, arguments in args[] public Value ceil() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.ceil(getNumber())); } else { throw new KettleValueException("Function CEIL only works with a number"); } return this; } // implement the COS function, arguments in args[] public Value cos() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.cos(getNumber())); } else { throw new KettleValueException("Function COS only works with a number"); } return this; } // implement the EXP function, arguments in args[] public Value exp() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.exp(getNumber())); } else { throw new KettleValueException("Function EXP only works with a number"); } return this; } // implement the FLOOR function, arguments in args[] public Value floor() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.floor(getNumber())); } else { throw new KettleValueException("Function FLOOR only works with a number"); } return this; } // implement the INITCAP function, arguments in args[] public Value initcap() throws KettleValueException { if (isNull()) return this; if (getType()==VALUE_TYPE_STRING) { if (getString()==null) { setNull(); } else { StringBuffer change=new StringBuffer(getString()); boolean new_word; int i; char lower, upper, ch; new_word=true; for (i=0 ; i<getString().length() ; i++) { lower=change.substring(i,i+1).toLowerCase().charAt(0); // Lowercase is default. upper=change.substring(i,i+1).toUpperCase().charAt(0); // Uppercase for new words. ch=upper; if (new_word) { change.setCharAt(i, upper); } else { change.setCharAt(i, lower); } new_word = false; if ( !(ch>='A' && ch<='Z') && !(ch>='0' && ch<='9') && ch!='_' ) new_word = true; } setValue( change.toString() ); } } else { throw new KettleValueException("Function INITCAP only works with a string"); } return this; } // implement the LENGTH function, arguments in args[] public Value length() throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_INTEGER); setValue(0L); return this; } if (getType()==VALUE_TYPE_STRING) { setValue((double)getString().length()); } else { throw new KettleValueException("Function LENGTH only works with a string"); } return this; } // implement the LOG function, arguments in args[] public Value log() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.log(getNumber())); } else { throw new KettleValueException("Function LOG only works with a number"); } return this; } // implement the LOWER function, arguments in args[] public Value lower() { if (isNull()) { setType(VALUE_TYPE_STRING); } else { setValue( getString().toLowerCase() ); } return this; } // implement the LPAD function: left pad strings or numbers... public Value lpad(Value len) { return lpad((int)len.getNumber(), " "); } public Value lpad(Value len, Value padstr) { return lpad((int)len.getNumber(), padstr.getString()); } public Value lpad(int len) { return lpad(len, " "); } public Value lpad(int len, String padstr) { if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getType()!=VALUE_TYPE_STRING) // also lpad other types! { setValue(getString()); } if (getString()!=null) { StringBuffer result = new StringBuffer(getString()); int pad=len; int l= ( pad-result.length() ) / padstr.length() + 1; int i; for (i=0;i<l;i++) result.insert(0, padstr); // Maybe we added one or two too many! i=result.length(); while (i>pad && pad>0) { result.deleteCharAt(0); i--; } setValue(result.toString()); } else { setNull(); } } setLength(len); return this; } // implement the LTRIM function public Value ltrim() { if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getString()!=null) { StringBuffer s; if (getType()==VALUE_TYPE_STRING) { s = new StringBuffer(getString()); } else { s = new StringBuffer(toString()); } // Left trim while (s.length()>0 && s.charAt(0)==' ') s.deleteCharAt(0); setValue(s); } else { setNull(); } } return this; } // implement the MOD function, arguments in args[] public Value mod(Value arg) throws KettleValueException { return mod(arg.getNumber()); } public Value mod(BigDecimal arg) throws KettleValueException { return mod(arg.doubleValue()); } public Value mod(long arg) throws KettleValueException { return mod((double)arg); } public Value mod(int arg) throws KettleValueException { return mod((double)arg); } public Value mod(byte arg) throws KettleValueException { return mod((double)arg); } public Value mod(double arg0) throws KettleValueException { if (isNull()) return this; if (isNumeric()) { double n1=getNumber(); double n2=arg0; setValue( n1 - (n2 * Math.floor(n1 /n2 )) ); } else { throw new KettleValueException("Function MOD only works with numeric data"); } return this; } // implement the NVL function, arguments in args[] public Value nvl(Value alt) { if (isNull()) setValue(alt); return this; } // implement the POWER function, arguments in args[] public Value power(BigDecimal arg) throws KettleValueException{ return power(new Value("tmp", arg)); } public Value power(double arg) throws KettleValueException{ return power(new Value("tmp", arg)); } public Value power(Value v) throws KettleValueException { if (isNull()) return this; else if (isNumeric()) { setValue( Math.pow(getNumber(), v.getNumber()) ); } else { throw new KettleValueException("Function POWER only works with numeric data"); } return this; } // implement the REPLACE function, arguments in args[] public Value replace(Value repl, Value with) { return replace(repl.getString(), with.getString()); } public Value replace(String repl, String with) { if (isNull()) return this; if (getString()==null) { setNull(); } else { setValue( Const.replace(getString(), repl, with) ); } return this; } /** * Rounds off to the nearest integer.<p> * See also: java.lang.Math.round() * * @return The rounded Number value. */ public Value round() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue( (double)Math.round(getNumber()) ); } else { throw new KettleValueException("Function ROUND only works with a number"); } return this; } /** * Rounds the Number value to a certain number decimal places. * @param decimalPlaces * @return The rounded Number Value * @throws KettleValueException in case it's not a number (or other problem). */ public Value round(int decimalPlaces) throws KettleValueException { if (isNull()) return this; if (isNumeric()) { if (isBigNumber()) { // Multiply by 10^decimalPlaces // For example 123.458343938437, Decimalplaces = 2 // BigDecimal bigDec = getBigNumber(); // System.out.println("ROUND decimalPlaces : "+decimalPlaces+", bigNumber = "+bigDec); bigDec = bigDec.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN); // System.out.println("ROUND finished result : "+bigDec); setValue( bigDec ); } else { setValue( (double)Const.round(getNumber(), decimalPlaces) ); } } else { throw new KettleValueException("Function ROUND only works with a number"); } return this; } // implement the RPAD function, arguments in args[] public Value rpad(Value len) { return rpad((int)len.getNumber(), " "); } public Value rpad(Value len, Value padstr) { return rpad((int)len.getNumber(), padstr.getString()); } public Value rpad(int len) { return rpad(len, " "); } public Value rpad(int len, String padstr) { if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getType()!=VALUE_TYPE_STRING) // also rpad other types! { setValue(getString()); } if (getString()!=null) { StringBuffer result = new StringBuffer(getString()); int pad=len; int l= ( pad-result.length() ) / padstr.length() + 1; int i; for (i=0;i<l;i++) result.append(padstr); // Maybe we added one or two too many! i=result.length(); while (i>pad && pad>0) { result.deleteCharAt(i-1); i--; } setValue(result.toString()); } else { setNull(); } } setLength(len); return this; } // implement the RTRIM function, arguments in args[] public Value rtrim() { if (isNull()) { setType(VALUE_TYPE_STRING); } else { StringBuffer s; if (getType()==VALUE_TYPE_STRING) { s = new StringBuffer(getString()); } else { s = new StringBuffer(toString()); } // Right trim while (s.length()>0 && s.charAt(s.length()-1)==' ') s.deleteCharAt(s.length()-1); setValue(s); } return this; } // implement the SIGN function, arguments in args[] public Value sign() throws KettleValueException { if (isNull()) return this; if (isNumber()) { int cmp = getBigNumber().compareTo(new BigDecimal(0L)); if (cmp>0) value.setBigNumber(new BigDecimal(1L)); else if (cmp<0) value.setBigNumber(new BigDecimal(-1L)); else value.setBigNumber(new BigDecimal(0L)); } else if (isNumber()) { if (getNumber()>0) value.setNumber(1.0); else if (getNumber()<0) value.setNumber(-1.0); else value.setNumber(0.0); } else if (isInteger()) { if (getInteger()>0) value.setInteger(1); else if (getInteger()<0) value.setInteger(-1); else value.setInteger(0); } else { throw new KettleValueException("Function SIGN only works with a number"); } return this; } // implement the SIN function, arguments in args[] public Value sin() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue( Math.sin(getNumber()) ); } else { throw new KettleValueException("Function SIN only works with a number"); } return this; } // implement the SQRT function, arguments in args[] public Value sqrt() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue( Math.sqrt(getNumber()) ); } else { throw new KettleValueException("Function SQRT only works with a number"); } return this; } // implement the SUBSTR function, arguments in args[] public Value substr(Value from, Value to) { return substr((int)from.getNumber(), (int)to.getNumber()); } public Value substr(Value from) { return substr((int)from.getNumber(), -1); } public Value substr(int from) { return substr(from, -1); } public Value substr(int from, int to) { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } setValue( getString() ); if (getString()!=null) { if (to<0 && from>=0) { setValue( getString().substring(from) ); } else if (to>=0 && from>=0) { setValue( getString().substring(from, to) ); } } else { setNull(); } if (!isString()) setType(VALUE_TYPE_STRING); return this; } // implement the RIGHTSTR function, arguments in args[] public Value rightstr(Value len) { return rightstr((int)len.getNumber()); } public Value rightstr(int len) { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } setValue( getString() ); int tot_len = getString()!=null?getString().length():0; if (tot_len>0) { int totlen = getString().length(); int f = totlen-len; if (f<0) f=0; setValue( getString().substring(f) ); } else { setNull(); } if (!isString()) setType(VALUE_TYPE_STRING); return this; } // implement the LEFTSTR function, arguments in args[] public Value leftstr(Value len) { return leftstr((int)len.getNumber()); } public Value leftstr(int len) { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } setValue( getString() ); int tot_len = getString()!=null?getString().length():0; if (tot_len>0) { int totlen = getString().length(); int f = totlen-len; if (f>0) { setValue( getString().substring(0,len) ); } } else { setNull(); } if (!isString()) setType(VALUE_TYPE_STRING); return this; } public Value startsWith(Value string) { return startsWith(string.getString()); } public Value startsWith(String string) { if (isNull()) { setType(VALUE_TYPE_BOOLEAN); return this; } if (string==null) { setValue(false); setNull(); return this; } setValue( getString().startsWith(string) ); return this; } // implement the SYSDATE function, arguments in args[] public Value sysdate() { setValue( Calendar.getInstance().getTime() ); return this; } // implement the TAN function, arguments in args[] public Value tan() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue( Math.tan(getNumber()) ); } else { throw new KettleValueException("Function TAN only works on a number"); } return this; } // implement the TO_CHAR function, arguments in args[] // number: NUM2STR( 123.456 ) : default format // number: NUM2STR( 123.456, '###,##0.000') : format // number: NUM2STR( 123.456, '###,##0.000', '.') : grouping // number: NUM2STR( 123.456, '###,##0.000', '.', ',') : decimal // number: NUM2STR( 123.456, '###,##0.000', '.', ',', '?') : currency public Value num2str() throws KettleValueException { return num2str(null, null, null, null); } public Value num2str(String format) throws KettleValueException { return num2str(format, null, null, null); } public Value num2str(String format, String decimalSymbol) throws KettleValueException { return num2str(format, decimalSymbol, null, null); } public Value num2str(String format, String decimalSymbol, String groupingSymbol) throws KettleValueException { return num2str(format, decimalSymbol, groupingSymbol, null); } public Value num2str(String format, String decimalSymbol, String groupingSymbol, String currencySymbol) throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_STRING); } else { // Number to String conversion... if (getType()==VALUE_TYPE_NUMBER || getType()==VALUE_TYPE_INTEGER) { NumberFormat nf = NumberFormat.getInstance(); DecimalFormat df = (DecimalFormat)nf; DecimalFormatSymbols dfs =new DecimalFormatSymbols(); if (currencySymbol!=null && currencySymbol.length()>0) dfs.setCurrencySymbol( currencySymbol ); if (groupingSymbol!=null && groupingSymbol.length()>0) dfs.setGroupingSeparator( groupingSymbol.charAt(0) ); if (decimalSymbol!=null && decimalSymbol.length()>0) dfs.setDecimalSeparator( decimalSymbol.charAt(0) ); df.setDecimalFormatSymbols(dfs); // in case of 4, 3 or 2 if (format!=null && format.length()>0) df.applyPattern(format); try { setValue( nf.format(getNumber()) ); } catch(Exception e) { setType(VALUE_TYPE_STRING); setNull(); throw new KettleValueException("Couldn't convert Number to String "+e.toString()); } } else { throw new KettleValueException("Function NUM2STR only works on Numbers and Integers"); } } return this; } // date: TO_CHAR( <date> , 'yyyy/mm/dd HH:mm:ss' public Value dat2str() throws KettleValueException { return dat2str(null, null); } public Value dat2str(String arg0) throws KettleValueException { return dat2str(arg0, null); } public Value dat2str(String arg0, String arg1) throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getType()==VALUE_TYPE_DATE) { SimpleDateFormat df = new SimpleDateFormat(); DateFormatSymbols dfs = new DateFormatSymbols(); if (arg1!=null) dfs.setLocalPatternChars(arg1); if (arg0!=null) df.applyPattern(arg0); try { setValue( df.format(getDate()) ); } catch(Exception e) { setType(VALUE_TYPE_STRING); setNull(); throw new KettleValueException("TO_CHAR Couldn't convert Date to String "+e.toString()); } } else { throw new KettleValueException("Function DAT2STR only works on a date"); } } return this; } // implement the TO_DATE function, arguments in args[] public Value num2dat() throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_DATE); } else { if (isNumeric()) { value = new ValueDate(); value.setInteger(getInteger()); setType(VALUE_TYPE_DATE); setLength(-1,-1); } else { throw new KettleValueException("Function NUM2DAT only works on a number"); } } return this; } public Value str2dat(String arg0) throws KettleValueException { return str2dat(arg0, null); } public Value str2dat(String arg0, String arg1) throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_DATE); } else { // System.out.println("Convert string ["+string+"] to date using pattern '"+arg0+"'"); SimpleDateFormat df = new SimpleDateFormat(); DateFormatSymbols dfs = new DateFormatSymbols(); if (arg1!=null) dfs.setLocalPatternChars(arg1); if (arg0!=null) df.applyPattern(arg0); try { value.setDate( df.parse(getString()) ); setType(VALUE_TYPE_DATE); setLength(-1,-1); } catch(Exception e) { setType(VALUE_TYPE_DATE); setNull(); throw new KettleValueException("TO_DATE Couldn't convert String to Date"+e.toString()); } } return this; } // implement the TO_NUMBER function, arguments in args[] public Value str2num() throws KettleValueException { return str2num(null, null, null, null); } public Value str2num(String pattern) throws KettleValueException { return str2num(pattern, null, null, null); } public Value str2num(String pattern, String decimal) throws KettleValueException { return str2num(pattern, decimal, null, null); } public Value str2num(String pattern, String decimal, String grouping) throws KettleValueException { return str2num(pattern, decimal, grouping, null); } public Value str2num(String pattern, String decimal, String grouping, String currency) throws KettleValueException { // 0 : pattern // 1 : Decimal separator // 2 : Grouping separator // 3 : Currency symbol if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getType()==VALUE_TYPE_STRING) { if (getString()==null) { setNull(); setValue(0.0); } else { NumberFormat nf = NumberFormat.getInstance(); DecimalFormat df = (DecimalFormat)nf; DecimalFormatSymbols dfs =new DecimalFormatSymbols(); if ( pattern !=null && pattern .length()>0 ) df.applyPattern( pattern ); if ( decimal !=null && decimal .length()>0 ) dfs.setDecimalSeparator( decimal.charAt(0) ); if ( grouping!=null && grouping.length()>0 ) dfs.setGroupingSeparator( grouping.charAt(0) ); if ( currency!=null && currency.length()>0 ) dfs.setCurrencySymbol( currency ); try { df.setDecimalFormatSymbols(dfs); setValue( nf.parse(getString()).doubleValue() ); } catch(Exception e) { String message = "Couldn't convert string to number "+e.toString(); if ( pattern !=null && pattern .length()>0 ) message+=" pattern="+pattern; if ( decimal !=null && decimal .length()>0 ) message+=" decimal="+decimal; if ( grouping!=null && grouping.length()>0 ) message+=" grouping="+grouping.charAt(0); if ( currency!=null && currency.length()>0 ) message+=" currency="+currency; throw new KettleValueException(message); } } } else { throw new KettleValueException("Function STR2NUM works only on strings"); } } return this; } public Value dat2num() throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_INTEGER); return this; } if (getType()==VALUE_TYPE_DATE) { if (getString()==null) { setNull(); setValue(0L); } else { setValue(getInteger()); } } else { throw new KettleValueException("Function DAT2NUM works only on dates"); } return this; } /** * Performs a right and left trim of spaces in the string. * If the value is not a string a conversion to String is performed first. * * @return The trimmed string value. */ public Value trim() { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } String str = Const.trim(getString()); setValue(str); return this; } // implement the UPPER function, arguments in args[] public Value upper() { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } setValue( getString().toUpperCase() ); return this; } // implement the E function, arguments in args[] public Value e() { setValue(Math.E); return this; } // implement the PI function, arguments in args[] public Value pi() { setValue(Math.PI); return this; } // implement the DECODE function, arguments in args[] public Value v_decode(Value args[]) throws KettleValueException { int i; boolean found; // Decode takes as input the first argument... // The next pair // Limit to 3, 5, 7, 9, ... arguments if (args.length>=3 && (args.length%2)==1) { i=0; found=false; while (i<args.length-1 && !found) { if (this.equals(args[i])) { setValue(args[i+1]); found=true; } i+=2; } if (!found) setValue(args[args.length-1]); } else { // ERROR with nr of arguments throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!"); } return this; } // implement the IF function, arguments in args[] // IF( <condition>, <then value>, <else value>) public Value v_if(Value args[]) throws KettleValueException { if (getType()==VALUE_TYPE_BOOLEAN) { if (args.length==1) { if (getBoolean()) setValue(args[0]); else setNull(); } else if (args.length==2) { if (getBoolean()) setValue(args[0]); else setValue(args[1]); } } else { throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!"); } return this; } // implement the ADD_MONTHS function, one argument public Value add_months(int months) throws KettleValueException { if (getType()==VALUE_TYPE_DATE) { if (!isNull() && getDate()!=null) { Calendar cal = Calendar.getInstance(); cal.setTime(getDate()); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); month+=months; int newyear = year+(int)Math.floor(month/12); int newmonth = month%12; cal.set(newyear, newmonth, 1); int newday = cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (newday<day) cal.set(Calendar.DAY_OF_MONTH, newday); else cal.set(Calendar.DAY_OF_MONTH, day); setValue( cal.getTime() ); } } else { throw new KettleValueException("Function add_months only works on a date!"); } return this; } /** * Add a number of days to a Date value. * * @param days The number of days to add to the current date value * @return The resulting value * @throws KettleValueException */ public Value add_days(long days) throws KettleValueException { if (getType()==VALUE_TYPE_DATE) { if (!isNull() && getDate()!=null) { Calendar cal = Calendar.getInstance(); cal.setTime(getDate()); cal.add(Calendar.DAY_OF_YEAR, (int)days); setValue( cal.getTime() ); } } else { throw new KettleValueException("Function add_days only works on a date!"); } return this; } // implement the LAST_DAY function, arguments in args[] public Value last_day() throws KettleValueException { if (getType()==VALUE_TYPE_DATE) { Calendar cal=Calendar.getInstance(); cal.setTime(getDate()); int last_day = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, last_day); setValue( cal.getTime() ); } else { throw new KettleValueException("Function last_day only works on a date"); } return this; } public Value first_day() throws KettleValueException { if (getType()==VALUE_TYPE_DATE) { Calendar cal=Calendar.getInstance(); cal.setTime(getDate()); cal.set(Calendar.DAY_OF_MONTH, 1); setValue( cal.getTime() ); } else { throw new KettleValueException("Function first_day only works on a date"); } return this; } // implement the TRUNC function, version without arguments public Value trunc() throws KettleValueException { if (isNull()) return this; // don't do anything, leave it at NULL! if (isBigNumber()) { getBigNumber().setScale(0, BigDecimal.ROUND_FLOOR); } else if (isNumber()) { setValue( Math.floor(getNumber()) ); } else if (isInteger()) { // Nothing } else if (isDate()) { Calendar cal=Calendar.getInstance(); cal.setTime(getDate()); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); setValue( cal.getTime() ); } else { throw new KettleValueException("Function TRUNC only works on numbers and dates"); } return this; } // implement the TRUNC function, arguments in args[] public Value trunc(double level) throws KettleValueException { return trunc((int)level); } public Value trunc(int level) throws KettleValueException { if (isNull()) return this; // don't do anything, leave it at NULL! if (isBigNumber()) { getBigNumber().setScale(level, BigDecimal.ROUND_FLOOR); } else if (isNumber()) { double pow=Math.pow(10, level); setValue( Math.floor( getNumber() * pow ) / pow ); } else if (isInteger()) { // Nothing! } else if (isDate()) { Calendar cal=Calendar.getInstance(); cal.setTime(getDate()); switch((int)level) { // MONTHS case 5: cal.set(Calendar.MONTH, 1); // DAYS case 4: cal.set(Calendar.DAY_OF_MONTH, 1); // HOURS case 3: cal.set(Calendar.HOUR_OF_DAY, 0); // MINUTES case 2: cal.set(Calendar.MINUTE, 0); // SECONDS case 1: cal.set(Calendar.SECOND, 0); break; default: throw new KettleValueException("Argument of TRUNC of date has to be between 1 and 5"); } } else { throw new KettleValueException("Function TRUNC only works with numbers and dates"); } return this; } /* Some javascript extensions... * */ public static final Value getInstance() { return new Value(); } public String getClassName() { return "Value"; } public void jsConstructor() { } public void jsConstructor(String name) { setName(name); } public void jsConstructor(String name, String value) { setName(name); setValue(value); } /** * Produce the XML representation of this value. * @return a String containing the XML to represent this Value. */ public String getXML() { StringBuffer retval = new StringBuffer(128); retval.append(XMLHandler.addTagValue("name", getName(), false)); retval.append(XMLHandler.addTagValue("type", getTypeDesc(), false)); retval.append(XMLHandler.addTagValue("text", toString(false), false)); retval.append(XMLHandler.addTagValue("length", getLength(), false)); retval.append(XMLHandler.addTagValue("precision", getPrecision(), false)); retval.append(XMLHandler.addTagValue("isnull", isNull(), false)); return retval.toString(); } /** * Construct a new Value and read the data from XML * @param valnode The XML Node to read from. */ public Value(Node valnode) { this(); loadXML(valnode); } /** * Read the data for this Value from an XML Node * @param valnode The XML Node to read from * @return true if all went well, false if something went wrong. */ public boolean loadXML(Node valnode) { try { String valname = XMLHandler.getTagValue(valnode, "name"); int valtype = getType( XMLHandler.getTagValue(valnode, "type") ); String text = XMLHandler.getTagValue(valnode, "text"); boolean isnull = "Y".equalsIgnoreCase(XMLHandler.getTagValue(valnode, "isnull")); int len = Const.toInt(XMLHandler.getTagValue(valnode, "length"), -1); int prec = Const.toInt(XMLHandler.getTagValue(valnode, "precision"), -1); setName(valname); setValue(text); setLength(len, prec); if (valtype!=VALUE_TYPE_STRING) { trim(); convertString(valtype); } if (isnull) setNull(); } catch(Exception e) { setNull(); return false; } return true; } /** * Convert this Value from type String to another type * @param newtype The Value type to convert to. */ public void convertString(int newtype) throws KettleValueException { switch(newtype) { case VALUE_TYPE_STRING : break; case VALUE_TYPE_NUMBER : setValue( getNumber() ); break; case VALUE_TYPE_DATE : setValue( getDate() ); break; case VALUE_TYPE_BOOLEAN : setValue( getBoolean() ); break; case VALUE_TYPE_INTEGER : setValue( getInteger() ); break; case VALUE_TYPE_BIGNUMBER : setValue( getBigNumber() ); break; default: throw new KettleValueException("Please specify the type to convert to from String type."); } } public Value(Repository rep, long id_value) throws KettleException { try { Row r = rep.getValue(id_value); if (r!=null) { name = r.getString("NAME", null); String valstr = r.getString("VALUE_STR", null); setValue( valstr ); int valtype = getType( r.getString("VALUE_TYPE", null) ); setType(valtype); setNull( r.getBoolean("IS_NULL", false) ); } } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load Value from repository with id_value="+id_value, dbe); } } }
src/be/ibridge/kettle/core/value/Value.java
/********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.core.value; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.math.BigDecimal; import java.text.DateFormatSymbols; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.w3c.dom.Node; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.XMLInterface; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleEOFException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleFileException; import be.ibridge.kettle.core.exception.KettleValueException; import be.ibridge.kettle.repository.Repository; /** * This class is one of the core classes of the Kettle framework. * It contains everything you need to manipulate atomic data (Values/Fields/...) * and to describe it in the form of meta-data. (name, length, precision, etc.) * * @author Matt * @since Beginning 2003 */ public class Value implements Cloneable, XMLInterface, Serializable { private static final long serialVersionUID = -6310073485210258622L; /** * Value type indicating that the value has no type set. */ public static final int VALUE_TYPE_NONE = 0; /** * Value type indicating that the value contains a floating point double precision number. */ public static final int VALUE_TYPE_NUMBER = 1; /** * Value type indicating that the value contains a text String. */ public static final int VALUE_TYPE_STRING = 2; /** * Value type indicating that the value contains a Date. */ public static final int VALUE_TYPE_DATE = 3; /** * Value type indicating that the value contains a boolean. */ public static final int VALUE_TYPE_BOOLEAN = 4; /** * Value type indicating that the value contains a long integer. */ public static final int VALUE_TYPE_INTEGER = 5; /** * Value type indicating that the value contains a floating point precision number with arbitrary precision. */ public static final int VALUE_TYPE_BIGNUMBER = 6; /** * Value type indicating that the value contains an Object. */ public static final int VALUE_TYPE_SERIALIZABLE = 7; /** * The descriptions of the value types. */ private static final String valueTypeCode[]= { "-", // $NON-NLS-1$ "Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable" // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$ $NON-NLS-5$ $NON-NLS-6$ }; private ValueInterface value; private String name; private String origin; private boolean NULL; /** * Constructs a new Value of type EMPTY * */ public Value() { clearValue(); } /** * Constructs a new Value with a name. * * @param name Sets the name of the Value */ public Value(String name) { clearValue(); setName(name); } /** * Constructs a new Value with a name and a type. * * @param name Sets the name of the Value * @param val_type Sets the type of the Value (Value.VALUE_TYPE_*) */ public Value(String name, int val_type) { clearValue(); newValue(val_type); setName(name); } /** * This method allocates a new value of the appropriate type.. * @param val_type The new type of value */ private void newValue(int val_type) { switch(val_type) { case VALUE_TYPE_NUMBER : value = new ValueNumber(); break; case VALUE_TYPE_STRING : value = new ValueString(); break; case VALUE_TYPE_DATE : value = new ValueDate(); break; case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(); break; case VALUE_TYPE_INTEGER : value = new ValueInteger(); break; case VALUE_TYPE_BIGNUMBER: value = new ValueBigNumber(); break; default: value = null; } } /** * Convert the value to another type. This only works if a value has been set previously. * That is the reason this method is private. Rather, use the public method setType(int type). * * @param val_type The type to convert to. */ private void convertTo(int val_type) { if (value!=null) { switch(val_type) { case VALUE_TYPE_NUMBER : value = new ValueNumber(value.getNumber()); break; case VALUE_TYPE_STRING : value = new ValueString(value.getString()); break; case VALUE_TYPE_DATE : value = new ValueDate(value.getDate()); break; case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(value.getBoolean()); break; case VALUE_TYPE_INTEGER : value = new ValueInteger(value.getInteger()); break; case VALUE_TYPE_BIGNUMBER : value = new ValueBigNumber(value.getBigNumber()); break; default: value = null; } } } /** * Constructs a new Value with a name, a type, length and precision. * * @param name Sets the name of the Value * @param val_type Sets the type of the Value (Value.VALUE_TYPE_*) * @param length The length of the value * @param precision The precision of the value */ public Value(String name, int val_type, int length, int precision) { this(name, val_type); setLength(length, precision); } /** * Constructs a new Value of Type VALUE_TYPE_BIGNUMBER, with a name, containing a BigDecimal number * * @param name Sets the name of the Value * @param bignum The number to store in this Value */ public Value(String name, BigDecimal bignum) { clearValue(); setValue(bignum); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_NUMBER, with a name, containing a number * * @param name Sets the name of the Value * @param num The number to store in this Value */ public Value(String name, double num) { clearValue(); setValue(num); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String * * @param name Sets the name of the Value * @param str The text to store in this Value */ public Value(String name, StringBuffer str) { this(name, str.toString()); } /** * Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String * * @param name Sets the name of the Value * @param str The text to store in this Value */ public Value(String name, String str) { clearValue(); setValue(str); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_DATE, with a name, containing a Date * * @param name Sets the name of the Value * @param dat The date to store in this Value */ public Value(String name, Date dat) { clearValue(); setValue(dat); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_BOOLEAN, with a name, containing a boolean value * * @param name Sets the name of the Value * @param bool The boolean to store in this Value */ public Value(String name, boolean bool) { clearValue(); setValue(bool); setName(name); } /** * Constructs a new Value of Type VALUE_TYPE_INTEGER, with a name, containing an integer number * * @param name Sets the name of the Value * @param l The integer to store in this Value */ public Value(String name, long l) { clearValue(); setValue(l); setName(name); } /** * Constructs a new Value as a copy of another value and renames it... * * @param name The new name of the copied Value * @param v The value to be copied */ public Value(String name, Value v) { this(v); setName(name); } /** * Constructs a new Value as a copy of another value * * @param v The Value to be copied */ public Value(Value v) { if (v!=null) { setType( v.getType() ); value = v.getValueCopy(); setName(v.getName()); setLength(v.getLength(), v.getPrecision()); setNull(v.isNull()); setOrigin(v.origin); } else { clearValue(); setNull(true); } } public Object clone() { Value retval = null; try { retval = (Value)super.clone(); } catch(CloneNotSupportedException e) { retval=null; } return retval; } /** * Build a copy of this Value * @return a copy of another value * */ public Value Clone() { Value v = new Value(this); return v; } /** * Clears the content and name of a Value * */ public void clearValue() { value = null; name = null; NULL = false; origin = null; } private ValueInterface getValueCopy() { if (value==null) return null; return (ValueInterface)value.clone(); } /** * Sets the name of a Value * * @param name The new name of the value */ public void setName(String name) { this.name = name; } /** * Obtain the name of a Value * * @return The name of the Value */ public String getName() { return name; } /** * This method allows you to set the origin of the Value by means of the name of the originating step. * * @param step_of_origin The step of origin. */ public void setOrigin(String step_of_origin) { origin = step_of_origin; } /** * Obtain the origin of the step. * * @return The name of the originating step */ public String getOrigin() { return origin; } /** * Sets the value to a BigDecimal number value. * @param num The number value to set the value to */ public void setValue(BigDecimal num) { if (value==null || value.getType()!=VALUE_TYPE_BIGNUMBER) value = new ValueBigNumber(num); else value.setBigNumber(num); setNull(false); } /** * Sets the value to a double Number value. * @param num The number value to set the value to */ public void setValue(double num) { if (value==null || value.getType()!=VALUE_TYPE_NUMBER) value = new ValueNumber(num); else value.setNumber(num); setNull(false); } /** * Sets the Value to a String text * @param str The StringBuffer to get the text from */ public void setValue(StringBuffer str) { if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str.toString()); else value.setString(str.toString()); setNull(str==null); } /** * Sets the Value to a String text * @param str The String to get the text from */ public void setValue(String str) { if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str); else value.setString(str); setNull(str==null); } public void setSerializedValue(Serializable ser) { if (value==null || value.getType()!=VALUE_TYPE_SERIALIZABLE) value = new ValueSerializable(ser); else value.setSerializable(ser); setNull(ser==null); } /** * Sets the Value to a Date * @param dat The Date to set the Value to */ public void setValue(Date dat) { if (value==null || value.getType()!=VALUE_TYPE_DATE) value = new ValueDate(dat); else value.setDate(dat); setNull(dat==null); } /** * Sets the Value to a boolean * @param bool The boolean to set the Value to */ public void setValue(boolean bool) { if (value==null || value.getType()!=VALUE_TYPE_BOOLEAN) value = new ValueBoolean(bool); else value.setBoolean(bool); setNull(false); } /** * Sets the Value to a long integer * @param b The byte to convert to a long integer to which the Value is set. */ public void setValue(byte b) { setValue((long)b); } /** * Sets the Value to a long integer * @param i The integer to convert to a long integer to which the Value is set. */ public void setValue(int i) { setValue((long)i); } /** * Sets the Value to a long integer * @param l The long integer to which the Value is set. */ public void setValue(long l) { if (value==null || value.getType()!=VALUE_TYPE_INTEGER) value = new ValueInteger(l); else value.setInteger(l); setNull(false); } /** * Copy the Value from another Value. * It doesn't copy the name. * @param v The Value to copy the settings and value from */ public void setValue(Value v) { if (v!=null) { value = v.getValueCopy(); setNull(v.isNull()); setOrigin(v.origin); } else { clearValue(); } } /** * Get the BigDecimal number of this Value. * If the value is not of type BIG_NUMBER, a conversion is done first. * @return the double precision floating point number of this Value. */ public BigDecimal getBigNumber() { if (value==null || isNull()) return null; return value.getBigNumber(); } /** * Get the double precision floating point number of this Value. * If the value is not of type NUMBER, a conversion is done first. * @return the double precision floating point number of this Value. */ public double getNumber() { if (value==null || isNull()) return 0.0; return value.getNumber(); } /** * Get the String text representing this value. * If the value is not of type STRING, a conversion if done first. * @return the String text representing this value. */ public String getString() { if (value==null || isNull()) return null; return value.getString(); } /** * Get the length of the String representing this value. * @return the length of the String representing this value. */ public int getStringLength() { String s = getString(); if (s==null) return 0; return s.length(); } /** * Get the Date of this Value. * If the Value is not of type DATE, a conversion is done first. * @return the Date of this Value. */ public Date getDate() { if (value==null || isNull()) return null; return value.getDate(); } /** * Get the Serializable of this Value. * If the Value is not of type Serializable, it returns null. * @return the Serializable of this Value. */ public Serializable getSerializable() { if (value==null || isNull() || value.getType() != VALUE_TYPE_SERIALIZABLE) return null; return value.getSerializable(); } /** * Get the boolean value of this Value. * If the Value is not of type BOOLEAN, it will be converted. * <p>Strings: "YES", "Y", "TRUE" (case insensitive) to true, the rest false * <p>Number: 0.0 is false, the rest is true. * <p>Integer: 0 is false, the rest is true. * <p>Date: always false. * @return the boolean representation of this Value. */ public boolean getBoolean() { if (value==null || isNull()) return false; return value.getBoolean(); } /** * Get the long integer representation of this value. * If the Value is not of type INTEGER, it will be converted: * <p>String: try to convert to a long value, 0L if it didn't work. * <p>Number: round the double value and return the resulting long integer. * <p>Date: return the number of miliseconds after <code>1970:01:01 00:00:00</code> * <p>Date: always false. * * @return the long integer representation of this value. */ public long getInteger() { if (value==null || isNull()) return 0L; return value.getInteger(); } /** * Set the type of this Value * @param val_type The type to which the Value will be set. */ public void setType(int val_type) { if (value==null) newValue(val_type); else // Convert the value to the appropriate type... { convertTo(val_type); } } /** * Returns the type of this Value * @return the type of this Value */ public int getType() { if (value==null) return VALUE_TYPE_NONE; return value.getType(); } /** * Checks whether or not this Value is empty. * A value is empty if it has the type VALUE_TYPE_EMPTY * @return true if the value is empty. */ public boolean isEmpty() { if (value==null) return true; return false; } /** * Checks wheter or not the value is a String. * @return true if the value is a String. */ public boolean isString() { if (value==null) return false; return value.getType()==VALUE_TYPE_STRING; } /** * Checks whether or not this value is a Date * @return true if the value is a Date */ public boolean isDate() { if (value==null) return false; return value.getType()==VALUE_TYPE_DATE; } /** * Checks whether or not the value is a Big Number * @return true is this value is a big number */ public boolean isBigNumber() { if (value==null) return false; return value.getType()==VALUE_TYPE_BIGNUMBER; } /** * Checks whether or not the value is a Number * @return true is this value is a number */ public boolean isNumber() { if (value==null) return false; return value.getType()==VALUE_TYPE_NUMBER; } /** * Checks whether or not this value is a boolean * @return true if this value has type boolean. */ public boolean isBoolean() { if (value==null) return false; return value.getType()==VALUE_TYPE_BOOLEAN; } /** * Checks whether or not this value is of type Serializable * @retur true if this value has type Serializable */ public boolean isSerializableType() { if(value == null) { return false; } return value.getType() == VALUE_TYPE_SERIALIZABLE; } /** * Checks whether or not this value is an Integer * @return true if this value is an integer */ public boolean isInteger() { if (value==null) return false; return value.getType()==VALUE_TYPE_INTEGER; } /** * Checks whether or not this Value is Numeric * A Value is numeric if it is either of type Number or Integer * @return true if the value is either of type Number or Integer */ public boolean isNumeric() { return isInteger() || isNumber() || isBigNumber(); } /** * Checks whether or not the specified type is either Integer or Number * @param t the type to check * @return true if the type is Integer or Number */ public static final boolean isNumeric(int t) { return t==VALUE_TYPE_INTEGER || t==VALUE_TYPE_NUMBER || t==VALUE_TYPE_BIGNUMBER; } /** * Returns a padded to length String text representation of this Value * @return a padded to length String text representation of this Value */ public String toString() { return toString(true); } /** * a String text representation of this Value, optionally padded to the specified length * @param pad true if you want to pad the resulting String * @return a String text representation of this Value, optionally padded to the specified length */ public String toString(boolean pad) { String retval; switch(getType()) { case VALUE_TYPE_STRING : retval=toStringString(pad); break; case VALUE_TYPE_NUMBER : retval=toStringNumber(pad); break; case VALUE_TYPE_DATE : retval=toStringDate(); break; case VALUE_TYPE_BOOLEAN: retval=toStringBoolean(); break; case VALUE_TYPE_INTEGER: retval=toStringInteger(pad); break; case VALUE_TYPE_BIGNUMBER: retval=toStringBigNumber(pad); break; default: retval=""; break; } return retval; } /** * a String text representation of this Value, optionally padded to the specified length * @param pad true if you want to pad the resulting String * @return a String text representation of this Value, optionally padded to the specified length */ public String toStringMeta() { // We (Sven Boden) did explicit performance testing for this // part. The original version used Strings instead of StringBuffers, // performance between the 2 does not differ that much. A few milliseconds // on 100000 iterations in the advantage of StringBuffers. The // lessened creation of objects may be worth it in the long run. StringBuffer retval=new StringBuffer(getTypeDesc()); switch(getType()) { case VALUE_TYPE_STRING : if (getLength()>0) retval.append('(').append(getLength()).append(')'); break; case VALUE_TYPE_NUMBER : case VALUE_TYPE_BIGNUMBER : if (getLength()>0) { retval.append('(').append(getLength()); if (getPrecision()>0) { retval.append(", ").append(getPrecision()); } retval.append(')'); } break; case VALUE_TYPE_INTEGER: if (getLength()>0) { retval.append('(').append(getLength()).append(')'); } break; default: break; } return retval.toString(); } /** * Converts a String Value to String optionally padded to the specified length. * @param pad true if you want to pad the resulting string to length. * @return a String optionally padded to the specified length. */ private String toStringString(boolean pad) { String retval=null; if (value==null) return null; if (value.getLength()<=0) // No length specified! { if (isNull() || value.getString()==null) retval = Const.NULL_STRING; else retval = value.getString(); } else { StringBuffer ret; if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING); else ret=new StringBuffer(value.getString()); if (pad) { int length = value.getLength(); if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS. Const.rightPad(ret, length); } retval=ret.toString(); } return retval; } /** * Converts a Number value to a String, optionally padding the result to the specified length. * @param pad true if you want to pad the resulting string to length. * @return a String optionally padded to the specified length. */ private String toStringNumber(boolean pad) { String retval; if (value==null) return null; if (pad) { if (value.getLength()<1) { if (isNull()) retval=Const.NULL_NUMBER; else { DecimalFormat form= new DecimalFormat(); form.applyPattern( " ##########0.0########;-#########0.0########" ); // System.out.println("local.pattern = ["+form.toLocalizedPattern()+"]"); retval=form. format(value.getNumber()); } } else { if (isNull()) { StringBuffer ret=new StringBuffer(Const.NULL_NUMBER); Const.rightPad(ret, value.getLength()); retval=ret.toString(); } else { StringBuffer fmt=new StringBuffer(); int i; DecimalFormat form; if (value.getNumber()>=0) fmt.append(' '); // to compensate for minus sign. if (value.getPrecision()<0) // Default: two decimals { if (value.getLength()<0) // format: 1234,56 (-1,-1) { fmt.append("0.00"); } else // format 0000001234,00 --> (10,-1) { for (i=0;i<value.getLength();i++) fmt.append('0'); fmt.append(".00"); // for the .00 } } else if (value.getLength()==0) // No decimals 0000001234 --> (10,0) { for (i=0;i<value.getLength();i++) fmt.append('0'); // all zeroes. } else // Floating point format 00001234,56 --> (12,2) { for (i=0;i<=value.getLength();i++) fmt.append('0'); // all zeroes. int pos = value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0); if (pos>=0 && pos <fmt.length()) { fmt.setCharAt(value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0), '.'); // one 'comma' } } form= new DecimalFormat(fmt.toString()); retval=form.format(value.getNumber()); } } } else { if (isNull()) retval=Const.NULL_NUMBER; else retval=""+value.getNumber(); } return retval; } /** * Converts a Date value to a String. * The date has format: <code>yyyy/MM/dd HH:mm:ss.SSS</code> * @return a String representing the Date Value. */ private String toStringDate() { String retval; if (value==null) return null; SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US); if (isNull() || value.getDate()==null) retval=Const.NULL_DATE; else { retval=df.format(value.getDate()).toString(); } /* This code was removed as TYPE_VALUE_DATE does not know "length", so this could never be called anyway else { StringBuffer ret; if (isNull() || value.getDate()==null) ret=new StringBuffer(Const.NULL_DATE); else ret=new StringBuffer(df.format(value.getDate()).toString()); Const.rightPad(ret, getLength()<=10?10:getLength()); retval=ret.toString(); } */ return retval; } /** * Returns a String representing the boolean value. * It will be either "true" or "false". * * @return a String representing the boolean value. */ private String toStringBoolean() { // Code was removed from this method as ValueBoolean // did not store length, so some parts could never be // called. String retval; if (value==null) return null; if (isNull()) { retval=Const.NULL_BOOLEAN; } else { retval=value.getBoolean()?"true":"false"; } return retval; } /** * Converts an Integer value to a String, optionally padding the result to the specified length. * @param pad true if you want to pad the resulting string to length. * @return a String optionally padded to the specified length. */ private String toStringInteger(boolean pad) { String retval; if (value==null) return null; if (getLength()<1) { if (isNull()) retval=Const.NULL_INTEGER; else { DecimalFormat form= new DecimalFormat(" ###############0;-###############0"); retval=form.format(value.getInteger()); } } else { if (isNull()) { StringBuffer ret=new StringBuffer(Const.NULL_INTEGER); Const.rightPad(ret, getLength()); retval=ret.toString(); } else { StringBuffer fmt=new StringBuffer(); int i; DecimalFormat form; if (value.getInteger()>=0) fmt.append(" "); // to compensate for minus sign. if (getPrecision()<0) // Default: two decimals { if (getLength()<0) // format: 1234,56 (-1,-1) { fmt.append("0.00"); } else // format 0000001234,00 --> (10,-1) { for (i=0;i<getLength();i++) fmt.append("0"); fmt.append(".00"); // for the .00 } } else if (getPrecision()==0) // No decimals 0000001234 --> (10,0) { for (i=0;i<getLength();i++) fmt.append("0"); // all zeroes. } else // Floating point format 00001234,56 --> (12,2) { for (i=0;i<=getLength();i++) fmt.append("0"); // all zeroes. fmt.setCharAt(getLength()-getPrecision()+1-(value.getInteger()<0?1:0), '.'); // one 'comma' } form= new DecimalFormat(fmt.toString()); retval=form.format(value.getInteger()); } } return retval; } /** * Converts a BigNumber value to a String, optionally padding the result to the specified length. // TODO: BigNumber padding * @param pad true if you want to pad the resulting string to length. * @return a String optionally padded to the specified length. */ private String toStringBigNumber(boolean pad) { if (value.getBigNumber()==null) return null; String retval = value.getString(); // Localise . to , if (Const.DEFAULT_DECIMAL_SEPARATOR!='.') { retval = retval.replace('.', Const.DEFAULT_DECIMAL_SEPARATOR); } return retval; } /** * Sets the length of the Number, Integer or String to the specified length * Note: no truncation of the value takes place, this is meta-data only! * @param l the length to which you want to set the Value. */ public void setLength(int l) { if (value==null) return; value.setLength(l); } /** * Sets the length and the precision of the Number, Integer or String to the specified length & precision * Note: no truncation of the value takes place, this is meta-data only! * @param l the length to which you want to set the Value. * @param p the precision to which you want to set this Value */ public void setLength(int l, int p) { if (value==null) return; value.setLength(l,p); } /** * Get the length of this Value. * @return the length of this Value. */ public int getLength() { if (value==null) return -1; return value.getLength(); } /** * get the precision of this Value * @return the precision of this Value. */ public int getPrecision() { if (value==null) return -1; return value.getPrecision(); } /** * Sets the precision of this Value * Note: no rounding or truncation takes place, this is meta-data only! * @param p the precision to which you want to set this Value. */ public void setPrecision(int p) { if (value==null) return; value.setPrecision(p); } /** * Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... * @return A String describing the type of value. */ public String getTypeDesc() { if (value==null) return "Unknown"; return value.getTypeDesc(); } /** * Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... given a certain integer type * @param t the type to convert to text. * @return A String describing the type of a certain value. */ public static final String getTypeDesc(int t) { return valueTypeCode[t]; } /** * Convert the String description of a type to an integer type. * @param desc The description of the type to convert * @return The integer type of the given String. (Value.VALUE_TYPE_...) */ public static final int getType(String desc) { int i; for (i=1;i<valueTypeCode.length;i++) { if (valueTypeCode[i].equalsIgnoreCase(desc)) { return i; } } return VALUE_TYPE_NONE; } /** * get an array of String describing the possible types a Value can have. * @return an array of String describing the possible types a Value can have. */ public static final String[] getTypes() { String retval[] = new String[valueTypeCode.length-1]; for (int i=1;i<valueTypeCode.length;i++) { retval[i-1]=valueTypeCode[i]; } return retval; } /** * get an array of String describing the possible types a Value can have. * @return an array of String describing the possible types a Value can have. */ public static final String[] getAllTypes() { String retval[] = new String[valueTypeCode.length]; System.arraycopy(valueTypeCode, 0, retval, 0, valueTypeCode.length); return retval; } /** * Sets the Value to null, no type is being changed. * */ public void setNull() { setNull(true); } /** * Sets or unsets a value to null, no type is being changed. * @param n true if you want the value to be null, false if you don't want this to be the case. */ public void setNull(boolean n) { NULL=n; } /** * Checks wheter or not a value is null. * @return true if the Value is null. */ public boolean isNull() { return NULL; } /** * Write the object to an ObjectOutputStream * @param out * @throws IOException */ private void writeObject(java.io.ObjectOutputStream out) throws IOException { writeObj(new DataOutputStream(out)); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { readObj(new DataInputStream(in)); } public void writeObj(DataOutputStream dos) throws IOException { int type=getType(); // Handle type dos.writeInt( getType() ); // Handle name-length dos.writeInt( name.length() ); // Write name dos.writeChars( name ); // length & precision dos.writeInt( getLength() ); dos.writeInt( getPrecision() ); // NULL? dos.writeBoolean(isNull()); // Handle Content -- only when not NULL if (!isNull()) { switch(type) { case VALUE_TYPE_STRING : case VALUE_TYPE_BIGNUMBER: if (getString()!=null && getString().getBytes().length>0) { dos.writeInt(getString().getBytes("UTF-8").length); dos.writeUTF(getString()); } else { dos.writeInt(0); } break; case VALUE_TYPE_DATE : dos.writeBoolean(getDate()!=null); if (getDate()!=null) { dos.writeLong(getDate().getTime()); } break; case VALUE_TYPE_NUMBER : dos.writeDouble(getNumber()); break; case VALUE_TYPE_BOOLEAN: dos.writeBoolean(getBoolean()); break; case VALUE_TYPE_INTEGER: dos.writeLong(getInteger()); break; default: break; // nothing } } } /** * Write the value, including the meta-data to a DataOutputStream * @param outputStream the OutputStream to write to . * @throws KettleFileException if something goes wrong. */ public void write(OutputStream outputStream) throws KettleFileException { try { writeObj(new DataOutputStream(outputStream)); } catch(Exception e) { throw new KettleFileException("Unable to write value to output stream", e); } } public void readObj(DataInputStream dis) throws IOException { // type int theType = dis.readInt(); newValue(theType); // name-length int nameLength=dis.readInt(); // name StringBuffer nameBuffer=new StringBuffer(); for (int i=0;i<nameLength;i++) nameBuffer.append( dis.readChar() ); setName(new String(nameBuffer)); // length & precision setLength( dis.readInt(), dis.readInt() ); // Null? setNull( dis.readBoolean() ); // Read the values if (!isNull()) { switch(getType()) { case VALUE_TYPE_STRING: case VALUE_TYPE_BIGNUMBER: // Handle lengths int dataLength=dis.readInt(); if (dataLength>0) { String string = dis.readUTF(); setValue( string ); } if (theType==VALUE_TYPE_BIGNUMBER) { try { convertString(theType); } catch(KettleValueException e) { throw new IOException("Unable to convert String to BigNumber while reading from data input stream ["+getString()+"]"); } } break; case VALUE_TYPE_DATE: if (dis.readBoolean()) { setValue(new Date(dis.readLong())); } break; case VALUE_TYPE_NUMBER: setValue( dis.readDouble() ); break; case VALUE_TYPE_INTEGER: setValue( dis.readLong() ); break; case VALUE_TYPE_BOOLEAN: setValue( dis.readBoolean() ); break; default: break; } } } /** * Read the Value, including meta-data from a DataInputStream * @param is The InputStream to read the value from * @throws KettleFileException when the Value couldn't be created by reading it from the DataInputStream. */ public Value(InputStream is) throws KettleFileException { try { readObj(new DataInputStream(is)); } catch(EOFException e) { throw new KettleEOFException("End of file reached", e); } catch(Exception e) { throw new KettleFileException("Error reading from data input stream", e); } } /** * Write the data of this Value, without the meta-data to a DataOutputStream * @param dos The DataOutputStream to write the data to * @return true if all went well, false if something went wrong. */ public boolean writeData(DataOutputStream dos) throws KettleFileException { try { // Is the value NULL? dos.writeBoolean(isNull()); // Handle Content -- only when not NULL if (!isNull()) { switch(getType()) { case VALUE_TYPE_STRING : case VALUE_TYPE_BIGNUMBER: if (getString()!=null && getString().getBytes().length>0) { dos.writeInt(getString().getBytes().length); dos.writeUTF(getString()); } else { dos.writeInt(0); } break; case VALUE_TYPE_DATE : dos.writeBoolean(getDate()!=null); if (getDate()!=null) { dos.writeLong(getDate().getTime()); } break; case VALUE_TYPE_NUMBER : dos.writeDouble(getNumber()); break; case VALUE_TYPE_BOOLEAN: dos.writeBoolean(getBoolean()); break; case VALUE_TYPE_INTEGER: dos.writeLong(getInteger()); break; default: break; // nothing } } } catch(IOException e) { throw new KettleFileException("Unable to write value data to output stream", e); } return true; } /** * Read the data of a Value from a DataInputStream, the meta-data of the value has to be set before calling this method! * @param dis the DataInputStream to read from * @throws KettleFileException when the value couldn't be read from the DataInputStream */ public Value(Value metaData, DataInputStream dis) throws KettleFileException { setValue(metaData); setName(metaData.getName()); try { // Is the value NULL? setNull(dis.readBoolean()); // Read the values if (!isNull()) { switch(getType()) { case VALUE_TYPE_STRING: case VALUE_TYPE_BIGNUMBER: // Handle lengths int dataLength=dis.readInt(); if (dataLength>0) { String string = dis.readUTF(); setValue( string ); if (metaData.isBigNumber()) convertString(metaData.getType()); } break; case VALUE_TYPE_DATE: if (dis.readBoolean()) { setValue(new Date(dis.readLong())); } break; case VALUE_TYPE_NUMBER: setValue( dis.readDouble() ); break; case VALUE_TYPE_INTEGER: setValue( dis.readLong() ); break; case VALUE_TYPE_BOOLEAN: setValue( dis.readBoolean() ); break; default: break; } } } catch(EOFException e) { throw new KettleEOFException("End of file reached", e); } catch(Exception e) { throw new KettleEOFException("Error reading value data from stream", e); } } /** * Compare 2 values of the same or different type! * The comparison of Strings is case insensitive * @param v the value to compare with. * @return -1 if The value was smaller, 1 bigger and 0 if both values are equal. */ public int compare(Value v) { return compare(v, true); } /** * Compare 2 values of the same or different type! * @param v the value to compare with. * @param caseInsensitive True if you want the comparison to be case insensitive * @return -1 if The value was smaller, 1 bigger and 0 if both values are equal. */ public int compare(Value v, boolean caseInsensitive) { boolean n1 = isNull() || ( isString() && ( getString()==null || getString().length()==0 )) || ( isDate() && getDate()==null) || ( isBigNumber() && getBigNumber()==null); boolean n2 = v.isNull() || (v.isString() && ( v.getString()==null || v.getString().length()==0 )) || (v.isDate() && v.getDate()==null) || (v.isBigNumber() && v.getBigNumber()==null); // null is always smaller! if ( n1 && !n2) return -1; if (!n1 && n2) return 1; if ( n1 && n2) return 0; switch(getType()) { case VALUE_TYPE_BOOLEAN: { if ( getBoolean() && v.getBoolean() || !getBoolean() && !v.getBoolean()) return 0; // true == true, false == false if ( getBoolean() && !v.getBoolean()) return 1; // true > false return -1; // false < true } case VALUE_TYPE_DATE : { return Double.compare(getNumber(), v.getNumber()); } case VALUE_TYPE_NUMBER : { return Double.compare(getNumber(), v.getNumber()); } case VALUE_TYPE_STRING: { String one = Const.rtrim(getString()); String two = Const.rtrim(v.getString()); int cmp=0; if (caseInsensitive) { cmp = one.compareToIgnoreCase(two); } else { cmp = one.compareTo(two); } return cmp; } case VALUE_TYPE_INTEGER: { return Double.compare(getNumber(), v.getNumber()); } case VALUE_TYPE_BIGNUMBER: { return getBigNumber().compareTo(v.getBigNumber()); } } // Still here? Not possible! But hey, give back 0, mkay? return 0; } public boolean equals(Object v) { if (compare((Value)v)==0) return true; else return false; } /** * Check whether this value is equal to the String supplied. * @param string The string to check for equality * @return true if the String representation of the value is equal to string. (ignoring case) */ public boolean isEqualTo(String string) { return getString().equalsIgnoreCase(string); } /** * Check whether this value is equal to the BigDecimal supplied. * @param number The BigDecimal to check for equality * @return true if the BigDecimal representation of the value is equal to number. */ public boolean isEqualTo(BigDecimal number) { return getBigNumber().equals(number); } /** * Check whether this value is equal to the Number supplied. * @param number The Number to check for equality * @return true if the Number representation of the value is equal to number. */ public boolean isEqualTo(double number) { return getNumber() == number; } /** * Check whether this value is equal to the Integer supplied. * @param number The Integer to check for equality * @return true if the Integer representation of the value is equal to number. */ public boolean isEqualTo(long number) { return getInteger() == number; } /** * Check whether this value is equal to the Integer supplied. * @param number The Integer to check for equality * @return true if the Integer representation of the value is equal to number. */ public boolean isEqualTo(int number) { return getInteger() == number; } /** * Check whether this value is equal to the Integer supplied. * @param number The Integer to check for equality * @return true if the Integer representation of the value is equal to number. */ public boolean isEqualTo(byte number) { return getInteger() == number; } /** * Check whether this value is equal to the Date supplied. * @param date The Date to check for equality * @return true if the Date representation of the value is equal to date. */ public boolean isEqualTo(Date date) { return getDate() == date; } public int hashCode() { int hash=0; // name.hashCode(); -> Name shouldn't be part of hashCode()! if (isNull()) { switch(getType()) { case VALUE_TYPE_BOOLEAN : hash^= 1; break; case VALUE_TYPE_DATE : hash^= 2; break; case VALUE_TYPE_NUMBER : hash^= 4; break; case VALUE_TYPE_STRING : hash^= 8; break; case VALUE_TYPE_INTEGER : hash^=16; break; case VALUE_TYPE_BIGNUMBER : hash^=32; break; case VALUE_TYPE_NONE : break; default: break; } } else { switch(getType()) { case VALUE_TYPE_BOOLEAN : hash^=Boolean.valueOf(getBoolean()).hashCode(); break; case VALUE_TYPE_DATE : if (getDate()!=null) hash^=getDate().hashCode(); break; case VALUE_TYPE_INTEGER : case VALUE_TYPE_NUMBER : hash^=(new Double(getNumber())).hashCode(); break; case VALUE_TYPE_STRING : if (getString()!=null) hash^=getString().hashCode(); break; case VALUE_TYPE_BIGNUMBER : if (getBigNumber()!=null) hash^=getBigNumber().hashCode(); break; case VALUE_TYPE_NONE : break; default: break; } } return hash; } // OPERATORS & COMPARATORS public Value and(Value v) { long n1 = getInteger(); long n2 = v.getInteger(); long res = n1 & n2; setValue(res); return this; } public Value xor(Value v) { long n1 = getInteger(); long n2 = v.getInteger(); long res = n1 ^ n2; setValue(res); return this; } public Value or(Value v) { long n1 = getInteger(); long n2 = v.getInteger(); long res = n1 | n2; setValue(res); return this; } public Value bool_and(Value v) { boolean b1 = getBoolean(); boolean b2 = v.getBoolean(); boolean res = b1 && b2; setValue(res); return this; } public Value bool_or(Value v) { boolean b1 = getBoolean(); boolean b2 = v.getBoolean(); boolean res = b1 || b2; setValue(res); return this; } public Value bool_xor(Value v) { boolean b1 = getBoolean(); boolean b2 = v.getBoolean(); boolean res = b1&&b2 ? false : !b1&&!b2 ? false : true; setValue(res); return this; } public Value bool_not() { if (getBoolean()) value.setBoolean(!getBoolean()); return this; } public Value greater_equal(Value v) { if (compare(v)>=0) setValue(true); else setValue(false); return this; } public Value smaller_equal(Value v) { if (compare(v)<=0) setValue(true); else setValue(false); return this; } public Value different(Value v) { if (compare(v)!=0) setValue(true); else setValue(false); return this; } public Value equal(Value v) { if (compare(v)==0) setValue(true); else setValue(false); return this; } public Value like(Value v) { String cmp=v.getString(); // Is cmp part of look? int idx=getString().indexOf(cmp); if (idx<0) setValue(false); else setValue(true); return this; } public Value greater(Value v) { if (compare(v)>0) setValue(true); else setValue(false); return this; } public Value smaller(Value v) { if (compare(v)<0) setValue(true); else setValue(false); return this; } public Value minus(BigDecimal v) throws KettleValueException { return minus(new Value("tmp", v)); } public Value minus(double v) throws KettleValueException { return minus(new Value("tmp", v)); } public Value minus(long v) throws KettleValueException { return minus(new Value("tmp", v)); } public Value minus(int v) throws KettleValueException { return minus(new Value("tmp", (long)v)); } public Value minus(byte v) throws KettleValueException { return minus(new Value("tmp", (long)v)); } public Value minus(Value v) throws KettleValueException { switch(getType()) { case VALUE_TYPE_BIGNUMBER : value.setBigNumber(getBigNumber().subtract(v.getBigNumber())); break; case VALUE_TYPE_NUMBER : value.setNumber(getNumber()-v.getNumber()); break; case VALUE_TYPE_INTEGER : value.setInteger(getInteger()-v.getInteger()); break; case VALUE_TYPE_BOOLEAN : case VALUE_TYPE_STRING : default: throw new KettleValueException("Subtraction can only be done with numbers!"); } return this; } public Value plus(BigDecimal v) { return plus(new Value("tmp", v)); } public Value plus(double v) { return plus(new Value("tmp", v)); } public Value plus(long v) { return plus(new Value("tmp", v)); } public Value plus(int v) { return plus(new Value("tmp", (long)v)); } public Value plus(byte v) { return plus(new Value("tmp", (long)v)); } public Value plus(Value v) { switch(getType()) { case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().add(v.getBigNumber())); break; case VALUE_TYPE_NUMBER : setValue(getNumber()+v.getNumber()); break; case VALUE_TYPE_INTEGER : setValue(getInteger()+v.getInteger()); break; case VALUE_TYPE_BOOLEAN : setValue(getBoolean()|v.getBoolean()); break; case VALUE_TYPE_STRING : setValue(getString()+v.getString()); break; default: break; } return this; } public Value divide(BigDecimal v) throws KettleValueException { return divide(new Value("tmp", v)); } public Value divide(double v) throws KettleValueException { return divide(new Value("tmp", v)); } public Value divide(long v) throws KettleValueException { return divide(new Value("tmp", v)); } public Value divide(int v) throws KettleValueException { return divide(new Value("tmp", (long)v)); } public Value divide(byte v) throws KettleValueException { return divide(new Value("tmp", (long)v)); } public Value divide(Value v) throws KettleValueException { if (isNull() || v.isNull()) { setNull(); } else { switch(getType()) { case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().divide(v.getBigNumber(), BigDecimal.ROUND_UP)); break; case VALUE_TYPE_NUMBER : setValue(getNumber()/v.getNumber()); break; case VALUE_TYPE_INTEGER : setValue(getInteger()/v.getInteger()); break; case VALUE_TYPE_BOOLEAN : case VALUE_TYPE_STRING : default: throw new KettleValueException("Division can only be done with numeric data!"); } } return this; } public Value multiply(BigDecimal v) throws KettleValueException { return multiply(new Value("tmp", v)); } public Value multiply(double v) throws KettleValueException { return multiply(new Value("tmp", v)); } public Value multiply(long v) throws KettleValueException { return multiply(new Value("tmp", v)); } public Value multiply(int v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); } public Value multiply(byte v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); } public Value multiply(Value v) throws KettleValueException { // a number and a string! if (isNull() || v.isNull()) { setNull(); return this; } if ((v.isString() && isNumeric()) || (v.isNumeric() && isString())) { StringBuffer s; String append=""; int n; if (v.isString()) { s=new StringBuffer(v.getString()); append=v.getString(); n=(int)getInteger(); } else { s=new StringBuffer(getString()); append=getString(); n=(int)v.getInteger(); } if (n==0) s.setLength(0); else for (int i=1;i<n;i++) s.append(append); setValue(s); } else // big numbers if (isBigNumber() || v.isBigNumber()) { setValue( getBigNumber().multiply(v.getBigNumber()) ); } else // numbers if (isNumber() || v.isNumber()) { setValue( getNumber()*v.getNumber() ); } else // integers if (isInteger() || v.isInteger()) { setValue( getInteger()*v.getInteger() ); } else { throw new KettleValueException("Multiplication can only be done with numbers or a number and a string!"); } return this; } // FUNCTIONS!! // implement the ABS function, arguments in args[] public Value abs() throws KettleValueException { if (isNull()) return this; if (isBigNumber()) { setValue(getBigNumber().abs()); } else if (isNumber()) { setValue(Math.abs(getNumber())); } else if (isInteger()) { setValue(Math.abs(getInteger())); } else { throw new KettleValueException("Function ABS only works with a number"); } return this; } // implement the ACOS function, arguments in args[] public Value acos() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.acos(getNumber())); } else { throw new KettleValueException("Function ACOS only works with numeric data"); } return this; } // implement the ASIN function, arguments in args[] public Value asin() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.asin(getNumber())); } else { throw new KettleValueException("Function ASIN only works with numeric data"); } return this; } // implement the ATAN function, arguments in args[] public Value atan() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.atan(getNumber())); } else { throw new KettleValueException("Function ATAN only works with numeric data"); } return this; } // implement the ATAN2 function, arguments in args[] public Value atan2(Value arg0) throws KettleValueException { return atan2(arg0.getNumber()); } public Value atan2(double arg0) throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.atan2(getNumber(), arg0)); } else { throw new KettleValueException("Function ATAN2 only works with numbers"); } return this; } // implement the CEIL function, arguments in args[] public Value ceil() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.ceil(getNumber())); } else { throw new KettleValueException("Function CEIL only works with a number"); } return this; } // implement the COS function, arguments in args[] public Value cos() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.cos(getNumber())); } else { throw new KettleValueException("Function COS only works with a number"); } return this; } // implement the EXP function, arguments in args[] public Value exp() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.exp(getNumber())); } else { throw new KettleValueException("Function EXP only works with a number"); } return this; } // implement the FLOOR function, arguments in args[] public Value floor() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.floor(getNumber())); } else { throw new KettleValueException("Function FLOOR only works with a number"); } return this; } // implement the INITCAP function, arguments in args[] public Value initcap() throws KettleValueException { if (isNull()) return this; if (getType()==VALUE_TYPE_STRING) { if (getString()==null) { setNull(); } else { StringBuffer change=new StringBuffer(getString()); boolean new_word; int i; char lower, upper, ch; new_word=true; for (i=0 ; i<getString().length() ; i++) { lower=change.substring(i,i+1).toLowerCase().charAt(0); // Lowercase is default. upper=change.substring(i,i+1).toUpperCase().charAt(0); // Uppercase for new words. ch=upper; if (new_word) { change.setCharAt(i, upper); } else { change.setCharAt(i, lower); } new_word = false; if ( !(ch>='A' && ch<='Z') && !(ch>='0' && ch<='9') && ch!='_' ) new_word = true; } setValue( change.toString() ); } } else { throw new KettleValueException("Function INITCAP only works with a string"); } return this; } // implement the LENGTH function, arguments in args[] public Value length() throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_INTEGER); setValue(0L); return this; } if (getType()==VALUE_TYPE_STRING) { setValue((double)getString().length()); } else { throw new KettleValueException("Function LENGTH only works with a string"); } return this; } // implement the LOG function, arguments in args[] public Value log() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue(Math.log(getNumber())); } else { throw new KettleValueException("Function LOG only works with a number"); } return this; } // implement the LOWER function, arguments in args[] public Value lower() { if (isNull()) { setType(VALUE_TYPE_STRING); } else { setValue( getString().toLowerCase() ); } return this; } // implement the LPAD function: left pad strings or numbers... public Value lpad(Value len) { return lpad((int)len.getNumber(), " "); } public Value lpad(Value len, Value padstr) { return lpad((int)len.getNumber(), padstr.getString()); } public Value lpad(int len) { return lpad(len, " "); } public Value lpad(int len, String padstr) { if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getType()!=VALUE_TYPE_STRING) // also lpad other types! { setValue(getString()); } if (getString()!=null) { StringBuffer result = new StringBuffer(getString()); int pad=len; int l= ( pad-result.length() ) / padstr.length() + 1; int i; for (i=0;i<l;i++) result.insert(0, padstr); // Maybe we added one or two too many! i=result.length(); while (i>pad && pad>0) { result.deleteCharAt(0); i--; } setValue(result.toString()); } else { setNull(); } } setLength(len); return this; } // implement the LTRIM function public Value ltrim() { if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getString()!=null) { StringBuffer s; if (getType()==VALUE_TYPE_STRING) { s = new StringBuffer(getString()); } else { s = new StringBuffer(toString()); } // Left trim while (s.length()>0 && s.charAt(0)==' ') s.deleteCharAt(0); setValue(s); } else { setNull(); } } return this; } // implement the MOD function, arguments in args[] public Value mod(Value arg) throws KettleValueException { return mod(arg.getNumber()); } public Value mod(BigDecimal arg) throws KettleValueException { return mod(arg.doubleValue()); } public Value mod(long arg) throws KettleValueException { return mod((double)arg); } public Value mod(int arg) throws KettleValueException { return mod((double)arg); } public Value mod(byte arg) throws KettleValueException { return mod((double)arg); } public Value mod(double arg0) throws KettleValueException { if (isNull()) return this; if (isNumeric()) { double n1=getNumber(); double n2=arg0; setValue( n1 - (n2 * Math.floor(n1 /n2 )) ); } else { throw new KettleValueException("Function MOD only works with numeric data"); } return this; } // implement the NVL function, arguments in args[] public Value nvl(Value alt) { if (isNull()) setValue(alt); return this; } // implement the POWER function, arguments in args[] public Value power(BigDecimal arg) throws KettleValueException{ return power(new Value("tmp", arg)); } public Value power(double arg) throws KettleValueException{ return power(new Value("tmp", arg)); } public Value power(Value v) throws KettleValueException { if (isNull()) return this; else if (isNumeric()) { setValue( Math.pow(getNumber(), v.getNumber()) ); } else { throw new KettleValueException("Function POWER only works with numeric data"); } return this; } // implement the REPLACE function, arguments in args[] public Value replace(Value repl, Value with) { return replace(repl.getString(), with.getString()); } public Value replace(String repl, String with) { if (isNull()) return this; if (getString()==null) { setNull(); } else { setValue( Const.replace(getString(), repl, with) ); } return this; } /** * Rounds off to the nearest integer.<p> * See also: java.lang.Math.round() * * @return The rounded Number value. */ public Value round() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue( (double)Math.round(getNumber()) ); } else { throw new KettleValueException("Function ROUND only works with a number"); } return this; } /** * Rounds the Number value to a certain number decimal places. * @param decimalPlaces * @return The rounded Number Value * @throws KettleValueException in case it's not a number (or other problem). */ public Value round(int decimalPlaces) throws KettleValueException { if (isNull()) return this; if (isNumeric()) { if (isBigNumber()) { // Multiply by 10^decimalPlaces // For example 123.458343938437, Decimalplaces = 2 // BigDecimal bigDec = getBigNumber(); // System.out.println("ROUND decimalPlaces : "+decimalPlaces+", bigNumber = "+bigDec); bigDec = bigDec.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN); // System.out.println("ROUND finished result : "+bigDec); setValue( bigDec ); } else { setValue( (double)Const.round(getNumber(), decimalPlaces) ); } } else { throw new KettleValueException("Function ROUND only works with a number"); } return this; } // implement the RPAD function, arguments in args[] public Value rpad(Value len) { return rpad((int)len.getNumber(), " "); } public Value rpad(Value len, Value padstr) { return rpad((int)len.getNumber(), padstr.getString()); } public Value rpad(int len) { return rpad(len, " "); } public Value rpad(int len, String padstr) { if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getType()!=VALUE_TYPE_STRING) // also rpad other types! { setValue(getString()); } if (getString()!=null) { StringBuffer result = new StringBuffer(getString()); int pad=len; int l= ( pad-result.length() ) / padstr.length() + 1; int i; for (i=0;i<l;i++) result.append(padstr); // Maybe we added one or two too many! i=result.length(); while (i>pad && pad>0) { result.deleteCharAt(i-1); i--; } setValue(result.toString()); } else { setNull(); } } setLength(len); return this; } // implement the RTRIM function, arguments in args[] public Value rtrim() { if (isNull()) { setType(VALUE_TYPE_STRING); } else { StringBuffer s; if (getType()==VALUE_TYPE_STRING) { s = new StringBuffer(getString()); } else { s = new StringBuffer(toString()); } // Right trim while (s.length()>0 && s.charAt(s.length()-1)==' ') s.deleteCharAt(s.length()-1); setValue(s); } return this; } // implement the SIGN function, arguments in args[] public Value sign() throws KettleValueException { if (isNull()) return this; if (isNumber()) { int cmp = getBigNumber().compareTo(new BigDecimal(0L)); if (cmp>0) value.setBigNumber(new BigDecimal(1L)); else if (cmp<0) value.setBigNumber(new BigDecimal(-1L)); else value.setBigNumber(new BigDecimal(0L)); } else if (isNumber()) { if (getNumber()>0) value.setNumber(1.0); else if (getNumber()<0) value.setNumber(-1.0); else value.setNumber(0.0); } else if (isInteger()) { if (getInteger()>0) value.setInteger(1); else if (getInteger()<0) value.setInteger(-1); else value.setInteger(0); } else { throw new KettleValueException("Function SIGN only works with a number"); } return this; } // implement the SIN function, arguments in args[] public Value sin() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue( Math.sin(getNumber()) ); } else { throw new KettleValueException("Function SIN only works with a number"); } return this; } // implement the SQRT function, arguments in args[] public Value sqrt() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue( Math.sqrt(getNumber()) ); } else { throw new KettleValueException("Function SQRT only works with a number"); } return this; } // implement the SUBSTR function, arguments in args[] public Value substr(Value from, Value to) { return substr((int)from.getNumber(), (int)to.getNumber()); } public Value substr(Value from) { return substr((int)from.getNumber(), -1); } public Value substr(int from) { return substr(from, -1); } public Value substr(int from, int to) { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } setValue( getString() ); if (getString()!=null) { if (to<0 && from>=0) { setValue( getString().substring(from) ); } else if (to>=0 && from>=0) { setValue( getString().substring(from, to) ); } } else { setNull(); } if (!isString()) setType(VALUE_TYPE_STRING); return this; } // implement the RIGHTSTR function, arguments in args[] public Value rightstr(Value len) { return rightstr((int)len.getNumber()); } public Value rightstr(int len) { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } setValue( getString() ); int tot_len = getString()!=null?getString().length():0; if (tot_len>0) { int totlen = getString().length(); int f = totlen-len; if (f<0) f=0; setValue( getString().substring(f) ); } else { setNull(); } if (!isString()) setType(VALUE_TYPE_STRING); return this; } // implement the LEFTSTR function, arguments in args[] public Value leftstr(Value len) { return leftstr((int)len.getNumber()); } public Value leftstr(int len) { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } setValue( getString() ); int tot_len = getString()!=null?getString().length():0; if (tot_len>0) { int totlen = getString().length(); int f = totlen-len; if (f>0) { setValue( getString().substring(0,len) ); } } else { setNull(); } if (!isString()) setType(VALUE_TYPE_STRING); return this; } public Value startsWith(Value string) { return startsWith(string.getString()); } public Value startsWith(String string) { if (isNull()) { setType(VALUE_TYPE_BOOLEAN); return this; } if (string==null) { setValue(false); setNull(); return this; } setValue( getString().startsWith(string) ); return this; } // implement the SYSDATE function, arguments in args[] public Value sysdate() { setValue( Calendar.getInstance().getTime() ); return this; } // implement the TAN function, arguments in args[] public Value tan() throws KettleValueException { if (isNull()) return this; if (isNumeric()) { setValue( Math.tan(getNumber()) ); } else { throw new KettleValueException("Function TAN only works on a number"); } return this; } // implement the TO_CHAR function, arguments in args[] // number: NUM2STR( 123.456 ) : default format // number: NUM2STR( 123.456, '###,##0.000') : format // number: NUM2STR( 123.456, '###,##0.000', '.') : grouping // number: NUM2STR( 123.456, '###,##0.000', '.', ',') : decimal // number: NUM2STR( 123.456, '###,##0.000', '.', ',', '?') : currency public Value num2str() throws KettleValueException { return num2str(null, null, null, null); } public Value num2str(String format) throws KettleValueException { return num2str(format, null, null, null); } public Value num2str(String format, String decimalSymbol) throws KettleValueException { return num2str(format, decimalSymbol, null, null); } public Value num2str(String format, String decimalSymbol, String groupingSymbol) throws KettleValueException { return num2str(format, decimalSymbol, groupingSymbol, null); } public Value num2str(String format, String decimalSymbol, String groupingSymbol, String currencySymbol) throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_STRING); } else { // Number to String conversion... if (getType()==VALUE_TYPE_NUMBER || getType()==VALUE_TYPE_INTEGER) { NumberFormat nf = NumberFormat.getInstance(); DecimalFormat df = (DecimalFormat)nf; DecimalFormatSymbols dfs =new DecimalFormatSymbols(); if (currencySymbol!=null && currencySymbol.length()>0) dfs.setCurrencySymbol( currencySymbol ); if (groupingSymbol!=null && groupingSymbol.length()>0) dfs.setGroupingSeparator( groupingSymbol.charAt(0) ); if (decimalSymbol!=null && decimalSymbol.length()>0) dfs.setDecimalSeparator( decimalSymbol.charAt(0) ); df.setDecimalFormatSymbols(dfs); // in case of 4, 3 or 2 if (format!=null && format.length()>0) df.applyPattern(format); try { setValue( nf.format(getNumber()) ); } catch(Exception e) { setType(VALUE_TYPE_STRING); setNull(); throw new KettleValueException("Couldn't convert Number to String "+e.toString()); } } else { throw new KettleValueException("Function NUM2STR only works on Numbers and Integers"); } } return this; } // date: TO_CHAR( <date> , 'yyyy/mm/dd HH:mm:ss' public Value dat2str() throws KettleValueException { return dat2str(null, null); } public Value dat2str(String arg0) throws KettleValueException { return dat2str(arg0, null); } public Value dat2str(String arg0, String arg1) throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getType()==VALUE_TYPE_DATE) { SimpleDateFormat df = new SimpleDateFormat(); DateFormatSymbols dfs = new DateFormatSymbols(); if (arg1!=null) dfs.setLocalPatternChars(arg1); if (arg0!=null) df.applyPattern(arg0); try { setValue( df.format(getDate()) ); } catch(Exception e) { setType(VALUE_TYPE_STRING); setNull(); throw new KettleValueException("TO_CHAR Couldn't convert Date to String "+e.toString()); } } else { throw new KettleValueException("Function DAT2STR only works on a date"); } } return this; } // implement the TO_DATE function, arguments in args[] public Value num2dat() throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_DATE); } else { if (isNumeric()) { value = new ValueDate(); value.setInteger(getInteger()); setType(VALUE_TYPE_DATE); setLength(-1,-1); } else { throw new KettleValueException("Function NUM2DAT only works on a number"); } } return this; } public Value str2dat(String arg0) throws KettleValueException { return str2dat(arg0, null); } public Value str2dat(String arg0, String arg1) throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_DATE); } else { // System.out.println("Convert string ["+string+"] to date using pattern '"+arg0+"'"); SimpleDateFormat df = new SimpleDateFormat(); DateFormatSymbols dfs = new DateFormatSymbols(); if (arg1!=null) dfs.setLocalPatternChars(arg1); if (arg0!=null) df.applyPattern(arg0); try { value.setDate( df.parse(getString()) ); setType(VALUE_TYPE_DATE); setLength(-1,-1); } catch(Exception e) { setType(VALUE_TYPE_DATE); setNull(); throw new KettleValueException("TO_DATE Couldn't convert String to Date"+e.toString()); } } return this; } // implement the TO_NUMBER function, arguments in args[] public Value str2num() throws KettleValueException { return str2num(null, null, null, null); } public Value str2num(String pattern) throws KettleValueException { return str2num(pattern, null, null, null); } public Value str2num(String pattern, String decimal) throws KettleValueException { return str2num(pattern, decimal, null, null); } public Value str2num(String pattern, String decimal, String grouping) throws KettleValueException { return str2num(pattern, decimal, grouping, null); } public Value str2num(String pattern, String decimal, String grouping, String currency) throws KettleValueException { // 0 : pattern // 1 : Decimal separator // 2 : Grouping separator // 3 : Currency symbol if (isNull()) { setType(VALUE_TYPE_STRING); } else { if (getType()==VALUE_TYPE_STRING) { if (getString()==null) { setNull(); setValue(0.0); } else { NumberFormat nf = NumberFormat.getInstance(); DecimalFormat df = (DecimalFormat)nf; DecimalFormatSymbols dfs =new DecimalFormatSymbols(); if ( pattern !=null && pattern .length()>0 ) df.applyPattern( pattern ); if ( decimal !=null && decimal .length()>0 ) dfs.setDecimalSeparator( decimal.charAt(0) ); if ( grouping!=null && grouping.length()>0 ) dfs.setGroupingSeparator( grouping.charAt(0) ); if ( currency!=null && currency.length()>0 ) dfs.setCurrencySymbol( currency ); try { df.setDecimalFormatSymbols(dfs); setValue( nf.parse(getString()).doubleValue() ); } catch(Exception e) { String message = "Couldn't convert string to number "+e.toString(); if ( pattern !=null && pattern .length()>0 ) message+=" pattern="+pattern; if ( decimal !=null && decimal .length()>0 ) message+=" decimal="+decimal; if ( grouping!=null && grouping.length()>0 ) message+=" grouping="+grouping.charAt(0); if ( currency!=null && currency.length()>0 ) message+=" currency="+currency; throw new KettleValueException(message); } } } else { throw new KettleValueException("Function STR2NUM works only on strings"); } } return this; } public Value dat2num() throws KettleValueException { if (isNull()) { setType(VALUE_TYPE_INTEGER); return this; } if (getType()==VALUE_TYPE_DATE) { if (getString()==null) { setNull(); setValue(0L); } else { setValue(getInteger()); } } else { throw new KettleValueException("Function DAT2NUM works only on dates"); } return this; } /** * Performs a right and left trim of spaces in the string. * If the value is not a string a conversion to String is performed first. * * @return The trimmed string value. */ public Value trim() { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } String str = Const.trim(getString()); setValue(str); return this; } // implement the UPPER function, arguments in args[] public Value upper() { if (isNull()) { setType(VALUE_TYPE_STRING); return this; } setValue( getString().toUpperCase() ); return this; } // implement the E function, arguments in args[] public Value e() { setValue(Math.E); return this; } // implement the PI function, arguments in args[] public Value pi() { setValue(Math.PI); return this; } // implement the DECODE function, arguments in args[] public Value v_decode(Value args[]) throws KettleValueException { int i; boolean found; // Decode takes as input the first argument... // The next pair // Limit to 3, 5, 7, 9, ... arguments if (args.length>=3 && (args.length%2)==1) { i=0; found=false; while (i<args.length-1 && !found) { if (this.equals(args[i])) { setValue(args[i+1]); found=true; } i+=2; } if (!found) setValue(args[args.length-1]); } else { // ERROR with nr of arguments throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!"); } return this; } // implement the IF function, arguments in args[] // IF( <condition>, <then value>, <else value>) public Value v_if(Value args[]) throws KettleValueException { if (getType()==VALUE_TYPE_BOOLEAN) { if (args.length==1) { if (getBoolean()) setValue(args[0]); else setNull(); } else if (args.length==2) { if (getBoolean()) setValue(args[0]); else setValue(args[1]); } } else { throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!"); } return this; } // implement the ADD_MONTHS function, one argument public Value add_months(int months) throws KettleValueException { if (getType()==VALUE_TYPE_DATE) { if (!isNull() && getDate()!=null) { Calendar cal = Calendar.getInstance(); cal.setTime(getDate()); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); month+=months; int newyear = year+(int)Math.floor(month/12); int newmonth = month%12; cal.set(newyear, newmonth, 1); int newday = cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (newday<day) cal.set(Calendar.DAY_OF_MONTH, newday); else cal.set(Calendar.DAY_OF_MONTH, day); setValue( cal.getTime() ); } } else { throw new KettleValueException("Function add_months only works on a date!"); } return this; } /** * Add a number of days to a Date value. * * @param days The number of days to add to the current date value * @return The resulting value * @throws KettleValueException */ public Value add_days(long days) throws KettleValueException { if (getType()==VALUE_TYPE_DATE) { if (!isNull() && getDate()!=null) { Calendar cal = Calendar.getInstance(); cal.setTime(getDate()); cal.add(Calendar.DAY_OF_YEAR, (int)days); setValue( cal.getTime() ); } } else { throw new KettleValueException("Function add_days only works on a date!"); } return this; } // implement the LAST_DAY function, arguments in args[] public Value last_day() throws KettleValueException { if (getType()==VALUE_TYPE_DATE) { Calendar cal=Calendar.getInstance(); cal.setTime(getDate()); int last_day = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, last_day); setValue( cal.getTime() ); } else { throw new KettleValueException("Function last_day only works on a date"); } return this; } public Value first_day() throws KettleValueException { if (getType()==VALUE_TYPE_DATE) { Calendar cal=Calendar.getInstance(); cal.setTime(getDate()); cal.set(Calendar.DAY_OF_MONTH, 1); setValue( cal.getTime() ); } else { throw new KettleValueException("Function first_day only works on a date"); } return this; } // implement the TRUNC function, version without arguments public Value trunc() throws KettleValueException { if (isNull()) return this; // don't do anything, leave it at NULL! if (isBigNumber()) { getBigNumber().setScale(0, BigDecimal.ROUND_FLOOR); } else if (isNumber()) { setValue( Math.floor(getNumber()) ); } else if (isInteger()) { // Nothing } else if (isDate()) { Calendar cal=Calendar.getInstance(); cal.setTime(getDate()); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); setValue( cal.getTime() ); } else { throw new KettleValueException("Function TRUNC only works on numbers and dates"); } return this; } // implement the TRUNC function, arguments in args[] public Value trunc(double level) throws KettleValueException { return trunc((int)level); } public Value trunc(int level) throws KettleValueException { if (isNull()) return this; // don't do anything, leave it at NULL! if (isBigNumber()) { getBigNumber().setScale(level, BigDecimal.ROUND_FLOOR); } else if (isNumber()) { double pow=Math.pow(10, level); setValue( Math.floor( getNumber() * pow ) / pow ); } else if (isInteger()) { // Nothing! } else if (isDate()) { Calendar cal=Calendar.getInstance(); cal.setTime(getDate()); switch((int)level) { // MONTHS case 5: cal.set(Calendar.MONTH, 1); // DAYS case 4: cal.set(Calendar.DAY_OF_MONTH, 1); // HOURS case 3: cal.set(Calendar.HOUR_OF_DAY, 0); // MINUTES case 2: cal.set(Calendar.MINUTE, 0); // SECONDS case 1: cal.set(Calendar.SECOND, 0); break; default: throw new KettleValueException("Argument of TRUNC of date has to be between 1 and 5"); } } else { throw new KettleValueException("Function TRUNC only works with numbers and dates"); } return this; } /* Some javascript extensions... * */ public static final Value getInstance() { return new Value(); } public String getClassName() { return "Value"; } public void jsConstructor() { } public void jsConstructor(String name) { setName(name); } public void jsConstructor(String name, String value) { setName(name); setValue(value); } /** * Produce the XML representation of this value. * @return a String containing the XML to represent this Value. */ public String getXML() { StringBuffer retval = new StringBuffer(128); retval.append(XMLHandler.addTagValue("name", getName(), false)); retval.append(XMLHandler.addTagValue("type", getTypeDesc(), false)); retval.append(XMLHandler.addTagValue("text", toString(false), false)); retval.append(XMLHandler.addTagValue("length", getLength(), false)); retval.append(XMLHandler.addTagValue("precision", getPrecision(), false)); retval.append(XMLHandler.addTagValue("isnull", isNull(), false)); return retval.toString(); } /** * Construct a new Value and read the data from XML * @param valnode The XML Node to read from. */ public Value(Node valnode) { this(); loadXML(valnode); } /** * Read the data for this Value from an XML Node * @param valnode The XML Node to read from * @return true if all went well, false if something went wrong. */ public boolean loadXML(Node valnode) { try { String valname = XMLHandler.getTagValue(valnode, "name"); int valtype = getType( XMLHandler.getTagValue(valnode, "type") ); String text = XMLHandler.getTagValue(valnode, "text"); boolean isnull = "Y".equalsIgnoreCase(XMLHandler.getTagValue(valnode, "isnull")); int len = Const.toInt(XMLHandler.getTagValue(valnode, "length"), -1); int prec = Const.toInt(XMLHandler.getTagValue(valnode, "precision"), -1); setName(valname); setValue(text); setLength(len, prec); if (valtype!=VALUE_TYPE_STRING) { trim(); convertString(valtype); } if (isnull) setNull(); } catch(Exception e) { setNull(); return false; } return true; } /** * Convert this Value from type String to another type * @param newtype The Value type to convert to. */ public void convertString(int newtype) throws KettleValueException { switch(newtype) { case VALUE_TYPE_STRING : break; case VALUE_TYPE_NUMBER : setValue( getNumber() ); break; case VALUE_TYPE_DATE : setValue( getDate() ); break; case VALUE_TYPE_BOOLEAN : setValue( getBoolean() ); break; case VALUE_TYPE_INTEGER : setValue( getInteger() ); break; case VALUE_TYPE_BIGNUMBER : setValue( getBigNumber() ); break; default: throw new KettleValueException("Please specify the type to convert to from String type."); } } public Value(Repository rep, long id_value) throws KettleException { try { Row r = rep.getValue(id_value); if (r!=null) { name = r.getString("NAME", null); String valstr = r.getString("VALUE_STR", null); setValue( valstr ); int valtype = getType( r.getString("VALUE_TYPE", null) ); setType(valtype); setNull( r.getBoolean("IS_NULL", false) ); } } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load Value from repository with id_value="+id_value, dbe); } } }
Check in for CR #2428 : very cosmetic changes git-svn-id: 9499f031eb5c9fb9d11553a06c92651e5446d292@1210 5fb7f6ec-07c1-534a-b4ca-9155e429e800
src/be/ibridge/kettle/core/value/Value.java
Check in for CR #2428 : very cosmetic changes
Java
lgpl-2.1
24f3dce7fdc8c3e1286f4e550e60ac534464ee81
0
sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2005, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.ba; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.annotation.Nonnull; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.FieldInstruction; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.MethodGen; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.MethodAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.FieldDescriptor; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.classfile.analysis.FieldInfo; import edu.umd.cs.findbugs.classfile.analysis.MethodInfo; import edu.umd.cs.findbugs.internalAnnotations.DottedClassName; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * Factory methods for creating XMethod objects. * * @author David Hovemeyer */ public class XFactory { public static final boolean DEBUG_UNRESOLVED = SystemProperties.getBoolean("findbugs.xfactory.debugunresolved"); private Set<ClassDescriptor> reflectiveClasses = new HashSet<ClassDescriptor>(); private Map<MethodDescriptor, XMethod> methods = new HashMap<MethodDescriptor, XMethod>(); private Map<FieldDescriptor, XField> fields = new HashMap<FieldDescriptor, XField>(); private Set<XMethod> calledMethods = new HashSet<XMethod>(); private Set<XField> emptyArrays = new HashSet<XField>(); private Set<String> calledMethodSignatures = new HashSet<String>(); public void canonicalizeAll() { DescriptorFactory descriptorFactory = DescriptorFactory.instance(); for(XMethod m : methods.values()) if (m instanceof MethodDescriptor) { descriptorFactory.canonicalize((MethodDescriptor)m); } for(XField f : fields.values()) if (f instanceof FieldDescriptor) descriptorFactory.canonicalize((FieldDescriptor)f); } /** * Constructor. */ public XFactory() { } public void intern(XClass c) { for (XMethod m : c.getXMethods()) { MethodInfo mi = (MethodInfo) m; methods.put(mi, mi); } for (XField f : c.getXFields()) { FieldInfo fi = (FieldInfo) f; fields.put(fi, fi); } } public Collection<XField> allFields() { return fields.values(); } public void addCalledMethod(MethodDescriptor m) { assert m.getClassDescriptor().getClassName().indexOf('.') == -1; calledMethods.add(createXMethod(m)); } public void addEmptyArrayField(XField f) { emptyArrays.add(f); } public boolean isEmptyArrayField(@CheckForNull XField f) { return emptyArrays.contains(f); } public boolean isCalled(XMethod m) { if (m.getName().equals("<clinit>")) return true; return calledMethods.contains(m); } public Set<XMethod> getCalledMethods() { return calledMethods; } public Set<ClassDescriptor> getReflectiveClasses() { return reflectiveClasses; } public boolean isReflectiveClass(ClassDescriptor c) { return reflectiveClasses.contains(c); } public boolean addReflectiveClasses(ClassDescriptor c) { return reflectiveClasses.add(c); } public boolean isCalledDirectlyOrIndirectly(XMethod m) { if (isCalled(m)) return true; if (m.isStatic() || m.isPrivate() || m.getName().equals("<init>")) return false; try { IAnalysisCache analysisCache = Global.getAnalysisCache(); XClass clazz = analysisCache.getClassAnalysis(XClass.class, m.getClassDescriptor()); if (isCalledDirectlyOrIndirectly(clazz.getSuperclassDescriptor(), m)) return true; for (ClassDescriptor i : clazz.getInterfaceDescriptorList()) if (isCalledDirectlyOrIndirectly(i, m)) return true; return false; } catch (edu.umd.cs.findbugs.classfile.MissingClassException e) { // AnalysisContext.reportMissingClass(e.getClassNotFoundException()); return false; } catch (MissingClassException e) { AnalysisContext.reportMissingClass(e.getClassNotFoundException()); return false; } catch (Exception e) { AnalysisContext.logError("Error checking to see if " + m + " is called (" + e.getClass().getCanonicalName() + ")", e); return false; } } /** * @param superclassDescriptor * @param m * @return * @throws CheckedAnalysisException */ private boolean isCalledDirectlyOrIndirectly(@CheckForNull ClassDescriptor clazzDescriptor, XMethod m) throws CheckedAnalysisException { if (clazzDescriptor == null) return false; IAnalysisCache analysisCache = Global.getAnalysisCache(); XClass clazz = analysisCache.getClassAnalysis(XClass.class, clazzDescriptor); XMethod m2 = clazz.findMethod(m.getName(), m.getSignature(), m.isStatic()); if (m2 != null && isCalled(m2)) return true; if (isCalledDirectlyOrIndirectly(clazz.getSuperclassDescriptor(), m)) return true; for (ClassDescriptor i : clazz.getInterfaceDescriptorList()) if (isCalledDirectlyOrIndirectly(i, m)) return true; return false; } public boolean nameAndSignatureIsCalled(XMethod m) { return calledMethodSignatures.contains(getDetailedSignature(m)); } /** * @param m2 * @return */ private static String getDetailedSignature(XMethod m2) { return m2.getName() + m2.getSignature() + m2.isStatic(); } @Deprecated public boolean isInterned(XMethod m) { return m.isResolved(); } public static String canonicalizeString(String s) { return DescriptorFactory.canonicalizeString(s); } /** * Create an XMethod object from a BCEL Method. * * @param className * the class to which the Method belongs * @param method * the Method * @return an XMethod representing the Method */ public static XMethod createXMethod(String className, Method method) { String methodName = method.getName(); String methodSig = method.getSignature(); int accessFlags = method.getAccessFlags(); return createXMethod(className, methodName, methodSig, accessFlags); } /* * Create a new, never-before-seen, XMethod object and intern it. */ private static XMethod createXMethod(@DottedClassName String className, String methodName, String methodSig, int accessFlags) { return createXMethod(className, methodName, methodSig, (accessFlags & Constants.ACC_STATIC) != 0); } /** * Create an XMethod object from a BCEL Method. * * @param javaClass * the class to which the Method belongs * @param method * the Method * @return an XMethod representing the Method */ public static XMethod createXMethod(JavaClass javaClass, Method method) { if (method == null) throw new NullPointerException("method must not be null"); XMethod xmethod = createXMethod(javaClass.getClassName(), method); assert xmethod.isResolved(); return xmethod; } /** * @param className * @param methodName * @param methodSig * @param isStatic * @return the created XMethod */ public static XMethod createXMethod(@DottedClassName String className, String methodName, String methodSig, boolean isStatic) { MethodDescriptor desc = DescriptorFactory.instance().getMethodDescriptor(ClassName.toSlashedClassName(className), methodName, methodSig, isStatic); return createXMethod(desc); } public static XMethod createXMethod(MethodDescriptor desc) { XFactory xFactory = AnalysisContext.currentXFactory(); XMethod m = xFactory.methods.get(desc); if (m != null) return m; m = xFactory.resolveXMethod(desc); if (m instanceof MethodDescriptor) { xFactory.methods.put((MethodDescriptor) m, m); DescriptorFactory.instance().canonicalize((MethodDescriptor) m); } else xFactory.methods.put(desc, m); return m; } public static void profile() { XFactory xFactory = AnalysisContext.currentXFactory(); int count = 0; for(XMethod m : xFactory.methods.values()) { if (m instanceof MethodInfo) count++; } System.out.printf("XFactory cached methods: %d/%d\n", count, xFactory.methods.size()); DescriptorFactory.instance().profile(); } private XMethod resolveXMethod(MethodDescriptor originalDescriptor) { MethodDescriptor desc = originalDescriptor; try { while (true) { XMethod m = methods.get(desc); if (m != null) return m; XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, desc.getClassDescriptor()); if (xClass == null) break; ClassDescriptor superClass = xClass.getSuperclassDescriptor(); if (superClass == null) break; desc = DescriptorFactory.instance().getMethodDescriptor(superClass.getClassName(), desc.getName(), desc.getSignature(), desc.isStatic()); } } catch (CheckedAnalysisException e) { assert true; } return new UnresolvedXMethod(originalDescriptor); } public static XMethod createXMethod(MethodAnnotation ma) { return createXMethod(ma.getClassName(), ma.getMethodName(), ma.getMethodSignature(), ma.isStatic()); } /** * Create an XField object * * @param className * @param fieldName * @param fieldSignature * @param isStatic * @return the created XField */ public static XField createXField(String className, String fieldName, String fieldSignature, boolean isStatic) { FieldDescriptor fieldDesc = DescriptorFactory.instance().getFieldDescriptor(ClassName.toSlashedClassName(className), fieldName, fieldSignature, isStatic); return createXField(fieldDesc); } public final static boolean DEBUG_CIRCULARITY = SystemProperties.getBoolean("circularity.debug"); /** * If a method is not marked as resolved, look in superclasses to see if the * method can be found there. Return whatever method is found. * * @param m * @return */ public static XField createXField(FieldInstruction fieldInstruction, ConstantPoolGen cpg) { String className = fieldInstruction.getClassName(cpg); String fieldName = fieldInstruction.getName(cpg); String fieldSig = fieldInstruction.getSignature(cpg); int opcode = fieldInstruction.getOpcode(); return createXField(className, fieldName, fieldSig, opcode == Constants.GETSTATIC || opcode == Constants.PUTSTATIC); } public static XField createReferencedXField(DismantleBytecode visitor) { return createXField(visitor.getDottedClassConstantOperand(), visitor.getNameConstantOperand(), visitor .getSigConstantOperand(), visitor.getRefFieldIsStatic()); } public static XMethod createReferencedXMethod(DismantleBytecode visitor) { return createXMethod(visitor.getDottedClassConstantOperand(), visitor.getNameConstantOperand(), visitor .getSigConstantOperand(), visitor.getOpcode() == Constants.INVOKESTATIC); } public static XField createXField(FieldAnnotation f) { return createXField(f.getClassName(), f.getFieldName(), f.getFieldSignature(), f.isStatic()); } public static XField createXField(JavaClass javaClass, Field field) { return createXField(javaClass.getClassName(), field); } /** * Create an XField object from a BCEL Field. * * @param className * the name of the Java class containing the field * @param field * the Field within the JavaClass * @return the created XField */ public static XField createXField(String className, Field field) { String fieldName = field.getName(); String fieldSig = field.getSignature(); XField xfield = getExactXField(className, fieldName, fieldSig, field.isStatic()); assert xfield.isResolved() : "Could not exactly resolve " + xfield; return xfield; } /** * Get an XField object exactly matching given class, name, and signature. * May return an unresolved object (if the class can't be found, or does not * directly declare named field). * * @param className * name of class containing the field * @param name * name of field * @param signature * field signature * @param isStatic * field access flags * @return XField exactly matching class name, field name, and field * signature */ public static XField getExactXField(String className, String name, String signature, boolean isStatic) { FieldDescriptor fieldDesc = DescriptorFactory.instance().getFieldDescriptor(ClassName.toSlashedClassName(className), name, signature, isStatic); return getExactXField(fieldDesc); } public static @Nonnull XField getExactXField(FieldDescriptor desc) { XFactory xFactory = AnalysisContext.currentXFactory(); XField f = xFactory.fields.get(desc); if (f == null) return new UnresolvedXField(desc); return f; } public static XField createXField(FieldDescriptor desc) { XFactory xFactory = AnalysisContext.currentXFactory(); XField m = xFactory.fields.get(desc); if (m != null) return m; m = xFactory.resolveXField(desc); xFactory.fields.put(desc, m); return m; } private XField resolveXField(FieldDescriptor originalDescriptor) { FieldDescriptor desc = originalDescriptor; try { while (true) { XField m = fields.get(desc); if (m != null) return m; XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, desc.getClassDescriptor()); if (xClass == null) break; ClassDescriptor superClass = xClass.getSuperclassDescriptor(); if (superClass == null) break; desc = DescriptorFactory.instance().getFieldDescriptor(superClass.getClassName(), desc.getName(), desc.getSignature(), desc.isStatic()); } } catch (CheckedAnalysisException e) { assert true; } return new UnresolvedXField(originalDescriptor); } /** * Create an XMethod object from an InvokeInstruction. * * @param invokeInstruction * the InvokeInstruction * @param cpg * ConstantPoolGen from the class containing the instruction * @return XMethod representing the method called by the InvokeInstruction */ public static XMethod createXMethod(InvokeInstruction invokeInstruction, ConstantPoolGen cpg) { String className = invokeInstruction.getClassName(cpg); String methodName = invokeInstruction.getName(cpg); String methodSig = invokeInstruction.getSignature(cpg); return createXMethod(className, methodName, methodSig, invokeInstruction.getOpcode() == Constants.INVOKESTATIC); } /** * Create an XMethod object from the method currently being visited by the * given PreorderVisitor. * * @param visitor * the PreorderVisitor * @return the XMethod representing the method currently being visited */ public static XMethod createXMethod(PreorderVisitor visitor) { JavaClass javaClass = visitor.getThisClass(); Method method = visitor.getMethod(); XMethod m = createXMethod(javaClass, method); return m; } /** * Create an XField object from the field currently being visited by the * given PreorderVisitor. * * @param visitor * the PreorderVisitor * @return the XField representing the method currently being visited */ public static XField createXField(PreorderVisitor visitor) { JavaClass javaClass = visitor.getThisClass(); Field field = visitor.getField(); XField f = createXField(javaClass, field); return f; } public static XMethod createXMethod(MethodGen methodGen) { String className = methodGen.getClassName(); String methodName = methodGen.getName(); String methodSig = methodGen.getSignature(); int accessFlags = methodGen.getAccessFlags(); return createXMethod(className, methodName, methodSig, accessFlags); } public static XMethod createXMethod(JavaClassAndMethod classAndMethod) { return createXMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod()); } /** * Get the XClass object providing information about the class named by the * given ClassDescriptor. * * @param classDescriptor * a ClassDescriptor * @return an XClass object providing information about the class, or null * if the class cannot be found */ public XClass getXClass(ClassDescriptor classDescriptor) { try { IAnalysisCache analysisCache = Global.getAnalysisCache(); return analysisCache.getClassAnalysis(XClass.class, classDescriptor); } catch (CheckedAnalysisException e) { return null; } } /** * Compare XMethod or XField object objects. * <em>All methods that implement XMethod or XField should * delegate to this method when implementing compareTo(Object) * if the right-hand object implements XField or XMethod.</em> * * @param lhs * an XMethod or XField * @param rhs * an XMethod or XField * @return comparison of lhs and rhs */ public static <E extends ClassMember> int compare(E lhs, E rhs) { int cmp; cmp = lhs.getClassName().compareTo(rhs.getClassName()); if (cmp != 0) { return cmp; } cmp = lhs.getName().compareTo(rhs.getName()); if (cmp != 0) { return cmp; } cmp = lhs.getSignature().compareTo(rhs.getSignature()); if (cmp != 0) { return cmp; } return (lhs.isStatic() ? 1 : 0) - (rhs.isStatic() ? 1 : 0); } }
findbugs/src/java/edu/umd/cs/findbugs/ba/XFactory.java
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2005, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.ba; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.annotation.Nonnull; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.FieldInstruction; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.MethodGen; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.MethodAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.FieldDescriptor; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.classfile.analysis.FieldInfo; import edu.umd.cs.findbugs.classfile.analysis.MethodInfo; import edu.umd.cs.findbugs.internalAnnotations.DottedClassName; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * Factory methods for creating XMethod objects. * * @author David Hovemeyer */ public class XFactory { public static final boolean DEBUG_UNRESOLVED = SystemProperties.getBoolean("findbugs.xfactory.debugunresolved"); private Set<ClassDescriptor> reflectiveClasses = new HashSet<ClassDescriptor>(); private Map<MethodDescriptor, XMethod> methods = new HashMap<MethodDescriptor, XMethod>(); private Map<FieldDescriptor, XField> fields = new HashMap<FieldDescriptor, XField>(); private Set<XMethod> calledMethods = new HashSet<XMethod>(); private Set<XField> emptyArrays = new HashSet<XField>(); private Set<String> calledMethodSignatures = new HashSet<String>(); public void canonicalizeAll() { DescriptorFactory descriptorFactory = DescriptorFactory.instance(); for(XMethod m : methods.values()) if (m instanceof MethodDescriptor) { descriptorFactory.canonicalize((MethodDescriptor)m); } for(XField f : fields.values()) if (f instanceof FieldDescriptor) descriptorFactory.canonicalize((FieldDescriptor)f); } /** * Constructor. */ public XFactory() { } public void intern(XClass c) { for (XMethod m : c.getXMethods()) { MethodInfo mi = (MethodInfo) m; methods.put(mi, mi); } for (XField f : c.getXFields()) { FieldInfo fi = (FieldInfo) f; fields.put(fi, fi); } } public Collection<XField> allFields() { return fields.values(); } public void addCalledMethod(MethodDescriptor m) { assert m.getClassDescriptor().getClassName().indexOf('.') == -1; calledMethods.add(createXMethod(m)); } public void addEmptyArrayField(XField f) { emptyArrays.add(f); } public boolean isEmptyArrayField(XField f) { return emptyArrays.contains(f); } public boolean isCalled(XMethod m) { if (m.getName().equals("<clinit>")) return true; return calledMethods.contains(m); } public Set<XMethod> getCalledMethods() { return calledMethods; } public Set<ClassDescriptor> getReflectiveClasses() { return reflectiveClasses; } public boolean isReflectiveClass(ClassDescriptor c) { return reflectiveClasses.contains(c); } public boolean addReflectiveClasses(ClassDescriptor c) { return reflectiveClasses.add(c); } public boolean isCalledDirectlyOrIndirectly(XMethod m) { if (isCalled(m)) return true; if (m.isStatic() || m.isPrivate() || m.getName().equals("<init>")) return false; try { IAnalysisCache analysisCache = Global.getAnalysisCache(); XClass clazz = analysisCache.getClassAnalysis(XClass.class, m.getClassDescriptor()); if (isCalledDirectlyOrIndirectly(clazz.getSuperclassDescriptor(), m)) return true; for (ClassDescriptor i : clazz.getInterfaceDescriptorList()) if (isCalledDirectlyOrIndirectly(i, m)) return true; return false; } catch (edu.umd.cs.findbugs.classfile.MissingClassException e) { // AnalysisContext.reportMissingClass(e.getClassNotFoundException()); return false; } catch (MissingClassException e) { AnalysisContext.reportMissingClass(e.getClassNotFoundException()); return false; } catch (Exception e) { AnalysisContext.logError("Error checking to see if " + m + " is called (" + e.getClass().getCanonicalName() + ")", e); return false; } } /** * @param superclassDescriptor * @param m * @return * @throws CheckedAnalysisException */ private boolean isCalledDirectlyOrIndirectly(@CheckForNull ClassDescriptor clazzDescriptor, XMethod m) throws CheckedAnalysisException { if (clazzDescriptor == null) return false; IAnalysisCache analysisCache = Global.getAnalysisCache(); XClass clazz = analysisCache.getClassAnalysis(XClass.class, clazzDescriptor); XMethod m2 = clazz.findMethod(m.getName(), m.getSignature(), m.isStatic()); if (m2 != null && isCalled(m2)) return true; if (isCalledDirectlyOrIndirectly(clazz.getSuperclassDescriptor(), m)) return true; for (ClassDescriptor i : clazz.getInterfaceDescriptorList()) if (isCalledDirectlyOrIndirectly(i, m)) return true; return false; } public boolean nameAndSignatureIsCalled(XMethod m) { return calledMethodSignatures.contains(getDetailedSignature(m)); } /** * @param m2 * @return */ private static String getDetailedSignature(XMethod m2) { return m2.getName() + m2.getSignature() + m2.isStatic(); } @Deprecated public boolean isInterned(XMethod m) { return m.isResolved(); } public static String canonicalizeString(String s) { return DescriptorFactory.canonicalizeString(s); } /** * Create an XMethod object from a BCEL Method. * * @param className * the class to which the Method belongs * @param method * the Method * @return an XMethod representing the Method */ public static XMethod createXMethod(String className, Method method) { String methodName = method.getName(); String methodSig = method.getSignature(); int accessFlags = method.getAccessFlags(); return createXMethod(className, methodName, methodSig, accessFlags); } /* * Create a new, never-before-seen, XMethod object and intern it. */ private static XMethod createXMethod(@DottedClassName String className, String methodName, String methodSig, int accessFlags) { return createXMethod(className, methodName, methodSig, (accessFlags & Constants.ACC_STATIC) != 0); } /** * Create an XMethod object from a BCEL Method. * * @param javaClass * the class to which the Method belongs * @param method * the Method * @return an XMethod representing the Method */ public static XMethod createXMethod(JavaClass javaClass, Method method) { if (method == null) throw new NullPointerException("method must not be null"); XMethod xmethod = createXMethod(javaClass.getClassName(), method); assert xmethod.isResolved(); return xmethod; } /** * @param className * @param methodName * @param methodSig * @param isStatic * @return the created XMethod */ public static XMethod createXMethod(@DottedClassName String className, String methodName, String methodSig, boolean isStatic) { MethodDescriptor desc = DescriptorFactory.instance().getMethodDescriptor(ClassName.toSlashedClassName(className), methodName, methodSig, isStatic); return createXMethod(desc); } public static XMethod createXMethod(MethodDescriptor desc) { XFactory xFactory = AnalysisContext.currentXFactory(); XMethod m = xFactory.methods.get(desc); if (m != null) return m; m = xFactory.resolveXMethod(desc); if (m instanceof MethodDescriptor) { xFactory.methods.put((MethodDescriptor) m, m); DescriptorFactory.instance().canonicalize((MethodDescriptor) m); } else xFactory.methods.put(desc, m); return m; } public static void profile() { XFactory xFactory = AnalysisContext.currentXFactory(); int count = 0; for(XMethod m : xFactory.methods.values()) { if (m instanceof MethodInfo) count++; } System.out.printf("XFactory cached methods: %d/%d\n", count, xFactory.methods.size()); DescriptorFactory.instance().profile(); } private XMethod resolveXMethod(MethodDescriptor originalDescriptor) { MethodDescriptor desc = originalDescriptor; try { while (true) { XMethod m = methods.get(desc); if (m != null) return m; XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, desc.getClassDescriptor()); if (xClass == null) break; ClassDescriptor superClass = xClass.getSuperclassDescriptor(); if (superClass == null) break; desc = DescriptorFactory.instance().getMethodDescriptor(superClass.getClassName(), desc.getName(), desc.getSignature(), desc.isStatic()); } } catch (CheckedAnalysisException e) { assert true; } return new UnresolvedXMethod(originalDescriptor); } public static XMethod createXMethod(MethodAnnotation ma) { return createXMethod(ma.getClassName(), ma.getMethodName(), ma.getMethodSignature(), ma.isStatic()); } /** * Create an XField object * * @param className * @param fieldName * @param fieldSignature * @param isStatic * @return the created XField */ public static XField createXField(String className, String fieldName, String fieldSignature, boolean isStatic) { FieldDescriptor fieldDesc = DescriptorFactory.instance().getFieldDescriptor(ClassName.toSlashedClassName(className), fieldName, fieldSignature, isStatic); return createXField(fieldDesc); } public final static boolean DEBUG_CIRCULARITY = SystemProperties.getBoolean("circularity.debug"); /** * If a method is not marked as resolved, look in superclasses to see if the * method can be found there. Return whatever method is found. * * @param m * @return */ public static XField createXField(FieldInstruction fieldInstruction, ConstantPoolGen cpg) { String className = fieldInstruction.getClassName(cpg); String fieldName = fieldInstruction.getName(cpg); String fieldSig = fieldInstruction.getSignature(cpg); int opcode = fieldInstruction.getOpcode(); return createXField(className, fieldName, fieldSig, opcode == Constants.GETSTATIC || opcode == Constants.PUTSTATIC); } public static XField createReferencedXField(DismantleBytecode visitor) { return createXField(visitor.getDottedClassConstantOperand(), visitor.getNameConstantOperand(), visitor .getSigConstantOperand(), visitor.getRefFieldIsStatic()); } public static XMethod createReferencedXMethod(DismantleBytecode visitor) { return createXMethod(visitor.getDottedClassConstantOperand(), visitor.getNameConstantOperand(), visitor .getSigConstantOperand(), visitor.getOpcode() == Constants.INVOKESTATIC); } public static XField createXField(FieldAnnotation f) { return createXField(f.getClassName(), f.getFieldName(), f.getFieldSignature(), f.isStatic()); } public static XField createXField(JavaClass javaClass, Field field) { return createXField(javaClass.getClassName(), field); } /** * Create an XField object from a BCEL Field. * * @param className * the name of the Java class containing the field * @param field * the Field within the JavaClass * @return the created XField */ public static XField createXField(String className, Field field) { String fieldName = field.getName(); String fieldSig = field.getSignature(); XField xfield = getExactXField(className, fieldName, fieldSig, field.isStatic()); assert xfield.isResolved() : "Could not exactly resolve " + xfield; return xfield; } /** * Get an XField object exactly matching given class, name, and signature. * May return an unresolved object (if the class can't be found, or does not * directly declare named field). * * @param className * name of class containing the field * @param name * name of field * @param signature * field signature * @param isStatic * field access flags * @return XField exactly matching class name, field name, and field * signature */ public static XField getExactXField(String className, String name, String signature, boolean isStatic) { FieldDescriptor fieldDesc = DescriptorFactory.instance().getFieldDescriptor(ClassName.toSlashedClassName(className), name, signature, isStatic); return getExactXField(fieldDesc); } public static @Nonnull XField getExactXField(FieldDescriptor desc) { XFactory xFactory = AnalysisContext.currentXFactory(); XField f = xFactory.fields.get(desc); if (f == null) return new UnresolvedXField(desc); return f; } public static XField createXField(FieldDescriptor desc) { XFactory xFactory = AnalysisContext.currentXFactory(); XField m = xFactory.fields.get(desc); if (m != null) return m; m = xFactory.resolveXField(desc); xFactory.fields.put(desc, m); return m; } private XField resolveXField(FieldDescriptor originalDescriptor) { FieldDescriptor desc = originalDescriptor; try { while (true) { XField m = fields.get(desc); if (m != null) return m; XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, desc.getClassDescriptor()); if (xClass == null) break; ClassDescriptor superClass = xClass.getSuperclassDescriptor(); if (superClass == null) break; desc = DescriptorFactory.instance().getFieldDescriptor(superClass.getClassName(), desc.getName(), desc.getSignature(), desc.isStatic()); } } catch (CheckedAnalysisException e) { assert true; } return new UnresolvedXField(originalDescriptor); } /** * Create an XMethod object from an InvokeInstruction. * * @param invokeInstruction * the InvokeInstruction * @param cpg * ConstantPoolGen from the class containing the instruction * @return XMethod representing the method called by the InvokeInstruction */ public static XMethod createXMethod(InvokeInstruction invokeInstruction, ConstantPoolGen cpg) { String className = invokeInstruction.getClassName(cpg); String methodName = invokeInstruction.getName(cpg); String methodSig = invokeInstruction.getSignature(cpg); return createXMethod(className, methodName, methodSig, invokeInstruction.getOpcode() == Constants.INVOKESTATIC); } /** * Create an XMethod object from the method currently being visited by the * given PreorderVisitor. * * @param visitor * the PreorderVisitor * @return the XMethod representing the method currently being visited */ public static XMethod createXMethod(PreorderVisitor visitor) { JavaClass javaClass = visitor.getThisClass(); Method method = visitor.getMethod(); XMethod m = createXMethod(javaClass, method); return m; } /** * Create an XField object from the field currently being visited by the * given PreorderVisitor. * * @param visitor * the PreorderVisitor * @return the XField representing the method currently being visited */ public static XField createXField(PreorderVisitor visitor) { JavaClass javaClass = visitor.getThisClass(); Field field = visitor.getField(); XField f = createXField(javaClass, field); return f; } public static XMethod createXMethod(MethodGen methodGen) { String className = methodGen.getClassName(); String methodName = methodGen.getName(); String methodSig = methodGen.getSignature(); int accessFlags = methodGen.getAccessFlags(); return createXMethod(className, methodName, methodSig, accessFlags); } public static XMethod createXMethod(JavaClassAndMethod classAndMethod) { return createXMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod()); } /** * Get the XClass object providing information about the class named by the * given ClassDescriptor. * * @param classDescriptor * a ClassDescriptor * @return an XClass object providing information about the class, or null * if the class cannot be found */ public XClass getXClass(ClassDescriptor classDescriptor) { try { IAnalysisCache analysisCache = Global.getAnalysisCache(); return analysisCache.getClassAnalysis(XClass.class, classDescriptor); } catch (CheckedAnalysisException e) { return null; } } /** * Compare XMethod or XField object objects. * <em>All methods that implement XMethod or XField should * delegate to this method when implementing compareTo(Object) * if the right-hand object implements XField or XMethod.</em> * * @param lhs * an XMethod or XField * @param rhs * an XMethod or XField * @return comparison of lhs and rhs */ public static <E extends ClassMember> int compare(E lhs, E rhs) { int cmp; cmp = lhs.getClassName().compareTo(rhs.getClassName()); if (cmp != 0) { return cmp; } cmp = lhs.getName().compareTo(rhs.getName()); if (cmp != 0) { return cmp; } cmp = lhs.getSignature().compareTo(rhs.getSignature()); if (cmp != 0) { return cmp; } return (lhs.isStatic() ? 1 : 0) - (rhs.isStatic() ? 1 : 0); } }
Mark method where default nonnull annotation does not apply git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9077 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/ba/XFactory.java
Mark method where default nonnull annotation does not apply
Java
apache-2.0
f35372a57fe723b43c41342d94b47bc666361455
0
rjainqb/jets3t-rj,rjainqb/jets3t-rj
package org.jets3t.apps.cockpit.gui; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import javax.swing.table.DefaultTableModel; import org.jets3t.service.model.S3Bucket; public class BucketTableModel extends DefaultTableModel { ArrayList bucketList = new ArrayList(); public BucketTableModel() { super(new String[] {"Bucket Name"}, 0); } public int addBucket(S3Bucket bucket) { int insertRow = Collections.binarySearch(bucketList, bucket, new Comparator() { public int compare(Object o1, Object o2) { String b1Name = ((S3Bucket)o1).getName(); String b2Name = ((S3Bucket)o2).getName(); int result = b1Name.compareToIgnoreCase(b2Name); return result; } }); if (insertRow >= 0) { // We already have an item with this key, replace it. bucketList.remove(insertRow); this.removeRow(insertRow); } else { insertRow = (-insertRow) - 1; } // New object to insert. bucketList.add(insertRow, bucket); this.insertRow(insertRow, new Object[] {bucket.getName()}); return insertRow; } public void removeBucket(S3Bucket bucket) { int index = bucketList.indexOf(bucket); this.removeRow(index); bucketList.remove(bucket); } public void removeAllBuckets() { int rowCount = this.getRowCount(); for (int i = 0; i < rowCount; i++) { this.removeRow(0); } bucketList.clear(); } public S3Bucket getBucket(int row) { return (S3Bucket) bucketList.get(row); } public S3Bucket[] getBuckets() { return (S3Bucket[]) bucketList.toArray(new S3Bucket[] {}); } public boolean isCellEditable(int row, int column) { return false; } }
src/org/jets3t/apps/cockpit/gui/BucketTableModel.java
package org.jets3t.apps.cockpit.gui; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import javax.swing.table.DefaultTableModel; import org.jets3t.service.model.S3Bucket; public class BucketTableModel extends DefaultTableModel { ArrayList bucketList = new ArrayList(); public BucketTableModel() { super(new String[] {"Buckets"}, 0); } public int addBucket(S3Bucket bucket) { int insertRow = Collections.binarySearch(bucketList, bucket, new Comparator() { public int compare(Object o1, Object o2) { String b1Name = ((S3Bucket)o1).getName(); String b2Name = ((S3Bucket)o2).getName(); int result = b1Name.compareToIgnoreCase(b2Name); return result; } }); if (insertRow >= 0) { // We already have an item with this key, replace it. bucketList.remove(insertRow); this.removeRow(insertRow); } else { insertRow = (-insertRow) - 1; } // New object to insert. bucketList.add(insertRow, bucket); this.insertRow(insertRow, new Object[] {bucket.getName()}); return insertRow; } public void removeBucket(S3Bucket bucket) { int index = bucketList.indexOf(bucket); this.removeRow(index); bucketList.remove(bucket); } public void removeAllBuckets() { int rowCount = this.getRowCount(); for (int i = 0; i < rowCount; i++) { this.removeRow(0); } bucketList.clear(); } public S3Bucket getBucket(int row) { return (S3Bucket) bucketList.get(row); } public S3Bucket[] getBuckets() { return (S3Bucket[]) bucketList.toArray(new S3Bucket[] {}); } public boolean isCellEditable(int row, int column) { return false; } }
More accurate table title: "Bucket Name"
src/org/jets3t/apps/cockpit/gui/BucketTableModel.java
More accurate table title: "Bucket Name"
Java
apache-2.0
cd2f1a691699ef5c43d5513a063154a5eb002da4
0
molw/postgisservice,molw/postgisservice
/* * JBoss, Home of Professional Open Source * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.molw.ws; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * A simple REST service which is able to say hello to someone using HelloService Please take a look at the web.xml where JAX-RS * is enabled * * @author [email protected] * */ @Path("birds") public class BirdsWS { @GET @Path("json") @Produces({ "application/json" }) public String getHelloWorldJSON() { System.out.printf("Hellow world from JSON"); return "{\"result\":\"" + "World" + "\"}"; } @GET @Path("xml") @Produces({ "application/xml" }) public String getHelloWorldXML() { return "<xml><result>world</result></xml>"; } }
src/main/java/org/molw/ws/BirdsWS.java
/* * JBoss, Home of Professional Open Source * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.molw.ws; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * A simple REST service which is able to say hello to someone using HelloService Please take a look at the web.xml where JAX-RS * is enabled * * @author [email protected] * */ @Path("/birds") public class BirdsWS { @GET @Path("/json") @Produces({ "application/json" }) public String getHelloWorldJSON() { return "{\"result\":\"" + "World" + "\"}"; } @GET @Path("/xml") @Produces({ "application/xml" }) public String getHelloWorldXML() { return "<xml><result>world</result></xml>"; } }
Trying to get it working without the web.xml
src/main/java/org/molw/ws/BirdsWS.java
Trying to get it working without the web.xml
Java
apache-2.0
f4e04e7ad53d22757cfea83bf0dc2a9dfce77237
0
hungdoan2/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,pinkbike/phonegap-googlemaps-plugin,Jerome2606/phonegap-googlemaps-plugin,rynomster/cordova-plugin-googlemaps,Nipher/phonegap-googlemaps-plugin,elwahid/plugin.google.maps,elwahid/plugin.google.maps,smcpjames/cordova-plugin-googlemaps,hungdoan2/phonegap-googlemaps-plugin,blanedaze/phonegap-googlemaps-plugin,mapsplugin/cordova-plugin-googlemaps,blanedaze/phonegap-googlemaps-plugin,snoopconsulting/phonegap-googlemaps-plugin,Nipher/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,mapsplugin/cordova-plugin-googlemaps,hitoci/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,smcpjames/cordova-plugin-googlemaps,hungdoan2/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,hungdoan2/phonegap-googlemaps-plugin,dukhanov/cordova-plugin-googlemaps,dukhanov/cordova-plugin-googlemaps,otreva/phonegap-googlemaps-plugin,joewoodhouse/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,roberthovhannisyan/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,edivancamargo/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,otreva/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,LouisMazel/cordova-plugin-googlemaps,elwahid/plugin.google.maps,Jerome2606/phonegap-googlemaps-plugin,roberthovhannisyan/phonegap-googlemaps-plugin,Nipher/phonegap-googlemaps-plugin,hitoci/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,pinkbike/phonegap-googlemaps-plugin,rynomster/cordova-plugin-googlemaps,cabify/cordova-plugin-googlemaps,edivancamargo/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,Jerome2606/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,wf9a5m75/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,Jerome2606/phonegap-googlemaps-plugin,denisbabineau/phonegap-googlemaps-plugin,denisbabineau/cordova-plugin-googlemaps,smcpjames/cordova-plugin-googlemaps,edivancamargo/phonegap-googlemaps-plugin,denisbabineau/phonegap-googlemaps-plugin,alexislg2/phonegap-googlemaps-plugin,roberthovhannisyan/phonegap-googlemaps-plugin,otreva/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,dukhanov/cordova-plugin-googlemaps,alexislg2/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,denisbabineau/cordova-plugin-googlemaps,denisbabineau/cordova-plugin-googlemaps,LouisMazel/cordova-plugin-googlemaps,wolf-s/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,mapsplugin/cordova-plugin-googlemaps,quiuquio/cordova-plugin-googlemaps,piotrbelina/phonegap-googlemaps-plugin,wf9a5m75/phonegap-googlemaps-plugin,joewoodhouse/phonegap-googlemaps-plugin,cabify/cordova-plugin-googlemaps,wf9a5m75/phonegap-googlemaps-plugin,blanedaze/phonegap-googlemaps-plugin,elwahid/plugin.google.maps,LouisMazel/cordova-plugin-googlemaps,snoopconsulting/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,hitoci/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,joewoodhouse/phonegap-googlemaps-plugin,hitoci/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,Nipher/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,cabify/cordova-plugin-googlemaps,snoopconsulting/phonegap-googlemaps-plugin,denisbabineau/phonegap-googlemaps-plugin,edivancamargo/phonegap-googlemaps-plugin,quiuquio/cordova-plugin-googlemaps,quiuquio/cordova-plugin-googlemaps,Skysurfer0110/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,pinkbike/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,otreva/phonegap-googlemaps-plugin,alexislg2/phonegap-googlemaps-plugin,snoopconsulting/phonegap-googlemaps-plugin,rynomster/cordova-plugin-googlemaps
package plugin.google.maps; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginEntry; import org.apache.cordova.PluginResult; import org.apache.cordova.ScrollEvent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import plugin.http.request.HttpRequest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Point; import android.graphics.Typeface; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Build; import android.os.Build.VERSION; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebSettings.RenderPriority; import android.widget.AbsoluteLayout; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks; import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter; import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLoadedCallback; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener; import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.CameraPosition.Builder; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.GroundOverlay; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.VisibleRegion; @SuppressWarnings("deprecation") public class GoogleMaps extends CordovaPlugin implements View.OnClickListener, OnMarkerClickListener, OnInfoWindowClickListener, OnMapClickListener, OnMapLongClickListener, OnCameraChangeListener, OnMapLoadedCallback, OnMarkerDragListener, OnMyLocationButtonClickListener, InfoWindowAdapter { private final String TAG = "GoogleMapsPlugin"; private final HashMap<String, PluginEntry> plugins = new HashMap<String, PluginEntry>(); private float density; private enum EVENTS { onScrollChanged } private enum TEXT_STYLE_ALIGNMENTS { left, center, right } private JSONObject mapDivLayoutJSON = null; private MapView mapView = null; public GoogleMap map = null; private Activity activity; private LinearLayout windowLayer = null; private ViewGroup root; private final int CLOSE_LINK_ID = 0x7f999990; //random private final int LICENSE_LINK_ID = 0x7f99991; //random private final String PLUGIN_VERSION = "1.2.4 beta"; private MyPluginLayout mPluginLayout = null; private LocationClient locationClient = null; private boolean isDebug = false; private boolean isCrossWalk = false; @SuppressLint("NewApi") @Override public void initialize(final CordovaInterface cordova, final CordovaWebView webView) { super.initialize(cordova, webView); activity = cordova.getActivity(); density = Resources.getSystem().getDisplayMetrics().density; root = (ViewGroup) webView.getParent(); // Is this app in debug mode? try { PackageManager manager = activity.getPackageManager(); ApplicationInfo appInfo = manager.getApplicationInfo(activity.getPackageName(), 0); isDebug = (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE; } catch (Exception e) {} Log.i("CordovaLog", "This app uses phonegap-googlemaps-plugin version " + PLUGIN_VERSION); if (isDebug) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { JSONArray params = new JSONArray(); params.put("get"); params.put("http://plugins.cordova.io/api/plugin.google.maps"); HttpRequest httpReq = new HttpRequest(); httpReq.initialize(cordova, null); httpReq.execute("execute", params, new CallbackContext("version_check", webView) { @Override public void sendPluginResult(PluginResult pluginResult) { if (pluginResult.getStatus() == PluginResult.Status.OK.ordinal()) { try { JSONObject result = new JSONObject(pluginResult.getStrMessage()); JSONObject distTags = result.getJSONObject("dist-tags"); String latestVersion = distTags.getString("latest"); if (latestVersion.equals(PLUGIN_VERSION) == false) { Log.i("CordovaLog", "phonegap-googlemaps-plugin version " + latestVersion + " is available."); } } catch (JSONException e) {} } } }); } catch (Exception e) {} } }); } cordova.getActivity().runOnUiThread(new Runnable() { @SuppressLint("NewApi") public void run() { if (isCrossWalk == false) { try { Method method = webView.getClass().getMethod("getSettings", null); WebSettings settings = (WebSettings)method.invoke(null, null); settings.setRenderPriority(RenderPriority.HIGH); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); } catch (Exception e) { e.printStackTrace(); } } if (Build.VERSION.SDK_INT >= 11){ webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } root.setBackgroundColor(Color.WHITE); if (VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) { activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); } if (VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { Log.d(TAG, "Google Maps Plugin reloads the browser to change the background color as transparent."); webView.setBackgroundColor(0); if (isCrossWalk == false) { try { Method method = webView.getClass().getMethod("reload", null); method.invoke(null, null); } catch (Exception e) { e.printStackTrace(); } } } } }); } @Override public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { if (isDebug) { if (args != null && args.length() > 0) { Log.d(TAG, "(debug)action=" + action + " args[0]=" + args.getString(0)); } else { Log.d(TAG, "(debug)action=" + action); } } Runnable runnable = new Runnable() { public void run() { if (("getMap".equals(action) == false && "isAvailable".equals(action) == false) && GoogleMaps.this.map == null) { Log.w(TAG, "Can not execute '" + action + "' because the map is not created."); return; } if ("exec".equals(action)) { try { String classMethod = args.getString(0); String[] params = classMethod.split("\\.", 0); if ("Map.setOptions".equals(classMethod)) { JSONObject jsonParams = args.getJSONObject(1); if (jsonParams.has("backgroundColor")) { JSONArray rgba = jsonParams.getJSONArray("backgroundColor"); int backgroundColor = Color.WHITE; if (rgba != null && rgba.length() == 4) { try { backgroundColor = PluginUtil.parsePluginColor(rgba); mPluginLayout.setBackgroundColor(backgroundColor); } catch (JSONException e) {} } } } // Load the class plugin GoogleMaps.this.loadPlugin(params[0]); PluginEntry entry = GoogleMaps.this.plugins.get(params[0]); if (params.length == 2 && entry != null) { entry.plugin.execute("execute", args, callbackContext); } else { callbackContext.error("'" + action + "' parameter is invalid length."); } } catch (Exception e) { e.printStackTrace(); callbackContext.error("Java Error\n" + e.getCause().getMessage()); } } else { try { Method method = GoogleMaps.this.getClass().getDeclaredMethod(action, JSONArray.class, CallbackContext.class); if (method.isAccessible() == false) { method.setAccessible(true); } method.invoke(GoogleMaps.this, args, callbackContext); } catch (Exception e) { e.printStackTrace(); callbackContext.error("'" + action + "' is not defined in GoogleMaps plugin."); } } } }; cordova.getActivity().runOnUiThread(runnable); return true; } @SuppressWarnings("unused") private void setDiv(JSONArray args, CallbackContext callbackContext) throws JSONException { if (args.length() == 0) { this.mapDivLayoutJSON = null; mPluginLayout.detachMyView(); this.sendNoResult(callbackContext); return; } if (args.length() == 2) { mPluginLayout.attachMyView(mapView); this.resizeMap(args, callbackContext); } } /** * Set visibility of the map * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException { boolean visible = args.getBoolean(0); if (this.windowLayer == null) { if (visible) { mapView.setVisibility(View.VISIBLE); } else { mapView.setVisibility(View.INVISIBLE); } } this.sendNoResult(callbackContext); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void getMap(JSONArray args, final CallbackContext callbackContext) throws JSONException { if (map != null) { callbackContext.success(); return; } mPluginLayout = new MyPluginLayout(webView, activity); // ------------------------------ // Check of Google Play Services // ------------------------------ int checkGooglePlayServices = GooglePlayServicesUtil .isGooglePlayServicesAvailable(activity); if (checkGooglePlayServices != ConnectionResult.SUCCESS) { // google play services is missing!!!! /* * Returns status code indicating whether there was an error. Can be one * of following in ConnectionResult: SUCCESS, SERVICE_MISSING, * SERVICE_VERSION_UPDATE_REQUIRED, SERVICE_DISABLED, SERVICE_INVALID. */ Log.e("CordovaLog", "---Google Play Services is not available: " + GooglePlayServicesUtil.getErrorString(checkGooglePlayServices)); Dialog errorDialog = null; try { //errorDialog = GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices, activity, 1); Method getErrorDialogMethod = GooglePlayServicesUtil.class.getMethod("getErrorDialog", int.class, Activity.class, int.class); errorDialog = (Dialog)getErrorDialogMethod.invoke(null, checkGooglePlayServices, activity, 1); } catch (Exception e) {}; if (errorDialog != null) { errorDialog.show(); } else { boolean isNeedToUpdate = false; String errorMsg = "Google Maps Android API v2 is not available for some reason on this device. Do you install the latest Google Play Services from Google Play Store?"; switch (checkGooglePlayServices) { case ConnectionResult.DATE_INVALID: errorMsg = "It seems your device date is set incorrectly. Please update the correct date and time."; break; case ConnectionResult.DEVELOPER_ERROR: errorMsg = "The application is misconfigured. This error is not recoverable and will be treated as fatal. The developer should look at the logs after this to determine more actionable information."; break; case ConnectionResult.INTERNAL_ERROR: errorMsg = "An internal error of Google Play Services occurred. Please retry, and it should resolve the problem."; break; case ConnectionResult.INVALID_ACCOUNT: errorMsg = "You attempted to connect to the service with an invalid account name specified."; break; case ConnectionResult.LICENSE_CHECK_FAILED: errorMsg = "The application is not licensed to the user. This error is not recoverable and will be treated as fatal."; break; case ConnectionResult.NETWORK_ERROR: errorMsg = "A network error occurred. Please retry, and it should resolve the problem."; break; case ConnectionResult.SERVICE_DISABLED: errorMsg = "The installed version of Google Play services has been disabled on this device. Please turn on Google Play Services."; break; case ConnectionResult.SERVICE_INVALID: errorMsg = "The version of the Google Play services installed on this device is not authentic. Please update the Google Play Services from Google Play Store."; isNeedToUpdate = true; break; case ConnectionResult.SERVICE_MISSING: errorMsg = "Google Play services is missing on this device. Please install the Google Play Services."; isNeedToUpdate = true; break; case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: errorMsg = "The installed version of Google Play services is out of date. Please update the Google Play Services from Google Play Store."; isNeedToUpdate = true; break; case ConnectionResult.SIGN_IN_REQUIRED: errorMsg = "You attempted to connect to the service but you are not signed in. Please check the Google Play Services configuration"; break; default: isNeedToUpdate = true; break; } final boolean finalIsNeedToUpdate = isNeedToUpdate; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity); alertDialogBuilder .setMessage(errorMsg) .setCancelable(false) .setPositiveButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.dismiss(); if (finalIsNeedToUpdate) { try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.gms"))); } catch (android.content.ActivityNotFoundException anfe) { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=appPackageName"))); } } } }); AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } callbackContext.error("Google Play Services is not available."); return; } // Check the API key ApplicationInfo appliInfo = null; try { appliInfo = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA); } catch (NameNotFoundException e) {} String API_KEY = appliInfo.metaData.getString("com.google.android.maps.v2.API_KEY"); if ("API_KEY_FOR_ANDROID".equals(API_KEY)) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity); alertDialogBuilder .setMessage("Please replace 'API_KEY_FOR_ANDROID' in the platforms/android/AndroidManifest.xml with your API Key!") .setCancelable(false) .setPositiveButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.dismiss(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } // ------------------------------ // Initialize Google Maps SDK // ------------------------------ try { MapsInitializer.initialize(activity); } catch (Exception e) { e.printStackTrace(); callbackContext.error(e.getMessage()); return; } GoogleMapOptions options = new GoogleMapOptions(); JSONObject params = args.getJSONObject(0); //background color if (params.has("backgroundColor")) { JSONArray rgba = params.getJSONArray("backgroundColor"); int backgroundColor = Color.WHITE; if (rgba != null && rgba.length() == 4) { try { backgroundColor = PluginUtil.parsePluginColor(rgba); this.mPluginLayout.setBackgroundColor(backgroundColor); } catch (JSONException e) {} } } //controls if (params.has("controls")) { JSONObject controls = params.getJSONObject("controls"); if (controls.has("compass")) { options.compassEnabled(controls.getBoolean("compass")); } if (controls.has("zoom")) { options.zoomControlsEnabled(controls.getBoolean("zoom")); } } //gestures if (params.has("gestures")) { JSONObject gestures = params.getJSONObject("gestures"); if (gestures.has("tilt")) { options.tiltGesturesEnabled(gestures.getBoolean("tilt")); } if (gestures.has("scroll")) { options.scrollGesturesEnabled(gestures.getBoolean("scroll")); } if (gestures.has("rotate")) { options.rotateGesturesEnabled(gestures.getBoolean("rotate")); } if (gestures.has("zoom")) { options.zoomGesturesEnabled(gestures.getBoolean("zoom")); } } // map type if (params.has("mapType")) { String typeStr = params.getString("mapType"); int mapTypeId = -1; mapTypeId = typeStr.equals("MAP_TYPE_NORMAL") ? GoogleMap.MAP_TYPE_NORMAL : mapTypeId; mapTypeId = typeStr.equals("MAP_TYPE_HYBRID") ? GoogleMap.MAP_TYPE_HYBRID : mapTypeId; mapTypeId = typeStr.equals("MAP_TYPE_SATELLITE") ? GoogleMap.MAP_TYPE_SATELLITE : mapTypeId; mapTypeId = typeStr.equals("MAP_TYPE_TERRAIN") ? GoogleMap.MAP_TYPE_TERRAIN : mapTypeId; mapTypeId = typeStr.equals("MAP_TYPE_NONE") ? GoogleMap.MAP_TYPE_NONE : mapTypeId; if (mapTypeId != -1) { options.mapType(mapTypeId); } } // initial camera position if (params.has("camera")) { JSONObject camera = params.getJSONObject("camera"); Builder builder = CameraPosition.builder(); if (camera.has("bearing")) { builder.bearing((float) camera.getDouble("bearing")); } if (camera.has("latLng")) { JSONObject latLng = camera.getJSONObject("latLng"); builder.target(new LatLng(latLng.getDouble("lat"), latLng.getDouble("lng"))); } if (camera.has("tilt")) { builder.tilt((float) camera.getDouble("tilt")); } if (camera.has("zoom")) { builder.zoom((float) camera.getDouble("zoom")); } options.camera(builder.build()); } mapView = new MapView(activity, options); mapView.onCreate(null); mapView.onResume(); map = mapView.getMap(); //controls if (params.has("controls")) { JSONObject controls = params.getJSONObject("controls"); if (controls.has("myLocationButton")) { Boolean isEnabled = controls.getBoolean("myLocationButton"); map.setMyLocationEnabled(isEnabled); map.getUiSettings().setMyLocationButtonEnabled(isEnabled); } if (controls.has("indoorPicker")) { Boolean isEnabled = controls.getBoolean("indoorPicker"); map.setIndoorEnabled(isEnabled); } } // Set event listener map.setOnCameraChangeListener(this); map.setOnInfoWindowClickListener(this); map.setOnMapClickListener(this); map.setOnMapLoadedCallback(this); map.setOnMapLongClickListener(this); map.setOnMarkerClickListener(this); map.setOnMarkerDragListener(this); map.setOnMyLocationButtonClickListener(this); // Load PluginMap class this.loadPlugin("Map"); //Custom info window map.setInfoWindowAdapter(this); callbackContext.success(); // ------------------------------ // Embed the map if a container is specified. // ------------------------------ if (args.length() == 3) { this.mapDivLayoutJSON = args.getJSONObject(1); mPluginLayout.attachMyView(mapView); this.resizeMap(args, callbackContext); } } private float contentToView(long d) { return d * this.density; } //----------------------------------- // Create the instance of class //----------------------------------- @SuppressWarnings("rawtypes") private void loadPlugin(String serviceName) { if (plugins.containsKey(serviceName)) { return; } try { Class pluginCls = Class.forName("plugin.google.maps.Plugin" + serviceName); CordovaPlugin plugin = (CordovaPlugin) pluginCls.newInstance(); PluginEntry pluginEntry = new PluginEntry("GoogleMaps", plugin); this.plugins.put(serviceName, pluginEntry); try { Class cordovaPref = Class.forName("org.apache.cordova.CordovaPreferences"); if (cordovaPref != null) { Method privateInit = CordovaPlugin.class.getMethod("privateInitialize", CordovaInterface.class, CordovaWebView.class, cordovaPref); if (privateInit != null) { privateInit.invoke(plugin, this.cordova, webView, null); } } } catch (Exception e2) {} plugin.initialize(this.cordova, webView); ((MyPluginInterface)plugin).setMapCtrl(this); if (map == null) { Log.e(TAG, "map is null!"); } } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unused") private Boolean myTest(JSONArray args, CallbackContext callbackContext) { PolygonOptions options = new PolygonOptions(); options.add(new LatLng(-45, -90)); options.add(new LatLng(-45, -180)); options.add(new LatLng(0, -180)); options.add(new LatLng(0, -90)); map.addPolygon(options); callbackContext.success(); return true; } @SuppressWarnings("unused") private Boolean getLicenseInfo(JSONArray args, CallbackContext callbackContext) { String msg = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(activity); callbackContext.success(msg); return true; } @Override public Object onMessage(String id, Object data) { EVENTS event = null; try { event = EVENTS.valueOf(id); }catch(Exception e) {} if (event == null) { return null; } switch(event) { case onScrollChanged: ScrollEvent scrollEvent = (ScrollEvent)data; if (mPluginLayout != null) { mPluginLayout.scrollTo(scrollEvent.nl, scrollEvent.nt); if (mapDivLayoutJSON != null) { try { float divW = contentToView(mapDivLayoutJSON.getLong("width")); float divH = contentToView(mapDivLayoutJSON.getLong("height")); float divLeft = contentToView(mapDivLayoutJSON.getLong("left")); float divTop = contentToView(mapDivLayoutJSON.getLong("top")); mPluginLayout.setDrawingRect( divLeft, divTop - scrollEvent.nt, divLeft + divW, divTop + divH - scrollEvent.nt); } catch (JSONException e) { e.printStackTrace(); } } } break; } return null; } private void closeWindow() { if (isCrossWalk == false) { try { Method method = webView.getClass().getMethod("hideCustomView", null); method.invoke(null, null); } catch (Exception e) { e.printStackTrace(); } } } @SuppressWarnings("unused") private void showDialog(final JSONArray args, final CallbackContext callbackContext) { if (windowLayer != null) { return; } // window layout windowLayer = new LinearLayout(activity); windowLayer.setPadding(0, 0, 0, 0); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layoutParams.gravity = Gravity.TOP | Gravity.LEFT; windowLayer.setLayoutParams(layoutParams); // dialog window layer FrameLayout dialogLayer = new FrameLayout(activity); dialogLayer.setLayoutParams(layoutParams); //dialogLayer.setPadding(15, 15, 15, 0); dialogLayer.setBackgroundColor(Color.LTGRAY); windowLayer.addView(dialogLayer); // map frame final FrameLayout mapFrame = new FrameLayout(activity); mapFrame.setPadding(0, 0, 0, (int)(40 * density)); dialogLayer.addView(mapFrame); if (this.mPluginLayout != null && this.mPluginLayout.getMyView() != null) { this.mPluginLayout.detachMyView(); } ViewGroup.LayoutParams lParams = (ViewGroup.LayoutParams) mapView.getLayoutParams(); if (lParams == null) { lParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } lParams.width = ViewGroup.LayoutParams.MATCH_PARENT; lParams.height = ViewGroup.LayoutParams.MATCH_PARENT; if (lParams instanceof AbsoluteLayout.LayoutParams) { AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) lParams; params.x = 0; params.y = 0; mapView.setLayoutParams(params); } else if (lParams instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lParams; params.topMargin = 0; params.leftMargin = 0; mapView.setLayoutParams(params); } else if (lParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) lParams; params.topMargin = 0; params.leftMargin = 0; mapView.setLayoutParams(params); } mapFrame.addView(this.mapView); // button frame LinearLayout buttonFrame = new LinearLayout(activity); buttonFrame.setOrientation(LinearLayout.HORIZONTAL); buttonFrame.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM); LinearLayout.LayoutParams buttonFrameParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); buttonFrame.setLayoutParams(buttonFrameParams); dialogLayer.addView(buttonFrame); //close button LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f); TextView closeLink = new TextView(activity); closeLink.setText("Close"); closeLink.setLayoutParams(buttonParams); closeLink.setTextColor(Color.BLUE); closeLink.setTextSize(20); closeLink.setGravity(Gravity.LEFT); closeLink.setPadding((int)(10 * density), 0, 0, (int)(10 * density)); closeLink.setOnClickListener(GoogleMaps.this); closeLink.setId(CLOSE_LINK_ID); buttonFrame.addView(closeLink); //license button TextView licenseLink = new TextView(activity); licenseLink.setText("Legal Notices"); licenseLink.setTextColor(Color.BLUE); licenseLink.setLayoutParams(buttonParams); licenseLink.setTextSize(20); licenseLink.setGravity(Gravity.RIGHT); licenseLink.setPadding((int)(10 * density), (int)(20 * density), (int)(10 * density), (int)(10 * density)); licenseLink.setOnClickListener(GoogleMaps.this); licenseLink.setId(LICENSE_LINK_ID); buttonFrame.addView(licenseLink); webView.setVisibility(View.GONE); root.addView(windowLayer); //Dummy view for the back-button event FrameLayout dummyLayout = new FrameLayout(activity); /* this.webView.showCustomView(dummyLayout, new WebChromeClient.CustomViewCallback() { @Override public void onCustomViewHidden() { mapFrame.removeView(mapView); if (mPluginLayout != null && mapDivLayoutJSON != null) { mPluginLayout.attachMyView(mapView); mPluginLayout.updateViewPosition(); } root.removeView(windowLayer); webView.setVisibility(View.VISIBLE); windowLayer = null; GoogleMaps.this.onMapEvent("map_close"); } }); */ this.sendNoResult(callbackContext); } private void resizeMap(JSONArray args, CallbackContext callbackContext) throws JSONException { if (mPluginLayout == null) { callbackContext.success(); return; } mapDivLayoutJSON = args.getJSONObject(args.length() - 2); JSONArray HTMLs = args.getJSONArray(args.length() - 1); JSONObject elemInfo, elemSize; String elemId; float divW, divH, divLeft, divTop; if (mPluginLayout == null) { this.sendNoResult(callbackContext); return; } this.mPluginLayout.clearHTMLElement(); for (int i = 0; i < HTMLs.length(); i++) { elemInfo = HTMLs.getJSONObject(i); try { elemId = elemInfo.getString("id"); elemSize = elemInfo.getJSONObject("size"); divW = contentToView(elemSize.getLong("width")); divH = contentToView(elemSize.getLong("height")); divLeft = contentToView(elemSize.getLong("left")); divTop = contentToView(elemSize.getLong("top")); mPluginLayout.putHTMLElement(elemId, divLeft, divTop, divLeft + divW, divTop + divH); } catch (Exception e){ e.printStackTrace(); } } //mPluginLayout.inValidate(); updateMapViewLayout(); this.sendNoResult(callbackContext); } private void updateMapViewLayout() { if (mPluginLayout == null) { return; } try { float divW = contentToView(mapDivLayoutJSON.getLong("width")); float divH = contentToView(mapDivLayoutJSON.getLong("height")); float divLeft = contentToView(mapDivLayoutJSON.getLong("left")); float divTop = contentToView(mapDivLayoutJSON.getLong("top")); // Update the plugin drawing view rect mPluginLayout.setDrawingRect( divLeft, divTop - webView.getScrollY(), divLeft + divW, divTop + divH - webView.getScrollY()); mPluginLayout.updateViewPosition(); mapView.requestLayout(); } catch (JSONException e) { e.printStackTrace(); } } @SuppressWarnings("unused") private void closeDialog(final JSONArray args, final CallbackContext callbackContext) { this.closeWindow(); this.sendNoResult(callbackContext); } @SuppressWarnings("unused") private void isAvailable(final JSONArray args, final CallbackContext callbackContext) throws JSONException { // ------------------------------ // Check of Google Play Services // ------------------------------ int checkGooglePlayServices = GooglePlayServicesUtil .isGooglePlayServicesAvailable(activity); if (checkGooglePlayServices != ConnectionResult.SUCCESS) { // google play services is missing!!!! callbackContext.error("Google Maps Android API v2 is not available, because this device does not have Google Play Service."); return; } // ------------------------------ // Check of Google Maps Android API v2 // ------------------------------ try { @SuppressWarnings({ "rawtypes" }) Class GoogleMapsClass = Class.forName("com.google.android.gms.maps.GoogleMap"); } catch (Exception e) { Log.e("GoogleMaps", "Error", e); callbackContext.error(e.getMessage()); return; } callbackContext.success(); } @SuppressWarnings("unused") private void getMyLocation(final JSONArray args, final CallbackContext callbackContext) throws JSONException { LocationManager locationManager = (LocationManager) this.activity.getSystemService(Context.LOCATION_SERVICE); List<String> providers = locationManager.getAllProviders(); if (providers.size() == 0) { JSONObject result = new JSONObject(); result.put("status", false); result.put("error_code", "not_available"); result.put("error_message", "Since this device does not have any location provider, this app can not detect your location."); callbackContext.error(result); return; } // enableHighAccuracy = true -> PRIORITY_HIGH_ACCURACY // enableHighAccuracy = false -> PRIORITY_BALANCED_POWER_ACCURACY JSONObject params = args.getJSONObject(0); boolean isHigh = false; if (params.has("enableHighAccuracy")) { isHigh = params.getBoolean("enableHighAccuracy"); } final boolean enableHighAccuracy = isHigh; String provider = null; if (enableHighAccuracy == true) { if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) { provider = LocationManager.PASSIVE_PROVIDER; } } else { if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) { provider = LocationManager.PASSIVE_PROVIDER; } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; } } if (provider == null) { //Ask the user to turn on the location services. AlertDialog.Builder builder = new AlertDialog.Builder(this.activity); builder.setTitle("Improve location accuracy"); builder.setMessage("To enhance your Maps experience:\n\n" + " - Enable Google apps location access\n\n" + " - Turn on GPS and mobile network location"); builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Launch settings, allowing user to make a change Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); activity.startActivity(intent); JSONObject result = new JSONObject(); try { result.put("status", false); result.put("error_code", "open_settings"); result.put("error_message", "User opened the settings of location service. So try again."); } catch (JSONException e) {} callbackContext.error(result); } }); builder.setNegativeButton("Skip", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //No location service, no Activity dialog.dismiss(); JSONObject result = new JSONObject(); try { result.put("status", false); result.put("error_code", "service_denied"); result.put("error_message", "This app has rejected to use Location Services."); } catch (JSONException e) {} callbackContext.error(result); } }); builder.create().show(); return; } Log.d("openCV", "provider = " + provider); Location location = locationManager.getLastKnownLocation(provider); if (location != null) { JSONObject result = PluginUtil.location2Json(location); result.put("status", true); callbackContext.success(result); return; } PluginResult tmpResult = new PluginResult(PluginResult.Status.NO_RESULT); tmpResult.setKeepCallback(true); callbackContext.sendPluginResult(tmpResult); locationClient = new LocationClient(this.activity, new ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { LocationRequest request = new LocationRequest(); int priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY; if (enableHighAccuracy) { priority = LocationRequest.PRIORITY_HIGH_ACCURACY; } request.setPriority(priority); locationClient.requestLocationUpdates(request, new LocationListener() { @Override public void onLocationChanged(Location location) { JSONObject result; try { result = PluginUtil.location2Json(location); result.put("status", true); callbackContext.success(result); } catch (JSONException e) {} locationClient.disconnect(); } }); } @Override public void onDisconnected() {} }, new OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult connectionResult) { int errorCode = connectionResult.getErrorCode(); String errorMsg = GooglePlayServicesUtil.getErrorString(errorCode); PluginResult result = new PluginResult(PluginResult.Status.ERROR, errorMsg); callbackContext.sendPluginResult(result); } }); locationClient.connect(); } private void showLicenseText() { AsyncLicenseInfo showLicense = new AsyncLicenseInfo(activity); showLicense.execute(); } /******************************************************** * Callbacks ********************************************************/ /** * Notify marker event to JS * @param eventName * @param marker */ private void onMarkerEvent(String eventName, Marker marker) { String markerId = "marker_" + marker.getId(); webView.loadUrl("javascript:plugin.google.maps.Map." + "_onMarkerEvent('" + eventName + "','" + markerId + "')"); } private void onOverlayEvent(String eventName, String overlayId, LatLng point) { webView.loadUrl("javascript:plugin.google.maps.Map." + "_onOverlayEvent(" + "'" + eventName + "','" + overlayId + "', " + "new window.plugin.google.maps.LatLng(" + point.latitude + "," + point.longitude + ")" + ")"); } private void onPolylineClick(Polyline polyline, LatLng point) { String overlayId = "polyline_" + polyline.getId(); this.onOverlayEvent("overlay_click", overlayId, point); } private void onPolygonClick(Polygon polygon, LatLng point) { String overlayId = "polygon_" + polygon.getId(); this.onOverlayEvent("overlay_click", overlayId, point); } private void onCircleClick(Circle circle, LatLng point) { String overlayId = "circle_" + circle.getId(); this.onOverlayEvent("overlay_click", overlayId, point); } private void onGroundOverlayClick(GroundOverlay groundOverlay, LatLng point) { String overlayId = "groundOverlay_" + groundOverlay.getId(); this.onOverlayEvent("overlay_click", overlayId, point); } @Override public boolean onMarkerClick(Marker marker) { this.onMarkerEvent("click", marker); JSONObject properties = null; String propertyId = "marker_property_" + marker.getId(); PluginEntry pluginEntry = this.plugins.get("Marker"); PluginMarker pluginMarker = (PluginMarker)pluginEntry.plugin; if (pluginMarker.objects.containsKey(propertyId)) { properties = (JSONObject) pluginMarker.objects.get(propertyId); if (properties.has("disableAutoPan")) { boolean disableAutoPan = false; try { disableAutoPan = properties.getBoolean("disableAutoPan"); } catch (JSONException e) {} if (disableAutoPan) { marker.showInfoWindow(); return true; } } } marker.showInfoWindow(); return true; //return false; } @Override public void onInfoWindowClick(Marker marker) { this.onMarkerEvent("info_click", marker); } @Override public void onMarkerDrag(Marker marker) { this.onMarkerEvent("drag", marker); } @Override public void onMarkerDragEnd(Marker marker) { this.onMarkerEvent("drag_end", marker); } @Override public void onMarkerDragStart(Marker marker) { this.onMarkerEvent("drag_start", marker); } /** * Notify map event to JS * @param eventName * @param point */ private void onMapEvent(final String eventName) { webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('" + eventName + "')"); } /** * Notify map event to JS * @param eventName * @param point */ private void onMapEvent(final String eventName, final LatLng point) { webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent(" + "'" + eventName + "', new window.plugin.google.maps.LatLng(" + point.latitude + "," + point.longitude + "))"); } @Override public void onMapLongClick(LatLng point) { this.onMapEvent("long_click", point); } private double calculateDistance(LatLng pt1, LatLng pt2){ float[] results = new float[1]; Location.distanceBetween(pt1.latitude, pt1.longitude, pt2.latitude, pt2.longitude, results); return results[0]; } /** * Notify map click event to JS, also checks for click on a polygon and triggers onPolygonEvent * @param point */ public void onMapClick(LatLng point) { boolean hitPoly = false; String key; LatLngBounds bounds; // Polyline PluginEntry polylinePlugin = this.plugins.get("Polyline"); if(polylinePlugin != null) { PluginPolyline polylineClass = (PluginPolyline) polylinePlugin.plugin; List<LatLng> points ; Polyline polyline; Point origin = new Point(); Point hitArea = new Point(); hitArea.x = 1; hitArea.y = 1; Projection projection = map.getProjection(); double threshold = this.calculateDistance( projection.fromScreenLocation(origin), projection.fromScreenLocation(hitArea)); for (HashMap.Entry<String, Object> entry : polylineClass.objects.entrySet()) { key = entry.getKey(); if (key.contains("polyline_bounds_")) { bounds = (LatLngBounds) entry.getValue(); if (bounds.contains(point)) { key = key.replace("bounds_", ""); polyline = polylineClass.getPolyline(key); points = polyline.getPoints(); if (polyline.isGeodesic()) { if (this.isPointOnTheGeodesicLine(points, point, threshold)) { hitPoly = true; this.onPolylineClick(polyline, point); } } else { if (this.isPointOnTheLine(points, point)) { hitPoly = true; this.onPolylineClick(polyline, point); } } } } } if (hitPoly) { return; } } // Loop through all polygons to check if within the touch point PluginEntry polygonPlugin = this.plugins.get("Polygon"); if (polygonPlugin != null) { PluginPolygon polygonClass = (PluginPolygon) polygonPlugin.plugin; for (HashMap.Entry<String, Object> entry : polygonClass.objects.entrySet()) { key = entry.getKey(); if (key.contains("polygon_bounds_")) { bounds = (LatLngBounds) entry.getValue(); if (bounds.contains(point)) { key = key.replace("_bounds", ""); Polygon polygon = polygonClass.getPolygon(key); if (this.isPolygonContains(polygon.getPoints(), point)) { hitPoly = true; this.onPolygonClick(polygon, point); } } } } if (hitPoly) { return; } } // Loop through all circles to check if within the touch point PluginEntry circlePlugin = this.plugins.get("Circle"); if (circlePlugin != null) { PluginCircle circleClass = (PluginCircle) circlePlugin.plugin; for (HashMap.Entry<String, Object> entry : circleClass.objects.entrySet()) { Circle circle = (Circle) entry.getValue(); if (this.isCircleContains(circle, point)) { hitPoly = true; this.onCircleClick(circle, point); } } if (hitPoly) { return; } } // Loop through ground overlays to check if within the touch point PluginEntry groundOverlayPlugin = this.plugins.get("GroundOverlay"); if (groundOverlayPlugin != null) { PluginGroundOverlay groundOverlayClass = (PluginGroundOverlay) groundOverlayPlugin.plugin; for (HashMap.Entry<String, Object> entry : groundOverlayClass.objects.entrySet()) { GroundOverlay groundOverlay = (GroundOverlay) entry.getValue(); if (this.isGroundOverlayContains(groundOverlay, point)) { hitPoly = true; this.onGroundOverlayClick(groundOverlay, point); } } if (hitPoly) { return; } } // Only emit click event if no overlays hit this.onMapEvent("click", point); } /** * Intersection for geodesic line * @ref http://my-clip-devdiary.blogspot.com/2014/01/html5canvas.html * * @param points * @param point * @param threshold * @return */ private boolean isPointOnTheGeodesicLine(List<LatLng> points, LatLng point, double threshold) { double trueDistance, testDistance1, testDistance2; Point p0, p1, touchPoint; touchPoint = new Point(); touchPoint.x = (int) (point.latitude * 100000); touchPoint.y = (int) (point.longitude * 100000); for (int i = 0; i < points.size() - 1; i++) { p0 = new Point(); p0.x = (int) (points.get(i).latitude * 100000); p0.y = (int) (points.get(i).longitude * 100000); p1 = new Point(); p1.x = (int) (points.get(i + 1).latitude * 100000); p1.y = (int) (points.get(i + 1).longitude * 100000); trueDistance = this.calculateDistance(points.get(i), points.get(i + 1)); testDistance1 = this.calculateDistance(points.get(i), point); testDistance2 = this.calculateDistance(point, points.get(i + 1)); // the distance is exactly same if the point is on the straight line if (Math.abs(trueDistance - (testDistance1 + testDistance2)) < threshold) { return true; } } return false; } /** * Intersection for non-geodesic line * @ref http://movingahead.seesaa.net/article/299962216.html * @ref http://www.softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm#Line-Plane * * @param points * @param point * @return */ private boolean isPointOnTheLine(List<LatLng> points, LatLng point) { double Sx, Sy; Projection projection = map.getProjection(); Point p0, p1, touchPoint; touchPoint = projection.toScreenLocation(point); p0 = projection.toScreenLocation(points.get(0)); for (int i = 1; i < points.size(); i++) { p1 = projection.toScreenLocation(points.get(i)); Sx = ((double)touchPoint.x - (double)p0.x) / ((double)p1.x - (double)p0.x); Sy = ((double)touchPoint.y - (double)p0.y) / ((double)p1.y - (double)p0.y); if (Math.abs(Sx - Sy) < 0.05 && Sx < 1 && Sx > 0) { return true; } p0 = p1; } return false; } /** * Intersects using thw Winding Number Algorithm * @ref http://www.nttpc.co.jp/company/r_and_d/technology/number_algorithm.html * @param path * @param point * @return */ private boolean isPolygonContains(List<LatLng> path, LatLng point) { int wn = 0; Projection projection = map.getProjection(); VisibleRegion visibleRegion = projection.getVisibleRegion(); LatLngBounds bounds = visibleRegion.latLngBounds; Point sw = projection.toScreenLocation(bounds.southwest); Point touchPoint = projection.toScreenLocation(point); touchPoint.y = sw.y - touchPoint.y; double vt; for (int i = 0; i < path.size() - 1; i++) { Point a = projection.toScreenLocation(path.get(i)); a.y = sw.y - a.y; Point b = projection.toScreenLocation(path.get(i + 1)); b.y = sw.y - b.y; if ((a.y <= touchPoint.y) && (b.y > touchPoint.y)) { vt = ((double)touchPoint.y - (double)a.y) / ((double)b.y - (double)a.y); if (touchPoint.x < ((double)a.x + (vt * ((double)b.x - (double)a.x)))) { wn++; } } else if ((a.y > touchPoint.y) && (b.y <= touchPoint.y)) { vt = ((double)touchPoint.y - (double)a.y) / ((double)b.y - (double)a.y); if (touchPoint.x < ((double)a.x + (vt * ((double)b.x - (double)a.x)))) { wn--; } } } return (wn != 0); } /** * Check if a circle contains a point * @param circle * @param point */ private boolean isCircleContains(Circle circle, LatLng point) { double r = circle.getRadius(); LatLng center = circle.getCenter(); double cX = center.latitude; double cY = center.longitude; double pX = point.latitude; double pY = point.longitude; float[] results = new float[1]; Location.distanceBetween(cX, cY, pX, pY, results); if(results[0] < r) { return true; } else { return false; } } /** * Check if a ground overlay contains a point * @param groundOverlay * @param point */ private boolean isGroundOverlayContains(GroundOverlay groundOverlay, LatLng point) { LatLngBounds groundOverlayBounds = groundOverlay.getBounds(); return groundOverlayBounds.contains(point); } @Override public boolean onMyLocationButtonClick() { webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('my_location_button_click')"); return false; } @Override public void onMapLoaded() { webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('map_loaded')"); } /** * Notify the myLocationChange event to JS */ @Override public void onCameraChange(CameraPosition position) { JSONObject params = new JSONObject(); String jsonStr = ""; try { JSONObject target = new JSONObject(); target.put("lat", position.target.latitude); target.put("lng", position.target.longitude); params.put("target", target); params.put("hashCode", position.hashCode()); params.put("bearing", position.bearing); params.put("tilt", position.tilt); params.put("zoom", position.zoom); jsonStr = params.toString(); } catch (JSONException e) { e.printStackTrace(); } webView.loadUrl("javascript:plugin.google.maps.Map._onCameraEvent('camera_change', " + jsonStr + ")"); } @Override public void onPause(boolean multitasking) { if (mapView != null) { mapView.onPause(); } super.onPause(multitasking); } @Override public void onResume(boolean multitasking) { if (mapView != null) { mapView.onResume(); } super.onResume(multitasking); } @Override public void onDestroy() { if (mapView != null) { mapView.onDestroy(); } super.onDestroy(); } @Override public void onClick(View view) { int viewId = view.getId(); if (viewId == CLOSE_LINK_ID) { closeWindow(); return; } if (viewId == LICENSE_LINK_ID) { showLicenseText(); return; } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public View getInfoContents(Marker marker) { String title = marker.getTitle(); String snippet = marker.getSnippet(); if ((title == null) && (snippet == null)) { return null; } JSONObject properties = null; JSONObject styles = null; String propertyId = "marker_property_" + marker.getId(); PluginEntry pluginEntry = this.plugins.get("Marker"); PluginMarker pluginMarker = (PluginMarker)pluginEntry.plugin; if (pluginMarker.objects.containsKey(propertyId)) { properties = (JSONObject) pluginMarker.objects.get(propertyId); if (properties.has("styles")) { try { styles = (JSONObject) properties.getJSONObject("styles"); } catch (JSONException e) {} } } // Linear layout LinearLayout windowLayer = new LinearLayout(activity); windowLayer.setPadding(3, 3, 3, 3); windowLayer.setOrientation(LinearLayout.VERTICAL); LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER; windowLayer.setLayoutParams(layoutParams); //---------------------------------------- // text-align = left | center | right //---------------------------------------- int gravity = Gravity.LEFT; int textAlignment = View.TEXT_ALIGNMENT_GRAVITY; if (styles != null) { try { String textAlignValue = styles.getString("text-align"); switch(TEXT_STYLE_ALIGNMENTS.valueOf(textAlignValue)) { case left: gravity = Gravity.LEFT; textAlignment = View.TEXT_ALIGNMENT_GRAVITY; break; case center: gravity = Gravity.CENTER; textAlignment = View.TEXT_ALIGNMENT_CENTER; break; case right: gravity = Gravity.RIGHT; textAlignment = View.TEXT_ALIGNMENT_VIEW_END; break; } } catch (Exception e) {} } if (title != null) { if (title.indexOf("data:image/") > -1 && title.indexOf(";base64,") > -1) { String[] tmp = title.split(","); Bitmap image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]); image = PluginUtil.scaleBitmapForDevice(image); ImageView imageView = new ImageView(this.cordova.getActivity()); imageView.setImageBitmap(image); windowLayer.addView(imageView); } else { TextView textView = new TextView(this.cordova.getActivity()); textView.setText(title); textView.setSingleLine(false); int titleColor = Color.BLACK; if (styles != null && styles.has("color")) { try { titleColor = PluginUtil.parsePluginColor(styles.getJSONArray("color")); } catch (JSONException e) {} } textView.setTextColor(titleColor); textView.setGravity(gravity); if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView.setTextAlignment(textAlignment); } //---------------------------------------- // font-style = normal | italic // font-weight = normal | bold //---------------------------------------- int fontStyle = Typeface.NORMAL; if (styles != null) { try { if ("italic".equals(styles.getString("font-style"))) { fontStyle = Typeface.ITALIC; } } catch (JSONException e) {} try { if ("bold".equals(styles.getString("font-weight"))) { fontStyle = fontStyle | Typeface.BOLD; } } catch (JSONException e) {} } textView.setTypeface(Typeface.DEFAULT, fontStyle); windowLayer.addView(textView); } } if (snippet != null) { //snippet = snippet.replaceAll("\n", ""); TextView textView2 = new TextView(this.cordova.getActivity()); textView2.setText(snippet); textView2.setTextColor(Color.GRAY); textView2.setTextSize((textView2.getTextSize() / 6 * 5) / density); textView2.setGravity(gravity); if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView2.setTextAlignment(textAlignment); } windowLayer.addView(textView2); } return windowLayer; } @Override public View getInfoWindow(Marker marker) { return null; } /** * Clear all markups * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void clear(JSONArray args, CallbackContext callbackContext) throws JSONException { Set<String> pluginNames = plugins.keySet(); Iterator<String> iterator = pluginNames.iterator(); String pluginName; PluginEntry pluginEntry; while(iterator.hasNext()) { pluginName = iterator.next(); if ("Map".equals(pluginName) == false) { pluginEntry = plugins.get(pluginName); ((MyPlugin) pluginEntry.plugin).clear(); } } this.map.clear(); this.sendNoResult(callbackContext); } @SuppressWarnings("unused") private void pluginLayer_pushHtmlElement(JSONArray args, CallbackContext callbackContext) throws JSONException { if (mPluginLayout != null) { String domId = args.getString(0); JSONObject elemSize = args.getJSONObject(1); float left = contentToView(elemSize.getLong("left")); float top = contentToView(elemSize.getLong("top")); float width = contentToView(elemSize.getLong("width")); float height = contentToView(elemSize.getLong("height")); mPluginLayout.putHTMLElement(domId, left, top, (left + width), (top + height)); this.mPluginLayout.inValidate(); } this.sendNoResult(callbackContext); } @SuppressWarnings("unused") private void pluginLayer_removeHtmlElement(JSONArray args, CallbackContext callbackContext) throws JSONException { if (mPluginLayout != null) { String domId = args.getString(0); mPluginLayout.removeHTMLElement(domId); this.mPluginLayout.inValidate(); } this.sendNoResult(callbackContext); } /** * Set click-ability of the map * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void pluginLayer_setClickable(JSONArray args, CallbackContext callbackContext) throws JSONException { boolean clickable = args.getBoolean(0); if (mapView != null && this.windowLayer == null) { this.mPluginLayout.setClickable(clickable); } this.sendNoResult(callbackContext); } /** * Set the app background * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void pluginLayer_setBackGroundColor(JSONArray args, CallbackContext callbackContext) throws JSONException { if (mPluginLayout != null) { JSONArray rgba = args.getJSONArray(0); int backgroundColor = Color.WHITE; if (rgba != null && rgba.length() == 4) { try { backgroundColor = PluginUtil.parsePluginColor(rgba); this.mPluginLayout.setBackgroundColor(backgroundColor); } catch (JSONException e) {} } } this.sendNoResult(callbackContext); } /** * Set the debug flag of myPluginLayer * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void pluginLayer_setDebuggable(JSONArray args, CallbackContext callbackContext) throws JSONException { boolean debuggable = args.getBoolean(0); if (mapView != null && this.windowLayer == null) { this.mPluginLayout.setDebug(debuggable); } this.sendNoResult(callbackContext); } /** * Destroy the map completely * @param args * @param callbackContext */ @SuppressWarnings("unused") private void remove(JSONArray args, CallbackContext callbackContext) { if (mPluginLayout != null) { this.mPluginLayout.setClickable(false); this.mPluginLayout.detachMyView(); this.mPluginLayout = null; } plugins.clear(); if (map != null) { map.setMyLocationEnabled(false); map.clear(); } if (mapView != null) { mapView.onDestroy(); } map = null; mapView = null; windowLayer = null; mapDivLayoutJSON = null; System.gc(); this.sendNoResult(callbackContext); } protected void sendNoResult(CallbackContext callbackContext) { PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); callbackContext.sendPluginResult(pluginResult); } }
src/android/plugin/google/maps/GoogleMaps.java
package plugin.google.maps; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginEntry; import org.apache.cordova.PluginResult; import org.apache.cordova.ScrollEvent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import plugin.http.request.HttpRequest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Point; import android.graphics.Typeface; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Build; import android.os.Build.VERSION; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebSettings.RenderPriority; import android.widget.AbsoluteLayout; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks; import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter; import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLoadedCallback; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener; import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.CameraPosition.Builder; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.GroundOverlay; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.VisibleRegion; @SuppressWarnings("deprecation") public class GoogleMaps extends CordovaPlugin implements View.OnClickListener, OnMarkerClickListener, OnInfoWindowClickListener, OnMapClickListener, OnMapLongClickListener, OnCameraChangeListener, OnMapLoadedCallback, OnMarkerDragListener, OnMyLocationButtonClickListener, InfoWindowAdapter { private final String TAG = "GoogleMapsPlugin"; private final HashMap<String, PluginEntry> plugins = new HashMap<String, PluginEntry>(); private float density; private enum EVENTS { onScrollChanged } private enum TEXT_STYLE_ALIGNMENTS { left, center, right } private JSONObject mapDivLayoutJSON = null; private MapView mapView = null; public GoogleMap map = null; private Activity activity; private LinearLayout windowLayer = null; private ViewGroup root; private final int CLOSE_LINK_ID = 0x7f999990; //random private final int LICENSE_LINK_ID = 0x7f99991; //random private final String PLUGIN_VERSION = "1.2.4 beta"; private MyPluginLayout mPluginLayout = null; private LocationClient locationClient = null; private boolean isDebug = false; private boolean isCrossWalk = false; @SuppressLint("NewApi") @Override public void initialize(final CordovaInterface cordova, final CordovaWebView webView) { super.initialize(cordova, webView); activity = cordova.getActivity(); density = Resources.getSystem().getDisplayMetrics().density; root = (ViewGroup) webView.getParent(); // Is this app in debug mode? try { PackageManager manager = activity.getPackageManager(); ApplicationInfo appInfo = manager.getApplicationInfo(activity.getPackageName(), 0); isDebug = (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE; } catch (Exception e) {} Log.i("CordovaLog", "This app uses phonegap-googlemaps-plugin version " + PLUGIN_VERSION); if (isDebug) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { JSONArray params = new JSONArray(); params.put("get"); params.put("http://plugins.cordova.io/api/plugin.google.maps"); HttpRequest httpReq = new HttpRequest(); httpReq.initialize(cordova, null); httpReq.execute("execute", params, new CallbackContext("version_check", webView) { @Override public void sendPluginResult(PluginResult pluginResult) { if (pluginResult.getStatus() == PluginResult.Status.OK.ordinal()) { try { JSONObject result = new JSONObject(pluginResult.getStrMessage()); JSONObject distTags = result.getJSONObject("dist-tags"); String latestVersion = distTags.getString("latest"); if (latestVersion.equals(PLUGIN_VERSION) == false) { Log.i("CordovaLog", "phonegap-googlemaps-plugin version " + latestVersion + " is available."); } } catch (JSONException e) {} } } }); } catch (Exception e) {} } }); } cordova.getActivity().runOnUiThread(new Runnable() { @SuppressLint("NewApi") public void run() { String settingClassName = webView.getSettings().getClass().toString(); if (settingClassName.indexOf("XWalkSetting") > 0) { Log.d("GoogleMaps", "--->CrossWalk mode"); isCrossWalk = true; } if (isCrossWalk == false) { try { Method method = webView.getClass().getMethod("getSettings", null); WebSettings settings = (WebSettings)method.invoke(null, null); settings.setRenderPriority(RenderPriority.HIGH); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); } catch (Exception e) { e.printStackTrace(); } } if (Build.VERSION.SDK_INT >= 11){ webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } root.setBackgroundColor(Color.WHITE); if (VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) { activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); } if (VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { Log.d(TAG, "Google Maps Plugin reloads the browser to change the background color as transparent."); webView.setBackgroundColor(0); if (isCrossWalk == false) { try { Method method = webView.getClass().getMethod("reload", null); method.invoke(null, null); } catch (Exception e) { e.printStackTrace(); } } } } }); } @Override public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { if (isDebug) { if (args != null && args.length() > 0) { Log.d(TAG, "(debug)action=" + action + " args[0]=" + args.getString(0)); } else { Log.d(TAG, "(debug)action=" + action); } } Runnable runnable = new Runnable() { public void run() { if (("getMap".equals(action) == false && "isAvailable".equals(action) == false) && GoogleMaps.this.map == null) { Log.w(TAG, "Can not execute '" + action + "' because the map is not created."); return; } if ("exec".equals(action)) { try { String classMethod = args.getString(0); String[] params = classMethod.split("\\.", 0); if ("Map.setOptions".equals(classMethod)) { JSONObject jsonParams = args.getJSONObject(1); if (jsonParams.has("backgroundColor")) { JSONArray rgba = jsonParams.getJSONArray("backgroundColor"); int backgroundColor = Color.WHITE; if (rgba != null && rgba.length() == 4) { try { backgroundColor = PluginUtil.parsePluginColor(rgba); mPluginLayout.setBackgroundColor(backgroundColor); } catch (JSONException e) {} } } } // Load the class plugin GoogleMaps.this.loadPlugin(params[0]); PluginEntry entry = GoogleMaps.this.plugins.get(params[0]); if (params.length == 2 && entry != null) { entry.plugin.execute("execute", args, callbackContext); } else { callbackContext.error("'" + action + "' parameter is invalid length."); } } catch (Exception e) { e.printStackTrace(); callbackContext.error("Java Error\n" + e.getCause().getMessage()); } } else { try { Method method = GoogleMaps.this.getClass().getDeclaredMethod(action, JSONArray.class, CallbackContext.class); if (method.isAccessible() == false) { method.setAccessible(true); } method.invoke(GoogleMaps.this, args, callbackContext); } catch (Exception e) { e.printStackTrace(); callbackContext.error("'" + action + "' is not defined in GoogleMaps plugin."); } } } }; cordova.getActivity().runOnUiThread(runnable); return true; } @SuppressWarnings("unused") private void setDiv(JSONArray args, CallbackContext callbackContext) throws JSONException { if (args.length() == 0) { this.mapDivLayoutJSON = null; mPluginLayout.detachMyView(); this.sendNoResult(callbackContext); return; } if (args.length() == 2) { mPluginLayout.attachMyView(mapView); this.resizeMap(args, callbackContext); } } /** * Set visibility of the map * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException { boolean visible = args.getBoolean(0); if (this.windowLayer == null) { if (visible) { mapView.setVisibility(View.VISIBLE); } else { mapView.setVisibility(View.INVISIBLE); } } this.sendNoResult(callbackContext); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void getMap(JSONArray args, final CallbackContext callbackContext) throws JSONException { if (map != null) { callbackContext.success(); return; } mPluginLayout = new MyPluginLayout(webView, activity); // ------------------------------ // Check of Google Play Services // ------------------------------ int checkGooglePlayServices = GooglePlayServicesUtil .isGooglePlayServicesAvailable(activity); if (checkGooglePlayServices != ConnectionResult.SUCCESS) { // google play services is missing!!!! /* * Returns status code indicating whether there was an error. Can be one * of following in ConnectionResult: SUCCESS, SERVICE_MISSING, * SERVICE_VERSION_UPDATE_REQUIRED, SERVICE_DISABLED, SERVICE_INVALID. */ Log.e("CordovaLog", "---Google Play Services is not available: " + GooglePlayServicesUtil.getErrorString(checkGooglePlayServices)); Dialog errorDialog = null; try { //errorDialog = GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices, activity, 1); Method getErrorDialogMethod = GooglePlayServicesUtil.class.getMethod("getErrorDialog", int.class, Activity.class, int.class); errorDialog = (Dialog)getErrorDialogMethod.invoke(null, checkGooglePlayServices, activity, 1); } catch (Exception e) {}; if (errorDialog != null) { errorDialog.show(); } else { boolean isNeedToUpdate = false; String errorMsg = "Google Maps Android API v2 is not available for some reason on this device. Do you install the latest Google Play Services from Google Play Store?"; switch (checkGooglePlayServices) { case ConnectionResult.DATE_INVALID: errorMsg = "It seems your device date is set incorrectly. Please update the correct date and time."; break; case ConnectionResult.DEVELOPER_ERROR: errorMsg = "The application is misconfigured. This error is not recoverable and will be treated as fatal. The developer should look at the logs after this to determine more actionable information."; break; case ConnectionResult.INTERNAL_ERROR: errorMsg = "An internal error of Google Play Services occurred. Please retry, and it should resolve the problem."; break; case ConnectionResult.INVALID_ACCOUNT: errorMsg = "You attempted to connect to the service with an invalid account name specified."; break; case ConnectionResult.LICENSE_CHECK_FAILED: errorMsg = "The application is not licensed to the user. This error is not recoverable and will be treated as fatal."; break; case ConnectionResult.NETWORK_ERROR: errorMsg = "A network error occurred. Please retry, and it should resolve the problem."; break; case ConnectionResult.SERVICE_DISABLED: errorMsg = "The installed version of Google Play services has been disabled on this device. Please turn on Google Play Services."; break; case ConnectionResult.SERVICE_INVALID: errorMsg = "The version of the Google Play services installed on this device is not authentic. Please update the Google Play Services from Google Play Store."; isNeedToUpdate = true; break; case ConnectionResult.SERVICE_MISSING: errorMsg = "Google Play services is missing on this device. Please install the Google Play Services."; isNeedToUpdate = true; break; case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: errorMsg = "The installed version of Google Play services is out of date. Please update the Google Play Services from Google Play Store."; isNeedToUpdate = true; break; case ConnectionResult.SIGN_IN_REQUIRED: errorMsg = "You attempted to connect to the service but you are not signed in. Please check the Google Play Services configuration"; break; default: isNeedToUpdate = true; break; } final boolean finalIsNeedToUpdate = isNeedToUpdate; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity); alertDialogBuilder .setMessage(errorMsg) .setCancelable(false) .setPositiveButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.dismiss(); if (finalIsNeedToUpdate) { try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.gms"))); } catch (android.content.ActivityNotFoundException anfe) { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=appPackageName"))); } } } }); AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } callbackContext.error("Google Play Services is not available."); return; } // Check the API key ApplicationInfo appliInfo = null; try { appliInfo = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA); } catch (NameNotFoundException e) {} String API_KEY = appliInfo.metaData.getString("com.google.android.maps.v2.API_KEY"); if ("API_KEY_FOR_ANDROID".equals(API_KEY)) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity); alertDialogBuilder .setMessage("Please replace 'API_KEY_FOR_ANDROID' in the platforms/android/AndroidManifest.xml with your API Key!") .setCancelable(false) .setPositiveButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.dismiss(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } // ------------------------------ // Initialize Google Maps SDK // ------------------------------ try { MapsInitializer.initialize(activity); } catch (Exception e) { e.printStackTrace(); callbackContext.error(e.getMessage()); return; } GoogleMapOptions options = new GoogleMapOptions(); JSONObject params = args.getJSONObject(0); //background color if (params.has("backgroundColor")) { JSONArray rgba = params.getJSONArray("backgroundColor"); int backgroundColor = Color.WHITE; if (rgba != null && rgba.length() == 4) { try { backgroundColor = PluginUtil.parsePluginColor(rgba); this.mPluginLayout.setBackgroundColor(backgroundColor); } catch (JSONException e) {} } } //controls if (params.has("controls")) { JSONObject controls = params.getJSONObject("controls"); if (controls.has("compass")) { options.compassEnabled(controls.getBoolean("compass")); } if (controls.has("zoom")) { options.zoomControlsEnabled(controls.getBoolean("zoom")); } } //gestures if (params.has("gestures")) { JSONObject gestures = params.getJSONObject("gestures"); if (gestures.has("tilt")) { options.tiltGesturesEnabled(gestures.getBoolean("tilt")); } if (gestures.has("scroll")) { options.scrollGesturesEnabled(gestures.getBoolean("scroll")); } if (gestures.has("rotate")) { options.rotateGesturesEnabled(gestures.getBoolean("rotate")); } if (gestures.has("zoom")) { options.zoomGesturesEnabled(gestures.getBoolean("zoom")); } } // map type if (params.has("mapType")) { String typeStr = params.getString("mapType"); int mapTypeId = -1; mapTypeId = typeStr.equals("MAP_TYPE_NORMAL") ? GoogleMap.MAP_TYPE_NORMAL : mapTypeId; mapTypeId = typeStr.equals("MAP_TYPE_HYBRID") ? GoogleMap.MAP_TYPE_HYBRID : mapTypeId; mapTypeId = typeStr.equals("MAP_TYPE_SATELLITE") ? GoogleMap.MAP_TYPE_SATELLITE : mapTypeId; mapTypeId = typeStr.equals("MAP_TYPE_TERRAIN") ? GoogleMap.MAP_TYPE_TERRAIN : mapTypeId; mapTypeId = typeStr.equals("MAP_TYPE_NONE") ? GoogleMap.MAP_TYPE_NONE : mapTypeId; if (mapTypeId != -1) { options.mapType(mapTypeId); } } // initial camera position if (params.has("camera")) { JSONObject camera = params.getJSONObject("camera"); Builder builder = CameraPosition.builder(); if (camera.has("bearing")) { builder.bearing((float) camera.getDouble("bearing")); } if (camera.has("latLng")) { JSONObject latLng = camera.getJSONObject("latLng"); builder.target(new LatLng(latLng.getDouble("lat"), latLng.getDouble("lng"))); } if (camera.has("tilt")) { builder.tilt((float) camera.getDouble("tilt")); } if (camera.has("zoom")) { builder.zoom((float) camera.getDouble("zoom")); } options.camera(builder.build()); } mapView = new MapView(activity, options); mapView.onCreate(null); mapView.onResume(); map = mapView.getMap(); //controls if (params.has("controls")) { JSONObject controls = params.getJSONObject("controls"); if (controls.has("myLocationButton")) { Boolean isEnabled = controls.getBoolean("myLocationButton"); map.setMyLocationEnabled(isEnabled); map.getUiSettings().setMyLocationButtonEnabled(isEnabled); } if (controls.has("indoorPicker")) { Boolean isEnabled = controls.getBoolean("indoorPicker"); map.setIndoorEnabled(isEnabled); } } // Set event listener map.setOnCameraChangeListener(this); map.setOnInfoWindowClickListener(this); map.setOnMapClickListener(this); map.setOnMapLoadedCallback(this); map.setOnMapLongClickListener(this); map.setOnMarkerClickListener(this); map.setOnMarkerDragListener(this); map.setOnMyLocationButtonClickListener(this); // Load PluginMap class this.loadPlugin("Map"); //Custom info window map.setInfoWindowAdapter(this); callbackContext.success(); // ------------------------------ // Embed the map if a container is specified. // ------------------------------ if (args.length() == 3) { this.mapDivLayoutJSON = args.getJSONObject(1); mPluginLayout.attachMyView(mapView); this.resizeMap(args, callbackContext); } } private float contentToView(long d) { return d * this.density; } //----------------------------------- // Create the instance of class //----------------------------------- @SuppressWarnings("rawtypes") private void loadPlugin(String serviceName) { if (plugins.containsKey(serviceName)) { return; } try { Class pluginCls = Class.forName("plugin.google.maps.Plugin" + serviceName); CordovaPlugin plugin = (CordovaPlugin) pluginCls.newInstance(); PluginEntry pluginEntry = new PluginEntry("GoogleMaps", plugin); this.plugins.put(serviceName, pluginEntry); try { Class cordovaPref = Class.forName("org.apache.cordova.CordovaPreferences"); if (cordovaPref != null) { Method privateInit = CordovaPlugin.class.getMethod("privateInitialize", CordovaInterface.class, CordovaWebView.class, cordovaPref); if (privateInit != null) { privateInit.invoke(plugin, this.cordova, webView, null); } } } catch (Exception e2) {} plugin.initialize(this.cordova, webView); ((MyPluginInterface)plugin).setMapCtrl(this); if (map == null) { Log.e(TAG, "map is null!"); } } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unused") private Boolean myTest(JSONArray args, CallbackContext callbackContext) { PolygonOptions options = new PolygonOptions(); options.add(new LatLng(-45, -90)); options.add(new LatLng(-45, -180)); options.add(new LatLng(0, -180)); options.add(new LatLng(0, -90)); map.addPolygon(options); callbackContext.success(); return true; } @SuppressWarnings("unused") private Boolean getLicenseInfo(JSONArray args, CallbackContext callbackContext) { String msg = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(activity); callbackContext.success(msg); return true; } @Override public Object onMessage(String id, Object data) { EVENTS event = null; try { event = EVENTS.valueOf(id); }catch(Exception e) {} if (event == null) { return null; } switch(event) { case onScrollChanged: ScrollEvent scrollEvent = (ScrollEvent)data; if (mPluginLayout != null) { mPluginLayout.scrollTo(scrollEvent.nl, scrollEvent.nt); if (mapDivLayoutJSON != null) { try { float divW = contentToView(mapDivLayoutJSON.getLong("width")); float divH = contentToView(mapDivLayoutJSON.getLong("height")); float divLeft = contentToView(mapDivLayoutJSON.getLong("left")); float divTop = contentToView(mapDivLayoutJSON.getLong("top")); mPluginLayout.setDrawingRect( divLeft, divTop - scrollEvent.nt, divLeft + divW, divTop + divH - scrollEvent.nt); } catch (JSONException e) { e.printStackTrace(); } } } break; } return null; } private void closeWindow() { if (isCrossWalk == false) { try { Method method = webView.getClass().getMethod("hideCustomView", null); method.invoke(null, null); } catch (Exception e) { e.printStackTrace(); } } } @SuppressWarnings("unused") private void showDialog(final JSONArray args, final CallbackContext callbackContext) { if (windowLayer != null) { return; } // window layout windowLayer = new LinearLayout(activity); windowLayer.setPadding(0, 0, 0, 0); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layoutParams.gravity = Gravity.TOP | Gravity.LEFT; windowLayer.setLayoutParams(layoutParams); // dialog window layer FrameLayout dialogLayer = new FrameLayout(activity); dialogLayer.setLayoutParams(layoutParams); //dialogLayer.setPadding(15, 15, 15, 0); dialogLayer.setBackgroundColor(Color.LTGRAY); windowLayer.addView(dialogLayer); // map frame final FrameLayout mapFrame = new FrameLayout(activity); mapFrame.setPadding(0, 0, 0, (int)(40 * density)); dialogLayer.addView(mapFrame); if (this.mPluginLayout != null && this.mPluginLayout.getMyView() != null) { this.mPluginLayout.detachMyView(); } ViewGroup.LayoutParams lParams = (ViewGroup.LayoutParams) mapView.getLayoutParams(); if (lParams == null) { lParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } lParams.width = ViewGroup.LayoutParams.MATCH_PARENT; lParams.height = ViewGroup.LayoutParams.MATCH_PARENT; if (lParams instanceof AbsoluteLayout.LayoutParams) { AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) lParams; params.x = 0; params.y = 0; mapView.setLayoutParams(params); } else if (lParams instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lParams; params.topMargin = 0; params.leftMargin = 0; mapView.setLayoutParams(params); } else if (lParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) lParams; params.topMargin = 0; params.leftMargin = 0; mapView.setLayoutParams(params); } mapFrame.addView(this.mapView); // button frame LinearLayout buttonFrame = new LinearLayout(activity); buttonFrame.setOrientation(LinearLayout.HORIZONTAL); buttonFrame.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM); LinearLayout.LayoutParams buttonFrameParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); buttonFrame.setLayoutParams(buttonFrameParams); dialogLayer.addView(buttonFrame); //close button LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f); TextView closeLink = new TextView(activity); closeLink.setText("Close"); closeLink.setLayoutParams(buttonParams); closeLink.setTextColor(Color.BLUE); closeLink.setTextSize(20); closeLink.setGravity(Gravity.LEFT); closeLink.setPadding((int)(10 * density), 0, 0, (int)(10 * density)); closeLink.setOnClickListener(GoogleMaps.this); closeLink.setId(CLOSE_LINK_ID); buttonFrame.addView(closeLink); //license button TextView licenseLink = new TextView(activity); licenseLink.setText("Legal Notices"); licenseLink.setTextColor(Color.BLUE); licenseLink.setLayoutParams(buttonParams); licenseLink.setTextSize(20); licenseLink.setGravity(Gravity.RIGHT); licenseLink.setPadding((int)(10 * density), (int)(20 * density), (int)(10 * density), (int)(10 * density)); licenseLink.setOnClickListener(GoogleMaps.this); licenseLink.setId(LICENSE_LINK_ID); buttonFrame.addView(licenseLink); webView.setVisibility(View.GONE); root.addView(windowLayer); //Dummy view for the back-button event FrameLayout dummyLayout = new FrameLayout(activity); /* this.webView.showCustomView(dummyLayout, new WebChromeClient.CustomViewCallback() { @Override public void onCustomViewHidden() { mapFrame.removeView(mapView); if (mPluginLayout != null && mapDivLayoutJSON != null) { mPluginLayout.attachMyView(mapView); mPluginLayout.updateViewPosition(); } root.removeView(windowLayer); webView.setVisibility(View.VISIBLE); windowLayer = null; GoogleMaps.this.onMapEvent("map_close"); } }); */ this.sendNoResult(callbackContext); } private void resizeMap(JSONArray args, CallbackContext callbackContext) throws JSONException { if (mPluginLayout == null) { callbackContext.success(); return; } mapDivLayoutJSON = args.getJSONObject(args.length() - 2); JSONArray HTMLs = args.getJSONArray(args.length() - 1); JSONObject elemInfo, elemSize; String elemId; float divW, divH, divLeft, divTop; if (mPluginLayout == null) { this.sendNoResult(callbackContext); return; } this.mPluginLayout.clearHTMLElement(); for (int i = 0; i < HTMLs.length(); i++) { elemInfo = HTMLs.getJSONObject(i); try { elemId = elemInfo.getString("id"); elemSize = elemInfo.getJSONObject("size"); divW = contentToView(elemSize.getLong("width")); divH = contentToView(elemSize.getLong("height")); divLeft = contentToView(elemSize.getLong("left")); divTop = contentToView(elemSize.getLong("top")); mPluginLayout.putHTMLElement(elemId, divLeft, divTop, divLeft + divW, divTop + divH); } catch (Exception e){ e.printStackTrace(); } } //mPluginLayout.inValidate(); updateMapViewLayout(); this.sendNoResult(callbackContext); } private void updateMapViewLayout() { if (mPluginLayout == null) { return; } try { float divW = contentToView(mapDivLayoutJSON.getLong("width")); float divH = contentToView(mapDivLayoutJSON.getLong("height")); float divLeft = contentToView(mapDivLayoutJSON.getLong("left")); float divTop = contentToView(mapDivLayoutJSON.getLong("top")); // Update the plugin drawing view rect mPluginLayout.setDrawingRect( divLeft, divTop - webView.getScrollY(), divLeft + divW, divTop + divH - webView.getScrollY()); mPluginLayout.updateViewPosition(); mapView.requestLayout(); } catch (JSONException e) { e.printStackTrace(); } } @SuppressWarnings("unused") private void closeDialog(final JSONArray args, final CallbackContext callbackContext) { this.closeWindow(); this.sendNoResult(callbackContext); } @SuppressWarnings("unused") private void isAvailable(final JSONArray args, final CallbackContext callbackContext) throws JSONException { // ------------------------------ // Check of Google Play Services // ------------------------------ int checkGooglePlayServices = GooglePlayServicesUtil .isGooglePlayServicesAvailable(activity); if (checkGooglePlayServices != ConnectionResult.SUCCESS) { // google play services is missing!!!! callbackContext.error("Google Maps Android API v2 is not available, because this device does not have Google Play Service."); return; } // ------------------------------ // Check of Google Maps Android API v2 // ------------------------------ try { @SuppressWarnings({ "rawtypes" }) Class GoogleMapsClass = Class.forName("com.google.android.gms.maps.GoogleMap"); } catch (Exception e) { Log.e("GoogleMaps", "Error", e); callbackContext.error(e.getMessage()); return; } callbackContext.success(); } @SuppressWarnings("unused") private void getMyLocation(final JSONArray args, final CallbackContext callbackContext) throws JSONException { LocationManager locationManager = (LocationManager) this.activity.getSystemService(Context.LOCATION_SERVICE); List<String> providers = locationManager.getAllProviders(); if (providers.size() == 0) { JSONObject result = new JSONObject(); result.put("status", false); result.put("error_code", "not_available"); result.put("error_message", "Since this device does not have any location provider, this app can not detect your location."); callbackContext.error(result); return; } // enableHighAccuracy = true -> PRIORITY_HIGH_ACCURACY // enableHighAccuracy = false -> PRIORITY_BALANCED_POWER_ACCURACY JSONObject params = args.getJSONObject(0); boolean isHigh = false; if (params.has("enableHighAccuracy")) { isHigh = params.getBoolean("enableHighAccuracy"); } final boolean enableHighAccuracy = isHigh; String provider = null; if (enableHighAccuracy == true) { if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) { provider = LocationManager.PASSIVE_PROVIDER; } } else { if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) { provider = LocationManager.PASSIVE_PROVIDER; } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; } } if (provider == null) { //Ask the user to turn on the location services. AlertDialog.Builder builder = new AlertDialog.Builder(this.activity); builder.setTitle("Improve location accuracy"); builder.setMessage("To enhance your Maps experience:\n\n" + " - Enable Google apps location access\n\n" + " - Turn on GPS and mobile network location"); builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Launch settings, allowing user to make a change Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); activity.startActivity(intent); JSONObject result = new JSONObject(); try { result.put("status", false); result.put("error_code", "open_settings"); result.put("error_message", "User opened the settings of location service. So try again."); } catch (JSONException e) {} callbackContext.error(result); } }); builder.setNegativeButton("Skip", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //No location service, no Activity dialog.dismiss(); JSONObject result = new JSONObject(); try { result.put("status", false); result.put("error_code", "service_denied"); result.put("error_message", "This app has rejected to use Location Services."); } catch (JSONException e) {} callbackContext.error(result); } }); builder.create().show(); return; } Log.d("openCV", "provider = " + provider); Location location = locationManager.getLastKnownLocation(provider); if (location != null) { JSONObject result = PluginUtil.location2Json(location); result.put("status", true); callbackContext.success(result); return; } PluginResult tmpResult = new PluginResult(PluginResult.Status.NO_RESULT); tmpResult.setKeepCallback(true); callbackContext.sendPluginResult(tmpResult); locationClient = new LocationClient(this.activity, new ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { LocationRequest request = new LocationRequest(); int priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY; if (enableHighAccuracy) { priority = LocationRequest.PRIORITY_HIGH_ACCURACY; } request.setPriority(priority); locationClient.requestLocationUpdates(request, new LocationListener() { @Override public void onLocationChanged(Location location) { JSONObject result; try { result = PluginUtil.location2Json(location); result.put("status", true); callbackContext.success(result); } catch (JSONException e) {} locationClient.disconnect(); } }); } @Override public void onDisconnected() {} }, new OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult connectionResult) { int errorCode = connectionResult.getErrorCode(); String errorMsg = GooglePlayServicesUtil.getErrorString(errorCode); PluginResult result = new PluginResult(PluginResult.Status.ERROR, errorMsg); callbackContext.sendPluginResult(result); } }); locationClient.connect(); } private void showLicenseText() { AsyncLicenseInfo showLicense = new AsyncLicenseInfo(activity); showLicense.execute(); } /******************************************************** * Callbacks ********************************************************/ /** * Notify marker event to JS * @param eventName * @param marker */ private void onMarkerEvent(String eventName, Marker marker) { String markerId = "marker_" + marker.getId(); webView.loadUrl("javascript:plugin.google.maps.Map." + "_onMarkerEvent('" + eventName + "','" + markerId + "')"); } private void onOverlayEvent(String eventName, String overlayId, LatLng point) { webView.loadUrl("javascript:plugin.google.maps.Map." + "_onOverlayEvent(" + "'" + eventName + "','" + overlayId + "', " + "new window.plugin.google.maps.LatLng(" + point.latitude + "," + point.longitude + ")" + ")"); } private void onPolylineClick(Polyline polyline, LatLng point) { String overlayId = "polyline_" + polyline.getId(); this.onOverlayEvent("overlay_click", overlayId, point); } private void onPolygonClick(Polygon polygon, LatLng point) { String overlayId = "polygon_" + polygon.getId(); this.onOverlayEvent("overlay_click", overlayId, point); } private void onCircleClick(Circle circle, LatLng point) { String overlayId = "circle_" + circle.getId(); this.onOverlayEvent("overlay_click", overlayId, point); } private void onGroundOverlayClick(GroundOverlay groundOverlay, LatLng point) { String overlayId = "groundOverlay_" + groundOverlay.getId(); this.onOverlayEvent("overlay_click", overlayId, point); } @Override public boolean onMarkerClick(Marker marker) { this.onMarkerEvent("click", marker); JSONObject properties = null; String propertyId = "marker_property_" + marker.getId(); PluginEntry pluginEntry = this.plugins.get("Marker"); PluginMarker pluginMarker = (PluginMarker)pluginEntry.plugin; if (pluginMarker.objects.containsKey(propertyId)) { properties = (JSONObject) pluginMarker.objects.get(propertyId); if (properties.has("disableAutoPan")) { boolean disableAutoPan = false; try { disableAutoPan = properties.getBoolean("disableAutoPan"); } catch (JSONException e) {} if (disableAutoPan) { marker.showInfoWindow(); return true; } } } marker.showInfoWindow(); return true; //return false; } @Override public void onInfoWindowClick(Marker marker) { this.onMarkerEvent("info_click", marker); } @Override public void onMarkerDrag(Marker marker) { this.onMarkerEvent("drag", marker); } @Override public void onMarkerDragEnd(Marker marker) { this.onMarkerEvent("drag_end", marker); } @Override public void onMarkerDragStart(Marker marker) { this.onMarkerEvent("drag_start", marker); } /** * Notify map event to JS * @param eventName * @param point */ private void onMapEvent(final String eventName) { webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('" + eventName + "')"); } /** * Notify map event to JS * @param eventName * @param point */ private void onMapEvent(final String eventName, final LatLng point) { webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent(" + "'" + eventName + "', new window.plugin.google.maps.LatLng(" + point.latitude + "," + point.longitude + "))"); } @Override public void onMapLongClick(LatLng point) { this.onMapEvent("long_click", point); } private double calculateDistance(LatLng pt1, LatLng pt2){ float[] results = new float[1]; Location.distanceBetween(pt1.latitude, pt1.longitude, pt2.latitude, pt2.longitude, results); return results[0]; } /** * Notify map click event to JS, also checks for click on a polygon and triggers onPolygonEvent * @param point */ public void onMapClick(LatLng point) { boolean hitPoly = false; String key; LatLngBounds bounds; // Polyline PluginEntry polylinePlugin = this.plugins.get("Polyline"); if(polylinePlugin != null) { PluginPolyline polylineClass = (PluginPolyline) polylinePlugin.plugin; List<LatLng> points ; Polyline polyline; Point origin = new Point(); Point hitArea = new Point(); hitArea.x = 1; hitArea.y = 1; Projection projection = map.getProjection(); double threshold = this.calculateDistance( projection.fromScreenLocation(origin), projection.fromScreenLocation(hitArea)); for (HashMap.Entry<String, Object> entry : polylineClass.objects.entrySet()) { key = entry.getKey(); if (key.contains("polyline_bounds_")) { bounds = (LatLngBounds) entry.getValue(); if (bounds.contains(point)) { key = key.replace("bounds_", ""); polyline = polylineClass.getPolyline(key); points = polyline.getPoints(); if (polyline.isGeodesic()) { if (this.isPointOnTheGeodesicLine(points, point, threshold)) { hitPoly = true; this.onPolylineClick(polyline, point); } } else { if (this.isPointOnTheLine(points, point)) { hitPoly = true; this.onPolylineClick(polyline, point); } } } } } if (hitPoly) { return; } } // Loop through all polygons to check if within the touch point PluginEntry polygonPlugin = this.plugins.get("Polygon"); if (polygonPlugin != null) { PluginPolygon polygonClass = (PluginPolygon) polygonPlugin.plugin; for (HashMap.Entry<String, Object> entry : polygonClass.objects.entrySet()) { key = entry.getKey(); if (key.contains("polygon_bounds_")) { bounds = (LatLngBounds) entry.getValue(); if (bounds.contains(point)) { key = key.replace("_bounds", ""); Polygon polygon = polygonClass.getPolygon(key); if (this.isPolygonContains(polygon.getPoints(), point)) { hitPoly = true; this.onPolygonClick(polygon, point); } } } } if (hitPoly) { return; } } // Loop through all circles to check if within the touch point PluginEntry circlePlugin = this.plugins.get("Circle"); if (circlePlugin != null) { PluginCircle circleClass = (PluginCircle) circlePlugin.plugin; for (HashMap.Entry<String, Object> entry : circleClass.objects.entrySet()) { Circle circle = (Circle) entry.getValue(); if (this.isCircleContains(circle, point)) { hitPoly = true; this.onCircleClick(circle, point); } } if (hitPoly) { return; } } // Loop through ground overlays to check if within the touch point PluginEntry groundOverlayPlugin = this.plugins.get("GroundOverlay"); if (groundOverlayPlugin != null) { PluginGroundOverlay groundOverlayClass = (PluginGroundOverlay) groundOverlayPlugin.plugin; for (HashMap.Entry<String, Object> entry : groundOverlayClass.objects.entrySet()) { GroundOverlay groundOverlay = (GroundOverlay) entry.getValue(); if (this.isGroundOverlayContains(groundOverlay, point)) { hitPoly = true; this.onGroundOverlayClick(groundOverlay, point); } } if (hitPoly) { return; } } // Only emit click event if no overlays hit this.onMapEvent("click", point); } /** * Intersection for geodesic line * @ref http://my-clip-devdiary.blogspot.com/2014/01/html5canvas.html * * @param points * @param point * @param threshold * @return */ private boolean isPointOnTheGeodesicLine(List<LatLng> points, LatLng point, double threshold) { double trueDistance, testDistance1, testDistance2; Point p0, p1, touchPoint; touchPoint = new Point(); touchPoint.x = (int) (point.latitude * 100000); touchPoint.y = (int) (point.longitude * 100000); for (int i = 0; i < points.size() - 1; i++) { p0 = new Point(); p0.x = (int) (points.get(i).latitude * 100000); p0.y = (int) (points.get(i).longitude * 100000); p1 = new Point(); p1.x = (int) (points.get(i + 1).latitude * 100000); p1.y = (int) (points.get(i + 1).longitude * 100000); trueDistance = this.calculateDistance(points.get(i), points.get(i + 1)); testDistance1 = this.calculateDistance(points.get(i), point); testDistance2 = this.calculateDistance(point, points.get(i + 1)); // the distance is exactly same if the point is on the straight line if (Math.abs(trueDistance - (testDistance1 + testDistance2)) < threshold) { return true; } } return false; } /** * Intersection for non-geodesic line * @ref http://movingahead.seesaa.net/article/299962216.html * @ref http://www.softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm#Line-Plane * * @param points * @param point * @return */ private boolean isPointOnTheLine(List<LatLng> points, LatLng point) { double Sx, Sy; Projection projection = map.getProjection(); Point p0, p1, touchPoint; touchPoint = projection.toScreenLocation(point); p0 = projection.toScreenLocation(points.get(0)); for (int i = 1; i < points.size(); i++) { p1 = projection.toScreenLocation(points.get(i)); Sx = ((double)touchPoint.x - (double)p0.x) / ((double)p1.x - (double)p0.x); Sy = ((double)touchPoint.y - (double)p0.y) / ((double)p1.y - (double)p0.y); if (Math.abs(Sx - Sy) < 0.05 && Sx < 1 && Sx > 0) { return true; } p0 = p1; } return false; } /** * Intersects using thw Winding Number Algorithm * @ref http://www.nttpc.co.jp/company/r_and_d/technology/number_algorithm.html * @param path * @param point * @return */ private boolean isPolygonContains(List<LatLng> path, LatLng point) { int wn = 0; Projection projection = map.getProjection(); VisibleRegion visibleRegion = projection.getVisibleRegion(); LatLngBounds bounds = visibleRegion.latLngBounds; Point sw = projection.toScreenLocation(bounds.southwest); Point touchPoint = projection.toScreenLocation(point); touchPoint.y = sw.y - touchPoint.y; double vt; for (int i = 0; i < path.size() - 1; i++) { Point a = projection.toScreenLocation(path.get(i)); a.y = sw.y - a.y; Point b = projection.toScreenLocation(path.get(i + 1)); b.y = sw.y - b.y; if ((a.y <= touchPoint.y) && (b.y > touchPoint.y)) { vt = ((double)touchPoint.y - (double)a.y) / ((double)b.y - (double)a.y); if (touchPoint.x < ((double)a.x + (vt * ((double)b.x - (double)a.x)))) { wn++; } } else if ((a.y > touchPoint.y) && (b.y <= touchPoint.y)) { vt = ((double)touchPoint.y - (double)a.y) / ((double)b.y - (double)a.y); if (touchPoint.x < ((double)a.x + (vt * ((double)b.x - (double)a.x)))) { wn--; } } } return (wn != 0); } /** * Check if a circle contains a point * @param circle * @param point */ private boolean isCircleContains(Circle circle, LatLng point) { double r = circle.getRadius(); LatLng center = circle.getCenter(); double cX = center.latitude; double cY = center.longitude; double pX = point.latitude; double pY = point.longitude; float[] results = new float[1]; Location.distanceBetween(cX, cY, pX, pY, results); if(results[0] < r) { return true; } else { return false; } } /** * Check if a ground overlay contains a point * @param groundOverlay * @param point */ private boolean isGroundOverlayContains(GroundOverlay groundOverlay, LatLng point) { LatLngBounds groundOverlayBounds = groundOverlay.getBounds(); return groundOverlayBounds.contains(point); } @Override public boolean onMyLocationButtonClick() { webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('my_location_button_click')"); return false; } @Override public void onMapLoaded() { webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('map_loaded')"); } /** * Notify the myLocationChange event to JS */ @Override public void onCameraChange(CameraPosition position) { JSONObject params = new JSONObject(); String jsonStr = ""; try { JSONObject target = new JSONObject(); target.put("lat", position.target.latitude); target.put("lng", position.target.longitude); params.put("target", target); params.put("hashCode", position.hashCode()); params.put("bearing", position.bearing); params.put("tilt", position.tilt); params.put("zoom", position.zoom); jsonStr = params.toString(); } catch (JSONException e) { e.printStackTrace(); } webView.loadUrl("javascript:plugin.google.maps.Map._onCameraEvent('camera_change', " + jsonStr + ")"); } @Override public void onPause(boolean multitasking) { if (mapView != null) { mapView.onPause(); } super.onPause(multitasking); } @Override public void onResume(boolean multitasking) { if (mapView != null) { mapView.onResume(); } super.onResume(multitasking); } @Override public void onDestroy() { if (mapView != null) { mapView.onDestroy(); } super.onDestroy(); } @Override public void onClick(View view) { int viewId = view.getId(); if (viewId == CLOSE_LINK_ID) { closeWindow(); return; } if (viewId == LICENSE_LINK_ID) { showLicenseText(); return; } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public View getInfoContents(Marker marker) { String title = marker.getTitle(); String snippet = marker.getSnippet(); if ((title == null) && (snippet == null)) { return null; } JSONObject properties = null; JSONObject styles = null; String propertyId = "marker_property_" + marker.getId(); PluginEntry pluginEntry = this.plugins.get("Marker"); PluginMarker pluginMarker = (PluginMarker)pluginEntry.plugin; if (pluginMarker.objects.containsKey(propertyId)) { properties = (JSONObject) pluginMarker.objects.get(propertyId); if (properties.has("styles")) { try { styles = (JSONObject) properties.getJSONObject("styles"); } catch (JSONException e) {} } } // Linear layout LinearLayout windowLayer = new LinearLayout(activity); windowLayer.setPadding(3, 3, 3, 3); windowLayer.setOrientation(LinearLayout.VERTICAL); LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER; windowLayer.setLayoutParams(layoutParams); //---------------------------------------- // text-align = left | center | right //---------------------------------------- int gravity = Gravity.LEFT; int textAlignment = View.TEXT_ALIGNMENT_GRAVITY; if (styles != null) { try { String textAlignValue = styles.getString("text-align"); switch(TEXT_STYLE_ALIGNMENTS.valueOf(textAlignValue)) { case left: gravity = Gravity.LEFT; textAlignment = View.TEXT_ALIGNMENT_GRAVITY; break; case center: gravity = Gravity.CENTER; textAlignment = View.TEXT_ALIGNMENT_CENTER; break; case right: gravity = Gravity.RIGHT; textAlignment = View.TEXT_ALIGNMENT_VIEW_END; break; } } catch (Exception e) {} } if (title != null) { if (title.indexOf("data:image/") > -1 && title.indexOf(";base64,") > -1) { String[] tmp = title.split(","); Bitmap image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]); image = PluginUtil.scaleBitmapForDevice(image); ImageView imageView = new ImageView(this.cordova.getActivity()); imageView.setImageBitmap(image); windowLayer.addView(imageView); } else { TextView textView = new TextView(this.cordova.getActivity()); textView.setText(title); textView.setSingleLine(false); int titleColor = Color.BLACK; if (styles != null && styles.has("color")) { try { titleColor = PluginUtil.parsePluginColor(styles.getJSONArray("color")); } catch (JSONException e) {} } textView.setTextColor(titleColor); textView.setGravity(gravity); if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView.setTextAlignment(textAlignment); } //---------------------------------------- // font-style = normal | italic // font-weight = normal | bold //---------------------------------------- int fontStyle = Typeface.NORMAL; if (styles != null) { try { if ("italic".equals(styles.getString("font-style"))) { fontStyle = Typeface.ITALIC; } } catch (JSONException e) {} try { if ("bold".equals(styles.getString("font-weight"))) { fontStyle = fontStyle | Typeface.BOLD; } } catch (JSONException e) {} } textView.setTypeface(Typeface.DEFAULT, fontStyle); windowLayer.addView(textView); } } if (snippet != null) { //snippet = snippet.replaceAll("\n", ""); TextView textView2 = new TextView(this.cordova.getActivity()); textView2.setText(snippet); textView2.setTextColor(Color.GRAY); textView2.setTextSize((textView2.getTextSize() / 6 * 5) / density); textView2.setGravity(gravity); if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView2.setTextAlignment(textAlignment); } windowLayer.addView(textView2); } return windowLayer; } @Override public View getInfoWindow(Marker marker) { return null; } /** * Clear all markups * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void clear(JSONArray args, CallbackContext callbackContext) throws JSONException { Set<String> pluginNames = plugins.keySet(); Iterator<String> iterator = pluginNames.iterator(); String pluginName; PluginEntry pluginEntry; while(iterator.hasNext()) { pluginName = iterator.next(); if ("Map".equals(pluginName) == false) { pluginEntry = plugins.get(pluginName); ((MyPlugin) pluginEntry.plugin).clear(); } } this.map.clear(); this.sendNoResult(callbackContext); } @SuppressWarnings("unused") private void pluginLayer_pushHtmlElement(JSONArray args, CallbackContext callbackContext) throws JSONException { if (mPluginLayout != null) { String domId = args.getString(0); JSONObject elemSize = args.getJSONObject(1); float left = contentToView(elemSize.getLong("left")); float top = contentToView(elemSize.getLong("top")); float width = contentToView(elemSize.getLong("width")); float height = contentToView(elemSize.getLong("height")); mPluginLayout.putHTMLElement(domId, left, top, (left + width), (top + height)); this.mPluginLayout.inValidate(); } this.sendNoResult(callbackContext); } @SuppressWarnings("unused") private void pluginLayer_removeHtmlElement(JSONArray args, CallbackContext callbackContext) throws JSONException { if (mPluginLayout != null) { String domId = args.getString(0); mPluginLayout.removeHTMLElement(domId); this.mPluginLayout.inValidate(); } this.sendNoResult(callbackContext); } /** * Set click-ability of the map * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void pluginLayer_setClickable(JSONArray args, CallbackContext callbackContext) throws JSONException { boolean clickable = args.getBoolean(0); if (mapView != null && this.windowLayer == null) { this.mPluginLayout.setClickable(clickable); } this.sendNoResult(callbackContext); } /** * Set the app background * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void pluginLayer_setBackGroundColor(JSONArray args, CallbackContext callbackContext) throws JSONException { if (mPluginLayout != null) { JSONArray rgba = args.getJSONArray(0); int backgroundColor = Color.WHITE; if (rgba != null && rgba.length() == 4) { try { backgroundColor = PluginUtil.parsePluginColor(rgba); this.mPluginLayout.setBackgroundColor(backgroundColor); } catch (JSONException e) {} } } this.sendNoResult(callbackContext); } /** * Set the debug flag of myPluginLayer * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void pluginLayer_setDebuggable(JSONArray args, CallbackContext callbackContext) throws JSONException { boolean debuggable = args.getBoolean(0); if (mapView != null && this.windowLayer == null) { this.mPluginLayout.setDebug(debuggable); } this.sendNoResult(callbackContext); } /** * Destroy the map completely * @param args * @param callbackContext */ @SuppressWarnings("unused") private void remove(JSONArray args, CallbackContext callbackContext) { if (mPluginLayout != null) { this.mPluginLayout.setClickable(false); this.mPluginLayout.detachMyView(); this.mPluginLayout = null; } plugins.clear(); if (map != null) { map.setMyLocationEnabled(false); map.clear(); } if (mapView != null) { mapView.onDestroy(); } map = null; mapView = null; windowLayer = null; mapDivLayoutJSON = null; System.gc(); this.sendNoResult(callbackContext); } protected void sendNoResult(CallbackContext callbackContext) { PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); callbackContext.sendPluginResult(pluginResult); } }
Update GoogleMaps.java
src/android/plugin/google/maps/GoogleMaps.java
Update GoogleMaps.java
Java
apache-2.0
df852f857444545c305d927fecfe8a8d986a6168
0
kole9273/uPortal,jonathanmtran/uPortal,EsupPortail/esup-uportal,GIP-RECIA/esup-uportal,apetro/uPortal,joansmith/uPortal,GIP-RECIA/esup-uportal,bjagg/uPortal,andrewstuart/uPortal,Mines-Albi/esup-uportal,vertein/uPortal,groybal/uPortal,doodelicious/uPortal,jonathanmtran/uPortal,Jasig/uPortal,cousquer/uPortal,phillips1021/uPortal,apetro/uPortal,EdiaEducationTechnology/uPortal,Mines-Albi/esup-uportal,pspaude/uPortal,phillips1021/uPortal,GIP-RECIA/esup-uportal,jl1955/uPortal5,timlevett/uPortal,doodelicious/uPortal,jonathanmtran/uPortal,vbonamy/esup-uportal,vbonamy/esup-uportal,mgillian/uPortal,timlevett/uPortal,jl1955/uPortal5,Jasig/uPortal-start,MichaelVose2/uPortal,timlevett/uPortal,cousquer/uPortal,kole9273/uPortal,doodelicious/uPortal,Jasig/SSP-Platform,andrewstuart/uPortal,GIP-RECIA/esup-uportal,joansmith/uPortal,cousquer/uPortal,MichaelVose2/uPortal,ASU-Capstone/uPortal-Forked,jameswennmacher/uPortal,Jasig/uPortal-start,jameswennmacher/uPortal,vbonamy/esup-uportal,joansmith/uPortal,Jasig/SSP-Platform,EsupPortail/esup-uportal,ASU-Capstone/uPortal,MichaelVose2/uPortal,chasegawa/uPortal,stalele/uPortal,bjagg/uPortal,chasegawa/uPortal,vertein/uPortal,vertein/uPortal,EsupPortail/esup-uportal,groybal/uPortal,Jasig/SSP-Platform,pspaude/uPortal,GIP-RECIA/esup-uportal,stalele/uPortal,drewwills/uPortal,GIP-RECIA/esco-portail,kole9273/uPortal,MichaelVose2/uPortal,Jasig/SSP-Platform,mgillian/uPortal,vertein/uPortal,jhelmer-unicon/uPortal,EsupPortail/esup-uportal,andrewstuart/uPortal,ASU-Capstone/uPortal-Forked,ASU-Capstone/uPortal-Forked,GIP-RECIA/esco-portail,EdiaEducationTechnology/uPortal,chasegawa/uPortal,Jasig/uPortal,vbonamy/esup-uportal,apetro/uPortal,Mines-Albi/esup-uportal,andrewstuart/uPortal,stalele/uPortal,chasegawa/uPortal,EdiaEducationTechnology/uPortal,Jasig/SSP-Platform,Jasig/uPortal,jameswennmacher/uPortal,phillips1021/uPortal,bjagg/uPortal,ASU-Capstone/uPortal,EsupPortail/esup-uportal,stalele/uPortal,pspaude/uPortal,ASU-Capstone/uPortal,ChristianMurphy/uPortal,drewwills/uPortal,jhelmer-unicon/uPortal,apetro/uPortal,timlevett/uPortal,jhelmer-unicon/uPortal,jameswennmacher/uPortal,groybal/uPortal,kole9273/uPortal,ASU-Capstone/uPortal,pspaude/uPortal,joansmith/uPortal,andrewstuart/uPortal,vbonamy/esup-uportal,jhelmer-unicon/uPortal,jl1955/uPortal5,GIP-RECIA/esco-portail,kole9273/uPortal,jhelmer-unicon/uPortal,apetro/uPortal,stalele/uPortal,doodelicious/uPortal,phillips1021/uPortal,jl1955/uPortal5,drewwills/uPortal,Mines-Albi/esup-uportal,joansmith/uPortal,EdiaEducationTechnology/uPortal,groybal/uPortal,ChristianMurphy/uPortal,ChristianMurphy/uPortal,phillips1021/uPortal,Mines-Albi/esup-uportal,ASU-Capstone/uPortal-Forked,doodelicious/uPortal,jameswennmacher/uPortal,groybal/uPortal,MichaelVose2/uPortal,drewwills/uPortal,ASU-Capstone/uPortal,mgillian/uPortal,chasegawa/uPortal,ASU-Capstone/uPortal-Forked,jl1955/uPortal5
/** * Copyright 2001 The JA-SIG Collaborative. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.jasig.portal.tools; import org.jasig.portal.PropertiesManager; import org.jasig.portal.RdbmServices; import org.jasig.portal.utils.DTDResolver; import org.jasig.portal.utils.XSLT; import java.io.File; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.net.URL; import java.sql.Connection; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.Types; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.xml.sax.XMLReader; import org.xml.sax.InputSource; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.ContentHandler; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; /** * <p>A tool to set up a uPortal database. This tool was created so that uPortal * developers would only have to maintain a single set of xml documents to define * the uPortal database schema and data. Previously it was necessary to maintain * different scripts for each database we wanted to support.</p> * * <p>DbLoader reads the generic types that are specified in tables.xml and * tries to map them to local types by querying the database metadata via methods * implemented by the JDBC driver. Fallback mappings can be supplied in * dbloader.xml for cases where the JDBC driver is not able to determine the * appropriate mapping. Such cases will be reported to standard out.</p> * * <p>An xsl transformation is used to produce the DROP TABLE and CREATE TABLE * SQL statements. These statements can be altered by modifying tables.xsl</p> * * <p>Generic data types (as defined in java.sql.Types) which may be specified * in tables.xml include: * <code>BIT, TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, REAL, DOUBLE, * NUMERIC, DECIMAL, CHAR, VARCHAR, LONGVARCHAR, DATE, TIME, TIMESTAMP, * BINARY, VARBINARY, LONGVARBINARY, NULL, OTHER, JAVA_OBJECT, DISTINCT, * STRUCT, ARRAY, BLOB, CLOB, REF</code> * * <p><strong>WARNING: YOU MAY WANT TO MAKE A BACKUP OF YOUR DATABASE BEFORE RUNNING DbLoader</strong></p> * * <p>DbLoader will perform the following steps: * <ol> * <li>Read configurable properties from dbloader.xml</li> * <li>Get database connection from RdbmServices * (reads JDBC database settings from rdbm.properties).</li> * <li>Read tables.xml and issue corresponding DROP TABLE and CREATE TABLE SQL statements.</li> * <li>Read data.xml and issue corresponding INSERT SQL statements.</li> * </ol> * </p> * * @author Ken Weiner, [email protected] * @version $Revision$ * @see java.sql.Types * @since uPortal 2.0 */ public class DbLoader { private static URL propertiesURL; private static URL tablesURL; private static String tablesXslUri; private static Connection con; private static Statement stmt; private static PreparedStatement pstmt; private static RdbmServices rdbmService; private static Document tablesDoc; private static Document tablesDocGeneric; private static boolean createScript; private static boolean dropTables; private static boolean createTables; private static boolean populateTables; private static PrintWriter scriptOut; public static void main(String[] args) { try { System.setProperty("org.xml.sax.driver", PropertiesManager.getProperty("org.xml.sax.driver")); propertiesURL = DbLoader.class.getResource("/properties/dbloader.xml"); con = rdbmService.getConnection (); if (con != null) { long startTime = System.currentTimeMillis(); // Read in the properties XMLReader parser = getXMLReader(); printInfo(); readProperties(parser); // Read drop/create/populate table settings dropTables = Boolean.valueOf(PropertiesHandler.properties.getDropTables()).booleanValue(); createTables = Boolean.valueOf(PropertiesHandler.properties.getCreateTables()).booleanValue(); populateTables = Boolean.valueOf(PropertiesHandler.properties.getPopulateTables()).booleanValue(); // Set up script createScript = Boolean.valueOf(PropertiesHandler.properties.getCreateScript()).booleanValue(); if (createScript) initScript(); try { // Read tables.xml DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder domParser = dbf.newDocumentBuilder(); // Eventually, write and validate against a DTD //domParser.setFeature ("http://xml.org/sax/features/validation", true); //domParser.setEntityResolver(new DTDResolver("tables.dtd")); tablesURL = DbLoader.class.getResource(PropertiesHandler.properties.getTablesUri()); tablesDoc = domParser.parse(new InputSource(tablesURL.openStream())); } catch (ParserConfigurationException pce) { System.out.println("Unable to instantiate DOM parser. Pease check your JAXP configuration."); pce.printStackTrace(); } catch(Exception e) { System.out.println("Could not open " + tablesURL); e.printStackTrace(); return; } // Hold on to tables xml with generic types tablesDocGeneric = (Document)tablesDoc.cloneNode(true); // Replace all generic data types with local data types replaceDataTypes(tablesDoc); // tables.xml + tables.xsl --> DROP TABLE and CREATE TABLE sql statements tablesXslUri = PropertiesHandler.properties.getTablesXslUri(); XSLT xslt = new XSLT(new DbLoader()); xslt.setXML(tablesDoc); xslt.setXSL(tablesXslUri); xslt.setTarget(new TableHandler()); xslt.transform(); // data.xml --> INSERT sql statements readData(parser); System.out.println("Done!"); long endTime = System.currentTimeMillis(); System.out.println("Elapsed time: " + ((endTime - startTime) / 1000f) + " seconds"); exit(); } else System.out.println("DbLoader couldn't obtain a database connection. See the portal log for details."); } catch (Exception e) { e.printStackTrace(); } finally // call local exit method to clean up. This does not actually // do a system.exit() allowing a stack trace to the console in // the case of a run time error. { exit(); } } private static XMLReader getXMLReader() throws SAXException, ParserConfigurationException { SAXParserFactory spf=SAXParserFactory.newInstance(); return spf.newSAXParser().getXMLReader(); } private static void printInfo () throws SQLException { DatabaseMetaData dbMetaData = con.getMetaData(); String dbName = dbMetaData.getDatabaseProductName(); String dbVersion = dbMetaData.getDatabaseProductVersion(); String driverName = dbMetaData.getDriverName(); String driverVersion = dbMetaData.getDriverVersion(); String driverClass = rdbmService.getJdbcDriver(); String url = rdbmService.getJdbcUrl(); String user = rdbmService.getJdbcUser(); System.out.println("Starting DbLoader..."); System.out.println("Database name: '" + dbName + "'"); System.out.println("Database version: '" + dbVersion + "'"); System.out.println("Driver name: '" + driverName + "'"); System.out.println("Driver version: '" + driverVersion + "'"); System.out.println("Driver class: '" + driverClass + "'"); System.out.println("Connection URL: '" + url + "'"); System.out.println("User: '" + user + "'"); } private static void readData (XMLReader parser) throws SAXException, IOException { InputSource dataInSrc = new InputSource(DbLoader.class.getResourceAsStream(PropertiesHandler.properties.getDataUri())); DataHandler dataHandler = new DataHandler(); parser.setContentHandler(dataHandler); parser.setErrorHandler(dataHandler); parser.parse(dataInSrc); } private static void initScript() throws java.io.IOException { String scriptFileName = PropertiesHandler.properties.getScriptFileName(); File scriptFile = new File(scriptFileName); if (scriptFile.exists()) scriptFile.delete(); scriptFile.createNewFile(); scriptOut = new PrintWriter(new BufferedWriter(new FileWriter(scriptFileName, true))); } private static void replaceDataTypes (Document tablesDoc) { Element tables = tablesDoc.getDocumentElement(); NodeList types = tables.getElementsByTagName("type"); for (int i = 0; i < types.getLength(); i++) { Node type = (Node)types.item(i); NodeList typeChildren = type.getChildNodes(); for (int j = 0; j < typeChildren.getLength(); j++) { Node text = (Node)typeChildren.item(j); String genericType = text.getNodeValue(); // Replace generic type with mapped local type text.setNodeValue(getLocalDataTypeName(genericType)); } } } private static int getJavaSqlDataTypeOfColumn(Document tablesDocGeneric, String tableName, String columnName) { int dataType = 0; // Find the right table element Element table = getTableWithName(tablesDocGeneric, tableName); // Find the columns element within Element columns = getFirstChildWithName(table, "columns"); // Search for the first column who's name is columnName for (Node ch = columns.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Element && ch.getNodeName().equals("column")) { Element name = getFirstChildWithName((Element)ch, "name"); if (getNodeValue(name).equals(columnName)) { // Get the corresponding type and return it's type code Element value = getFirstChildWithName((Element)ch, "type"); dataType = getJavaSqlType(getNodeValue(value)); } } } return dataType; } private static Element getFirstChildWithName (Element parent, String name) { Element child = null; for (Node ch = parent.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Element && ch.getNodeName().equals(name)) { child = (Element)ch; break; } } return child; } private static Element getTableWithName (Document tablesDoc, String tableName) { Element tableElement = null; NodeList tables = tablesDoc.getElementsByTagName("table"); for (int i = 0; i < tables.getLength(); i++) { Node table = (Node)tables.item(i); for (Node tableChild = table.getFirstChild(); tableChild != null; tableChild = tableChild.getNextSibling()) { if (tableChild instanceof Element && tableChild.getNodeName() != null && tableChild.getNodeName().equals("name")) { if (tableName.equals(getNodeValue(tableChild))) { tableElement = (Element)table; break; } } } } return tableElement; } private static String getNodeValue (Node node) { String nodeVal = null; for (Node ch = node.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Text) nodeVal = ch.getNodeValue(); } return nodeVal; } private static String getLocalDataTypeName (String genericDataTypeName) { String localDataTypeName = null; try { DatabaseMetaData dbmd = con.getMetaData(); String dbName = dbmd.getDatabaseProductName(); String dbVersion = dbmd.getDatabaseProductVersion(); String driverName = dbmd.getDriverName(); String driverVersion = dbmd.getDriverVersion(); // Check for a mapping in DbLoader.xml localDataTypeName = PropertiesHandler.properties.getMappedDataTypeName(dbName, dbVersion, driverName, driverVersion, genericDataTypeName); if (localDataTypeName != null) return localDataTypeName; // Find the type code for this generic type name int dataTypeCode = getJavaSqlType(genericDataTypeName); // Find the first local type name matching the type code ResultSet rs = dbmd.getTypeInfo(); try { while (rs.next()) { int localDataTypeCode = rs.getInt("DATA_TYPE"); if (dataTypeCode == localDataTypeCode) { try { localDataTypeName = rs.getString("TYPE_NAME"); } catch (SQLException sqle) { } break; } } } finally { rs.close(); } if (localDataTypeName != null) return localDataTypeName; // No matching type found, report an error System.out.println("Your database driver, '"+ driverName + "', version '" + driverVersion + "', was unable to find a local type name that matches the generic type name, '" + genericDataTypeName + "'."); System.out.println("Please add a mapped type for database '" + dbName + "', version '" + dbVersion + "' inside '" + propertiesURL + "' and run this program again."); System.out.println("Exiting..."); exit(); } catch (Exception e) { e.printStackTrace(); exit(); } return null; } private static int getJavaSqlType (String genericDataTypeName) { // Find the type code for this generic type name int dataTypeCode = 0; if (genericDataTypeName.equalsIgnoreCase("BIT")) dataTypeCode = Types.BIT; // -7 else if (genericDataTypeName.equalsIgnoreCase("TINYINT")) dataTypeCode = Types.TINYINT; // -6 else if (genericDataTypeName.equalsIgnoreCase("SMALLINT")) dataTypeCode = Types.SMALLINT; // 5 else if (genericDataTypeName.equalsIgnoreCase("INTEGER")) dataTypeCode = Types.INTEGER; // 4 else if (genericDataTypeName.equalsIgnoreCase("BIGINT")) dataTypeCode = Types.BIGINT; // -5 else if (genericDataTypeName.equalsIgnoreCase("FLOAT")) dataTypeCode = Types.FLOAT; // 6 else if (genericDataTypeName.equalsIgnoreCase("REAL")) dataTypeCode = Types.REAL; // 7 else if (genericDataTypeName.equalsIgnoreCase("DOUBLE")) dataTypeCode = Types.DOUBLE; // 8 else if (genericDataTypeName.equalsIgnoreCase("NUMERIC")) dataTypeCode = Types.NUMERIC; // 2 else if (genericDataTypeName.equalsIgnoreCase("DECIMAL")) dataTypeCode = Types.DECIMAL; // 3 else if (genericDataTypeName.equalsIgnoreCase("CHAR")) dataTypeCode = Types.CHAR; // 1 else if (genericDataTypeName.equalsIgnoreCase("VARCHAR")) dataTypeCode = Types.VARCHAR; // 12 else if (genericDataTypeName.equalsIgnoreCase("LONGVARCHAR")) dataTypeCode = Types.LONGVARCHAR; // -1 else if (genericDataTypeName.equalsIgnoreCase("DATE")) dataTypeCode = Types.DATE; // 91 else if (genericDataTypeName.equalsIgnoreCase("TIME")) dataTypeCode = Types.TIME; // 92 else if (genericDataTypeName.equalsIgnoreCase("TIMESTAMP")) dataTypeCode = Types.TIMESTAMP; // 93 else if (genericDataTypeName.equalsIgnoreCase("BINARY")) dataTypeCode = Types.BINARY; // -2 else if (genericDataTypeName.equalsIgnoreCase("VARBINARY")) dataTypeCode = Types.VARBINARY; // -3 else if (genericDataTypeName.equalsIgnoreCase("LONGVARBINARY")) dataTypeCode = Types.LONGVARBINARY; // -4 else if (genericDataTypeName.equalsIgnoreCase("NULL")) dataTypeCode = Types.NULL; // 0 else if (genericDataTypeName.equalsIgnoreCase("OTHER")) dataTypeCode = Types.OTHER; // 1111 else if (genericDataTypeName.equalsIgnoreCase("JAVA_OBJECT")) dataTypeCode = Types.JAVA_OBJECT; // 2000 else if (genericDataTypeName.equalsIgnoreCase("DISTINCT")) dataTypeCode = Types.DISTINCT; // 2001 else if (genericDataTypeName.equalsIgnoreCase("STRUCT")) dataTypeCode = Types.STRUCT; // 2002 else if (genericDataTypeName.equalsIgnoreCase("ARRAY")) dataTypeCode = Types.ARRAY; // 2003 else if (genericDataTypeName.equalsIgnoreCase("BLOB")) dataTypeCode = Types.BLOB; // 2004 else if (genericDataTypeName.equalsIgnoreCase("CLOB")) dataTypeCode = Types.CLOB; // 2005 else if (genericDataTypeName.equalsIgnoreCase("REF")) dataTypeCode = Types.REF; // 2006 return dataTypeCode; } private static void dropTable (String dropTableStatement) { System.out.print("..."); if (createScript) scriptOut.println(dropTableStatement + PropertiesHandler.properties.getStatementTerminator()); try { stmt = con.createStatement(); try { stmt.executeUpdate(dropTableStatement); } catch (SQLException sqle) {/*Table didn't exist*/} } catch (Exception e) { e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } private static void createTable (String createTableStatement) { System.out.print("..."); if (createScript) scriptOut.println(createTableStatement + PropertiesHandler.properties.getStatementTerminator()); try { stmt = con.createStatement(); stmt.executeUpdate(createTableStatement); } catch (Exception e) { System.out.println(createTableStatement); e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } private static void readProperties (XMLReader parser) throws SAXException, IOException { PropertiesHandler propertiesHandler = new PropertiesHandler(); parser.setContentHandler(propertiesHandler); parser.setErrorHandler(propertiesHandler); parser.parse(new InputSource(propertiesURL.openStream())); } static class PropertiesHandler extends DefaultHandler { private static StringBuffer charBuff = null; static Properties properties; static DbTypeMapping dbTypeMapping; static Type type; public void startDocument () { System.out.print("Parsing " + propertiesURL + "..."); } public void endDocument () { System.out.println(""); } public void startElement (String namespaceURI, String localName, String qName, Attributes atts) { charBuff = new StringBuffer(); if (qName.equals("properties")) properties = new Properties(); else if (qName.equals("db-type-mapping")) dbTypeMapping = new DbTypeMapping(); else if (qName.equals("type")) type = new Type(); } public void endElement (String namespaceURI, String localName, String qName) { if (qName.equals("drop-tables")) // drop tables ("true" or "false") properties.setDropTables(charBuff.toString()); else if (qName.equals("create-tables")) // create tables ("true" or "false") properties.setCreateTables(charBuff.toString()); else if (qName.equals("populate-tables")) // populate tables ("true" or "false") properties.setPopulateTables(charBuff.toString()); else if (qName.equals("tables-uri")) // tables URI properties.setTablesUri(charBuff.toString()); else if (qName.equals("tables-xsl-uri")) // tables xsl URI properties.setTablesXslUri(charBuff.toString()); else if (qName.equals("data-uri")) // data xml URI properties.setDataUri(charBuff.toString()); else if (qName.equals("create-script")) // create script ("true" or "false") properties.setCreateScript(charBuff.toString()); else if (qName.equals("script-file-name")) // script file name properties.setScriptFileName(charBuff.toString()); else if (qName.equals("statement-terminator")) // statement terminator properties.setStatementTerminator(charBuff.toString()); else if (qName.equals("db-type-mapping")) properties.addDbTypeMapping(dbTypeMapping); else if (qName.equals("db-name")) // database name dbTypeMapping.setDbName(charBuff.toString()); else if (qName.equals("db-version")) // database version dbTypeMapping.setDbVersion(charBuff.toString()); else if (qName.equals("driver-name")) // driver name dbTypeMapping.setDriverName(charBuff.toString()); else if (qName.equals("driver-version")) // driver version dbTypeMapping.setDriverVersion(charBuff.toString()); else if (qName.equals("type")) dbTypeMapping.addType(type); else if (qName.equals("generic")) // generic type type.setGeneric(charBuff.toString()); else if (qName.equals("local")) // local type type.setLocal(charBuff.toString()); } public void characters (char ch[], int start, int length) { charBuff.append(ch, start, length); } class Properties { private String dropTables; private String createTables; private String populateTables; private String tablesUri; private String tablesXslUri; private String dataUri; private String dataXslUri; private String createScript; private String scriptFileName; private String statementTerminator; private ArrayList dbTypeMappings = new ArrayList(); public String getDropTables() { return dropTables; } public String getCreateTables() { return createTables; } public String getPopulateTables() { return populateTables; } public String getTablesUri() { return tablesUri; } public String getTablesXslUri() { return tablesXslUri; } public String getDataUri() { return dataUri; } public String getDataXslUri() { return dataXslUri; } public String getCreateScript() { return createScript; } public String getScriptFileName() { return scriptFileName; } public String getStatementTerminator() { return statementTerminator; } public ArrayList getDbTypeMappings() { return dbTypeMappings; } public void setDropTables(String dropTables) { this.dropTables = dropTables; } public void setCreateTables(String createTables) { this.createTables = createTables; } public void setPopulateTables(String populateTables) { this.populateTables = populateTables; } public void setTablesUri(String tablesUri) { this.tablesUri = tablesUri; } public void setTablesXslUri(String tablesXslUri) { this.tablesXslUri = tablesXslUri; } public void setDataUri(String dataUri) { this.dataUri = dataUri; } public void setDataXslUri(String dataXslUri) { this.dataXslUri = dataXslUri; } public void setCreateScript(String createScript) { this.createScript = createScript; } public void setScriptFileName(String scriptFileName) { this.scriptFileName = scriptFileName; } public void setStatementTerminator(String statementTerminator) { this.statementTerminator = statementTerminator; } public void addDbTypeMapping(DbTypeMapping dbTypeMapping) { dbTypeMappings.add(dbTypeMapping); } public String getMappedDataTypeName(String dbName, String dbVersion, String driverName, String driverVersion, String genericDataTypeName) { String mappedDataTypeName = null; Iterator iterator = dbTypeMappings.iterator(); while (iterator.hasNext()) { DbTypeMapping dbTypeMapping = (DbTypeMapping)iterator.next(); String dbNameProp = dbTypeMapping.getDbName(); String dbVersionProp = dbTypeMapping.getDbVersion(); String driverNameProp = dbTypeMapping.getDriverName(); String driverVersionProp = dbTypeMapping.getDriverVersion(); if (dbNameProp.equalsIgnoreCase(dbName) && dbVersionProp.equalsIgnoreCase(dbVersion) && driverNameProp.equalsIgnoreCase(driverName) && driverVersionProp.equalsIgnoreCase(driverVersion)) { // Found a matching database/driver combination mappedDataTypeName = dbTypeMapping.getMappedDataTypeName(genericDataTypeName); } } return mappedDataTypeName; } } class DbTypeMapping { String dbName; String dbVersion; String driverName; String driverVersion; ArrayList types = new ArrayList(); public String getDbName() { return dbName; } public String getDbVersion() { return dbVersion; } public String getDriverName() { return driverName; } public String getDriverVersion() { return driverVersion; } public ArrayList getTypes() { return types; } public void setDbName(String dbName) { this.dbName = dbName; } public void setDbVersion(String dbVersion) { this.dbVersion = dbVersion; } public void setDriverName(String driverName) { this.driverName = driverName; } public void setDriverVersion(String driverVersion) { this.driverVersion = driverVersion; } public void addType(Type type) { types.add(type); } public String getMappedDataTypeName(String genericDataTypeName) { String mappedDataTypeName = null; Iterator iterator = types.iterator(); while (iterator.hasNext()) { Type type = (Type)iterator.next(); if (type.getGeneric().equalsIgnoreCase(genericDataTypeName)) mappedDataTypeName = type.getLocal(); } return mappedDataTypeName; } } class Type { String genericType; // "generic" is a Java reserved word String local; public String getGeneric() { return genericType; } public String getLocal() { return local; } public void setGeneric(String genericType) { this.genericType = genericType; } public void setLocal(String local) { this.local = local; } } } static class TableHandler implements ContentHandler { private static final int UNSET = -1; private static final int DROP = 0; private static final int CREATE = 1; private static int mode = UNSET; private static StringBuffer stmtBuffer; public void startDocument () { } public void endDocument () { System.out.println(); } public void startElement (String namespaceURI, String localName, String qName, Attributes atts) { if (qName.equals("statement")) { stmtBuffer = new StringBuffer(1024); String statementType = atts.getValue("type"); if (mode == UNSET || mode == CREATE && statementType != null && statementType.equals("drop")) { mode = DROP; System.out.print("Dropping tables..."); if (!dropTables) System.out.print("disabled."); } else if (mode == UNSET || mode == DROP && statementType != null && statementType.equals("create")) { mode = CREATE; System.out.print("\nCreating tables..."); if (!createTables) System.out.print("disabled."); } } } public void endElement (String namespaceURI, String localName, String qName) { if (qName.equals("statement")) { String statement = stmtBuffer.toString(); switch (mode) { case DROP: if (dropTables) dropTable(statement); break; case CREATE: if (createTables) createTable(statement); break; default: break; } } } public void characters (char ch[], int start, int length) { stmtBuffer.append(ch, start, length); } public void setDocumentLocator (Locator locator) { } public void processingInstruction (String target, String data) { } public void ignorableWhitespace (char[] ch, int start, int length) { } public void startPrefixMapping (String prefix, String uri) throws SAXException {}; public void endPrefixMapping (String prefix) throws SAXException {}; public void skippedEntity(String name) throws SAXException {}; } static class DataHandler extends DefaultHandler { private static StringBuffer charBuff = null; private static boolean insideData = false; private static boolean insideTable = false; private static boolean insideName = false; private static boolean insideRow = false; private static boolean insideColumn = false; private static boolean insideValue = false; private static boolean supportsPreparedStatements = false; static Table table; static Row row; static Column column; public void startDocument () { System.out.print("Populating tables..."); if (!populateTables) System.out.print("disabled."); supportsPreparedStatements = supportsPreparedStatements(); } public void endDocument () { System.out.println(""); } public void startElement (String namespaceURI, String localName, String qName, Attributes atts) { charBuff = new StringBuffer(); if (qName.equals("data")) insideData = true; else if (qName.equals("table")) { insideTable = true; table = new Table(); } else if (qName.equals("name")) insideName = true; else if (qName.equals("row")) { insideRow = true; row = new Row(); } else if (qName.equals("column")) { insideColumn = true; column = new Column(); } else if (qName.equals("value")) insideValue = true; } public void endElement (String namespaceURI, String localName, String qName) { if (qName.equals("data")) insideData = false; else if (qName.equals("table")) insideTable = false; else if (qName.equals("name")) { insideName = false; if (!insideColumn) // table name table.setName(charBuff.toString()); else // column name column.setName(charBuff.toString()); } else if (qName.equals("row")) { insideRow = false; if (populateTables) insertRow(table, row); } else if (qName.equals("column")) { insideColumn = false; row.addColumn(column); } else if (qName.equals("value")) { insideValue = false; if (insideColumn) // column value column.setValue(charBuff.toString()); } } public void characters (char ch[], int start, int length) { charBuff.append(ch, start, length); } private String prepareInsertStatement (Row row, boolean preparedStatement) { StringBuffer sb = new StringBuffer("INSERT INTO "); sb.append(table.getName()).append(" ("); ArrayList columns = row.getColumns(); Iterator iterator = columns.iterator(); while (iterator.hasNext()) { Column column = (Column)iterator.next(); sb.append(column.getName()).append(", "); } // Delete comma and space after last column name (kind of sloppy, but it works) sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.append(") VALUES ("); iterator = columns.iterator(); while (iterator.hasNext()) { Column column = (Column)iterator.next(); if (preparedStatement) sb.append("?"); else { String value = column.getValue(); if (value != null) { if (value.equals("SYSDATE")) sb.append(value); else if (value.equals("NULL")) sb.append(value); else if (getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()) == Types.INTEGER) // this column is an integer, so don't put quotes (Sybase cares about this) sb.append(value); else { sb.append("'"); sb.append(value.trim()); sb.append("'"); } } else sb.append("''"); } sb.append(", "); } // Delete comma and space after last value (kind of sloppy, but it works) sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.append(")"); return sb.toString(); } private void insertRow (Table table, Row row) { System.out.print("..."); if (createScript) scriptOut.println(prepareInsertStatement(row, false) + PropertiesHandler.properties.getStatementTerminator()); if (supportsPreparedStatements) { String preparedStatement = ""; try { preparedStatement = prepareInsertStatement(row, true); //System.out.println(preparedStatement); pstmt = con.prepareStatement(preparedStatement); pstmt.clearParameters (); // Loop through parameters and set them, checking for any that excede 4k ArrayList columns = row.getColumns(); Iterator iterator = columns.iterator(); for (int i = 1; iterator.hasNext(); i++) { Column column = (Column)iterator.next(); String value = column.getValue(); // Get a java sql data type for column name int javaSqlDataType = getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()); if (value == null) pstmt.setString(i, ""); else if (value.equals("NULL")) pstmt.setNull(i, javaSqlDataType); else if (javaSqlDataType == Types.TIMESTAMP) { if (value.equals("SYSDATE")) pstmt.setTimestamp(i, new java.sql.Timestamp(System.currentTimeMillis())); else pstmt.setTimestamp(i, java.sql.Timestamp.valueOf(value)); } else { value = value.trim(); // portal can't read xml properly without this, don't know why yet int valueLength = value.length(); if (valueLength <= 4000) { try { // Needed for Sybase and maybe others pstmt.setObject(i, value, javaSqlDataType); } catch (Exception e) { // Needed for Oracle and maybe others pstmt.setObject(i, value); } } else { try { try { // Needed for Sybase and maybe others pstmt.setObject(i, value, javaSqlDataType); } catch (Exception e) { // Needed for Oracle and maybe others pstmt.setObject(i, value); } } catch (SQLException sqle) { // For Oracle and maybe others pstmt.setCharacterStream(i, new StringReader(value), valueLength); } } } } pstmt.executeUpdate(); } catch (SQLException sqle) { System.err.println(); System.err.println(preparedStatement); sqle.printStackTrace(); } catch (Exception e) { System.err.println(); e.printStackTrace(); } finally { try { pstmt.close(); } catch (Exception e) { } } } else { // If prepared statements aren't supported, try a normal insert statement String insertStatement = prepareInsertStatement(row, false); //System.out.println(insertStatement); try { stmt = con.createStatement(); stmt.executeUpdate(insertStatement); } catch (Exception e) { System.err.println(); System.err.println(insertStatement); e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } } private static boolean supportsPreparedStatements() { boolean supportsPreparedStatements = true; try { // Issue a prepared statement to see if database/driver accepts them. // The assumption is that if a SQLException is thrown, it doesn't support them. // I don't know of any other way to check if the database/driver accepts // prepared statements. If you do, please change this method! Statement stmt; stmt = con.createStatement(); try { stmt.executeUpdate("CREATE TABLE PREP_TEST (A VARCHAR(1))"); } catch (Exception e){/* Assume it already exists */ } finally { try {stmt.close();} catch (Exception e) { } } pstmt = con.prepareStatement("SELECT A FROM PREP_TEST WHERE A=?"); pstmt.clearParameters (); pstmt.setString(1, "D"); pstmt.executeQuery(); } catch (SQLException sqle) { supportsPreparedStatements = false; sqle.printStackTrace(); } finally { try { stmt = con.createStatement(); stmt.executeUpdate("DROP TABLE PREP_TEST"); } catch (Exception e){/* Assume it already exists */ } finally { try {stmt.close();} catch (Exception e) { } } try { pstmt.close(); } catch (Exception e) { } } return supportsPreparedStatements; } class Table { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Row { ArrayList columns = new ArrayList(); public ArrayList getColumns() { return columns; } public void addColumn(Column column) { columns.add(column); } } class Column { private String name; private String value; public String getName() { return name; } public String getValue() { return value; } public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } } } private static void exit() { rdbmService.releaseConnection(con); if (scriptOut != null) scriptOut.close(); } }
source/org/jasig/portal/tools/DbLoader.java
/** * Copyright 2001 The JA-SIG Collaborative. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.jasig.portal.tools; import org.jasig.portal.PropertiesManager; import org.jasig.portal.RdbmServices; import org.jasig.portal.utils.DTDResolver; import org.jasig.portal.utils.XSLT; import java.io.File; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.net.URL; import java.sql.Connection; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.Types; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.xml.sax.XMLReader; import org.xml.sax.InputSource; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.ContentHandler; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; /** * <p>A tool to set up a uPortal database. This tool was created so that uPortal * developers would only have to maintain a single set of xml documents to define * the uPortal database schema and data. Previously it was necessary to maintain * different scripts for each database we wanted to support.</p> * * <p>DbLoader reads the generic types that are specified in tables.xml and * tries to map them to local types by querying the database metadata via methods * implemented by the JDBC driver. Fallback mappings can be supplied in * dbloader.xml for cases where the JDBC driver is not able to determine the * appropriate mapping. Such cases will be reported to standard out.</p> * * <p>An xsl transformation is used to produce the DROP TABLE and CREATE TABLE * SQL statements. These statements can be altered by modifying tables.xsl</p> * * <p>Generic data types (as defined in java.sql.Types) which may be specified * in tables.xml include: * <code>BIT, TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, REAL, DOUBLE, * NUMERIC, DECIMAL, CHAR, VARCHAR, LONGVARCHAR, DATE, TIME, TIMESTAMP, * BINARY, VARBINARY, LONGVARBINARY, NULL, OTHER, JAVA_OBJECT, DISTINCT, * STRUCT, ARRAY, BLOB, CLOB, REF</code> * * <p><strong>WARNING: YOU MAY WANT TO MAKE A BACKUP OF YOUR DATABASE BEFORE RUNNING DbLoader</strong></p> * * <p>DbLoader will perform the following steps: * <ol> * <li>Read configurable properties from <portal.home>/properties/dbloader.xml</li> * <li>Get database connection from RdbmServices * (reads JDBC database settings from <portal.home>/properties/rdbm.properties).</li> * <li>Read tables.xml and issue corresponding DROP TABLE and CREATE TABLE SQL statements.</li> * <li>Read data.xml and issue corresponding INSERT SQL statements.</li> * </ol></p> * * <p>You will need to set the system property "portal.home" For example, * java -Dportal.home=/usr/local/uPortal</p> * * @author Ken Weiner, [email protected] * @version $Revision$ * @see java.sql.Types * @since uPortal 2.0 */ public class DbLoader { private static URL propertiesURL; private static URL tablesURL; private static String tablesXslUri; private static Connection con; private static Statement stmt; private static PreparedStatement pstmt; private static RdbmServices rdbmService; private static Document tablesDoc; private static Document tablesDocGeneric; private static boolean createScript; private static boolean dropTables; private static boolean createTables; private static boolean populateTables; private static PrintWriter scriptOut; public static void main(String[] args) { try { System.setProperty("org.xml.sax.driver", PropertiesManager.getProperty("org.xml.sax.driver")); propertiesURL = DbLoader.class.getResource("/properties/dbloader.xml"); con = rdbmService.getConnection (); if (con != null) { long startTime = System.currentTimeMillis(); // Read in the properties XMLReader parser = getXMLReader(); printInfo(); readProperties(parser); // Read drop/create/populate table settings dropTables = Boolean.valueOf(PropertiesHandler.properties.getDropTables()).booleanValue(); createTables = Boolean.valueOf(PropertiesHandler.properties.getCreateTables()).booleanValue(); populateTables = Boolean.valueOf(PropertiesHandler.properties.getPopulateTables()).booleanValue(); // Set up script createScript = Boolean.valueOf(PropertiesHandler.properties.getCreateScript()).booleanValue(); if (createScript) initScript(); try { // Read tables.xml DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder domParser = dbf.newDocumentBuilder(); // Eventually, write and validate against a DTD //domParser.setFeature ("http://xml.org/sax/features/validation", true); //domParser.setEntityResolver(new DTDResolver("tables.dtd")); tablesURL = DbLoader.class.getResource(PropertiesHandler.properties.getTablesUri()); tablesDoc = domParser.parse(new InputSource(tablesURL.openStream())); } catch (ParserConfigurationException pce) { System.out.println("Unable to instantiate DOM parser. Pease check your JAXP configuration."); pce.printStackTrace(); } catch(Exception e) { System.out.println("Could not open " + tablesURL); e.printStackTrace(); return; } // Hold on to tables xml with generic types tablesDocGeneric = (Document)tablesDoc.cloneNode(true); // Replace all generic data types with local data types replaceDataTypes(tablesDoc); // tables.xml + tables.xsl --> DROP TABLE and CREATE TABLE sql statements tablesXslUri = PropertiesHandler.properties.getTablesXslUri(); XSLT xslt = new XSLT(new DbLoader()); xslt.setXML(tablesDoc); xslt.setXSL(tablesXslUri); xslt.setTarget(new TableHandler()); xslt.transform(); // data.xml --> INSERT sql statements readData(parser); System.out.println("Done!"); long endTime = System.currentTimeMillis(); System.out.println("Elapsed time: " + ((endTime - startTime) / 1000f) + " seconds"); exit(); } else System.out.println("DbLoader couldn't obtain a database connection."); } catch (Exception e) { e.printStackTrace(); } finally // call local exit method to clean up. This does not actually // do a system.exit() allowing a stack trace to the console in // the case of a run time error. { exit(); } } private static XMLReader getXMLReader() throws SAXException, ParserConfigurationException { SAXParserFactory spf=SAXParserFactory.newInstance(); return spf.newSAXParser().getXMLReader(); } private static void printInfo () throws SQLException { DatabaseMetaData dbMetaData = con.getMetaData(); String dbName = dbMetaData.getDatabaseProductName(); String dbVersion = dbMetaData.getDatabaseProductVersion(); String driverName = dbMetaData.getDriverName(); String driverVersion = dbMetaData.getDriverVersion(); String driverClass = rdbmService.getJdbcDriver(); String url = rdbmService.getJdbcUrl(); String user = rdbmService.getJdbcUser(); System.out.println("Starting DbLoader..."); System.out.println("Database name: '" + dbName + "'"); System.out.println("Database version: '" + dbVersion + "'"); System.out.println("Driver name: '" + driverName + "'"); System.out.println("Driver version: '" + driverVersion + "'"); System.out.println("Driver class: '" + driverClass + "'"); System.out.println("Connection URL: '" + url + "'"); System.out.println("User: '" + user + "'"); } private static void readData (XMLReader parser) throws SAXException, IOException { InputSource dataInSrc = new InputSource(DbLoader.class.getResourceAsStream(PropertiesHandler.properties.getDataUri())); DataHandler dataHandler = new DataHandler(); parser.setContentHandler(dataHandler); parser.setErrorHandler(dataHandler); parser.parse(dataInSrc); } private static void initScript() throws java.io.IOException { String scriptFileName = PropertiesHandler.properties.getScriptFileName(); File scriptFile = new File(scriptFileName); if (scriptFile.exists()) scriptFile.delete(); scriptFile.createNewFile(); scriptOut = new PrintWriter(new BufferedWriter(new FileWriter(scriptFileName, true))); } private static void replaceDataTypes (Document tablesDoc) { Element tables = tablesDoc.getDocumentElement(); NodeList types = tables.getElementsByTagName("type"); for (int i = 0; i < types.getLength(); i++) { Node type = (Node)types.item(i); NodeList typeChildren = type.getChildNodes(); for (int j = 0; j < typeChildren.getLength(); j++) { Node text = (Node)typeChildren.item(j); String genericType = text.getNodeValue(); // Replace generic type with mapped local type text.setNodeValue(getLocalDataTypeName(genericType)); } } } private static int getJavaSqlDataTypeOfColumn(Document tablesDocGeneric, String tableName, String columnName) { int dataType = 0; // Find the right table element Element table = getTableWithName(tablesDocGeneric, tableName); // Find the columns element within Element columns = getFirstChildWithName(table, "columns"); // Search for the first column who's name is columnName for (Node ch = columns.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Element && ch.getNodeName().equals("column")) { Element name = getFirstChildWithName((Element)ch, "name"); if (getNodeValue(name).equals(columnName)) { // Get the corresponding type and return it's type code Element value = getFirstChildWithName((Element)ch, "type"); dataType = getJavaSqlType(getNodeValue(value)); } } } return dataType; } private static Element getFirstChildWithName (Element parent, String name) { Element child = null; for (Node ch = parent.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Element && ch.getNodeName().equals(name)) { child = (Element)ch; break; } } return child; } private static Element getTableWithName (Document tablesDoc, String tableName) { Element tableElement = null; NodeList tables = tablesDoc.getElementsByTagName("table"); for (int i = 0; i < tables.getLength(); i++) { Node table = (Node)tables.item(i); for (Node tableChild = table.getFirstChild(); tableChild != null; tableChild = tableChild.getNextSibling()) { if (tableChild instanceof Element && tableChild.getNodeName() != null && tableChild.getNodeName().equals("name")) { if (tableName.equals(getNodeValue(tableChild))) { tableElement = (Element)table; break; } } } } return tableElement; } private static String getNodeValue (Node node) { String nodeVal = null; for (Node ch = node.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Text) nodeVal = ch.getNodeValue(); } return nodeVal; } private static String getLocalDataTypeName (String genericDataTypeName) { String localDataTypeName = null; try { DatabaseMetaData dbmd = con.getMetaData(); String dbName = dbmd.getDatabaseProductName(); String dbVersion = dbmd.getDatabaseProductVersion(); String driverName = dbmd.getDriverName(); String driverVersion = dbmd.getDriverVersion(); // Check for a mapping in DbLoader.xml localDataTypeName = PropertiesHandler.properties.getMappedDataTypeName(dbName, dbVersion, driverName, driverVersion, genericDataTypeName); if (localDataTypeName != null) return localDataTypeName; // Find the type code for this generic type name int dataTypeCode = getJavaSqlType(genericDataTypeName); // Find the first local type name matching the type code ResultSet rs = dbmd.getTypeInfo(); try { while (rs.next()) { int localDataTypeCode = rs.getInt("DATA_TYPE"); if (dataTypeCode == localDataTypeCode) { try { localDataTypeName = rs.getString("TYPE_NAME"); } catch (SQLException sqle) { } break; } } } finally { rs.close(); } if (localDataTypeName != null) return localDataTypeName; // No matching type found, report an error System.out.println("Your database driver, '"+ driverName + "', version '" + driverVersion + "', was unable to find a local type name that matches the generic type name, '" + genericDataTypeName + "'."); System.out.println("Please add a mapped type for database '" + dbName + "', version '" + dbVersion + "' inside '" + propertiesURL + "' and run this program again."); System.out.println("Exiting..."); exit(); } catch (Exception e) { e.printStackTrace(); exit(); } return null; } private static int getJavaSqlType (String genericDataTypeName) { // Find the type code for this generic type name int dataTypeCode = 0; if (genericDataTypeName.equalsIgnoreCase("BIT")) dataTypeCode = Types.BIT; // -7 else if (genericDataTypeName.equalsIgnoreCase("TINYINT")) dataTypeCode = Types.TINYINT; // -6 else if (genericDataTypeName.equalsIgnoreCase("SMALLINT")) dataTypeCode = Types.SMALLINT; // 5 else if (genericDataTypeName.equalsIgnoreCase("INTEGER")) dataTypeCode = Types.INTEGER; // 4 else if (genericDataTypeName.equalsIgnoreCase("BIGINT")) dataTypeCode = Types.BIGINT; // -5 else if (genericDataTypeName.equalsIgnoreCase("FLOAT")) dataTypeCode = Types.FLOAT; // 6 else if (genericDataTypeName.equalsIgnoreCase("REAL")) dataTypeCode = Types.REAL; // 7 else if (genericDataTypeName.equalsIgnoreCase("DOUBLE")) dataTypeCode = Types.DOUBLE; // 8 else if (genericDataTypeName.equalsIgnoreCase("NUMERIC")) dataTypeCode = Types.NUMERIC; // 2 else if (genericDataTypeName.equalsIgnoreCase("DECIMAL")) dataTypeCode = Types.DECIMAL; // 3 else if (genericDataTypeName.equalsIgnoreCase("CHAR")) dataTypeCode = Types.CHAR; // 1 else if (genericDataTypeName.equalsIgnoreCase("VARCHAR")) dataTypeCode = Types.VARCHAR; // 12 else if (genericDataTypeName.equalsIgnoreCase("LONGVARCHAR")) dataTypeCode = Types.LONGVARCHAR; // -1 else if (genericDataTypeName.equalsIgnoreCase("DATE")) dataTypeCode = Types.DATE; // 91 else if (genericDataTypeName.equalsIgnoreCase("TIME")) dataTypeCode = Types.TIME; // 92 else if (genericDataTypeName.equalsIgnoreCase("TIMESTAMP")) dataTypeCode = Types.TIMESTAMP; // 93 else if (genericDataTypeName.equalsIgnoreCase("BINARY")) dataTypeCode = Types.BINARY; // -2 else if (genericDataTypeName.equalsIgnoreCase("VARBINARY")) dataTypeCode = Types.VARBINARY; // -3 else if (genericDataTypeName.equalsIgnoreCase("LONGVARBINARY")) dataTypeCode = Types.LONGVARBINARY; // -4 else if (genericDataTypeName.equalsIgnoreCase("NULL")) dataTypeCode = Types.NULL; // 0 else if (genericDataTypeName.equalsIgnoreCase("OTHER")) dataTypeCode = Types.OTHER; // 1111 else if (genericDataTypeName.equalsIgnoreCase("JAVA_OBJECT")) dataTypeCode = Types.JAVA_OBJECT; // 2000 else if (genericDataTypeName.equalsIgnoreCase("DISTINCT")) dataTypeCode = Types.DISTINCT; // 2001 else if (genericDataTypeName.equalsIgnoreCase("STRUCT")) dataTypeCode = Types.STRUCT; // 2002 else if (genericDataTypeName.equalsIgnoreCase("ARRAY")) dataTypeCode = Types.ARRAY; // 2003 else if (genericDataTypeName.equalsIgnoreCase("BLOB")) dataTypeCode = Types.BLOB; // 2004 else if (genericDataTypeName.equalsIgnoreCase("CLOB")) dataTypeCode = Types.CLOB; // 2005 else if (genericDataTypeName.equalsIgnoreCase("REF")) dataTypeCode = Types.REF; // 2006 return dataTypeCode; } private static void dropTable (String dropTableStatement) { System.out.print("..."); if (createScript) scriptOut.println(dropTableStatement + PropertiesHandler.properties.getStatementTerminator()); try { stmt = con.createStatement(); try { stmt.executeUpdate(dropTableStatement); } catch (SQLException sqle) {/*Table didn't exist*/} } catch (Exception e) { e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } private static void createTable (String createTableStatement) { System.out.print("..."); if (createScript) scriptOut.println(createTableStatement + PropertiesHandler.properties.getStatementTerminator()); try { stmt = con.createStatement(); stmt.executeUpdate(createTableStatement); } catch (Exception e) { System.out.println(createTableStatement); e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } private static void readProperties (XMLReader parser) throws SAXException, IOException { PropertiesHandler propertiesHandler = new PropertiesHandler(); parser.setContentHandler(propertiesHandler); parser.setErrorHandler(propertiesHandler); parser.parse(new InputSource(propertiesURL.openStream())); } static class PropertiesHandler extends DefaultHandler { private static StringBuffer charBuff = null; static Properties properties; static DbTypeMapping dbTypeMapping; static Type type; public void startDocument () { System.out.print("Parsing " + propertiesURL + "..."); } public void endDocument () { System.out.println(""); } public void startElement (String namespaceURI, String localName, String qName, Attributes atts) { charBuff = new StringBuffer(); if (qName.equals("properties")) properties = new Properties(); else if (qName.equals("db-type-mapping")) dbTypeMapping = new DbTypeMapping(); else if (qName.equals("type")) type = new Type(); } public void endElement (String namespaceURI, String localName, String qName) { if (qName.equals("drop-tables")) // drop tables ("true" or "false") properties.setDropTables(charBuff.toString()); else if (qName.equals("create-tables")) // create tables ("true" or "false") properties.setCreateTables(charBuff.toString()); else if (qName.equals("populate-tables")) // populate tables ("true" or "false") properties.setPopulateTables(charBuff.toString()); else if (qName.equals("tables-uri")) // tables URI properties.setTablesUri(charBuff.toString()); else if (qName.equals("tables-xsl-uri")) // tables xsl URI properties.setTablesXslUri(charBuff.toString()); else if (qName.equals("data-uri")) // data xml URI properties.setDataUri(charBuff.toString()); else if (qName.equals("create-script")) // create script ("true" or "false") properties.setCreateScript(charBuff.toString()); else if (qName.equals("script-file-name")) // script file name properties.setScriptFileName(charBuff.toString()); else if (qName.equals("statement-terminator")) // statement terminator properties.setStatementTerminator(charBuff.toString()); else if (qName.equals("db-type-mapping")) properties.addDbTypeMapping(dbTypeMapping); else if (qName.equals("db-name")) // database name dbTypeMapping.setDbName(charBuff.toString()); else if (qName.equals("db-version")) // database version dbTypeMapping.setDbVersion(charBuff.toString()); else if (qName.equals("driver-name")) // driver name dbTypeMapping.setDriverName(charBuff.toString()); else if (qName.equals("driver-version")) // driver version dbTypeMapping.setDriverVersion(charBuff.toString()); else if (qName.equals("type")) dbTypeMapping.addType(type); else if (qName.equals("generic")) // generic type type.setGeneric(charBuff.toString()); else if (qName.equals("local")) // local type type.setLocal(charBuff.toString()); } public void characters (char ch[], int start, int length) { charBuff.append(ch, start, length); } class Properties { private String dropTables; private String createTables; private String populateTables; private String tablesUri; private String tablesXslUri; private String dataUri; private String dataXslUri; private String createScript; private String scriptFileName; private String statementTerminator; private ArrayList dbTypeMappings = new ArrayList(); public String getDropTables() { return dropTables; } public String getCreateTables() { return createTables; } public String getPopulateTables() { return populateTables; } public String getTablesUri() { return tablesUri; } public String getTablesXslUri() { return tablesXslUri; } public String getDataUri() { return dataUri; } public String getDataXslUri() { return dataXslUri; } public String getCreateScript() { return createScript; } public String getScriptFileName() { return scriptFileName; } public String getStatementTerminator() { return statementTerminator; } public ArrayList getDbTypeMappings() { return dbTypeMappings; } public void setDropTables(String dropTables) { this.dropTables = dropTables; } public void setCreateTables(String createTables) { this.createTables = createTables; } public void setPopulateTables(String populateTables) { this.populateTables = populateTables; } public void setTablesUri(String tablesUri) { this.tablesUri = tablesUri; } public void setTablesXslUri(String tablesXslUri) { this.tablesXslUri = tablesXslUri; } public void setDataUri(String dataUri) { this.dataUri = dataUri; } public void setDataXslUri(String dataXslUri) { this.dataXslUri = dataXslUri; } public void setCreateScript(String createScript) { this.createScript = createScript; } public void setScriptFileName(String scriptFileName) { this.scriptFileName = scriptFileName; } public void setStatementTerminator(String statementTerminator) { this.statementTerminator = statementTerminator; } public void addDbTypeMapping(DbTypeMapping dbTypeMapping) { dbTypeMappings.add(dbTypeMapping); } public String getMappedDataTypeName(String dbName, String dbVersion, String driverName, String driverVersion, String genericDataTypeName) { String mappedDataTypeName = null; Iterator iterator = dbTypeMappings.iterator(); while (iterator.hasNext()) { DbTypeMapping dbTypeMapping = (DbTypeMapping)iterator.next(); String dbNameProp = dbTypeMapping.getDbName(); String dbVersionProp = dbTypeMapping.getDbVersion(); String driverNameProp = dbTypeMapping.getDriverName(); String driverVersionProp = dbTypeMapping.getDriverVersion(); if (dbNameProp.equalsIgnoreCase(dbName) && dbVersionProp.equalsIgnoreCase(dbVersion) && driverNameProp.equalsIgnoreCase(driverName) && driverVersionProp.equalsIgnoreCase(driverVersion)) { // Found a matching database/driver combination mappedDataTypeName = dbTypeMapping.getMappedDataTypeName(genericDataTypeName); } } return mappedDataTypeName; } } class DbTypeMapping { String dbName; String dbVersion; String driverName; String driverVersion; ArrayList types = new ArrayList(); public String getDbName() { return dbName; } public String getDbVersion() { return dbVersion; } public String getDriverName() { return driverName; } public String getDriverVersion() { return driverVersion; } public ArrayList getTypes() { return types; } public void setDbName(String dbName) { this.dbName = dbName; } public void setDbVersion(String dbVersion) { this.dbVersion = dbVersion; } public void setDriverName(String driverName) { this.driverName = driverName; } public void setDriverVersion(String driverVersion) { this.driverVersion = driverVersion; } public void addType(Type type) { types.add(type); } public String getMappedDataTypeName(String genericDataTypeName) { String mappedDataTypeName = null; Iterator iterator = types.iterator(); while (iterator.hasNext()) { Type type = (Type)iterator.next(); if (type.getGeneric().equalsIgnoreCase(genericDataTypeName)) mappedDataTypeName = type.getLocal(); } return mappedDataTypeName; } } class Type { String genericType; // "generic" is a Java reserved word String local; public String getGeneric() { return genericType; } public String getLocal() { return local; } public void setGeneric(String genericType) { this.genericType = genericType; } public void setLocal(String local) { this.local = local; } } } static class TableHandler implements ContentHandler { private static final int UNSET = -1; private static final int DROP = 0; private static final int CREATE = 1; private static int mode = UNSET; private static StringBuffer stmtBuffer; public void startDocument () { } public void endDocument () { System.out.println(); } public void startElement (String namespaceURI, String localName, String qName, Attributes atts) { if (qName.equals("statement")) { stmtBuffer = new StringBuffer(1024); String statementType = atts.getValue("type"); if (mode == UNSET || mode == CREATE && statementType != null && statementType.equals("drop")) { mode = DROP; System.out.print("Dropping tables..."); if (!dropTables) System.out.print("disabled."); } else if (mode == UNSET || mode == DROP && statementType != null && statementType.equals("create")) { mode = CREATE; System.out.print("\nCreating tables..."); if (!createTables) System.out.print("disabled."); } } } public void endElement (String namespaceURI, String localName, String qName) { if (qName.equals("statement")) { String statement = stmtBuffer.toString(); switch (mode) { case DROP: if (dropTables) dropTable(statement); break; case CREATE: if (createTables) createTable(statement); break; default: break; } } } public void characters (char ch[], int start, int length) { stmtBuffer.append(ch, start, length); } public void setDocumentLocator (Locator locator) { } public void processingInstruction (String target, String data) { } public void ignorableWhitespace (char[] ch, int start, int length) { } public void startPrefixMapping (String prefix, String uri) throws SAXException {}; public void endPrefixMapping (String prefix) throws SAXException {}; public void skippedEntity(String name) throws SAXException {}; } static class DataHandler extends DefaultHandler { private static StringBuffer charBuff = null; private static boolean insideData = false; private static boolean insideTable = false; private static boolean insideName = false; private static boolean insideRow = false; private static boolean insideColumn = false; private static boolean insideValue = false; private static boolean supportsPreparedStatements = false; static Table table; static Row row; static Column column; public void startDocument () { System.out.print("Populating tables..."); if (!populateTables) System.out.print("disabled."); supportsPreparedStatements = supportsPreparedStatements(); } public void endDocument () { System.out.println(""); } public void startElement (String namespaceURI, String localName, String qName, Attributes atts) { charBuff = new StringBuffer(); if (qName.equals("data")) insideData = true; else if (qName.equals("table")) { insideTable = true; table = new Table(); } else if (qName.equals("name")) insideName = true; else if (qName.equals("row")) { insideRow = true; row = new Row(); } else if (qName.equals("column")) { insideColumn = true; column = new Column(); } else if (qName.equals("value")) insideValue = true; } public void endElement (String namespaceURI, String localName, String qName) { if (qName.equals("data")) insideData = false; else if (qName.equals("table")) insideTable = false; else if (qName.equals("name")) { insideName = false; if (!insideColumn) // table name table.setName(charBuff.toString()); else // column name column.setName(charBuff.toString()); } else if (qName.equals("row")) { insideRow = false; if (populateTables) insertRow(table, row); } else if (qName.equals("column")) { insideColumn = false; row.addColumn(column); } else if (qName.equals("value")) { insideValue = false; if (insideColumn) // column value column.setValue(charBuff.toString()); } } public void characters (char ch[], int start, int length) { charBuff.append(ch, start, length); } private String prepareInsertStatement (Row row, boolean preparedStatement) { StringBuffer sb = new StringBuffer("INSERT INTO "); sb.append(table.getName()).append(" ("); ArrayList columns = row.getColumns(); Iterator iterator = columns.iterator(); while (iterator.hasNext()) { Column column = (Column)iterator.next(); sb.append(column.getName()).append(", "); } // Delete comma and space after last column name (kind of sloppy, but it works) sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.append(") VALUES ("); iterator = columns.iterator(); while (iterator.hasNext()) { Column column = (Column)iterator.next(); if (preparedStatement) sb.append("?"); else { String value = column.getValue(); if (value != null) { if (value.equals("SYSDATE")) sb.append(value); else if (value.equals("NULL")) sb.append(value); else if (getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()) == Types.INTEGER) // this column is an integer, so don't put quotes (Sybase cares about this) sb.append(value); else { sb.append("'"); sb.append(value.trim()); sb.append("'"); } } else sb.append("''"); } sb.append(", "); } // Delete comma and space after last value (kind of sloppy, but it works) sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.append(")"); return sb.toString(); } private void insertRow (Table table, Row row) { System.out.print("..."); if (createScript) scriptOut.println(prepareInsertStatement(row, false) + PropertiesHandler.properties.getStatementTerminator()); if (supportsPreparedStatements) { String preparedStatement = ""; try { preparedStatement = prepareInsertStatement(row, true); //System.out.println(preparedStatement); pstmt = con.prepareStatement(preparedStatement); pstmt.clearParameters (); // Loop through parameters and set them, checking for any that excede 4k ArrayList columns = row.getColumns(); Iterator iterator = columns.iterator(); for (int i = 1; iterator.hasNext(); i++) { Column column = (Column)iterator.next(); String value = column.getValue(); // Get a java sql data type for column name int javaSqlDataType = getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()); if (value == null) pstmt.setString(i, ""); else if (value.equals("NULL")) pstmt.setNull(i, javaSqlDataType); else if (javaSqlDataType == Types.TIMESTAMP) { if (value.equals("SYSDATE")) pstmt.setTimestamp(i, new java.sql.Timestamp(System.currentTimeMillis())); else pstmt.setTimestamp(i, java.sql.Timestamp.valueOf(value)); } else { value = value.trim(); // portal can't read xml properly without this, don't know why yet int valueLength = value.length(); if (valueLength <= 4000) { try { // Needed for Sybase and maybe others pstmt.setObject(i, value, javaSqlDataType); } catch (Exception e) { // Needed for Oracle and maybe others pstmt.setObject(i, value); } } else { try { try { // Needed for Sybase and maybe others pstmt.setObject(i, value, javaSqlDataType); } catch (Exception e) { // Needed for Oracle and maybe others pstmt.setObject(i, value); } } catch (SQLException sqle) { // For Oracle and maybe others pstmt.setCharacterStream(i, new StringReader(value), valueLength); } } } } pstmt.executeUpdate(); } catch (SQLException sqle) { System.err.println(); System.err.println(preparedStatement); sqle.printStackTrace(); } catch (Exception e) { System.err.println(); e.printStackTrace(); } finally { try { pstmt.close(); } catch (Exception e) { } } } else { // If prepared statements aren't supported, try a normal insert statement String insertStatement = prepareInsertStatement(row, false); //System.out.println(insertStatement); try { stmt = con.createStatement(); stmt.executeUpdate(insertStatement); } catch (Exception e) { System.err.println(); System.err.println(insertStatement); e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } } private static boolean supportsPreparedStatements() { boolean supportsPreparedStatements = true; try { // Issue a prepared statement to see if database/driver accepts them. // The assumption is that if a SQLException is thrown, it doesn't support them. // I don't know of any other way to check if the database/driver accepts // prepared statements. If you do, please change this method! Statement stmt; stmt = con.createStatement(); try { stmt.executeUpdate("CREATE TABLE PREP_TEST (A VARCHAR(1))"); } catch (Exception e){/* Assume it already exists */ } finally { try {stmt.close();} catch (Exception e) { } } pstmt = con.prepareStatement("SELECT A FROM PREP_TEST WHERE A=?"); pstmt.clearParameters (); pstmt.setString(1, "D"); pstmt.executeQuery(); } catch (SQLException sqle) { supportsPreparedStatements = false; sqle.printStackTrace(); } finally { try { stmt = con.createStatement(); stmt.executeUpdate("DROP TABLE PREP_TEST"); } catch (Exception e){/* Assume it already exists */ } finally { try {stmt.close();} catch (Exception e) { } } try { pstmt.close(); } catch (Exception e) { } } return supportsPreparedStatements; } class Table { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Row { ArrayList columns = new ArrayList(); public ArrayList getColumns() { return columns; } public void addColumn(Column column) { columns.add(column); } } class Column { private String name; private String value; public String getName() { return name; } public String getValue() { return value; } public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } } } private static void exit() { rdbmService.releaseConnection(con); if (scriptOut != null) scriptOut.close(); } }
Changed some comments and error message for when DbLoader can't obtain a database connection git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@5493 f5dbab47-78f9-eb45-b975-e544023573eb
source/org/jasig/portal/tools/DbLoader.java
Changed some comments and error message for when DbLoader can't obtain a database connection
Java
apache-2.0
4b18b37c1940c3828edac0988edbf47fe64652cd
0
Dsuarezj/TWU-Biblioteca-Denisse
package com.twu.biblioteca; import java.util.Arrays; import java.util.List; import java.util.Scanner; class Menu { private List<String> mainMenu = Arrays.asList("List of Books", "List of Movies", "Quit"); Biblioteca biblioteca = new Biblioteca(); int userInput; void displayWelcome() { String bibliotecaName = "Bangalore Public Library"; String welcomeMessage = "Welcome to: " + bibliotecaName; System.out.println(welcomeMessage); } void readInput() { Scanner input = new Scanner(System.in); userInput = input.nextInt(); } int getInput() { readInput(); return userInput; } void displayMenu(List<String> menuItems) { System.out.println("++++++++++ Menu Option ++++++++++"); displayAListOfItems(menuItems); } void selectMainMenuOption() { while (userInput != mainMenu.size()) { BorrowReturnMenu borrowReturnMenu = new BorrowReturnMenu(); switch (userInput) { case 1: borrowReturnMenu.displayItemList(Biblioteca.section.BOOK); return; case 2: borrowReturnMenu.displayItemList(Biblioteca.section.MOVIE); return; default: System.out.printf("You chose wrong, try again. Select the option number \n"); readInput(); } } System.out.printf("Come back again"); System.exit(0); } void callMainMenu() { displayMenu(getMainMenu()); getInput(); selectMainMenuOption(); } List<String> getMainMenu() { return mainMenu; } private void displayAListOfItems(List<String> items) { for (int i = 0; i < items.size(); i++) { System.out.print((i + 1) + ". " + items.get(i) + "\t"); } System.out.println(); System.out.println("Select the option number"); } }
src/com/twu/biblioteca/Menu.java
package com.twu.biblioteca; import java.util.Arrays; import java.util.List; import java.util.Scanner; class Menu { private List<String> mainMenu = Arrays.asList("List of Books", "List of Movies", "Quit"); Biblioteca biblioteca = new Biblioteca(); int userInput; void displayWelcome() { String bibliotecaName = "Bangalore Public Library"; String welcomeMessage = "Welcome to: " + bibliotecaName; System.out.println(welcomeMessage); } void readInput() { Scanner input = new Scanner(System.in); userInput = input.nextInt(); } int getInput() { readInput(); return userInput; } void displayMenu(List<String> menuItems) { System.out.println("++++++++++ Menu Option ++++++++++"); buildAListOfItems(menuItems); } void selectMainMenuOption() { while (userInput != mainMenu.size()) { BorrowReturnMenu borrowReturnMenu = new BorrowReturnMenu(); switch (userInput) { case 1: borrowReturnMenu.displayItemList(Biblioteca.section.BOOK); return; case 2: borrowReturnMenu.displayItemList(Biblioteca.section.MOVIE); return; default: System.out.printf("You chose wrong, try again. Select the option number \n"); readInput(); } } System.out.printf("Come back again"); System.exit(0); } void callMainMenu() { displayMenu(getMainMenu()); getInput(); selectMainMenuOption(); } List<String> getMainMenu() { return mainMenu; } private void buildAListOfItems(List<String> items) { for (int i = 0; i < items.size(); i++) { System.out.print((i + 1) + ". " + items.get(i) + "\t"); } System.out.println(); System.out.println("Select the option number"); } }
refactor Menu
src/com/twu/biblioteca/Menu.java
refactor Menu
Java
apache-2.0
8c9df2df7a034ad0cf24c24778e41c7b1f644bd4
0
google/closure-templates,google/closure-templates,google/closure-templates,google/closure-templates,yext/closure-templates,yext/closure-templates,yext/closure-templates,google/closure-templates,yext/closure-templates
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.exprtree; import static com.google.common.base.Preconditions.checkArgument; import static com.google.template.soy.exprtree.Operator.Associativity.LEFT; import static com.google.template.soy.exprtree.Operator.Associativity.RIGHT; import static com.google.template.soy.exprtree.Operator.Constants.OPERAND_0; import static com.google.template.soy.exprtree.Operator.Constants.OPERAND_1; import static com.google.template.soy.exprtree.Operator.Constants.OPERAND_2; import static com.google.template.soy.exprtree.Operator.Constants.SP; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableTable; import com.google.errorprone.annotations.Immutable; import com.google.template.soy.base.SourceLocation; import com.google.template.soy.exprtree.ExprNode.OperatorNode; import com.google.template.soy.exprtree.OperatorNodes.AndOpNode; import com.google.template.soy.exprtree.OperatorNodes.ConditionalOpNode; import com.google.template.soy.exprtree.OperatorNodes.DivideByOpNode; import com.google.template.soy.exprtree.OperatorNodes.EqualOpNode; import com.google.template.soy.exprtree.OperatorNodes.GreaterThanOpNode; import com.google.template.soy.exprtree.OperatorNodes.GreaterThanOrEqualOpNode; import com.google.template.soy.exprtree.OperatorNodes.LessThanOpNode; import com.google.template.soy.exprtree.OperatorNodes.LessThanOrEqualOpNode; import com.google.template.soy.exprtree.OperatorNodes.MinusOpNode; import com.google.template.soy.exprtree.OperatorNodes.ModOpNode; import com.google.template.soy.exprtree.OperatorNodes.NegativeOpNode; import com.google.template.soy.exprtree.OperatorNodes.NotEqualOpNode; import com.google.template.soy.exprtree.OperatorNodes.NotOpNode; import com.google.template.soy.exprtree.OperatorNodes.NullCoalescingOpNode; import com.google.template.soy.exprtree.OperatorNodes.OrOpNode; import com.google.template.soy.exprtree.OperatorNodes.PlusOpNode; import com.google.template.soy.exprtree.OperatorNodes.TimesOpNode; import java.util.List; import javax.annotation.Nullable; /** * Enum of Soy expression operators. * * <p>Important: Do not use outside of Soy code (treat as superpackage-private). * */ public enum Operator { NEGATIVE(ImmutableList.of(new Token("-"), OPERAND_0), 8, RIGHT, "- (unary)") { @Override public OperatorNode createNode(SourceLocation location) { return new NegativeOpNode(location); } }, NOT(ImmutableList.of(new Token("not"), SP, OPERAND_0), 8, RIGHT) { @Override public OperatorNode createNode(SourceLocation location) { return new NotOpNode(location); } }, TIMES(ImmutableList.of(OPERAND_0, SP, new Token("*"), SP, OPERAND_1), 7, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new TimesOpNode(location); } }, DIVIDE_BY(ImmutableList.of(OPERAND_0, SP, new Token("/"), SP, OPERAND_1), 7, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new DivideByOpNode(location); } }, MOD(ImmutableList.of(OPERAND_0, SP, new Token("%"), SP, OPERAND_1), 7, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new ModOpNode(location); } }, PLUS(ImmutableList.of(OPERAND_0, SP, new Token("+"), SP, OPERAND_1), 6, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new PlusOpNode(location); } }, MINUS(ImmutableList.of(OPERAND_0, SP, new Token("-"), SP, OPERAND_1), 6, LEFT, "- (binary)") { @Override public OperatorNode createNode(SourceLocation location) { return new MinusOpNode(location); } }, LESS_THAN(ImmutableList.of(OPERAND_0, SP, new Token("<"), SP, OPERAND_1), 5, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new LessThanOpNode(location); } }, GREATER_THAN(ImmutableList.of(OPERAND_0, SP, new Token(">"), SP, OPERAND_1), 5, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new GreaterThanOpNode(location); } }, LESS_THAN_OR_EQUAL(ImmutableList.of(OPERAND_0, SP, new Token("<="), SP, OPERAND_1), 5, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new LessThanOrEqualOpNode(location); } }, GREATER_THAN_OR_EQUAL(ImmutableList.of(OPERAND_0, SP, new Token(">="), SP, OPERAND_1), 5, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new GreaterThanOrEqualOpNode(location); } }, EQUAL(ImmutableList.of(OPERAND_0, SP, new Token("=="), SP, OPERAND_1), 4, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new EqualOpNode(location); } }, NOT_EQUAL(ImmutableList.of(OPERAND_0, SP, new Token("!="), SP, OPERAND_1), 4, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new NotEqualOpNode(location); } }, AND(ImmutableList.of(OPERAND_0, SP, new Token("and"), SP, OPERAND_1), 3, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new AndOpNode(location); } }, OR(ImmutableList.of(OPERAND_0, SP, new Token("or"), SP, OPERAND_1), 2, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new OrOpNode(location); } }, NULL_COALESCING(ImmutableList.of(OPERAND_0, SP, new Token("?:"), SP, OPERAND_1), 1, RIGHT) { @Override public OperatorNode createNode(SourceLocation location) { return new NullCoalescingOpNode(location); } }, CONDITIONAL( ImmutableList.of( OPERAND_0, SP, new Token("?"), SP, OPERAND_1, SP, new Token(":"), SP, OPERAND_2), 1, RIGHT) { @Override public OperatorNode createNode(SourceLocation location) { return new ConditionalOpNode(location); } }, ; /** Constants used in the enum definitions above. */ static class Constants { static final Spacer SP = new Spacer(); static final Operand OPERAND_0 = new Operand(0); static final Operand OPERAND_1 = new Operand(1); static final Operand OPERAND_2 = new Operand(2); } // ----------------------------------------------------------------------------------------------- /** Map used for fetching an Operator from the pair (tokenString, numOperands). */ private static final ImmutableTable<String, Integer, Operator> OPERATOR_TABLE; static { ImmutableTable.Builder<String, Integer, Operator> builder = ImmutableTable.builder(); for (Operator op : Operator.values()) { builder.put(op.getTokenString(), op.getNumOperands(), op); } OPERATOR_TABLE = builder.build(); } /** * Create an operator node, given the token, precedence, and list of children (arguments). * * @param op A string listing the operator token. If multiple tokens (e.g. the ternary conditional * operator), separate them using a space. * @param prec The precedence of an operator. Must match the precedence specified by {@code op}. * @param children The list of children (arguments) for the operator. * @return The matching OperatorNode. * @throws IllegalArgumentException If there is no Soy operator matching the given data. */ public static final OperatorNode createOperatorNode( SourceLocation location, String op, int prec, ExprNode... children) { checkArgument(OPERATOR_TABLE.containsRow(op)); Operator operator = OPERATOR_TABLE.get(op, children.length); if (operator.getPrecedence() != prec) { throw new IllegalArgumentException("invalid precedence " + prec + " for operator " + op); } return operator.createNode(location, children); } // ----------------------------------------------------------------------------------------------- /** The canonical syntax for this operator, including spacing. */ private final ImmutableList<SyntaxElement> syntax; /** * This operator's token. Multiple tokens (e.g. the ternary conditional operator) are separated * using a space. */ private final String tokenString; /** The number of operands that this operator takes. */ private final int numOperands; /** This operator's precedence level. */ private final int precedence; /** This operator's associativity. */ private final Associativity associativity; /** A short description of this operator (usually just the token string). */ private final String description; /** * Constructor that doesn't specify a description string (defaults to using the token string). * * @param syntax The canonical syntax for this operator, including spacing. * @param precedence This operator's precedence level. * @param associativity This operator's associativity. */ private Operator( ImmutableList<SyntaxElement> syntax, int precedence, Associativity associativity) { this(syntax, precedence, associativity, /* description= */ null); } /** * Constructor that specifies a description string. * * @param syntax The canonical syntax for this operator, including spacing. * @param precedence This operator's precedence level. * @param associativity This operator's associativity. * @param description A short description of this operator. */ private Operator( ImmutableList<SyntaxElement> syntax, int precedence, Associativity associativity, @Nullable String description) { this.syntax = syntax; String tokenString = null; int numOperands = 0; for (SyntaxElement syntaxEl : syntax) { if (syntaxEl instanceof Operand) { numOperands += 1; } else if (syntaxEl instanceof Token) { if (tokenString == null) { tokenString = ((Token) syntaxEl).getValue(); } else { tokenString += " " + ((Token) syntaxEl).getValue(); } } } checkArgument(tokenString != null && numOperands > 0); this.tokenString = tokenString; this.numOperands = numOperands; this.precedence = precedence; this.associativity = associativity; this.description = (description != null) ? description : tokenString; } /** Returns the canonical syntax for this operator, including spacing. */ public List<SyntaxElement> getSyntax() { return syntax; } /** * Returns this operator's token. Multiple tokens (e.g. the ternary conditional operator) are * separated using a space. */ public String getTokenString() { return tokenString; } /** Returns the number of operands that this operator takes. */ public int getNumOperands() { return numOperands; } /** Whether this is a binary operand. */ public boolean isBinary() { return getNumOperands() == 2; } /** Returns this operator's precedence level. */ public int getPrecedence() { return precedence; } /** Returns this operator's associativity. */ public Associativity getAssociativity() { return associativity; } /** Returns a short description of this operator (usually just the token string). */ public String getDescription() { return description; } /** Creates a node representing this operator. */ public abstract OperatorNode createNode(SourceLocation location); /** Creates a node representing this operator, with the given children. */ public final OperatorNode createNode(SourceLocation location, ExprNode... children) { checkArgument(children.length == getNumOperands()); OperatorNode node = createNode(location); for (ExprNode child : children) { node.addChild(child); } return node; } // ----------------------------------------------------------------------------------------------- /** Enum for an operator's associativity. */ public static enum Associativity { /** Left-to-right. */ LEFT, /** Right-to-left. */ RIGHT } /** Represents a syntax element (used in a syntax specification for an operator). */ @Immutable public static interface SyntaxElement {} /** A syntax element for an operand. */ @Immutable public static class Operand implements SyntaxElement { private final int index; private Operand(int index) { this.index = index; } /** Returns the index of this operand. */ public int getIndex() { return index; } } /** A syntax element for a token. */ @Immutable public static class Token implements SyntaxElement { private final String value; private Token(String value) { this.value = value; } /** Returns this token's string literal. */ public String getValue() { return value; } } /** A syntax element for a space character. */ @Immutable public static class Spacer implements SyntaxElement { private Spacer() {} } }
java/src/com/google/template/soy/exprtree/Operator.java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.exprtree; import static com.google.common.base.Preconditions.checkArgument; import static com.google.template.soy.exprtree.Operator.Associativity.LEFT; import static com.google.template.soy.exprtree.Operator.Associativity.RIGHT; import static com.google.template.soy.exprtree.Operator.Constants.OPERAND_0; import static com.google.template.soy.exprtree.Operator.Constants.OPERAND_1; import static com.google.template.soy.exprtree.Operator.Constants.OPERAND_2; import static com.google.template.soy.exprtree.Operator.Constants.SP; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableTable; import com.google.errorprone.annotations.Immutable; import com.google.template.soy.base.SourceLocation; import com.google.template.soy.exprtree.ExprNode.OperatorNode; import com.google.template.soy.exprtree.OperatorNodes.AndOpNode; import com.google.template.soy.exprtree.OperatorNodes.ConditionalOpNode; import com.google.template.soy.exprtree.OperatorNodes.DivideByOpNode; import com.google.template.soy.exprtree.OperatorNodes.EqualOpNode; import com.google.template.soy.exprtree.OperatorNodes.GreaterThanOpNode; import com.google.template.soy.exprtree.OperatorNodes.GreaterThanOrEqualOpNode; import com.google.template.soy.exprtree.OperatorNodes.LessThanOpNode; import com.google.template.soy.exprtree.OperatorNodes.LessThanOrEqualOpNode; import com.google.template.soy.exprtree.OperatorNodes.MinusOpNode; import com.google.template.soy.exprtree.OperatorNodes.ModOpNode; import com.google.template.soy.exprtree.OperatorNodes.NegativeOpNode; import com.google.template.soy.exprtree.OperatorNodes.NotEqualOpNode; import com.google.template.soy.exprtree.OperatorNodes.NotOpNode; import com.google.template.soy.exprtree.OperatorNodes.NullCoalescingOpNode; import com.google.template.soy.exprtree.OperatorNodes.OrOpNode; import com.google.template.soy.exprtree.OperatorNodes.PlusOpNode; import com.google.template.soy.exprtree.OperatorNodes.TimesOpNode; import java.util.List; import javax.annotation.Nullable; /** * Enum of Soy expression operators. * * <p>Important: Do not use outside of Soy code (treat as superpackage-private). * */ public enum Operator { NEGATIVE(ImmutableList.of(new Token("-"), OPERAND_0), 8, RIGHT, "- (unary)") { @Override public OperatorNode createNode(SourceLocation location) { return new NegativeOpNode(location); } }, NOT(ImmutableList.of(new Token("not"), SP, OPERAND_0), 8, RIGHT) { @Override public OperatorNode createNode(SourceLocation location) { return new NotOpNode(location); } }, TIMES(ImmutableList.of(OPERAND_0, SP, new Token("*"), SP, OPERAND_1), 7, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new TimesOpNode(location); } }, DIVIDE_BY(ImmutableList.of(OPERAND_0, SP, new Token("/"), SP, OPERAND_1), 7, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new DivideByOpNode(location); } }, MOD(ImmutableList.of(OPERAND_0, SP, new Token("%"), SP, OPERAND_1), 7, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new ModOpNode(location); } }, PLUS(ImmutableList.of(OPERAND_0, SP, new Token("+"), SP, OPERAND_1), 6, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new PlusOpNode(location); } }, MINUS(ImmutableList.of(OPERAND_0, SP, new Token("-"), SP, OPERAND_1), 6, LEFT, "- (binary)") { @Override public OperatorNode createNode(SourceLocation location) { return new MinusOpNode(location); } }, LESS_THAN(ImmutableList.of(OPERAND_0, SP, new Token("<"), SP, OPERAND_1), 5, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new LessThanOpNode(location); } }, GREATER_THAN(ImmutableList.of(OPERAND_0, SP, new Token(">"), SP, OPERAND_1), 5, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new GreaterThanOpNode(location); } }, LESS_THAN_OR_EQUAL(ImmutableList.of(OPERAND_0, SP, new Token("<="), SP, OPERAND_1), 5, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new LessThanOrEqualOpNode(location); } }, GREATER_THAN_OR_EQUAL(ImmutableList.of(OPERAND_0, SP, new Token(">="), SP, OPERAND_1), 5, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new GreaterThanOrEqualOpNode(location); } }, EQUAL(ImmutableList.of(OPERAND_0, SP, new Token("=="), SP, OPERAND_1), 4, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new EqualOpNode(location); } }, NOT_EQUAL(ImmutableList.of(OPERAND_0, SP, new Token("!="), SP, OPERAND_1), 4, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new NotEqualOpNode(location); } }, AND(ImmutableList.of(OPERAND_0, SP, new Token("and"), SP, OPERAND_1), 3, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new AndOpNode(location); } }, OR(ImmutableList.of(OPERAND_0, SP, new Token("or"), SP, OPERAND_1), 2, LEFT) { @Override public OperatorNode createNode(SourceLocation location) { return new OrOpNode(location); } }, NULL_COALESCING(ImmutableList.of(OPERAND_0, SP, new Token("?:"), SP, OPERAND_1), 1, RIGHT) { @Override public OperatorNode createNode(SourceLocation location) { return new NullCoalescingOpNode(location); } }, CONDITIONAL( ImmutableList.of( OPERAND_0, SP, new Token("?"), SP, OPERAND_1, SP, new Token(":"), SP, OPERAND_2), 1, RIGHT) { @Override public OperatorNode createNode(SourceLocation location) { return new ConditionalOpNode(location); } }, ; /** Constants used in the enum definitions above. */ static class Constants { static final Spacer SP = new Spacer(); static final Operand OPERAND_0 = new Operand(0); static final Operand OPERAND_1 = new Operand(1); static final Operand OPERAND_2 = new Operand(2); } // ----------------------------------------------------------------------------------------------- /** Map used for fetching an Operator from the pair (tokenString, numOperands). */ private static final ImmutableTable<String, Integer, Operator> OPERATOR_TABLE; static { ImmutableTable.Builder<String, Integer, Operator> builder = ImmutableTable.builder(); for (Operator op : Operator.values()) { builder.put(op.getTokenString(), op.getNumOperands(), op); } OPERATOR_TABLE = builder.build(); } /** * Create an operator node, given the token, precedence, and list of children (arguments). * * @param op A string listing the operator token. If multiple tokens (e.g. the ternary conditional * operator), separate them using a space. * @param prec The precedence of an operator. Must match the precedence specified by {@code op}. * @param children The list of children (arguments) for the operator. * @return The matching OperatorNode. * @throws IllegalArgumentException If there is no Soy operator matching the given data. */ public static final OperatorNode createOperatorNode( SourceLocation location, String op, int prec, ExprNode... children) { checkArgument(OPERATOR_TABLE.containsRow(op)); Operator operator = OPERATOR_TABLE.get(op, children.length); if (operator.getPrecedence() != prec) { throw new IllegalArgumentException("invalid precedence " + prec + " for operator " + op); } return operator.createNode(location, children); } // ----------------------------------------------------------------------------------------------- /** The canonical syntax for this operator, including spacing. */ private final ImmutableList<SyntaxElement> syntax; /** * This operator's token. Multiple tokens (e.g. the ternary conditional operator) are separated * using a space. */ private final String tokenString; /** The number of operands that this operator takes. */ private final int numOperands; /** This operator's precedence level. */ private final int precedence; /** This operator's associativity. */ private final Associativity associativity; /** A short description of this operator (usually just the token string). */ private final String description; /** * Constructor that doesn't specify a description string (defaults to using the token string). * * @param syntax The canonical syntax for this operator, including spacing. * @param precedence This operator's precedence level. * @param associativity This operator's associativity. */ private Operator( ImmutableList<SyntaxElement> syntax, int precedence, Associativity associativity) { this(syntax, precedence, associativity, /* description= */ null); } /** * Constructor that specifies a description string. * * @param syntax The canonical syntax for this operator, including spacing. * @param precedence This operator's precedence level. * @param associativity This operator's associativity. * @param description A short description of this operator. */ private Operator( ImmutableList<SyntaxElement> syntax, int precedence, Associativity associativity, @Nullable String description) { this.syntax = syntax; String tokenString = null; int numOperands = 0; for (SyntaxElement syntaxEl : syntax) { if (syntaxEl instanceof Operand) { numOperands += 1; } else if (syntaxEl instanceof Token) { if (tokenString == null) { tokenString = ((Token) syntaxEl).getValue(); } else { tokenString += " " + ((Token) syntaxEl).getValue(); } } } checkArgument(tokenString != null && numOperands > 0); this.tokenString = tokenString; this.numOperands = numOperands; this.precedence = precedence; this.associativity = associativity; this.description = (description != null) ? description : tokenString; } /** Returns the canonical syntax for this operator, including spacing. */ public List<SyntaxElement> getSyntax() { return syntax; } /** * Returns this operator's token. Multiple tokens (e.g. the ternary conditional operator) are * separated using a space. */ public String getTokenString() { return tokenString; } /** Returns the number of operands that this operator takes. */ public int getNumOperands() { return numOperands; } /** Returns this operator's precedence level. */ public int getPrecedence() { return precedence; } /** Returns this operator's associativity. */ public Associativity getAssociativity() { return associativity; } /** Returns a short description of this operator (usually just the token string). */ public String getDescription() { return description; } /** Creates a node representing this operator. */ public abstract OperatorNode createNode(SourceLocation location); /** Creates a node representing this operator, with the given children. */ public final OperatorNode createNode(SourceLocation location, ExprNode... children) { checkArgument(children.length == getNumOperands()); OperatorNode node = createNode(location); for (ExprNode child : children) { node.addChild(child); } return node; } // ----------------------------------------------------------------------------------------------- /** Enum for an operator's associativity. */ public static enum Associativity { /** Left-to-right. */ LEFT, /** Right-to-left. */ RIGHT } /** Represents a syntax element (used in a syntax specification for an operator). */ @Immutable public static interface SyntaxElement {} /** A syntax element for an operand. */ @Immutable public static class Operand implements SyntaxElement { private final int index; private Operand(int index) { this.index = index; } /** Returns the index of this operand. */ public int getIndex() { return index; } } /** A syntax element for a token. */ @Immutable public static class Token implements SyntaxElement { private final String value; private Token(String value) { this.value = value; } /** Returns this token's string literal. */ public String getValue() { return value; } } /** A syntax element for a space character. */ @Immutable public static class Spacer implements SyntaxElement { private Spacer() {} } }
Add nested expr formatting. GITHUB_BREAKING_CHANGES=NA ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=297943905
java/src/com/google/template/soy/exprtree/Operator.java
Add nested expr formatting.
Java
apache-2.0
f51c2b8e078059b5ae11dd0255941f9bf710b946
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.command.err; import org.smoothbuild.problem.Error; public class CommandLineError extends Error { public CommandLineError(String message) { super(null, "Incorrect command line\n " + message); } }
src/java/org/smoothbuild/command/err/CommandLineError.java
package org.smoothbuild.command.err; import org.smoothbuild.problem.Error; public class CommandLineError extends Error { public CommandLineError(String message) { super(null, "Incorrect command line:\n" + message); } }
improved error message in CommandLineError
src/java/org/smoothbuild/command/err/CommandLineError.java
improved error message in CommandLineError
Java
apache-2.0
44cf671ae7a9a8ca95e136571849cf14a84a48d8
0
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
/** * Copyright 2007-2008 University Of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.isi.pegasus.planner.dax; import java.util.List; import java.util.LinkedList; import java.util.Collections; import edu.isi.pegasus.common.logging.LogManager; import edu.isi.pegasus.common.logging.LogManagerFactory; import edu.isi.pegasus.common.util.Separator; import edu.isi.pegasus.common.util.XMLWriter; import java.util.LinkedHashSet; import java.util.Set; /** * * @author gmehta * @version $Revision$ */ public class AbstractJob { protected List mArguments; protected List<Profile> mProfiles; protected File mStdin; protected File mStdout; protected File mStderr; protected Set<File> mUses; protected List<Invoke> mInvokes; protected String mName; protected String mId; protected String mNamespace; protected String mVersion; protected String mNodeLabel; protected static LogManager mLogger; private static final String ARG_DELIMITER = " "; private static final String FILE_DELIMITER = " "; protected AbstractJob() { mLogger = LogManagerFactory.loadSingletonInstance(); mArguments = new LinkedList(); mUses = new LinkedHashSet<File>(); mInvokes = new LinkedList<Invoke>(); mProfiles = new LinkedList<Profile>(); } protected static void checkID(String id) { if (!Patterns.isNodeIdValid(id)) { mLogger.log( "Id: " + id + " should of the type [A-Za-z0-9][-A-Za-z0-9]*", LogManager.ERROR_MESSAGE_LEVEL); } } /** * Return the argument List. The List contains both {@link String} as well as {@link File} objects * @return List */ public List getArguments() { return Collections.unmodifiableList(mArguments); } /** * Add a string argument to the argument List. Each call to argument adds a space in between entries * @param argument * @return AbstractJob */ public AbstractJob addArgument(String argument) { if (argument != null) { if (!mArguments.isEmpty()) { mArguments.add(ARG_DELIMITER); } mArguments.add(argument); } return this; } /** * Add a file object to the argument List. Each call to argument adds a space between entries. * @param file * @return AbstractJob * @see File */ public AbstractJob addArgument(File file) { if (file != null) { if (!mArguments.isEmpty()) { mArguments.add(ARG_DELIMITER); } mArguments.add(file); } return this; } /** * Add a Array of {@link File} objects to the argument list. The files will be separated by space when rendered on the command line * @param files File[] * @return AbstractJob * @see File */ public AbstractJob addArgument(File[] files) { this.addArgument(files, FILE_DELIMITER); return this; } /** * Add a List of {@link File} objects to the argument list. The files will be separated by space when rendered on the command line * @param files List<File> * @return AbstractJob * @see File */ public AbstractJob addArgument(List<File> files) { this.addArgument(files, FILE_DELIMITER); return this; } /** * Add a Array of {@link File} objects to the argument list. * The files will be separated by the filedelimiter(default is space) when rendered on the command line. * @param files File[] Array of file objects * @param filedelimiter String delimiter for the files. Default is space * @return AbstractJob * @see File */ public AbstractJob addArgument(File[] files, String filedelimiter) { filedelimiter = (filedelimiter == null) ? FILE_DELIMITER : filedelimiter; if (files != null && files.length > 0) { if (!mArguments.isEmpty()) { mArguments.add(ARG_DELIMITER); } boolean first = true; for (File f : files) { if (!first) { mArguments.add(filedelimiter); } mArguments.add(f); first = false; } } return this; } /** * Add a List of {@link File} objects to the argument list. * The files will be separated by the filedelimiter(default is space) when rendered on the command line. * @param files List<File> Array of file objects * @param filedelimiter String delimiter for the files. Default is space * @return AbstractJob * @see File */ public AbstractJob addArgument(List<File> files, String filedelimiter) { if (files != null && !files.isEmpty()) { this.addArgument((File[]) files.toArray(), filedelimiter); } return this; } /** * Add a argument key and value to the argument List. * The argkey and argvalue are seperated by space. * Example addArgument("-p","0") will result in the argument being added as * -p 0<Br> * Multiple calls to addArgument results in the arguments being separated by space. * @param argkey String * @param argvalue String * @return AbstractJob */ public AbstractJob addArgument(String argkey, String argvalue) { this.addArgument(argkey, argvalue, ARG_DELIMITER); return this; } /** * Add a argument key and value to the argument List.<Br> * The argkey and argvalue are seperated by argdelimiter.<br> * Example addArgument("-p","0","=") will result in the argument being added as * -p=0<Br> * Multiple calls to addArgument results in the arguments being separated by space. * @param argkey String Key * @param argvalue String Value * @param argdelimiter String argdelimiter * @return AbstractJob * */ public AbstractJob addArgument(String argkey, String argvalue, String argdelimiter) { argdelimiter = (argdelimiter == null) ? ARG_DELIMITER : argdelimiter; if (argkey != null && argvalue != null) { this.addArgument(argkey + argdelimiter + argvalue); } return this; } /** * Add a argument key and File value to the argument List.<Br> * The argkey and argvalue are seperated by space.<br> * Example addArgument("-i",new File("f.a")) will result in the argument being added as * -i &lt;file name="f.a"&gt;<Br> * Multiple calls to addArgument results in the arguments being separated by space. * @param argkey String * @param argvalue File * @return AbstractJob */ public AbstractJob addArgument(String argkey, File argvalue) { this.addArgument(argkey, argvalue, ARG_DELIMITER); return this; } /** * Add a argument key and File value to the argument List.<Br> * The argkey and argvalue are separated by the argdelimiter.<br> * Example addArgument("-i",new File("f.a"),"=") will result in the argument being added as * -i=&lt;file name="f.a"&gt;<Br> * Multiple calls to addArgument results in the arguments being separated by space. * @param argkey String * @param argvalue File * @param argdelimiter * @return AbstractJob */ public AbstractJob addArgument(String argkey, File argvalue, String argdelimiter) { argdelimiter = (argdelimiter == null) ? ARG_DELIMITER : argdelimiter; if (argkey != null && argvalue != null) { this.addArgument(argkey + argdelimiter); mArguments.add(argvalue); } return this; } /** * Add a argument key and an array of Files to the argument List.<Br> * The argkey and argvalue are separated space.<br> * The files are separated by a space <br> * Example:<br> * <i>File[] files = {new File("f.a1"), new File("f.a2")};<br> * job.addArgument("-i",files)</i><br> * will result in the argument being added as * <b>-i &lt;file name="f.a1"&gt; &lt;file name="f.a2"&gt;</b><Br> * Multiple calls to addArgument results in the arguments being separated by space. * @param argkey String * @param argvalue File[] * @return AbstractJob */ public AbstractJob addArgument(String argkey, File[] argvalue) { this.addArgument(argkey, argvalue, ARG_DELIMITER, FILE_DELIMITER); return this; } /** * Add a argument key and a List of Files to the argument List.<Br> * The argkey and argvalue are separated space.<br> * The files are separated by a space <br> * Example:<br> * <i>List<File> files = new LinkedList<File>();<br> * files.add(new File("f.a1"));<br> * files.add(new File("f.a2"));<br> * job.addArgument("-i",files)</i><br> * will result in the argument being added as * <b>-i &lt;file name="f.a1"&gt; &lt;file name="f.a2"&gt;</b><Br> * Multiple calls to addArgument results in the arguments being separated by space. * @param argkey String * @param argvalue List<File> * @return AbstractJob */ public AbstractJob addArgument(String argkey, List<File> argvalue) { this.addArgument(argkey, argvalue, ARG_DELIMITER, FILE_DELIMITER); return this; } /** * Add a argument key and an array of Files to the argument List.<Br> * The argkey and argvalue are separated by the argdelimiter.<br> * The files are separated by a filedelimiter <br> * Example:<br> * <i>File[] files = {new File("f.a1"), new File("f.a2")};<br> * job.addArgument("-i",files,"=",",")</i><br> * will result in the argument being added as * <b>-i=&lt;file name="f.a1"&gt;,&lt;file name="f.a2"&gt;</b><Br> * Multiple calls to addArgument results in the arguments being separated by space. * @param argkey String * @param argvalue File[] * @param argdelimiter String * @param filedelimiter String * @return AbstractJob */ public AbstractJob addArgument(String argkey, File[] argvalue, String argdelimiter, String filedelimiter) { argdelimiter = (argdelimiter == null) ? ARG_DELIMITER : argdelimiter; filedelimiter = (filedelimiter == null) ? FILE_DELIMITER : filedelimiter; if (argkey != null && argvalue != null && argvalue.length > 0) { this.addArgument(argkey + argdelimiter); boolean first = true; for (File f : argvalue) { if (!first) { mArguments.add(filedelimiter); } mArguments.add(f); first = false; } } return this; } /** * Add a argument key and a List of Files to the argument List.<Br> * The argkey and argvalue are separated by the argdelimiter.<br> * The files are separated by a filedelimter <br> * Example:<br> * <i>List<File> files = new LinkedList<File>();<br> * files.add(new File("f.a1"));<br> * files.add(new File("f.a2"));<br> * job.addArgument("-i",files,"=",",")</i><br> * will result in the argument being added as * <b>-i=&lt;file name="f.a1"&gt;,&lt;file name="f.a2"&gt;</b><Br> * Multiple calls to addArgument results in the arguments being separated by space. * @param argkey String * @param argvalue List&lt;File&gt; List of File objects * @param argdelimiter String * @param filedelimiter String * @return AbstractJob */ public AbstractJob addArgument(String argkey, List<File> argvalue, String argdelimiter, String filedelimiter) { if (argkey != null && argvalue != null && !argvalue.isEmpty()) { this.addArgument(argkey, (File[]) argvalue.toArray(), argdelimiter, filedelimiter); } return this; } /** * Add a profile to the job * @param namespace String * @param key String * @param value String * @return AbstractJob */ public AbstractJob addProfile(String namespace, String key, String value) { mProfiles.add(new Profile(namespace, key, value)); return this; } /** * Add a profile to the job * @param namespace {@link Profile.NAMESPACE} * @param key String * @param value String * @return AbstractJob */ public AbstractJob addProfile(Profile.NAMESPACE namespace, String key, String value) { mProfiles.add(new Profile(namespace, key, value)); return this; } /** * Add a Profile object * @param profile * @return AbstractJob * @see Profile */ public AbstractJob addProfile(Profile profile) { mProfiles.add(new Profile(profile)); return this; } /** * Add a list of Profile objects * @param profiles List&lt;Profile&gt; * @return */ public AbstractJob addProfiles(List<Profile> profiles) { mProfiles.addAll(Collections.unmodifiableCollection(profiles)); return this; } /** * Get the STDIN file object * @return File */ public File getStdin() { return mStdin; } /** * * @param stdin * @return AbstractJob */ public AbstractJob setStdin(File stdin) { File f = new File(stdin, File.LINK.INPUT); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @return AbstractJob */ public AbstractJob setStdin(File stdin, File.TRANSFER transfer) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param register * @return AbstractJob */ public AbstractJob setStdin(File stdin, boolean register) { File f = new File(stdin, File.LINK.INPUT); f.setRegister(register); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @param register * @return AbstractJob */ public AbstractJob setStdin(File stdin, File.TRANSFER transfer, boolean register) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); f.setRegister(register); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @param register * @return AbstractJob */ public AbstractJob setStdin(File stdin, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @return AbstractJob */ public AbstractJob setStdin(String stdin) { File f = new File(stdin, File.LINK.INPUT); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @return AbstractJob */ public AbstractJob setStdin(String stdin, File.TRANSFER transfer) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param register * @return AbstractJob */ public AbstractJob setStdin(String stdin, boolean register) { File f = new File(stdin, File.LINK.INPUT); f.setRegister(register); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @param register * @return AbstractJob */ public AbstractJob setStdin(String stdin, File.TRANSFER transfer, boolean register) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); f.setRegister(register); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @param register * @param optional * @return AbstractJob */ public AbstractJob setStdin(String stdin, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @return File */ public File getStdout() { return mStdout; } /** * * @param stdout * @return AbstractJob */ public AbstractJob setStdout(File stdout) { File f = new File(stdout, File.LINK.OUTPUT); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @return AbstractJob */ public AbstractJob setStdout(File stdout, File.TRANSFER transfer) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param register * @return AbstractJob */ public AbstractJob setStdout(File stdout, boolean register) { File f = new File(stdout, File.LINK.OUTPUT); f.setRegister(register); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @param register * @return AbstractJob */ public AbstractJob setStdout(File stdout, File.TRANSFER transfer, boolean register) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @param register * @param optional * @return AbstractJob */ public AbstractJob setStdout(File stdout, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @return AbstractJob */ public AbstractJob setStdout(String stdout) { File f = new File(stdout, File.LINK.OUTPUT); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @return AbstractJob */ public AbstractJob setStdout(String stdout, File.TRANSFER transfer) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param register * @return AbstractJob */ public AbstractJob setStdout(String stdout, boolean register) { File f = new File(stdout, File.LINK.OUTPUT); f.setRegister(register); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @param register * @return AbstractJob */ public AbstractJob setStdout(String stdout, File.TRANSFER transfer, boolean register) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); mStdout = f; mUses.add(f); return this; } /** * * @param stdout * @param transfer * @param register * @param optional * @return AbstractJob */ public AbstractJob setStdout(String stdout, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @return File */ public File getStderr() { return mStderr; } /** * * @param stderr * @return AbstractJob */ public AbstractJob setStderr(File stderr) { File f = new File(stderr, File.LINK.OUTPUT); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @return AbstractJob */ public AbstractJob setStderr(File stderr, File.TRANSFER transfer) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param register * @return AbstractJob */ public AbstractJob setStderr(File stderr, boolean register) { File f = new File(stderr, File.LINK.OUTPUT); f.setRegister(register); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @param register * @return AbstractJob */ public AbstractJob setStderr(File stderr, File.TRANSFER transfer, boolean register) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @param register * @param optional * @return AbstractJob */ public AbstractJob setStderr(File stderr, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @return AbstractJob */ public AbstractJob setStderr(String stderr) { File f = new File(stderr, File.LINK.OUTPUT); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @return AbstractJob */ public AbstractJob setStderr(String stderr, File.TRANSFER transfer) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param register * @return AbstractJob */ public AbstractJob setStderr(String stderr, boolean register) { File f = new File(stderr, File.LINK.OUTPUT); f.setRegister(register); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @param register * @return AbstractJob */ public AbstractJob setStderr(String stderr, File.TRANSFER transfer, boolean register) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @param register * @param optional * @return AbstractJob */ public AbstractJob setStderr(String stderr, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @return Set<File> */ public Set<File> getUses() { return Collections.unmodifiableSet(mUses); } /** * * * * * @param file * @param link * @return AbstractJob */ public AbstractJob uses(String file, File.LINK link) { File f = new File(file, link); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator. combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param register * @return AbstractJob */ public AbstractJob uses(String file, File.LINK link, boolean register) { File f = new File(file, link); f.setRegister(register); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator. combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @return AbstractJob */ public AbstractJob uses(String file, File.LINK link, File.TRANSFER transfer) { File f = new File(file, link); f.setTransfer(transfer); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator. combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @param register * @return AbstractJob */ public AbstractJob uses(String file, File.LINK link, File.TRANSFER transfer, boolean register) { File f = new File(file, link); f.setRegister(register); f.setTransfer(transfer); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator. combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @param register * @param optional * @param executable * @return AbstractJob */ public AbstractJob uses(String file, File.LINK link, File.TRANSFER transfer, boolean register, boolean optional, boolean executable) { File f = new File(file, link); f.setRegister(register); f.setOptional(optional); f.setTransfer(transfer); f.setExecutable(executable); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @return AbstractJob */ public AbstractJob uses(File file, File.LINK link) { File f = new File(file, link); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @return AbstractJob */ public AbstractJob uses(File file, File.LINK link, File.TRANSFER transfer) { File f = new File(file, link); f.setTransfer(transfer); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param register * @return AbstractJob */ public AbstractJob uses(File file, File.LINK link, boolean register) { File f = new File(file, link); f.setRegister(register); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @param register * @return AbstractJob */ public AbstractJob uses(File file, File.LINK link, File.TRANSFER transfer, boolean register) { File f = new File(file, link); f.setTransfer(transfer); f.setRegister(register); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @param register * @param optional * @param executable * @return AbstractJob */ public AbstractJob uses(File file, File.LINK link, File.TRANSFER transfer, boolean register, boolean optional, boolean executable) { File f = new File(file, link); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); f.setExecutable(executable); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param files * @param link * @return AbstractJob */ public AbstractJob uses(List<File> files, File.LINK link) { for (File file : files) { File f = new File(file, link); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } } return this; } /** * * @return List<Invoke> */ public List<Invoke> getInvoke() { return Collections.unmodifiableList(mInvokes); } /** * * @param when * @param what * @return AbstractJob */ public AbstractJob addInvoke(Invoke.WHEN when, String what) { Invoke i = new Invoke(when, what); mInvokes.add(i); return this; } /** * * @param invoke * @return AbstractJob */ public AbstractJob addInvoke(Invoke invoke) { mInvokes.add(invoke); return this; } /** * * @param invokes * @return AbstractJob */ public AbstractJob addInvoke(List<Invoke> invokes) { this.mInvokes.addAll(invokes); return this; } /** * * @return String */ public String getName() { return mName; } /** * * @return String */ public String getId() { return mId; } /** * * @return String */ public String getNodeLabel() { return mNodeLabel; } /** * * @param label */ public void setNodeLabel(String label) { this.mNodeLabel = label; } /** * * @param writer */ public void toXML(XMLWriter writer) { toXML(writer, 0); } /** * * @param writer * @param indent */ public void toXML(XMLWriter writer, int indent) { Class c = this.getClass(); //Check if its a dax, dag or job class if (c == DAX.class) { writer.startElement( "dax", indent); writer.writeAttribute( "id", mId); writer.writeAttribute( "file", mName); } else if (c == DAG.class) { writer.startElement( "dag", indent); writer.writeAttribute( "id", mId); writer.writeAttribute( "file", mName); } else if (c == Job.class) { writer.startElement( "job", indent); writer.writeAttribute( "id", mId); if (mNamespace != null && !mNamespace.isEmpty()) { writer.writeAttribute("namespace", mNamespace); } writer.writeAttribute("name", mName); if (mVersion != null && !mVersion.isEmpty()) { writer.writeAttribute("version", mVersion); } } if (mNodeLabel != null && !mNodeLabel.isEmpty()) { writer.writeAttribute("node-label", mNodeLabel); } //add argument if (!mArguments.isEmpty()) { writer.startElement("argument", indent + 1); for (Object o : mArguments) { if (o.getClass() == String.class) { //if class is string add argument string in the data section writer.writeData( (String) o); } if (o.getClass() == File.class) { //add file tags in the argument elements data section ((File) o).toXML(writer, 0, "argument"); } } writer.endElement(); } //add profiles for (Profile p : mProfiles) { p.toXML(writer, indent + 1); } //add stdin if (mStdin != null) { mStdin.toXML(writer, indent + 1, "stdin"); } //add stdout if (mStdout != null) { mStdout.toXML(writer, indent + 1, "stdout"); } //add stderr if (mStderr != null) { mStderr.toXML(writer, indent + 1, "stderr"); } //add uses for (File f : mUses) { f.toXML(writer, indent + 1, "uses"); } //add invoke for (Invoke i : mInvokes) { i.toXML(writer, indent + 1); } if (!(mUses.isEmpty() && mInvokes.isEmpty() && mStderr == null && mStdout == null && mStdin == null && mProfiles. isEmpty() && mArguments.isEmpty())) { writer.endElement(indent); } else { writer.endElement(); } } }
src/edu/isi/pegasus/planner/dax/AbstractJob.java
/** * Copyright 2007-2008 University Of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.isi.pegasus.planner.dax; import java.util.List; import java.util.LinkedList; import java.util.Collections; import edu.isi.pegasus.common.logging.LogManager; import edu.isi.pegasus.common.logging.LogManagerFactory; import edu.isi.pegasus.common.util.Separator; import edu.isi.pegasus.common.util.XMLWriter; import java.util.LinkedHashSet; import java.util.Set; /** * * @author gmehta * @version $Revision$ */ public class AbstractJob { protected List mArguments; protected List<Profile> mProfiles; protected File mStdin; protected File mStdout; protected File mStderr; protected Set<File> mUses; protected List<Invoke> mInvokes; protected String mName; protected String mId; protected String mNamespace; protected String mVersion; protected String mNodeLabel; protected static LogManager mLogger; private static final String ARG_DELIMITER = " "; private static final String FILE_DELIMITER = " "; protected AbstractJob() { mLogger = LogManagerFactory.loadSingletonInstance(); mArguments = new LinkedList(); mUses = new LinkedHashSet<File>(); mInvokes = new LinkedList<Invoke>(); mProfiles = new LinkedList<Profile>(); } protected static void checkID(String id) { if (!Patterns.isNodeIdValid(id)) { mLogger.log( "Id: " + id + " should of the type [A-Za-z0-9][-A-Za-z0-9]*", LogManager.ERROR_MESSAGE_LEVEL); } } /** * * @return */ public List getArguments() { return Collections.unmodifiableList(mArguments); } /** * * @param argument * @return */ public AbstractJob addArgument(String argument) { if (argument != null) { if (!mArguments.isEmpty()) { mArguments.add(ARG_DELIMITER); } mArguments.add(argument); } return this; } /** * * @param file * @return */ public AbstractJob addArgument(File file) { if (file != null) { if (!mArguments.isEmpty()) { mArguments.add(ARG_DELIMITER); } mArguments.add(file); } return this; } /** * * @param files * @return */ public AbstractJob addArgument(File[] files) { this.addArgument(files, FILE_DELIMITER); return this; } /** * * @param files * @return */ public AbstractJob addArgument(List<File> files) { this.addArgument(files, FILE_DELIMITER); return this; } /** * * @param files * @param filedelimiter * @return */ public AbstractJob addArgument(File[] files, String filedelimiter) { filedelimiter = (filedelimiter == null) ? FILE_DELIMITER : filedelimiter; if (files != null && files.length > 0) { if (!mArguments.isEmpty()) { mArguments.add(ARG_DELIMITER); } boolean first = true; for (File f : files) { if (!first) { mArguments.add(filedelimiter); } mArguments.add(f); first = false; } } return this; } /** * * @param files * @param filedelimiter * @return */ public AbstractJob addArgument(List<File> files, String filedelimiter) { if (files != null && !files.isEmpty()) { this.addArgument((File[]) files.toArray(), filedelimiter); } return this; } /** * * @param argkey * @param argvalue * @return */ public AbstractJob addArgument(String argkey, String argvalue) { this.addArgument(argkey, argvalue, ARG_DELIMITER); return this; } /** * * @param argkey * @param argvalue * @param argdelimiter * @return */ public AbstractJob addArgument(String argkey, String argvalue, String argdelimiter) { argdelimiter = (argdelimiter == null) ? ARG_DELIMITER : argdelimiter; if (argkey != null && argvalue != null) { this.addArgument(argkey + argdelimiter + argvalue); } return this; } /** * * @param argkey * @param argvalue * @return */ public AbstractJob addArgument(String argkey, File argvalue) { this.addArgument(argkey, argvalue, ARG_DELIMITER); return this; } /** * * @param argkey * @param argvalue * @param argdelimiter * @return */ public AbstractJob addArgument(String argkey, File argvalue, String argdelimiter) { argdelimiter = (argdelimiter == null) ? ARG_DELIMITER : argdelimiter; if (argkey != null && argvalue != null) { this.addArgument(argkey + argdelimiter); mArguments.add(argvalue); } return this; } /** * * @param argkey * @param argvalue * @return */ public AbstractJob addArgument(String argkey, File[] argvalue) { this.addArgument(argkey, argvalue, ARG_DELIMITER, FILE_DELIMITER); return this; } /** * * @param argkey * @param argvalue * @return */ public AbstractJob addArgument(String argkey, List<File> argvalue) { this.addArgument(argkey, argvalue, ARG_DELIMITER, FILE_DELIMITER); return this; } /** * * @param argkey * @param argvalue * @param argdelimiter * @param filedelimiter * @return */ public AbstractJob addArgument(String argkey, File[] argvalue, String argdelimiter, String filedelimiter) { argdelimiter = (argdelimiter == null) ? ARG_DELIMITER : argdelimiter; filedelimiter = (filedelimiter == null) ? FILE_DELIMITER : filedelimiter; if (argkey != null && argvalue != null && argvalue.length > 0) { this.addArgument(argkey + argdelimiter); boolean first = true; for (File f : argvalue) { if (!first) { mArguments.add(filedelimiter); } mArguments.add(f); first = false; } } return this; } /** * * @param argkey * @param argvalue * @param argdelimiter * @param filedelimiter * @return */ public AbstractJob addArgument(String argkey, List<File> argvalue, String argdelimiter, String filedelimiter) { if (argkey != null && argvalue != null && !argvalue.isEmpty()) { this.addArgument(argkey, (File[]) argvalue.toArray(), argdelimiter, filedelimiter); } return this; } /** * * @param namespace * @param key * @param value * @return */ public AbstractJob addProfile(String namespace, String key, String value) { mProfiles.add(new Profile(namespace, key, value)); return this; } /** * * @param namespace * @param key * @param value * @return */ public AbstractJob addProfile(Profile.NAMESPACE namespace, String key, String value) { mProfiles.add(new Profile(namespace, key, value)); return this; } /** * * @return */ public File getStdin() { return mStdin; } /** * * @param stdin * @return */ public AbstractJob setStdin(File stdin) { File f = new File(stdin, File.LINK.INPUT); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @return */ public AbstractJob setStdin(File stdin, File.TRANSFER transfer) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param register * @return */ public AbstractJob setStdin(File stdin, boolean register) { File f = new File(stdin, File.LINK.INPUT); f.setRegister(register); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @param register * @return */ public AbstractJob setStdin(File stdin, File.TRANSFER transfer, boolean register) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); f.setRegister(register); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @param register * @param optional * @return */ public AbstractJob setStdin(File stdin, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @return */ public AbstractJob setStdin(String stdin) { File f = new File(stdin, File.LINK.INPUT); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @return */ public AbstractJob setStdin(String stdin, File.TRANSFER transfer) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param register * @return */ public AbstractJob setStdin(String stdin, boolean register) { File f = new File(stdin, File.LINK.INPUT); f.setRegister(register); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @param register * @return */ public AbstractJob setStdin(String stdin, File.TRANSFER transfer, boolean register) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); f.setRegister(register); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdin * @param transfer * @param register * @param optional * @return */ public AbstractJob setStdin(String stdin, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stdin, File.LINK.INPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStdin = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @return */ public File getStdout() { return mStdout; } /** * * @param stdout * @return */ public AbstractJob setStdout(File stdout) { File f = new File(stdout, File.LINK.OUTPUT); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @return */ public AbstractJob setStdout(File stdout, File.TRANSFER transfer) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param register * @return */ public AbstractJob setStdout(File stdout, boolean register) { File f = new File(stdout, File.LINK.OUTPUT); f.setRegister(register); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @param register * @return */ public AbstractJob setStdout(File stdout, File.TRANSFER transfer, boolean register) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @param register * @param optional * @return */ public AbstractJob setStdout(File stdout, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @return */ public AbstractJob setStdout(String stdout) { File f = new File(stdout, File.LINK.OUTPUT); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @return */ public AbstractJob setStdout(String stdout, File.TRANSFER transfer) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param register * @return */ public AbstractJob setStdout(String stdout, boolean register) { File f = new File(stdout, File.LINK.OUTPUT); f.setRegister(register); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stdout * @param transfer * @param register * @return */ public AbstractJob setStdout(String stdout, File.TRANSFER transfer, boolean register) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); mStdout = f; mUses.add(f); return this; } /** * * @param stdout * @param transfer * @param register * @param optional * @return */ public AbstractJob setStdout(String stdout, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stdout, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStdout = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @return */ public File getStderr() { return mStderr; } /** * * @param stderr * @return */ public AbstractJob setStderr(File stderr) { File f = new File(stderr, File.LINK.OUTPUT); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @return */ public AbstractJob setStderr(File stderr, File.TRANSFER transfer) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param register * @return */ public AbstractJob setStderr(File stderr, boolean register) { File f = new File(stderr, File.LINK.OUTPUT); f.setRegister(register); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @param register * @return */ public AbstractJob setStderr(File stderr, File.TRANSFER transfer, boolean register) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @param register * @param optional * @return */ public AbstractJob setStderr(File stderr, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @return */ public AbstractJob setStderr(String stderr) { File f = new File(stderr, File.LINK.OUTPUT); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @return */ public AbstractJob setStderr(String stderr, File.TRANSFER transfer) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param register * @return */ public AbstractJob setStderr(String stderr, boolean register) { File f = new File(stderr, File.LINK.OUTPUT); f.setRegister(register); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @param register * @return */ public AbstractJob setStderr(String stderr, File.TRANSFER transfer, boolean register) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @param stderr * @param transfer * @param register * @param optional * @return */ public AbstractJob setStderr(String stderr, File.TRANSFER transfer, boolean register, boolean optional) { File f = new File(stderr, File.LINK.OUTPUT); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); mStderr = f; if (!mUses.contains(f)) { mUses.add(f); } return this; } /** * * @return */ public Set<File> getUses() { return Collections.unmodifiableSet(mUses); } /** * * * * * @param file * @param link * @return */ public AbstractJob uses(String file, File.LINK link) { File f = new File(file, link); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator. combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param register * @return */ public AbstractJob uses(String file, File.LINK link, boolean register) { File f = new File(file, link); f.setRegister(register); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator. combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @return */ public AbstractJob uses(String file, File.LINK link, File.TRANSFER transfer) { File f = new File(file, link); f.setTransfer(transfer); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator. combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @param register * @return */ public AbstractJob uses(String file, File.LINK link, File.TRANSFER transfer, boolean register) { File f = new File(file, link); f.setRegister(register); f.setTransfer(transfer); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator. combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @param register * @param optional * @param executable * @return */ public AbstractJob uses(String file, File.LINK link, File.TRANSFER transfer, boolean register, boolean optional, boolean executable) { File f = new File(file, link); f.setRegister(register); f.setOptional(optional); f.setTransfer(transfer); f.setExecutable(executable); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @return */ public AbstractJob uses(File file, File.LINK link) { File f = new File(file, link); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @return */ public AbstractJob uses(File file, File.LINK link, File.TRANSFER transfer) { File f = new File(file, link); f.setTransfer(transfer); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param register * @return */ public AbstractJob uses(File file, File.LINK link, boolean register) { File f = new File(file, link); f.setRegister(register); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine(f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @param register * @return */ public AbstractJob uses(File file, File.LINK link, File.TRANSFER transfer, boolean register) { File f = new File(file, link); f.setTransfer(transfer); f.setRegister(register); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param file * @param link * @param transfer * @param register * @param optional * @param executable * @return */ public AbstractJob uses(File file, File.LINK link, File.TRANSFER transfer, boolean register, boolean optional, boolean executable) { File f = new File(file, link); f.setTransfer(transfer); f.setRegister(register); f.setOptional(optional); f.setExecutable(executable); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } return this; } /** * * @param files * @param link * @return */ public AbstractJob uses(List<File> files, File.LINK link) { for (File file : files) { File f = new File(file, link); if (!mUses.contains(f)) { mUses.add(f); } else { mLogger.log("Job " + Separator.combine(mNamespace, mName, mVersion) + "already contains a file " + Separator.combine( f.mNamespace, f.mName, f.mVersion) + ". Ignoring", LogManager.WARNING_MESSAGE_LEVEL); } } return this; } /** * * @return */ public List<Invoke> getInvoke() { return Collections.unmodifiableList(mInvokes); } /** * * @param when * @param what * @return */ public AbstractJob addInvoke(Invoke.WHEN when, String what) { Invoke i = new Invoke(when, what); mInvokes.add(i); return this; } /** * * @param invoke * @return */ public AbstractJob addInvoke(Invoke invoke) { mInvokes.add(invoke); return this; } /** * * @param invokes * @return */ public AbstractJob addInvoke(List<Invoke> invokes) { this.mInvokes.addAll(invokes); return this; } /** * * @return */ public String getName() { return mName; } /** * * @return */ public String getId() { return mId; } /** * * @return */ public String getNodeLabel() { return mNodeLabel; } /** * * @param label */ public void setNodeLabel(String label) { this.mNodeLabel = label; } /** * * @param writer */ public void toXML(XMLWriter writer) { toXML(writer, 0); } /** * * @param writer * @param indent */ public void toXML(XMLWriter writer, int indent) { Class c = this.getClass(); //Check if its a dax, dag or job class if (c == DAX.class) { writer.startElement( "dax", indent); writer.writeAttribute( "id", mId); writer.writeAttribute( "file", mName); } else if (c == DAG.class) { writer.startElement( "dag", indent); writer.writeAttribute( "id", mId); writer.writeAttribute( "file", mName); } else if (c == Job.class) { writer.startElement( "job", indent); writer.writeAttribute( "id", mId); if (mNamespace != null && !mNamespace.isEmpty()) { writer.writeAttribute("namespace", mNamespace); } writer.writeAttribute("name", mName); if (mVersion != null && !mVersion.isEmpty()) { writer.writeAttribute("version", mVersion); } } if (mNodeLabel != null && !mNodeLabel.isEmpty()) { writer.writeAttribute("node-label", mNodeLabel); } //add argument if (!mArguments.isEmpty()) { writer.startElement("argument", indent + 1); for (Object o : mArguments) { if (o.getClass() == String.class) { //if class is string add argument string in the data section writer.writeData( (String) o); } if (o.getClass() == File.class) { //add file tags in the argument elements data section ((File) o).toXML(writer, 0, "argument"); } } writer.endElement(); } //add profiles for (Profile p : mProfiles) { p.toXML(writer, indent + 1); } //add stdin if (mStdin != null) { mStdin.toXML(writer, indent + 1, "stdin"); } //add stdout if (mStdout != null) { mStdout.toXML(writer, indent + 1, "stdout"); } //add stderr if (mStderr != null) { mStderr.toXML(writer, indent + 1, "stderr"); } //add uses for (File f : mUses) { f.toXML(writer, indent + 1, "uses"); } //add invoke for (Invoke i : mInvokes) { i.toXML(writer, indent + 1); } if (!(mUses.isEmpty() && mInvokes.isEmpty() && mStderr == null && mStdout == null && mStdin == null && mProfiles. isEmpty() && mArguments.isEmpty())) { writer.endElement(indent); } else { writer.endElement(); } } }
Added Javadoc
src/edu/isi/pegasus/planner/dax/AbstractJob.java
Added Javadoc
Java
apache-2.0
314974bf482e89edee3fe3575245cb8242f5da66
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.core; import java.io.*; import java.nio.channels.FileChannel; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeoutException; import java.text.SimpleDateFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import org.apache.solr.cloud.CloudDescriptor; import org.apache.solr.cloud.SolrZkServer; import org.apache.solr.cloud.ZkController; import org.apache.solr.cloud.ZkSolrResourceLoader; import org.apache.solr.common.SolrException; import org.apache.solr.common.cloud.ZooKeeperException; import org.apache.solr.common.params.CoreAdminParams; import org.apache.solr.common.util.DOMUtil; import org.apache.solr.common.util.XML; import org.apache.solr.common.util.FileUtils; import org.apache.solr.handler.admin.CoreAdminHandler; import org.apache.solr.schema.IndexSchema; import org.apache.zookeeper.KeeperException; import org.apache.commons.io.IOUtils; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * @version $Id$ * @since solr 1.3 */ public class CoreContainer { private static final String DEFAULT_DEFAULT_CORE_NAME = "collection1"; protected static Logger log = LoggerFactory.getLogger(CoreContainer.class); protected final Map<String, SolrCore> cores = new LinkedHashMap<String, SolrCore>(); protected boolean persistent = false; protected String adminPath = null; protected String managementPath = null; protected String hostPort; protected String hostContext; protected String host; protected CoreAdminHandler coreAdminHandler = null; protected File configFile = null; protected String libDir = null; protected ClassLoader libLoader = null; protected SolrResourceLoader loader = null; protected Properties containerProperties; protected Map<String ,IndexSchema> indexSchemaCache; protected String adminHandler; protected boolean shareSchema; protected String solrHome; @Deprecated protected String solrConfigFilenameOverride; private String defaultCoreName = ""; private ZkController zkController; private SolrZkServer zkServer; private String zkHost; public CoreContainer() { solrHome = SolrResourceLoader.locateSolrHome(); log.info("New CoreContainer: solrHome=" + solrHome + " instance="+System.identityHashCode(this)); } private void initZooKeeper(String zkHost, int zkClientTimeout) { // if zkHost sys property is not set, we are not using ZooKeeper String zookeeperHost; if(zkHost == null) { zookeeperHost = System.getProperty("zkHost"); } else { zookeeperHost = zkHost; } String zkRun = System.getProperty("zkRun"); if (zkRun == null && zookeeperHost == null) return; // not in zk mode zkServer = new SolrZkServer(zkRun, zookeeperHost, solrHome, hostPort); zkServer.parseConfig(); zkServer.start(); // set client from server config if not already set if (zookeeperHost == null) { zookeeperHost = zkServer.getClientString(); } int zkClientConnectTimeout = 5000; if (zookeeperHost != null) { // we are ZooKeeper enabled try { // If this is an ensemble, allow for a long connect time for other servers to come up if (zkRun != null && zkServer.getServers().size() > 1) { zkClientConnectTimeout = 24 * 60 * 60 * 1000; // 1 day for embedded ensemble log.info("Zookeeper client=" + zookeeperHost + " Waiting for a quorum."); } else { log.info("Zookeeper client=" + zookeeperHost); } zkController = new ZkController(zookeeperHost, zkClientTimeout, zkClientConnectTimeout, host, hostPort, hostContext); String confDir = System.getProperty("bootstrap_confdir"); if(confDir != null) { File dir = new File(confDir); if(!dir.isDirectory()) { throw new IllegalArgumentException("bootstrap_confdir must be a directory of configuration files"); } String confName = System.getProperty(ZkController.COLLECTION_PARAM_PREFIX+ZkController.CONFIGNAME_PROP, "configuration1"); zkController.uploadConfigDir(dir, confName); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (TimeoutException e) { log.error("Could not connect to ZooKeeper", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (IOException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } } public Properties getContainerProperties() { return containerProperties; } // Helper class to initialize the CoreContainer public static class Initializer { protected String solrConfigFilename = null; protected String dataDir = null; // override datadir for single core mode /** * @deprecated all cores now abort on configuration error regardless of configuration */ @Deprecated public boolean isAbortOnConfigurationError() { return true; } /** * @exception generates an error if you attempt to set this value to false * @deprecated all cores now abort on configuration error regardless of configuration */ @Deprecated public void setAbortOnConfigurationError(boolean abortOnConfigurationError) { if (false == abortOnConfigurationError) throw new SolrException (SolrException.ErrorCode.SERVER_ERROR, "Setting abortOnConfigurationError==false is no longer supported"); } public String getSolrConfigFilename() { return solrConfigFilename; } @Deprecated public void setSolrConfigFilename(String solrConfigFilename) { this.solrConfigFilename = solrConfigFilename; } // core container instantiation public CoreContainer initialize() throws IOException, ParserConfigurationException, SAXException { CoreContainer cores = null; String solrHome = SolrResourceLoader.locateSolrHome(); // TODO : fix broken logic confusing solr.xml with solrconfig.xml File fconf = new File(solrHome, solrConfigFilename == null ? "solr.xml" : solrConfigFilename); log.info("looking for solr.xml: " + fconf.getAbsolutePath()); cores = new CoreContainer(); if (fconf.exists()) { cores.load(solrHome, fconf); } else { log.info("no solr.xml file found - using default"); cores.load(solrHome, new ByteArrayInputStream(DEF_SOLR_XML.getBytes())); cores.configFile = fconf; } solrConfigFilename = cores.getConfigFile().getName(); return cores; } } private static Properties getCoreProps(String instanceDir, String file, Properties defaults) { if(file == null) file = "conf"+File.separator+ "solrcore.properties"; File corePropsFile = new File(file); if(!corePropsFile.isAbsolute()){ corePropsFile = new File(instanceDir, file); } Properties p = defaults; if (corePropsFile.exists() && corePropsFile.isFile()) { p = new Properties(defaults); InputStream is = null; try { is = new FileInputStream(corePropsFile); p.load(is); } catch (IOException e) { log.warn("Error loading properties ",e); } finally{ IOUtils.closeQuietly(is); } } return p; } /** * Initalize CoreContainer directly from the constructor * * @param dir * @param configFile * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public CoreContainer(String dir, File configFile) throws ParserConfigurationException, IOException, SAXException { this.load(dir, configFile); } /** * Minimal CoreContainer constructor. * @param loader the CoreContainer resource loader */ public CoreContainer(SolrResourceLoader loader) { this.loader = loader; this.solrHome = loader.getInstanceDir(); } public CoreContainer(String solrHome) { this.solrHome = solrHome; } //------------------------------------------------------------------- // Initialization / Cleanup //------------------------------------------------------------------- /** * Load a config file listing the available solr cores. * @param dir the home directory of all resources. * @param configFile the configuration file * @throws javax.xml.parsers.ParserConfigurationException * @throws java.io.IOException * @throws org.xml.sax.SAXException */ public void load(String dir, File configFile ) throws ParserConfigurationException, IOException, SAXException { this.configFile = configFile; this.load(dir, new FileInputStream(configFile)); } /** * Load a config file listing the available solr cores. * * @param dir the home directory of all resources. * @param cfgis the configuration file InputStream * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public void load(String dir, InputStream cfgis) throws ParserConfigurationException, IOException, SAXException { this.loader = new SolrResourceLoader(dir); solrHome = loader.getInstanceDir(); try { Config cfg = new Config(loader, null, cfgis, null); String dcoreName = cfg.get("solr/cores/@defaultCoreName", null); if(dcoreName != null) { defaultCoreName = dcoreName; } persistent = cfg.getBool("solr/@persistent", false); libDir = cfg.get("solr/@sharedLib", null); zkHost = cfg.get("solr/@zkHost" , null); adminPath = cfg.get("solr/cores/@adminPath", null); shareSchema = cfg.getBool("solr/cores/@shareSchema", false); int zkClientTimeout = cfg.getInt("solr/cores/@zkClientTimeout", 10000); hostPort = System.getProperty("hostPort"); if (hostPort == null) { hostPort = cfg.get("solr/cores/@hostPort", "8983"); } hostContext = cfg.get("solr/cores/@hostContext", "solr"); host = cfg.get("solr/cores/@host", null); if(shareSchema){ indexSchemaCache = new ConcurrentHashMap<String ,IndexSchema>(); } adminHandler = cfg.get("solr/cores/@adminHandler", null ); managementPath = cfg.get("solr/cores/@managementPath", null ); zkClientTimeout = Integer.parseInt(System.getProperty("zkClientTimeout", Integer.toString(zkClientTimeout))); initZooKeeper(zkHost, zkClientTimeout); if (libDir != null) { File f = FileUtils.resolvePath(new File(dir), libDir); log.info( "loading shared library: "+f.getAbsolutePath() ); libLoader = SolrResourceLoader.createClassLoader(f, null); } if (adminPath != null) { if (adminHandler == null) { coreAdminHandler = new CoreAdminHandler(this); } else { coreAdminHandler = this.createMultiCoreHandler(adminHandler); } } try { containerProperties = readProperties(cfg, ((NodeList) cfg.evaluate("solr", XPathConstants.NODESET)).item(0)); } catch (Throwable e) { SolrConfig.severeErrors.add(e); SolrException.logOnce(log,null,e); } NodeList nodes = (NodeList)cfg.evaluate("solr/cores/core", XPathConstants.NODESET); boolean defaultCoreFound = false; for (int i=0; i<nodes.getLength(); i++) { Node node = nodes.item(i); try { String name = DOMUtil.getAttr(node, "name", null); if (null == name) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Each core in solr.xml must have a 'name'"); } if (name.equals(defaultCoreName)){ // for the default core we use a blank name, // later on attempts to access it by it's full name will // be mapped to this. name=""; } CoreDescriptor p = new CoreDescriptor(this, name, DOMUtil.getAttr(node, "instanceDir", null)); // deal with optional settings String opt = DOMUtil.getAttr(node, "config", null); if(solrConfigFilenameOverride != null) { p.setConfigName(solrConfigFilenameOverride); } else if (opt != null) { p.setConfigName(opt); } opt = DOMUtil.getAttr(node, "schema", null); if (opt != null) { p.setSchemaName(opt); } if (zkController != null) { opt = DOMUtil.getAttr(node, "shard", null); if (opt != null && opt.length() > 0) { p.getCloudDescriptor().setShardId(opt); } opt = DOMUtil.getAttr(node, "collection", null); if (opt != null) { p.getCloudDescriptor().setCollectionName(opt); } } opt = DOMUtil.getAttr(node, "properties", null); if (opt != null) { p.setPropertiesName(opt); } opt = DOMUtil.getAttr(node, CoreAdminParams.DATA_DIR, null); if (opt != null) { p.setDataDir(opt); } p.setCoreProperties(readProperties(cfg, node)); SolrCore core = create(p); register(name, core, false); } catch (Throwable ex) { SolrConfig.severeErrors.add( ex ); SolrException.logOnce(log,null,ex); } } } finally { if (cfgis != null) { try { cfgis.close(); } catch (Exception xany) {} } } if(zkController != null) { try { synchronized (zkController.getZkStateReader().getUpdateLock()) { zkController.getZkStateReader().makeShardZkNodeWatches(false); zkController.getZkStateReader().updateCloudState(true); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (IOException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } } private Properties readProperties(Config cfg, Node node) throws XPathExpressionException { XPath xpath = cfg.getXPath(); NodeList props = (NodeList) xpath.evaluate("property", node, XPathConstants.NODESET); Properties properties = new Properties(); for (int i=0; i<props.getLength(); i++) { Node prop = props.item(i); properties.setProperty(DOMUtil.getAttr(prop, "name"), DOMUtil.getAttr(prop, "value")); } return properties; } private boolean isShutDown = false; /** * Stops all cores. */ public void shutdown() { synchronized(cores) { try { for(SolrCore core : cores.values()) { core.close(); } cores.clear(); } finally { if(zkController != null) { zkController.close(); } if (zkServer != null) { zkServer.stop(); } isShutDown = true; } } } @Override protected void finalize() throws Throwable { try { if(!isShutDown){ log.error("CoreContainer was not shutdown prior to finalize(), indicates a bug -- POSSIBLE RESOURCE LEAK!!! instance=" + System.identityHashCode(this)); shutdown(); } } finally { super.finalize(); } } /** * Registers a SolrCore descriptor in the registry using the specified name. * If returnPrevNotClosed==false, the old core, if different, is closed. if true, it is returned w/o closing the core * * @return a previous core having the same name if it existed */ public SolrCore register(String name, SolrCore core, boolean returnPrevNotClosed) { if( core == null ) { throw new RuntimeException( "Can not register a null core." ); } if( name == null || name.indexOf( '/' ) >= 0 || name.indexOf( '\\' ) >= 0 ){ throw new RuntimeException( "Invalid core name: "+name ); } SolrCore old = null; synchronized (cores) { old = cores.put(name, core); core.setName(name); } if (zkController != null) { try { zkController.register(core.getName(), core.getCoreDescriptor().getCloudDescriptor(), true); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (IOException e) { log.error("", e); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } if( old == null || old == core) { log.info( "registering core: "+name ); return null; } else { log.info( "replacing core: "+name ); if (!returnPrevNotClosed) { old.close(); } return old; } } /** * Registers a SolrCore descriptor in the registry using the core's name. * If returnPrev==false, the old core, if different, is closed. * @return a previous core having the same name if it existed and returnPrev==true */ public SolrCore register(SolrCore core, boolean returnPrev) { return register(core.getName(), core, returnPrev); } /** * Creates a new core based on a descriptor but does not register it. * * @param dcore a core descriptor * @return the newly created core * @throws javax.xml.parsers.ParserConfigurationException * @throws java.io.IOException * @throws org.xml.sax.SAXException */ public SolrCore create(CoreDescriptor dcore) throws ParserConfigurationException, IOException, SAXException { // Make the instanceDir relative to the cores instanceDir if not absolute File idir = new File(dcore.getInstanceDir()); if (!idir.isAbsolute()) { idir = new File(solrHome, dcore.getInstanceDir()); } String instanceDir = idir.getPath(); // Initialize the solr config SolrResourceLoader solrLoader = null; SolrConfig config = null; String zkConfigName = null; if(zkController == null) { solrLoader = new SolrResourceLoader(instanceDir, libLoader, getCoreProps(instanceDir, dcore.getPropertiesName(),dcore.getCoreProperties())); config = new SolrConfig(solrLoader, dcore.getConfigName(), null); } else { try { String collection = dcore.getCloudDescriptor().getCollectionName(); zkController.createCollectionZkNode(dcore.getCloudDescriptor()); // zkController.createCollectionZkNode(collection); zkConfigName = zkController.readConfigName(collection); if (zkConfigName == null) { log.error("Could not find config name for collection:" + collection); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "Could not find config name for collection:" + collection); } solrLoader = new ZkSolrResourceLoader(instanceDir, zkConfigName, libLoader, getCoreProps(instanceDir, dcore.getPropertiesName(),dcore.getCoreProperties()), zkController); config = getSolrConfigFromZk(zkConfigName, dcore.getConfigName(), solrLoader); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } IndexSchema schema = null; if (indexSchemaCache != null) { if (zkController != null) { File schemaFile = new File(dcore.getSchemaName()); if (!schemaFile.isAbsolute()) { schemaFile = new File(solrLoader.getInstanceDir() + "conf" + File.separator + dcore.getSchemaName()); } if (schemaFile.exists()) { String key = schemaFile.getAbsolutePath() + ":" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date( schemaFile.lastModified())); schema = indexSchemaCache.get(key); if (schema == null) { log.info("creating new schema object for core: " + dcore.name); schema = new IndexSchema(config, dcore.getSchemaName(), null); indexSchemaCache.put(key, schema); } else { log.info("re-using schema object for core: " + dcore.name); } } } else { // TODO: handle caching from ZooKeeper - perhaps using ZooKeepers versioning // Don't like this cache though - how does it empty as last modified changes? } } if(schema == null){ if(zkController != null) { try { schema = getSchemaFromZk(zkConfigName, dcore.getSchemaName(), config, solrLoader); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } else { schema = new IndexSchema(config, dcore.getSchemaName(), null); } } String dataDir = null; SolrCore core = new SolrCore(dcore.getName(), dataDir, config, schema, dcore); return core; } /** * @return a Collection of registered SolrCores */ public Collection<SolrCore> getCores() { List<SolrCore> lst = new ArrayList<SolrCore>(); synchronized (cores) { lst.addAll(this.cores.values()); } return lst; } /** * @return a Collection of the names that cores are mapped to */ public Collection<String> getCoreNames() { List<String> lst = new ArrayList<String>(); synchronized (cores) { lst.addAll(this.cores.keySet()); } return lst; } /** This method is currently experimental. * @return a Collection of the names that a specific core is mapped to. */ public Collection<String> getCoreNames(SolrCore core) { List<String> lst = new ArrayList<String>(); synchronized (cores) { for (Map.Entry<String,SolrCore> entry : cores.entrySet()) { if (core == entry.getValue()) { lst.add(entry.getKey()); } } } return lst; } // ---------------- Core name related methods --------------- /** * Recreates a SolrCore. * While the new core is loading, requests will continue to be dispatched to * and processed by the old core * * @param name the name of the SolrCore to reload * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public void reload(String name) throws ParserConfigurationException, IOException, SAXException { name= checkDefault(name); SolrCore core; synchronized(cores) { core = cores.get(name); } if (core == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "No such core: " + name ); SolrCore newCore = create(core.getCoreDescriptor()); register(name, newCore, false); } private String checkDefault(String name) { return name.length() == 0 || defaultCoreName.equals(name) || name.trim().length() == 0 ? "" : name; } /** * Swaps two SolrCore descriptors. * @param n0 * @param n1 */ public void swap(String n0, String n1) { if( n0 == null || n1 == null ) { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Can not swap unnamed cores." ); } n0 = checkDefault(n0); n1 = checkDefault(n1); synchronized( cores ) { SolrCore c0 = cores.get(n0); SolrCore c1 = cores.get(n1); if (c0 == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "No such core: " + n0 ); if (c1 == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "No such core: " + n1 ); cores.put(n0, c1); cores.put(n1, c0); c0.setName(n1); c0.getCoreDescriptor().name = n1; c1.setName(n0); c1.getCoreDescriptor().name = n0; } log.info("swaped: "+n0 + " with " + n1); } /** Removes and returns registered core w/o decrementing it's reference count */ public SolrCore remove( String name ) { name = checkDefault(name); synchronized(cores) { return cores.remove( name ); } } /** Gets a core by name and increase its refcount. * @see SolrCore#open() * @see SolrCore#close() * @param name the core name * @return the core if found */ public SolrCore getCore(String name) { name= checkDefault(name); synchronized(cores) { SolrCore core = cores.get(name); if (core != null) core.open(); // increment the ref count while still synchronized return core; } } // ---------------- Multicore self related methods --------------- /** * Creates a CoreAdminHandler for this MultiCore. * @return a CoreAdminHandler */ protected CoreAdminHandler createMultiCoreHandler(final String adminHandlerClass) { SolrResourceLoader loader = new SolrResourceLoader(null, libLoader, null); Object obj = loader.newAdminHandlerInstance(CoreContainer.this, adminHandlerClass); if ( !(obj instanceof CoreAdminHandler)) { throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, "adminHandlerClass is not of type "+ CoreAdminHandler.class ); } return (CoreAdminHandler) obj; } public CoreAdminHandler getMultiCoreHandler() { return coreAdminHandler; } public String getDefaultCoreName() { return defaultCoreName; } // all of the following properties aren't synchronized // but this should be OK since they normally won't be changed rapidly public boolean isPersistent() { return persistent; } public void setPersistent(boolean persistent) { this.persistent = persistent; } public String getAdminPath() { return adminPath; } public void setAdminPath(String adminPath) { this.adminPath = adminPath; } public String getManagementPath() { return managementPath; } /** * Sets the alternate path for multicore handling: * This is used in case there is a registered unnamed core (aka name is "") to * declare an alternate way of accessing named cores. * This can also be used in a pseudo single-core environment so admins can prepare * a new version before swapping. * @param path */ public void setManagementPath(String path) { this.managementPath = path; } public File getConfigFile() { return configFile; } /** Persists the cores config file in cores.xml. */ public void persist() { persistFile(null); } /** Persists the cores config file in a user provided file. */ public void persistFile(File file) { log.info("Persisting cores config to " + (file==null ? configFile : file)); File tmpFile = null; try { // write in temp first if (file == null) { file = tmpFile = File.createTempFile("solr", ".xml", configFile.getParentFile()); } java.io.FileOutputStream out = new java.io.FileOutputStream(file); Writer writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); persist(writer); writer.flush(); writer.close(); out.close(); // rename over origin or copy it this fails if (tmpFile != null) { if (tmpFile.renameTo(configFile)) tmpFile = null; else fileCopy(tmpFile, configFile); } } catch(java.io.FileNotFoundException xnf) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, xnf); } catch(java.io.IOException xio) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, xio); } finally { if (tmpFile != null) { if (!tmpFile.delete()) tmpFile.deleteOnExit(); } } } /** Write the cores configuration through a writer.*/ void persist(Writer w) throws IOException { w.write("<?xml version='1.0' encoding='UTF-8'?>"); w.write("<solr"); if (this.libDir != null) { writeAttribute(w,"sharedLib",libDir); } writeAttribute(w,"persistent",isPersistent()); w.write(">\n"); if (containerProperties != null && !containerProperties.isEmpty()) { writeProperties(w, containerProperties); } w.write("<cores"); writeAttribute(w, "adminPath",adminPath); if(adminHandler != null) writeAttribute(w, "adminHandler",adminHandler); if(shareSchema) writeAttribute(w, "shareSchema","true"); w.write(">\n"); synchronized(cores) { for (SolrCore solrCore : cores.values()) { persist(w,solrCore.getCoreDescriptor()); } } w.write("</cores>\n"); w.write("</solr>\n"); } private void writeAttribute(Writer w, String name, Object value) throws IOException { if (value == null) return; w.write(" "); w.write(name); w.write("=\""); XML.escapeAttributeValue(value.toString(), w); w.write("\""); } /** Writes the cores configuration node for a given core. */ void persist(Writer w, CoreDescriptor dcore) throws IOException { w.write(" <core"); writeAttribute(w,"name",dcore.name); writeAttribute(w,"instanceDir",dcore.getInstanceDir()); //write config (if not default) String opt = dcore.getConfigName(); if (opt != null && !opt.equals(dcore.getDefaultConfigName())) { writeAttribute(w, "config",opt); } //write schema (if not default) opt = dcore.getSchemaName(); if (opt != null && !opt.equals(dcore.getDefaultSchemaName())) { writeAttribute(w,"schema",opt); } opt = dcore.getPropertiesName(); if (opt != null) { writeAttribute(w,"properties",opt); } opt = dcore.dataDir; if (opt != null) writeAttribute(w,"dataDir",opt); CloudDescriptor cd = dcore.getCloudDescriptor(); if (cd != null) { opt = cd.getShardId(); if (opt != null) writeAttribute(w,"shard",opt); // only write out the collection name if it's not the default (the core name) opt = cd.getCollectionName(); if (opt != null && !opt.equals(dcore.name)) writeAttribute(w,"collection",opt); } if (dcore.getCoreProperties() == null || dcore.getCoreProperties().isEmpty()) w.write("/>\n"); // core else { w.write(">\n"); writeProperties(w, dcore.getCoreProperties()); w.write("</core>"); } } private void writeProperties(Writer w, Properties props) throws IOException { for (Map.Entry<Object, Object> entry : props.entrySet()) { w.write("<property"); writeAttribute(w,"name",entry.getKey()); writeAttribute(w,"value",entry.getValue()); w.write("/>\n"); } } /** Copies a src file to a dest file: * used to circumvent the platform discrepancies regarding renaming files. */ public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); // do the file copy 32Mb at a time final int MB32 = 32*1024*1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch(IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch(IOException xio) {} if (fos != null) try { fos.close(); fos = null; } catch(IOException xio) {} if (fcin != null && fcin.isOpen() ) try { fcin.close(); fcin = null; } catch(IOException xio) {} if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch(IOException xio) {} } if (xforward != null) { throw xforward; } } public String getSolrHome() { return solrHome; } public boolean isZooKeeperAware() { return zkController != null; } public ZkController getZkController() { return zkController; } private SolrConfig getSolrConfigFromZk(String zkConfigName, String solrConfigFileName, SolrResourceLoader resourceLoader) throws IOException, ParserConfigurationException, SAXException, KeeperException, InterruptedException { byte[] config = zkController.getConfigFileData(zkConfigName, solrConfigFileName); InputStream is = new ByteArrayInputStream(config); SolrConfig cfg = solrConfigFileName == null ? new SolrConfig( resourceLoader, SolrConfig.DEFAULT_CONF_FILE, is) : new SolrConfig( resourceLoader, solrConfigFileName, is); return cfg; } private IndexSchema getSchemaFromZk(String zkConfigName, String schemaName, SolrConfig config, SolrResourceLoader resourceLoader) throws KeeperException, InterruptedException { byte[] configBytes = zkController.getConfigFileData(zkConfigName, schemaName); InputStream is = new ByteArrayInputStream(configBytes); IndexSchema schema = new IndexSchema(config, schemaName, is); return schema; } private static final String DEF_SOLR_XML ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<solr persistent=\"false\">\n" + " <cores adminPath=\"/admin/cores\" defaultCoreName=\"" + DEFAULT_DEFAULT_CORE_NAME + "\">\n" + " <core name=\""+ DEFAULT_DEFAULT_CORE_NAME + "\" instanceDir=\".\" />\n" + " </cores>\n" + "</solr>"; }
solr/src/java/org/apache/solr/core/CoreContainer.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.core; import java.io.*; import java.nio.channels.FileChannel; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeoutException; import java.text.SimpleDateFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import org.apache.solr.cloud.CloudDescriptor; import org.apache.solr.cloud.SolrZkServer; import org.apache.solr.cloud.ZkController; import org.apache.solr.cloud.ZkSolrResourceLoader; import org.apache.solr.common.SolrException; import org.apache.solr.common.cloud.ZooKeeperException; import org.apache.solr.common.params.CoreAdminParams; import org.apache.solr.common.util.DOMUtil; import org.apache.solr.common.util.XML; import org.apache.solr.common.util.FileUtils; import org.apache.solr.handler.admin.CoreAdminHandler; import org.apache.solr.schema.IndexSchema; import org.apache.zookeeper.KeeperException; import org.apache.commons.io.IOUtils; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * @version $Id$ * @since solr 1.3 */ public class CoreContainer { private static final String DEFAULT_DEFAULT_CORE_NAME = "collection1"; protected static Logger log = LoggerFactory.getLogger(CoreContainer.class); protected final Map<String, SolrCore> cores = new LinkedHashMap<String, SolrCore>(); protected boolean persistent = false; protected String adminPath = null; protected String managementPath = null; protected String hostPort; protected String hostContext; protected String host; protected CoreAdminHandler coreAdminHandler = null; protected File configFile = null; protected String libDir = null; protected ClassLoader libLoader = null; protected SolrResourceLoader loader = null; protected Properties containerProperties; protected Map<String ,IndexSchema> indexSchemaCache; protected String adminHandler; protected boolean shareSchema; protected String solrHome; @Deprecated protected String solrConfigFilenameOverride; private String defaultCoreName = ""; private ZkController zkController; private SolrZkServer zkServer; private String zkHost; public CoreContainer() { solrHome = SolrResourceLoader.locateSolrHome(); } private void initZooKeeper(String zkHost, int zkClientTimeout) { // if zkHost sys property is not set, we are not using ZooKeeper String zookeeperHost; if(zkHost == null) { zookeeperHost = System.getProperty("zkHost"); } else { zookeeperHost = zkHost; } String zkRun = System.getProperty("zkRun"); if (zkRun == null && zookeeperHost == null) return; // not in zk mode zkServer = new SolrZkServer(zkRun, zookeeperHost, solrHome, hostPort); zkServer.parseConfig(); zkServer.start(); // set client from server config if not already set if (zookeeperHost == null) { zookeeperHost = zkServer.getClientString(); } int zkClientConnectTimeout = 5000; if (zookeeperHost != null) { // we are ZooKeeper enabled try { // If this is an ensemble, allow for a long connect time for other servers to come up if (zkRun != null && zkServer.getServers().size() > 1) { zkClientConnectTimeout = 24 * 60 * 60 * 1000; // 1 day for embedded ensemble log.info("Zookeeper client=" + zookeeperHost + " Waiting for a quorum."); } else { log.info("Zookeeper client=" + zookeeperHost); } zkController = new ZkController(zookeeperHost, zkClientTimeout, zkClientConnectTimeout, host, hostPort, hostContext); String confDir = System.getProperty("bootstrap_confdir"); if(confDir != null) { File dir = new File(confDir); if(!dir.isDirectory()) { throw new IllegalArgumentException("bootstrap_confdir must be a directory of configuration files"); } String confName = System.getProperty(ZkController.COLLECTION_PARAM_PREFIX+ZkController.CONFIGNAME_PROP, "configuration1"); zkController.uploadConfigDir(dir, confName); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (TimeoutException e) { log.error("Could not connect to ZooKeeper", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (IOException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } } public Properties getContainerProperties() { return containerProperties; } // Helper class to initialize the CoreContainer public static class Initializer { protected String solrConfigFilename = null; protected String dataDir = null; // override datadir for single core mode /** * @deprecated all cores now abort on configuration error regardless of configuration */ @Deprecated public boolean isAbortOnConfigurationError() { return true; } /** * @exception generates an error if you attempt to set this value to false * @deprecated all cores now abort on configuration error regardless of configuration */ @Deprecated public void setAbortOnConfigurationError(boolean abortOnConfigurationError) { if (false == abortOnConfigurationError) throw new SolrException (SolrException.ErrorCode.SERVER_ERROR, "Setting abortOnConfigurationError==false is no longer supported"); } public String getSolrConfigFilename() { return solrConfigFilename; } @Deprecated public void setSolrConfigFilename(String solrConfigFilename) { this.solrConfigFilename = solrConfigFilename; } // core container instantiation public CoreContainer initialize() throws IOException, ParserConfigurationException, SAXException { CoreContainer cores = null; String solrHome = SolrResourceLoader.locateSolrHome(); // TODO : fix broken logic confusing solr.xml with solrconfig.xml File fconf = new File(solrHome, solrConfigFilename == null ? "solr.xml" : solrConfigFilename); log.info("looking for solr.xml: " + fconf.getAbsolutePath()); cores = new CoreContainer(); if (fconf.exists()) { cores.load(solrHome, fconf); } else { log.info("no solr.xml file found - using default"); cores.load(solrHome, new ByteArrayInputStream(DEF_SOLR_XML.getBytes())); cores.configFile = fconf; } solrConfigFilename = cores.getConfigFile().getName(); return cores; } } private static Properties getCoreProps(String instanceDir, String file, Properties defaults) { if(file == null) file = "conf"+File.separator+ "solrcore.properties"; File corePropsFile = new File(file); if(!corePropsFile.isAbsolute()){ corePropsFile = new File(instanceDir, file); } Properties p = defaults; if (corePropsFile.exists() && corePropsFile.isFile()) { p = new Properties(defaults); InputStream is = null; try { is = new FileInputStream(corePropsFile); p.load(is); } catch (IOException e) { log.warn("Error loading properties ",e); } finally{ IOUtils.closeQuietly(is); } } return p; } /** * Initalize CoreContainer directly from the constructor * * @param dir * @param configFile * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public CoreContainer(String dir, File configFile) throws ParserConfigurationException, IOException, SAXException { this.load(dir, configFile); } /** * Minimal CoreContainer constructor. * @param loader the CoreContainer resource loader */ public CoreContainer(SolrResourceLoader loader) { this.loader = loader; this.solrHome = loader.getInstanceDir(); } public CoreContainer(String solrHome) { this.solrHome = solrHome; } //------------------------------------------------------------------- // Initialization / Cleanup //------------------------------------------------------------------- /** * Load a config file listing the available solr cores. * @param dir the home directory of all resources. * @param configFile the configuration file * @throws javax.xml.parsers.ParserConfigurationException * @throws java.io.IOException * @throws org.xml.sax.SAXException */ public void load(String dir, File configFile ) throws ParserConfigurationException, IOException, SAXException { this.configFile = configFile; this.load(dir, new FileInputStream(configFile)); } /** * Load a config file listing the available solr cores. * * @param dir the home directory of all resources. * @param cfgis the configuration file InputStream * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public void load(String dir, InputStream cfgis) throws ParserConfigurationException, IOException, SAXException { this.loader = new SolrResourceLoader(dir); solrHome = loader.getInstanceDir(); try { Config cfg = new Config(loader, null, cfgis, null); String dcoreName = cfg.get("solr/cores/@defaultCoreName", null); if(dcoreName != null) { defaultCoreName = dcoreName; } persistent = cfg.getBool("solr/@persistent", false); libDir = cfg.get("solr/@sharedLib", null); zkHost = cfg.get("solr/@zkHost" , null); adminPath = cfg.get("solr/cores/@adminPath", null); shareSchema = cfg.getBool("solr/cores/@shareSchema", false); int zkClientTimeout = cfg.getInt("solr/cores/@zkClientTimeout", 10000); hostPort = System.getProperty("hostPort"); if (hostPort == null) { hostPort = cfg.get("solr/cores/@hostPort", "8983"); } hostContext = cfg.get("solr/cores/@hostContext", "solr"); host = cfg.get("solr/cores/@host", null); if(shareSchema){ indexSchemaCache = new ConcurrentHashMap<String ,IndexSchema>(); } adminHandler = cfg.get("solr/cores/@adminHandler", null ); managementPath = cfg.get("solr/cores/@managementPath", null ); zkClientTimeout = Integer.parseInt(System.getProperty("zkClientTimeout", Integer.toString(zkClientTimeout))); initZooKeeper(zkHost, zkClientTimeout); if (libDir != null) { File f = FileUtils.resolvePath(new File(dir), libDir); log.info( "loading shared library: "+f.getAbsolutePath() ); libLoader = SolrResourceLoader.createClassLoader(f, null); } if (adminPath != null) { if (adminHandler == null) { coreAdminHandler = new CoreAdminHandler(this); } else { coreAdminHandler = this.createMultiCoreHandler(adminHandler); } } try { containerProperties = readProperties(cfg, ((NodeList) cfg.evaluate("solr", XPathConstants.NODESET)).item(0)); } catch (Throwable e) { SolrConfig.severeErrors.add(e); SolrException.logOnce(log,null,e); } NodeList nodes = (NodeList)cfg.evaluate("solr/cores/core", XPathConstants.NODESET); boolean defaultCoreFound = false; for (int i=0; i<nodes.getLength(); i++) { Node node = nodes.item(i); try { String name = DOMUtil.getAttr(node, "name", null); if (null == name) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Each core in solr.xml must have a 'name'"); } if (name.equals(defaultCoreName)){ // for the default core we use a blank name, // later on attempts to access it by it's full name will // be mapped to this. name=""; } CoreDescriptor p = new CoreDescriptor(this, name, DOMUtil.getAttr(node, "instanceDir", null)); // deal with optional settings String opt = DOMUtil.getAttr(node, "config", null); if(solrConfigFilenameOverride != null) { p.setConfigName(solrConfigFilenameOverride); } else if (opt != null) { p.setConfigName(opt); } opt = DOMUtil.getAttr(node, "schema", null); if (opt != null) { p.setSchemaName(opt); } if (zkController != null) { opt = DOMUtil.getAttr(node, "shard", null); if (opt != null && opt.length() > 0) { p.getCloudDescriptor().setShardId(opt); } opt = DOMUtil.getAttr(node, "collection", null); if (opt != null) { p.getCloudDescriptor().setCollectionName(opt); } } opt = DOMUtil.getAttr(node, "properties", null); if (opt != null) { p.setPropertiesName(opt); } opt = DOMUtil.getAttr(node, CoreAdminParams.DATA_DIR, null); if (opt != null) { p.setDataDir(opt); } p.setCoreProperties(readProperties(cfg, node)); SolrCore core = create(p); register(name, core, false); } catch (Throwable ex) { SolrConfig.severeErrors.add( ex ); SolrException.logOnce(log,null,ex); } } } finally { if (cfgis != null) { try { cfgis.close(); } catch (Exception xany) {} } } if(zkController != null) { try { synchronized (zkController.getZkStateReader().getUpdateLock()) { zkController.getZkStateReader().makeShardZkNodeWatches(false); zkController.getZkStateReader().updateCloudState(true); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (IOException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } } private Properties readProperties(Config cfg, Node node) throws XPathExpressionException { XPath xpath = cfg.getXPath(); NodeList props = (NodeList) xpath.evaluate("property", node, XPathConstants.NODESET); Properties properties = new Properties(); for (int i=0; i<props.getLength(); i++) { Node prop = props.item(i); properties.setProperty(DOMUtil.getAttr(prop, "name"), DOMUtil.getAttr(prop, "value")); } return properties; } private boolean isShutDown = false; /** * Stops all cores. */ public void shutdown() { synchronized(cores) { try { for(SolrCore core : cores.values()) { core.close(); } cores.clear(); } finally { if(zkController != null) { zkController.close(); } if (zkServer != null) { zkServer.stop(); } isShutDown = true; } } } @Override protected void finalize() throws Throwable { try { if(!isShutDown){ log.error("CoreContainer was not shutdown prior to finalize(), indicates a bug -- POSSIBLE RESOURCE LEAK!!!"); shutdown(); } } finally { super.finalize(); } } /** * Registers a SolrCore descriptor in the registry using the specified name. * If returnPrevNotClosed==false, the old core, if different, is closed. if true, it is returned w/o closing the core * * @return a previous core having the same name if it existed */ public SolrCore register(String name, SolrCore core, boolean returnPrevNotClosed) { if( core == null ) { throw new RuntimeException( "Can not register a null core." ); } if( name == null || name.indexOf( '/' ) >= 0 || name.indexOf( '\\' ) >= 0 ){ throw new RuntimeException( "Invalid core name: "+name ); } SolrCore old = null; synchronized (cores) { old = cores.put(name, core); core.setName(name); } if (zkController != null) { try { zkController.register(core.getName(), core.getCoreDescriptor().getCloudDescriptor(), true); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (IOException e) { log.error("", e); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } if( old == null || old == core) { log.info( "registering core: "+name ); return null; } else { log.info( "replacing core: "+name ); if (!returnPrevNotClosed) { old.close(); } return old; } } /** * Registers a SolrCore descriptor in the registry using the core's name. * If returnPrev==false, the old core, if different, is closed. * @return a previous core having the same name if it existed and returnPrev==true */ public SolrCore register(SolrCore core, boolean returnPrev) { return register(core.getName(), core, returnPrev); } /** * Creates a new core based on a descriptor but does not register it. * * @param dcore a core descriptor * @return the newly created core * @throws javax.xml.parsers.ParserConfigurationException * @throws java.io.IOException * @throws org.xml.sax.SAXException */ public SolrCore create(CoreDescriptor dcore) throws ParserConfigurationException, IOException, SAXException { // Make the instanceDir relative to the cores instanceDir if not absolute File idir = new File(dcore.getInstanceDir()); if (!idir.isAbsolute()) { idir = new File(solrHome, dcore.getInstanceDir()); } String instanceDir = idir.getPath(); // Initialize the solr config SolrResourceLoader solrLoader = null; SolrConfig config = null; String zkConfigName = null; if(zkController == null) { solrLoader = new SolrResourceLoader(instanceDir, libLoader, getCoreProps(instanceDir, dcore.getPropertiesName(),dcore.getCoreProperties())); config = new SolrConfig(solrLoader, dcore.getConfigName(), null); } else { try { String collection = dcore.getCloudDescriptor().getCollectionName(); zkController.createCollectionZkNode(dcore.getCloudDescriptor()); // zkController.createCollectionZkNode(collection); zkConfigName = zkController.readConfigName(collection); if (zkConfigName == null) { log.error("Could not find config name for collection:" + collection); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "Could not find config name for collection:" + collection); } solrLoader = new ZkSolrResourceLoader(instanceDir, zkConfigName, libLoader, getCoreProps(instanceDir, dcore.getPropertiesName(),dcore.getCoreProperties()), zkController); config = getSolrConfigFromZk(zkConfigName, dcore.getConfigName(), solrLoader); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } IndexSchema schema = null; if (indexSchemaCache != null) { if (zkController != null) { File schemaFile = new File(dcore.getSchemaName()); if (!schemaFile.isAbsolute()) { schemaFile = new File(solrLoader.getInstanceDir() + "conf" + File.separator + dcore.getSchemaName()); } if (schemaFile.exists()) { String key = schemaFile.getAbsolutePath() + ":" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date( schemaFile.lastModified())); schema = indexSchemaCache.get(key); if (schema == null) { log.info("creating new schema object for core: " + dcore.name); schema = new IndexSchema(config, dcore.getSchemaName(), null); indexSchemaCache.put(key, schema); } else { log.info("re-using schema object for core: " + dcore.name); } } } else { // TODO: handle caching from ZooKeeper - perhaps using ZooKeepers versioning // Don't like this cache though - how does it empty as last modified changes? } } if(schema == null){ if(zkController != null) { try { schema = getSchemaFromZk(zkConfigName, dcore.getSchemaName(), config, solrLoader); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } else { schema = new IndexSchema(config, dcore.getSchemaName(), null); } } String dataDir = null; SolrCore core = new SolrCore(dcore.getName(), dataDir, config, schema, dcore); return core; } /** * @return a Collection of registered SolrCores */ public Collection<SolrCore> getCores() { List<SolrCore> lst = new ArrayList<SolrCore>(); synchronized (cores) { lst.addAll(this.cores.values()); } return lst; } /** * @return a Collection of the names that cores are mapped to */ public Collection<String> getCoreNames() { List<String> lst = new ArrayList<String>(); synchronized (cores) { lst.addAll(this.cores.keySet()); } return lst; } /** This method is currently experimental. * @return a Collection of the names that a specific core is mapped to. */ public Collection<String> getCoreNames(SolrCore core) { List<String> lst = new ArrayList<String>(); synchronized (cores) { for (Map.Entry<String,SolrCore> entry : cores.entrySet()) { if (core == entry.getValue()) { lst.add(entry.getKey()); } } } return lst; } // ---------------- Core name related methods --------------- /** * Recreates a SolrCore. * While the new core is loading, requests will continue to be dispatched to * and processed by the old core * * @param name the name of the SolrCore to reload * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public void reload(String name) throws ParserConfigurationException, IOException, SAXException { name= checkDefault(name); SolrCore core; synchronized(cores) { core = cores.get(name); } if (core == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "No such core: " + name ); SolrCore newCore = create(core.getCoreDescriptor()); register(name, newCore, false); } private String checkDefault(String name) { return name.length() == 0 || defaultCoreName.equals(name) || name.trim().length() == 0 ? "" : name; } /** * Swaps two SolrCore descriptors. * @param n0 * @param n1 */ public void swap(String n0, String n1) { if( n0 == null || n1 == null ) { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Can not swap unnamed cores." ); } n0 = checkDefault(n0); n1 = checkDefault(n1); synchronized( cores ) { SolrCore c0 = cores.get(n0); SolrCore c1 = cores.get(n1); if (c0 == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "No such core: " + n0 ); if (c1 == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "No such core: " + n1 ); cores.put(n0, c1); cores.put(n1, c0); c0.setName(n1); c0.getCoreDescriptor().name = n1; c1.setName(n0); c1.getCoreDescriptor().name = n0; } log.info("swaped: "+n0 + " with " + n1); } /** Removes and returns registered core w/o decrementing it's reference count */ public SolrCore remove( String name ) { name = checkDefault(name); synchronized(cores) { return cores.remove( name ); } } /** Gets a core by name and increase its refcount. * @see SolrCore#open() * @see SolrCore#close() * @param name the core name * @return the core if found */ public SolrCore getCore(String name) { name= checkDefault(name); synchronized(cores) { SolrCore core = cores.get(name); if (core != null) core.open(); // increment the ref count while still synchronized return core; } } // ---------------- Multicore self related methods --------------- /** * Creates a CoreAdminHandler for this MultiCore. * @return a CoreAdminHandler */ protected CoreAdminHandler createMultiCoreHandler(final String adminHandlerClass) { SolrResourceLoader loader = new SolrResourceLoader(null, libLoader, null); Object obj = loader.newAdminHandlerInstance(CoreContainer.this, adminHandlerClass); if ( !(obj instanceof CoreAdminHandler)) { throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, "adminHandlerClass is not of type "+ CoreAdminHandler.class ); } return (CoreAdminHandler) obj; } public CoreAdminHandler getMultiCoreHandler() { return coreAdminHandler; } public String getDefaultCoreName() { return defaultCoreName; } // all of the following properties aren't synchronized // but this should be OK since they normally won't be changed rapidly public boolean isPersistent() { return persistent; } public void setPersistent(boolean persistent) { this.persistent = persistent; } public String getAdminPath() { return adminPath; } public void setAdminPath(String adminPath) { this.adminPath = adminPath; } public String getManagementPath() { return managementPath; } /** * Sets the alternate path for multicore handling: * This is used in case there is a registered unnamed core (aka name is "") to * declare an alternate way of accessing named cores. * This can also be used in a pseudo single-core environment so admins can prepare * a new version before swapping. * @param path */ public void setManagementPath(String path) { this.managementPath = path; } public File getConfigFile() { return configFile; } /** Persists the cores config file in cores.xml. */ public void persist() { persistFile(null); } /** Persists the cores config file in a user provided file. */ public void persistFile(File file) { log.info("Persisting cores config to " + (file==null ? configFile : file)); File tmpFile = null; try { // write in temp first if (file == null) { file = tmpFile = File.createTempFile("solr", ".xml", configFile.getParentFile()); } java.io.FileOutputStream out = new java.io.FileOutputStream(file); Writer writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); persist(writer); writer.flush(); writer.close(); out.close(); // rename over origin or copy it this fails if (tmpFile != null) { if (tmpFile.renameTo(configFile)) tmpFile = null; else fileCopy(tmpFile, configFile); } } catch(java.io.FileNotFoundException xnf) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, xnf); } catch(java.io.IOException xio) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, xio); } finally { if (tmpFile != null) { if (!tmpFile.delete()) tmpFile.deleteOnExit(); } } } /** Write the cores configuration through a writer.*/ void persist(Writer w) throws IOException { w.write("<?xml version='1.0' encoding='UTF-8'?>"); w.write("<solr"); if (this.libDir != null) { writeAttribute(w,"sharedLib",libDir); } writeAttribute(w,"persistent",isPersistent()); w.write(">\n"); if (containerProperties != null && !containerProperties.isEmpty()) { writeProperties(w, containerProperties); } w.write("<cores"); writeAttribute(w, "adminPath",adminPath); if(adminHandler != null) writeAttribute(w, "adminHandler",adminHandler); if(shareSchema) writeAttribute(w, "shareSchema","true"); w.write(">\n"); synchronized(cores) { for (SolrCore solrCore : cores.values()) { persist(w,solrCore.getCoreDescriptor()); } } w.write("</cores>\n"); w.write("</solr>\n"); } private void writeAttribute(Writer w, String name, Object value) throws IOException { if (value == null) return; w.write(" "); w.write(name); w.write("=\""); XML.escapeAttributeValue(value.toString(), w); w.write("\""); } /** Writes the cores configuration node for a given core. */ void persist(Writer w, CoreDescriptor dcore) throws IOException { w.write(" <core"); writeAttribute(w,"name",dcore.name); writeAttribute(w,"instanceDir",dcore.getInstanceDir()); //write config (if not default) String opt = dcore.getConfigName(); if (opt != null && !opt.equals(dcore.getDefaultConfigName())) { writeAttribute(w, "config",opt); } //write schema (if not default) opt = dcore.getSchemaName(); if (opt != null && !opt.equals(dcore.getDefaultSchemaName())) { writeAttribute(w,"schema",opt); } opt = dcore.getPropertiesName(); if (opt != null) { writeAttribute(w,"properties",opt); } opt = dcore.dataDir; if (opt != null) writeAttribute(w,"dataDir",opt); CloudDescriptor cd = dcore.getCloudDescriptor(); if (cd != null) { opt = cd.getShardId(); if (opt != null) writeAttribute(w,"shard",opt); // only write out the collection name if it's not the default (the core name) opt = cd.getCollectionName(); if (opt != null && !opt.equals(dcore.name)) writeAttribute(w,"collection",opt); } if (dcore.getCoreProperties() == null || dcore.getCoreProperties().isEmpty()) w.write("/>\n"); // core else { w.write(">\n"); writeProperties(w, dcore.getCoreProperties()); w.write("</core>"); } } private void writeProperties(Writer w, Properties props) throws IOException { for (Map.Entry<Object, Object> entry : props.entrySet()) { w.write("<property"); writeAttribute(w,"name",entry.getKey()); writeAttribute(w,"value",entry.getValue()); w.write("/>\n"); } } /** Copies a src file to a dest file: * used to circumvent the platform discrepancies regarding renaming files. */ public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); // do the file copy 32Mb at a time final int MB32 = 32*1024*1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch(IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch(IOException xio) {} if (fos != null) try { fos.close(); fos = null; } catch(IOException xio) {} if (fcin != null && fcin.isOpen() ) try { fcin.close(); fcin = null; } catch(IOException xio) {} if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch(IOException xio) {} } if (xforward != null) { throw xforward; } } public String getSolrHome() { return solrHome; } public boolean isZooKeeperAware() { return zkController != null; } public ZkController getZkController() { return zkController; } private SolrConfig getSolrConfigFromZk(String zkConfigName, String solrConfigFileName, SolrResourceLoader resourceLoader) throws IOException, ParserConfigurationException, SAXException, KeeperException, InterruptedException { byte[] config = zkController.getConfigFileData(zkConfigName, solrConfigFileName); InputStream is = new ByteArrayInputStream(config); SolrConfig cfg = solrConfigFileName == null ? new SolrConfig( resourceLoader, SolrConfig.DEFAULT_CONF_FILE, is) : new SolrConfig( resourceLoader, solrConfigFileName, is); return cfg; } private IndexSchema getSchemaFromZk(String zkConfigName, String schemaName, SolrConfig config, SolrResourceLoader resourceLoader) throws KeeperException, InterruptedException { byte[] configBytes = zkController.getConfigFileData(zkConfigName, schemaName); InputStream is = new ByteArrayInputStream(configBytes); IndexSchema schema = new IndexSchema(config, schemaName, is); return schema; } private static final String DEF_SOLR_XML ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<solr persistent=\"false\">\n" + " <cores adminPath=\"/admin/cores\" defaultCoreName=\"" + DEFAULT_DEFAULT_CORE_NAME + "\">\n" + " <core name=\""+ DEFAULT_DEFAULT_CORE_NAME + "\" instanceDir=\".\" />\n" + " </cores>\n" + "</solr>"; }
tests: add instance id to CoreContainer git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1022710 13f79535-47bb-0310-9956-ffa450edef68
solr/src/java/org/apache/solr/core/CoreContainer.java
tests: add instance id to CoreContainer
Java
apache-2.0
ffe11f0583feb09f73aa6198c8d3438ed6aba758
0
dustalov/maxmax
/* * Copyright 2018 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.nlpub.watset.cli; import com.beust.jcommander.Parameter; import org.jgrapht.Graph; import org.jgrapht.graph.DefaultWeightedEdge; import org.nlpub.graph.DummyClustering; import org.nlpub.vsm.DummyContextSimilarity; import org.nlpub.watset.Application; import org.nlpub.watset.Watset; import org.nlpub.watset.sense.IndexedSense; import org.nlpub.watset.sense.Sense; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Locale; import java.util.Map; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class CommandSenses implements Runnable { private final Application application; public CommandSenses(Application application) { this.application = application; } @Parameter(required = true, description = "Local clustering algorithm", names = {"-l", "--local"}) private String local; @Parameter(description = "Local clustering algorithm parameters", names = {"-lp", "--local-params"}) private String localParams; @Override public void run() { requireNonNull(local); final AlgorithmProvider<String, DefaultWeightedEdge> algorithm = new AlgorithmProvider<>(local, localParams); final Graph<String, DefaultWeightedEdge> graph = application.getGraph(); final Watset<String, DefaultWeightedEdge> watset = new Watset<>( graph, algorithm, DummyClustering.provider(), new DummyContextSimilarity<>() ); watset.run(); final Map<String, Map<Sense<String>, Map<String, Number>>> inventory = watset.getInventory(); try { write(application.output, inventory); } catch (IOException e) { throw new RuntimeException(e); } } private void write(Path path, Map<String, Map<Sense<String>, Map<String, Number>>> inventory) throws IOException { try (final BufferedWriter writer = Files.newBufferedWriter(path)) { for (final Map.Entry<String, Map<Sense<String>, Map<String, Number>>> wordEntry : inventory.entrySet()) { final String word = wordEntry.getKey(); for (final Map.Entry<Sense<String>, Map<String, Number>> senseEntry : wordEntry.getValue().entrySet()) { final IndexedSense<String> sense = (IndexedSense<String>) senseEntry.getKey(); final String context = senseEntry.getValue().entrySet().stream(). map(e -> String.format("%s:%f", e.getKey(), e.getValue().doubleValue())). collect(joining(",")); writer.write(String.format(Locale.ROOT, "%s\t%d\t%s\n", word, sense.getSense(), context)); } } } } }
src/main/java/org/nlpub/watset/cli/CommandSenses.java
/* * Copyright 2018 Dmitry Ustalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.nlpub.watset.cli; import com.beust.jcommander.Parameter; import org.jgrapht.Graph; import org.jgrapht.graph.DefaultWeightedEdge; import org.nlpub.graph.DummyClustering; import org.nlpub.vsm.DummyContextSimilarity; import org.nlpub.watset.Application; import org.nlpub.watset.Watset; import org.nlpub.watset.sense.Sense; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Locale; import java.util.Map; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class CommandSenses implements Runnable { private final Application application; public CommandSenses(Application application) { this.application = application; } @Parameter(required = true, description = "Local clustering algorithm", names = {"-l", "--local"}) private String local; @Parameter(description = "Local clustering algorithm parameters", names = {"-lp", "--local-params"}) private String localParams; @Override public void run() { requireNonNull(local); final AlgorithmProvider<String, DefaultWeightedEdge> algorithm = new AlgorithmProvider<>(local, localParams); final Graph<String, DefaultWeightedEdge> graph = application.getGraph(); final Watset<String, DefaultWeightedEdge> watset = new Watset<>( graph, algorithm, DummyClustering.provider(), new DummyContextSimilarity<>() ); watset.run(); final Map<String, Map<Sense<String>, Map<String, Number>>> inventory = watset.getInventory(); try { write(application.output, inventory); } catch (IOException e) { throw new RuntimeException(e); } } private void write(Path path, Map<String, Map<Sense<String>, Map<String, Number>>> inventory) throws IOException { try (final BufferedWriter writer = Files.newBufferedWriter(path)) { for (final Map.Entry<String, Map<Sense<String>, Map<String, Number>>> wordEntry : inventory.entrySet()) { final String word = wordEntry.getKey(); int i = 0; for (final Map.Entry<Sense<String>, Map<String, Number>> senseEntry : wordEntry.getValue().entrySet()) { final String context = senseEntry.getValue().entrySet().stream(). map(e -> String.format("%s:%f", e.getKey(), e.getValue().doubleValue())). collect(joining(",")); writer.write(String.format(Locale.ROOT, "%s\t%d\t%s\n", word, i++, context)); } } } } }
Use the real sense identifiers
src/main/java/org/nlpub/watset/cli/CommandSenses.java
Use the real sense identifiers
Java
apache-2.0
d9ad5434d746c2489e9815ece0f0429bbb45c92e
0
nikclayton/android-squeezer,lovethisshit/android-squeezer,kaaholst/android-squeezer,stefandb/android-squeezer
package com.danga.squeezer; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.text.Html; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.danga.squeezer.framework.SqueezerBaseActivity; import com.danga.squeezer.itemlists.SqueezerAlbumListActivity; import com.danga.squeezer.itemlists.SqueezerCurrentPlaylistActivity; import com.danga.squeezer.itemlists.SqueezerPlayerListActivity; import com.danga.squeezer.itemlists.SqueezerSongListActivity; import com.danga.squeezer.model.SqueezerAlbum; import com.danga.squeezer.model.SqueezerArtist; import com.danga.squeezer.model.SqueezerSong; import com.danga.squeezer.service.SqueezeService; public class SqueezerActivity extends SqueezerBaseActivity { private static final int DIALOG_ABOUT = 0; private static final int DIALOG_CONNECTING = 1; protected static final int HOME_REQUESTCODE = 0; private AtomicBoolean isConnected = new AtomicBoolean(false); private AtomicBoolean isPlaying = new AtomicBoolean(false); private AtomicReference<String> currentAlbumArtUrl = new AtomicReference<String>(); private TextView albumText; private TextView artistText; private TextView trackText; private TextView currentTime; private TextView totalTime; private ImageButton homeButton; private ImageButton curPlayListButton; private ImageButton playPauseButton; private ImageButton nextButton; private ImageButton prevButton; private ImageView albumArt; private SeekBar seekBar; private final ScheduledThreadPoolExecutor backgroundExecutor = new ScheduledThreadPoolExecutor(1); // Where we're connecting to. private boolean connectInProgress = false; private String connectingTo = null; private ProgressDialog connectingDialog = null; // Updating the seekbar private boolean updateSeekBar = true; private volatile int secondsIn; private volatile int secondsTotal; private final static int UPDATE_TIME = 1; private Handler uiThreadHandler = new Handler() { // Normally I'm lazy and just post Runnables to the uiThreadHandler // but time updating is special enough (it happens every second) to // take care not to allocate so much memory which forces Dalvik to GC // all the time. @Override public void handleMessage (Message msg) { if (msg.what == UPDATE_TIME) { updateTimeDisplayTo(secondsIn, secondsTotal); } } }; @Override public Handler getUIThreadHandler() { return uiThreadHandler; } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); albumText = (TextView) findViewById(R.id.albumname); artistText = (TextView) findViewById(R.id.artistname); trackText = (TextView) findViewById(R.id.trackname); homeButton = (ImageButton) findViewById(R.id.ic_mp_Home_btn); curPlayListButton = (ImageButton) findViewById(R.id.curplaylist); playPauseButton = (ImageButton) findViewById(R.id.pause); nextButton = (ImageButton) findViewById(R.id.next); prevButton = (ImageButton) findViewById(R.id.prev); albumArt = (ImageView) findViewById(R.id.album); currentTime = (TextView) findViewById(R.id.currenttime); totalTime = (TextView) findViewById(R.id.totaltime); seekBar = (SeekBar) findViewById(R.id.seekbar); // TODO: Simplify these following the notes at // http://developer.android.com/resources/articles/ui-1.6.html homeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (!isConnected()) return; SqueezerHomeActivity.show(SqueezerActivity.this); } }); curPlayListButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (!isConnected()) return; SqueezerCurrentPlaylistActivity.show(SqueezerActivity.this); } }); playPauseButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (getService() == null) return; try { if (isConnected.get()) { Log.v(getTag(), "Pause..."); getService().togglePausePlay(); } else { // When we're not connected, the play/pause // button turns into a green connect button. onUserInitiatesConnect(); } } catch (RemoteException e) { Log.e(getTag(), "Service exception from togglePausePlay(): " + e); } } }); nextButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (getService() == null) return; try { getService().nextTrack(); } catch (RemoteException e) { } } }); prevButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (getService() == null) return; try { getService().previousTrack(); } catch (RemoteException e) { } } }); artistText.setOnClickListener(new OnClickListener() { public void onClick(View v) { SqueezerSong song = getCurrentSong(); if (song != null) { SqueezerAlbumListActivity.show(SqueezerActivity.this, new SqueezerArtist(song.getArtist_id(), song.getArtist())); } } }); albumText.setOnClickListener(new OnClickListener() { public void onClick(View v) { SqueezerSong song = getCurrentSong(); if (song != null) { SqueezerSongListActivity.show(SqueezerActivity.this, new SqueezerAlbum(song.getAlbum_id(), song.getAlbum())); } } }); trackText.setOnClickListener(new OnClickListener() { public void onClick(View v) { SqueezerSong song = getCurrentSong(); if (song != null) { SqueezerSongListActivity.show(SqueezerActivity.this, new SqueezerArtist(song.getArtist_id(), song.getArtist())); } } }); seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { SqueezerSong seekingSong; // Update the time indicator to reflect the dragged thumb position. public void onProgressChanged(SeekBar s, int progress, boolean fromUser) { if (fromUser) { currentTime.setText(Util.makeTimeString(progress)); } } // Disable updates when user drags the thumb. public void onStartTrackingTouch(SeekBar s) { seekingSong = getCurrentSong(); updateSeekBar = false; } // Re-enable updates. If the current song is the same as when // we started seeking then jump to the new point in the track, // otherwise ignore the seek. public void onStopTrackingTouch(SeekBar s) { SqueezerSong thisSong = getCurrentSong(); updateSeekBar = true; if (seekingSong == thisSong) { setSecondsElapsed(s.getProgress()); } } }); } /* * Intercept hardware volume control keys to control Squeezeserver * volume. * * Change the volume when the key is depressed. Suppress the keyUp * event, otherwise you get a notification beep as well as the volume * changing. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: changeVolumeBy(+5); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: changeVolumeBy(-5); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: return true; } return super.onKeyUp(keyCode, event); } private boolean changeVolumeBy(int delta) { Log.v(getTag(), "Adjust volume by: " + delta); if (getService() == null) { return false; } try { getService().adjustVolumeBy(delta); return true; } catch (RemoteException e) { } return false; } // Should only be called the UI thread. private void setConnected(boolean connected, boolean postConnect) { Log.v(getTag(), "setConnected(" + connected + ", " + postConnect + ")"); if (postConnect) { connectInProgress = false; Log.v(getTag(), "Post-connect; connectingDialog == " + connectingDialog); if (connectingDialog != null) { Log.v(getTag(), "Dismissing..."); connectingDialog.dismiss(); connectInProgress = false; if (!connected) { Toast.makeText(this, getText(R.string.connection_failed_text), Toast.LENGTH_LONG).show(); return; } } } isConnected.set(connected); nextButton.setEnabled(connected); prevButton.setEnabled(connected); if (!connected) { nextButton.setImageResource(0); prevButton.setImageResource(0); albumArt.setImageDrawable(null); updateSongInfo(null); artistText.setText(getText(R.string.disconnected_text)); setTitleForPlayer(null); currentTime.setText("--:--"); totalTime.setText("--:--"); seekBar.setEnabled(false); seekBar.setProgress(0); } else { nextButton.setImageResource(android.R.drawable.ic_media_next); prevButton.setImageResource(android.R.drawable.ic_media_previous); updateSongInfoFromService(); seekBar.setEnabled(true); } updatePlayPauseIcon(); } private void updatePlayPauseIcon() { uiThreadHandler.post(new Runnable() { public void run() { if (!isConnected.get()) { playPauseButton.setImageResource(android.R.drawable.presence_online); // green circle } else if (isPlaying.get()) { playPauseButton.setImageResource(android.R.drawable.ic_media_pause); } else { playPauseButton.setImageResource(android.R.drawable.ic_media_play); } } }); } // May be called from any thread. private void setTitleForPlayer(final String playerName) { uiThreadHandler.post(new Runnable() { public void run() { if (playerName != null && !"".equals(playerName)) { setTitle(getText(R.string.app_name) + ": " + playerName); } else { setTitle(getText(R.string.app_name)); } } }); } @Override protected void onServiceConnected() throws RemoteException { Log.v(getTag(), "Service bound"); uiThreadHandler.post(new Runnable() { public void run() { updateUIFromServiceState(); // Assume they want to connect... if (!isConnected()) { String ipPort = getConfiguredCliIpPort(); if (ipPort != null) { startVisibleConnectionTo(ipPort); } } } }); getService().registerCallback(serviceCallback); } @Override public void onResume() { super.onResume(); Log.d(getTag(), "onResume..."); // Start it and have it run forever (until it shuts itself down). // This is required so swapping out the activity (and unbinding the // service connection in onPause) doesn't cause the service to be // killed due to zero refcount. This is our signal that we want // it running in the background. startService(new Intent(this, SqueezeService.class)); if (getService() != null) { updateUIFromServiceState(); // If they've already set this up in the past, what they probably // want to do at this point is connect to the server, so do it // automatically. (Requires a serviceStub. Else we'll do this // on the service connection callback.) if (!isConnected()) { String ipPort = getConfiguredCliIpPort(); if (ipPort != null) { startVisibleConnectionTo(ipPort); } } } } // Should only be called from the UI thread. private void updateUIFromServiceState() { // Update the UI to reflect connection state. Basically just for // the initial display, as changing the prev/next buttons to empty // doesn't seem to work in onCreate. (LayoutInflator still running?) setConnected(isConnected(), false); // TODO(bradfitz): remove this check once everything is converted into // safe accessors like isConnected() already is. if (getService() == null) { Log.e(getTag(), "Can't update UI with null serviceStub"); return; } try { setTitleForPlayer(getService().getActivePlayerName()); isPlaying.set(getService().isPlaying()); updatePlayPauseIcon(); } catch (RemoteException e) { Log.e(getTag(), "Service exception: " + e); } } private void updateTimeDisplayTo(int secondsIn, int secondsTotal) { if (updateSeekBar) { if (seekBar.getMax() != secondsTotal) { seekBar.setMax(secondsTotal); totalTime.setText(Util.makeTimeString(secondsTotal)); } seekBar.setProgress(secondsIn); currentTime.setText(Util.makeTimeString(secondsIn)); } } // Should only be called from the UI thread. private void updateSongInfoFromService() { updateSongInfo(getCurrentSong()); updateTimeDisplayTo(getSecondsElapsed(), getSecondsTotal()); updateAlbumArtIfNeeded(); } private void updateSongInfo(SqueezerSong song) { if (song != null) { artistText.setText(song.getArtist()); albumText.setText(song.getAlbum()); trackText.setText(song.getName()); } else { artistText.setText(""); albumText.setText(""); trackText.setText(""); } } // Should only be called from the UI thread. private void updateAlbumArtIfNeeded() { final String albumArtUrl = getCurrentAlbumArtUrl(); if (Util.atomicStringUpdated(currentAlbumArtUrl, albumArtUrl)) { albumArt.setImageResource(R.drawable.icon_album_noart_143); if (albumArtUrl != null && albumArtUrl.length() > 0) { backgroundExecutor.execute(new Runnable() { public void run() { if (!albumArtUrl.equals(currentAlbumArtUrl.get())) { // Bail out before fetch the resource if the song // album art has changed since this Runnable got // scheduled. return; } URL url; InputStream inputStream = null; boolean gotContent = false; try { url = new URL(albumArtUrl); inputStream = (InputStream) url.getContent(); gotContent = true; } catch (MalformedURLException e) { } catch (IOException e) { } if (!gotContent) { return; } final Drawable drawable = Drawable.createFromStream(inputStream, "src"); uiThreadHandler.post(new Runnable() { public void run() { if (albumArtUrl.equals(currentAlbumArtUrl.get())) { // Only set the image if the song art hasn't changed since we // started and finally fetched the image over the network // and decoded it. albumArt.setImageDrawable(drawable); } } }); } }); } } } private int getSecondsElapsed() { if (getService() == null) { return 0; } try { return getService().getSecondsElapsed(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in getSecondsElapsed(): " + e); } return 0; } private int getSecondsTotal() { if (getService() == null) { return 0; } try { return getService().getSecondsTotal(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in getSecondsTotal(): " + e); } return 0; } private boolean setSecondsElapsed(int seconds) { if (getService() == null) { return false; } try { return getService().setSecondsElapsed(seconds); } catch (RemoteException e) { Log.e(getTag(), "Service exception in setSecondsElapsed(" + seconds + "): " + e); } return true; } private SqueezerSong getCurrentSong() { if (getService() == null) { return null; } try { return getService().currentSong(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in getServiceCurrentSong(): " + e); } return null; } private String getCurrentAlbumArtUrl() { if (getService() == null) { return ""; } try { return getService().currentAlbumArtUrl(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in getCurrentAlbumArtUrl(): " + e); } return ""; } private boolean isConnected() { if (getService() == null) { return false; } try { return getService().isConnected(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in isConnected(): " + e); } return false; } private boolean canPowerOn() { if (getService() == null) { return false; } try { return getService().canPowerOn(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in canPowerOn(): " + e); } return false; } private boolean canPowerOff() { if (getService() == null) { return false; } try { return getService().canPowerOff(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in canPowerOff(): " + e); } return false; } @Override public void onPause() { if (getService() != null) { try { getService().unregisterCallback(serviceCallback); } catch (RemoteException e) { Log.e(getTag(), "Service exception in onPause(): " + e); } } super.onPause(); } @Override public boolean onSearchRequested() { SqueezerSearchActivity.show(this); return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.squeezer, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean connected = isConnected.get(); // Only show one of connect and disconnect: MenuItem connect = menu.findItem(R.id.menu_item_connect); connect.setVisible(!connected); MenuItem disconnect = menu.findItem(R.id.menu_item_disconnect); disconnect.setVisible(connected); // Only show power on/off, according to playerstate MenuItem powerOn = menu.findItem(R.id.menu_item_poweron); powerOn.setVisible(canPowerOn()); MenuItem powerOff = menu.findItem(R.id.menu_item_poweroff); powerOff.setVisible(canPowerOff()); // Disable things that don't work when not connected. MenuItem players = menu.findItem(R.id.menu_item_players); players.setEnabled(connected); MenuItem search = menu.findItem(R.id.menu_item_search); search.setEnabled(connected); return true; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ABOUT: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getText(R.string.about_title)); PackageManager pm = getPackageManager(); PackageInfo info; String aboutText; try { info = pm.getPackageInfo("com.danga.squeezer", 0); aboutText = getString(R.string.about_text, info.versionName); } catch (NameNotFoundException e) { aboutText = "Package not found."; } builder.setMessage(Html.fromHtml(aboutText)); return builder.create(); case DIALOG_CONNECTING: // Note: this only happens the first time. onPrepareDialog is called on each connect. connectingDialog = new ProgressDialog(this); connectingDialog.setTitle(getText(R.string.connecting_text)); connectingDialog.setIndeterminate(true); return connectingDialog; } return null; } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_CONNECTING: ProgressDialog connectingDialog = (ProgressDialog) dialog; connectingDialog.setMessage(getString(R.string.connecting_to_text, connectingTo)); if (!connectInProgress) { // Lose the race? If Service/network is very fast. connectingDialog.dismiss(); } return; } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_settings: SettingsActivity.show(this); return true; case R.id.menu_item_search: SqueezerSearchActivity.show(this); return true; case R.id.menu_item_connect: onUserInitiatesConnect(); return true; case R.id.menu_item_disconnect: try { getService().disconnect(); } catch (RemoteException e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); } return true; case R.id.menu_item_poweron: try { getService().powerOn(); } catch (RemoteException e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); } return true; case R.id.menu_item_poweroff: try { getService().powerOff(); } catch (RemoteException e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); } return true; case R.id.menu_item_players: SqueezerPlayerListActivity.show(this); return true; case R.id.menu_item_about: showDialog(DIALOG_ABOUT); return true; } return super.onMenuItemSelected(featureId, item); } // Returns null if not configured. private String getConfiguredCliIpPort() { final SharedPreferences preferences = getSharedPreferences(Preferences.NAME, 0); final String ipPort = preferences.getString(Preferences.KEY_SERVERADDR, null); if (ipPort == null || ipPort.length() == 0) { return null; } return ipPort; } private void onUserInitiatesConnect() { if (getService() == null) { Log.e(getTag(), "serviceStub is null."); return; } String ipPort = getConfiguredCliIpPort(); if (ipPort == null) { SettingsActivity.show(this); return; } Log.v(getTag(), "User-initiated connect to: " + ipPort); startVisibleConnectionTo(ipPort); } private void startVisibleConnectionTo(String ipPort) { connectInProgress = true; connectingTo = ipPort; showDialog(DIALOG_CONNECTING); try { getService().startConnect(ipPort); } catch (RemoteException e) { Toast.makeText(this, "startConnection error: " + e, Toast.LENGTH_LONG).show(); } } public static void show(Context context) { final Intent intent = new Intent(context, SqueezerActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); context.startActivity(intent); } private IServiceCallback serviceCallback = new IServiceCallback.Stub() { public void onConnectionChanged(final boolean isConnected, final boolean postConnect) throws RemoteException { Log.v(getTag(), "Connected == " + isConnected + " (postConnect==" + postConnect + ")"); uiThreadHandler.post(new Runnable() { public void run() { setConnected(isConnected, postConnect); } }); } public void onPlayerChanged(final String playerId, final String playerName) throws RemoteException { Log.v(getTag(), "player now " + playerId + ": " + playerName); setTitleForPlayer(playerName); } public void onMusicChanged() throws RemoteException { uiThreadHandler.post(new Runnable() { public void run() { updateSongInfoFromService(); } }); } public void onVolumeChange(final int newVolume) throws RemoteException { Log.v(getTag(), "Volume = " + newVolume); // uiThreadHandler.post(new Runnable() { // public void run() { // Do something here if necessary // } // }); } public void onPlayStatusChanged(boolean newStatus) throws RemoteException { isPlaying.set(newStatus); updatePlayPauseIcon(); } public void onTimeInSongChange(final int secondsIn, final int secondsTotal) throws RemoteException { SqueezerActivity.this.secondsIn = secondsIn; SqueezerActivity.this.secondsTotal = secondsTotal; uiThreadHandler.sendEmptyMessage(UPDATE_TIME); } }; }
src/com/danga/squeezer/SqueezerActivity.java
package com.danga.squeezer; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.text.Html; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.danga.squeezer.framework.SqueezerBaseActivity; import com.danga.squeezer.itemlists.SqueezerAlbumListActivity; import com.danga.squeezer.itemlists.SqueezerCurrentPlaylistActivity; import com.danga.squeezer.itemlists.SqueezerPlayerListActivity; import com.danga.squeezer.itemlists.SqueezerSongListActivity; import com.danga.squeezer.model.SqueezerAlbum; import com.danga.squeezer.model.SqueezerArtist; import com.danga.squeezer.model.SqueezerSong; import com.danga.squeezer.service.SqueezeService; public class SqueezerActivity extends SqueezerBaseActivity { private static final int DIALOG_ABOUT = 0; private static final int DIALOG_CONNECTING = 1; protected static final int HOME_REQUESTCODE = 0; private AtomicBoolean isConnected = new AtomicBoolean(false); private AtomicBoolean isPlaying = new AtomicBoolean(false); private AtomicReference<String> currentAlbumArtUrl = new AtomicReference<String>(); private TextView albumText; private TextView artistText; private TextView trackText; private TextView currentTime; private TextView totalTime; private ImageButton homeButton; private ImageButton curPlayListButton; private ImageButton playPauseButton; private ImageButton nextButton; private ImageButton prevButton; private ImageView albumArt; private SeekBar seekBar; private final ScheduledThreadPoolExecutor backgroundExecutor = new ScheduledThreadPoolExecutor(1); // Where we're connecting to. private boolean connectInProgress = false; private String connectingTo = null; private ProgressDialog connectingDialog = null; // Updating the seekbar private boolean updateSeekBar = true; private volatile int secondsIn; private volatile int secondsTotal; private final static int UPDATE_TIME = 1; private Handler uiThreadHandler = new Handler() { // Normally I'm lazy and just post Runnables to the uiThreadHandler // but time updating is special enough (it happens every second) to // take care not to allocate so much memory which forces Dalvik to GC // all the time. @Override public void handleMessage (Message msg) { if (msg.what == UPDATE_TIME) { updateTimeDisplayTo(secondsIn, secondsTotal); } } }; @Override public Handler getUIThreadHandler() { return uiThreadHandler; } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); albumText = (TextView) findViewById(R.id.albumname); artistText = (TextView) findViewById(R.id.artistname); trackText = (TextView) findViewById(R.id.trackname); homeButton = (ImageButton) findViewById(R.id.ic_mp_Home_btn); curPlayListButton = (ImageButton) findViewById(R.id.curplaylist); playPauseButton = (ImageButton) findViewById(R.id.pause); nextButton = (ImageButton) findViewById(R.id.next); prevButton = (ImageButton) findViewById(R.id.prev); albumArt = (ImageView) findViewById(R.id.album); currentTime = (TextView) findViewById(R.id.currenttime); totalTime = (TextView) findViewById(R.id.totaltime); seekBar = (SeekBar) findViewById(R.id.seekbar); homeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (!isConnected()) return; SqueezerHomeActivity.show(SqueezerActivity.this); } }); curPlayListButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (!isConnected()) return; SqueezerCurrentPlaylistActivity.show(SqueezerActivity.this); } }); playPauseButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (getService() == null) return; try { if (isConnected.get()) { Log.v(getTag(), "Pause..."); getService().togglePausePlay(); } else { // When we're not connected, the play/pause // button turns into a green connect button. onUserInitiatesConnect(); } } catch (RemoteException e) { Log.e(getTag(), "Service exception from togglePausePlay(): " + e); } } }); nextButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (getService() == null) return; try { getService().nextTrack(); } catch (RemoteException e) { } } }); prevButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (getService() == null) return; try { getService().previousTrack(); } catch (RemoteException e) { } } }); artistText.setOnClickListener(new OnClickListener() { public void onClick(View v) { SqueezerSong song = getCurrentSong(); if (song != null) { SqueezerAlbumListActivity.show(SqueezerActivity.this, new SqueezerArtist(song.getArtist_id(), song.getArtist())); } } }); albumText.setOnClickListener(new OnClickListener() { public void onClick(View v) { SqueezerSong song = getCurrentSong(); if (song != null) { SqueezerSongListActivity.show(SqueezerActivity.this, new SqueezerAlbum(song.getAlbum_id(), song.getAlbum())); } } }); trackText.setOnClickListener(new OnClickListener() { public void onClick(View v) { SqueezerSong song = getCurrentSong(); if (song != null) { SqueezerSongListActivity.show(SqueezerActivity.this, new SqueezerArtist(song.getArtist_id(), song.getArtist())); } } }); seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { SqueezerSong seekingSong; // Update the time indicator to reflect the dragged thumb position. public void onProgressChanged(SeekBar s, int progress, boolean fromUser) { if (fromUser) { currentTime.setText(Util.makeTimeString(progress)); } } // Disable updates when user drags the thumb. public void onStartTrackingTouch(SeekBar s) { seekingSong = getCurrentSong(); updateSeekBar = false; } // Re-enable updates. If the current song is the same as when // we started seeking then jump to the new point in the track, // otherwise ignore the seek. public void onStopTrackingTouch(SeekBar s) { SqueezerSong thisSong = getCurrentSong(); updateSeekBar = true; if (seekingSong == thisSong) { setSecondsElapsed(s.getProgress()); } } }); } /* * Intercept hardware volume control keys to control Squeezeserver * volume. * * Change the volume when the key is depressed. Suppress the keyUp * event, otherwise you get a notification beep as well as the volume * changing. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: changeVolumeBy(+5); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: changeVolumeBy(-5); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: return true; } return super.onKeyUp(keyCode, event); } private boolean changeVolumeBy(int delta) { Log.v(getTag(), "Adjust volume by: " + delta); if (getService() == null) { return false; } try { getService().adjustVolumeBy(delta); return true; } catch (RemoteException e) { } return false; } // Should only be called the UI thread. private void setConnected(boolean connected, boolean postConnect) { Log.v(getTag(), "setConnected(" + connected + ", " + postConnect + ")"); if (postConnect) { connectInProgress = false; Log.v(getTag(), "Post-connect; connectingDialog == " + connectingDialog); if (connectingDialog != null) { Log.v(getTag(), "Dismissing..."); connectingDialog.dismiss(); connectInProgress = false; if (!connected) { Toast.makeText(this, getText(R.string.connection_failed_text), Toast.LENGTH_LONG).show(); return; } } } isConnected.set(connected); nextButton.setEnabled(connected); prevButton.setEnabled(connected); if (!connected) { nextButton.setImageResource(0); prevButton.setImageResource(0); albumArt.setImageDrawable(null); updateSongInfo(null); artistText.setText(getText(R.string.disconnected_text)); setTitleForPlayer(null); currentTime.setText("--:--"); totalTime.setText("--:--"); seekBar.setEnabled(false); seekBar.setProgress(0); } else { nextButton.setImageResource(android.R.drawable.ic_media_next); prevButton.setImageResource(android.R.drawable.ic_media_previous); updateSongInfoFromService(); seekBar.setEnabled(true); } updatePlayPauseIcon(); } private void updatePlayPauseIcon() { uiThreadHandler.post(new Runnable() { public void run() { if (!isConnected.get()) { playPauseButton.setImageResource(android.R.drawable.presence_online); // green circle } else if (isPlaying.get()) { playPauseButton.setImageResource(android.R.drawable.ic_media_pause); } else { playPauseButton.setImageResource(android.R.drawable.ic_media_play); } } }); } // May be called from any thread. private void setTitleForPlayer(final String playerName) { uiThreadHandler.post(new Runnable() { public void run() { if (playerName != null && !"".equals(playerName)) { setTitle(getText(R.string.app_name) + ": " + playerName); } else { setTitle(getText(R.string.app_name)); } } }); } @Override protected void onServiceConnected() throws RemoteException { Log.v(getTag(), "Service bound"); uiThreadHandler.post(new Runnable() { public void run() { updateUIFromServiceState(); // Assume they want to connect... if (!isConnected()) { String ipPort = getConfiguredCliIpPort(); if (ipPort != null) { startVisibleConnectionTo(ipPort); } } } }); getService().registerCallback(serviceCallback); } @Override public void onResume() { super.onResume(); Log.d(getTag(), "onResume..."); // Start it and have it run forever (until it shuts itself down). // This is required so swapping out the activity (and unbinding the // service connection in onPause) doesn't cause the service to be // killed due to zero refcount. This is our signal that we want // it running in the background. startService(new Intent(this, SqueezeService.class)); if (getService() != null) { updateUIFromServiceState(); // If they've already set this up in the past, what they probably // want to do at this point is connect to the server, so do it // automatically. (Requires a serviceStub. Else we'll do this // on the service connection callback.) if (!isConnected()) { String ipPort = getConfiguredCliIpPort(); if (ipPort != null) { startVisibleConnectionTo(ipPort); } } } } // Should only be called from the UI thread. private void updateUIFromServiceState() { // Update the UI to reflect connection state. Basically just for // the initial display, as changing the prev/next buttons to empty // doesn't seem to work in onCreate. (LayoutInflator still running?) setConnected(isConnected(), false); // TODO(bradfitz): remove this check once everything is converted into // safe accessors like isConnected() already is. if (getService() == null) { Log.e(getTag(), "Can't update UI with null serviceStub"); return; } try { setTitleForPlayer(getService().getActivePlayerName()); isPlaying.set(getService().isPlaying()); updatePlayPauseIcon(); } catch (RemoteException e) { Log.e(getTag(), "Service exception: " + e); } } private void updateTimeDisplayTo(int secondsIn, int secondsTotal) { if (updateSeekBar) { if (seekBar.getMax() != secondsTotal) { seekBar.setMax(secondsTotal); totalTime.setText(Util.makeTimeString(secondsTotal)); } seekBar.setProgress(secondsIn); currentTime.setText(Util.makeTimeString(secondsIn)); } } // Should only be called from the UI thread. private void updateSongInfoFromService() { updateSongInfo(getCurrentSong()); updateTimeDisplayTo(getSecondsElapsed(), getSecondsTotal()); updateAlbumArtIfNeeded(); } private void updateSongInfo(SqueezerSong song) { if (song != null) { artistText.setText(song.getArtist()); albumText.setText(song.getAlbum()); trackText.setText(song.getName()); } else { artistText.setText(""); albumText.setText(""); trackText.setText(""); } } // Should only be called from the UI thread. private void updateAlbumArtIfNeeded() { final String albumArtUrl = getCurrentAlbumArtUrl(); if (Util.atomicStringUpdated(currentAlbumArtUrl, albumArtUrl)) { albumArt.setImageResource(R.drawable.icon_album_noart_143); if (albumArtUrl != null && albumArtUrl.length() > 0) { backgroundExecutor.execute(new Runnable() { public void run() { if (!albumArtUrl.equals(currentAlbumArtUrl.get())) { // Bail out before fetch the resource if the song // album art has changed since this Runnable got // scheduled. return; } URL url; InputStream inputStream = null; boolean gotContent = false; try { url = new URL(albumArtUrl); inputStream = (InputStream) url.getContent(); gotContent = true; } catch (MalformedURLException e) { } catch (IOException e) { } if (!gotContent) { return; } final Drawable drawable = Drawable.createFromStream(inputStream, "src"); uiThreadHandler.post(new Runnable() { public void run() { if (albumArtUrl.equals(currentAlbumArtUrl.get())) { // Only set the image if the song art hasn't changed since we // started and finally fetched the image over the network // and decoded it. albumArt.setImageDrawable(drawable); } } }); } }); } } } private int getSecondsElapsed() { if (getService() == null) { return 0; } try { return getService().getSecondsElapsed(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in getSecondsElapsed(): " + e); } return 0; } private int getSecondsTotal() { if (getService() == null) { return 0; } try { return getService().getSecondsTotal(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in getSecondsTotal(): " + e); } return 0; } private boolean setSecondsElapsed(int seconds) { if (getService() == null) { return false; } try { return getService().setSecondsElapsed(seconds); } catch (RemoteException e) { Log.e(getTag(), "Service exception in setSecondsElapsed(" + seconds + "): " + e); } return true; } private SqueezerSong getCurrentSong() { if (getService() == null) { return null; } try { return getService().currentSong(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in getServiceCurrentSong(): " + e); } return null; } private String getCurrentAlbumArtUrl() { if (getService() == null) { return ""; } try { return getService().currentAlbumArtUrl(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in getCurrentAlbumArtUrl(): " + e); } return ""; } private boolean isConnected() { if (getService() == null) { return false; } try { return getService().isConnected(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in isConnected(): " + e); } return false; } private boolean canPowerOn() { if (getService() == null) { return false; } try { return getService().canPowerOn(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in canPowerOn(): " + e); } return false; } private boolean canPowerOff() { if (getService() == null) { return false; } try { return getService().canPowerOff(); } catch (RemoteException e) { Log.e(getTag(), "Service exception in canPowerOff(): " + e); } return false; } @Override public void onPause() { if (getService() != null) { try { getService().unregisterCallback(serviceCallback); } catch (RemoteException e) { Log.e(getTag(), "Service exception in onPause(): " + e); } } super.onPause(); } @Override public boolean onSearchRequested() { SqueezerSearchActivity.show(this); return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.squeezer, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean connected = isConnected.get(); // Only show one of connect and disconnect: MenuItem connect = menu.findItem(R.id.menu_item_connect); connect.setVisible(!connected); MenuItem disconnect = menu.findItem(R.id.menu_item_disconnect); disconnect.setVisible(connected); // Only show power on/off, according to playerstate MenuItem powerOn = menu.findItem(R.id.menu_item_poweron); powerOn.setVisible(canPowerOn()); MenuItem powerOff = menu.findItem(R.id.menu_item_poweroff); powerOff.setVisible(canPowerOff()); // Disable things that don't work when not connected. MenuItem players = menu.findItem(R.id.menu_item_players); players.setEnabled(connected); MenuItem search = menu.findItem(R.id.menu_item_search); search.setEnabled(connected); return true; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ABOUT: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getText(R.string.about_title)); PackageManager pm = getPackageManager(); PackageInfo info; String aboutText; try { info = pm.getPackageInfo("com.danga.squeezer", 0); aboutText = getString(R.string.about_text, info.versionName); } catch (NameNotFoundException e) { aboutText = "Package not found."; } builder.setMessage(Html.fromHtml(aboutText)); return builder.create(); case DIALOG_CONNECTING: // Note: this only happens the first time. onPrepareDialog is called on each connect. connectingDialog = new ProgressDialog(this); connectingDialog.setTitle(getText(R.string.connecting_text)); connectingDialog.setIndeterminate(true); return connectingDialog; } return null; } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_CONNECTING: ProgressDialog connectingDialog = (ProgressDialog) dialog; connectingDialog.setMessage(getString(R.string.connecting_to_text, connectingTo)); if (!connectInProgress) { // Lose the race? If Service/network is very fast. connectingDialog.dismiss(); } return; } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_settings: SettingsActivity.show(this); return true; case R.id.menu_item_search: SqueezerSearchActivity.show(this); return true; case R.id.menu_item_connect: onUserInitiatesConnect(); return true; case R.id.menu_item_disconnect: try { getService().disconnect(); } catch (RemoteException e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); } return true; case R.id.menu_item_poweron: try { getService().powerOn(); } catch (RemoteException e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); } return true; case R.id.menu_item_poweroff: try { getService().powerOff(); } catch (RemoteException e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); } return true; case R.id.menu_item_players: SqueezerPlayerListActivity.show(this); return true; case R.id.menu_item_about: showDialog(DIALOG_ABOUT); return true; } return super.onMenuItemSelected(featureId, item); } // Returns null if not configured. private String getConfiguredCliIpPort() { final SharedPreferences preferences = getSharedPreferences(Preferences.NAME, 0); final String ipPort = preferences.getString(Preferences.KEY_SERVERADDR, null); if (ipPort == null || ipPort.length() == 0) { return null; } return ipPort; } private void onUserInitiatesConnect() { if (getService() == null) { Log.e(getTag(), "serviceStub is null."); return; } String ipPort = getConfiguredCliIpPort(); if (ipPort == null) { SettingsActivity.show(this); return; } Log.v(getTag(), "User-initiated connect to: " + ipPort); startVisibleConnectionTo(ipPort); } private void startVisibleConnectionTo(String ipPort) { connectInProgress = true; connectingTo = ipPort; showDialog(DIALOG_CONNECTING); try { getService().startConnect(ipPort); } catch (RemoteException e) { Toast.makeText(this, "startConnection error: " + e, Toast.LENGTH_LONG).show(); } } public static void show(Context context) { final Intent intent = new Intent(context, SqueezerActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); context.startActivity(intent); } private IServiceCallback serviceCallback = new IServiceCallback.Stub() { public void onConnectionChanged(final boolean isConnected, final boolean postConnect) throws RemoteException { Log.v(getTag(), "Connected == " + isConnected + " (postConnect==" + postConnect + ")"); uiThreadHandler.post(new Runnable() { public void run() { setConnected(isConnected, postConnect); } }); } public void onPlayerChanged(final String playerId, final String playerName) throws RemoteException { Log.v(getTag(), "player now " + playerId + ": " + playerName); setTitleForPlayer(playerName); } public void onMusicChanged() throws RemoteException { uiThreadHandler.post(new Runnable() { public void run() { updateSongInfoFromService(); } }); } public void onVolumeChange(final int newVolume) throws RemoteException { Log.v(getTag(), "Volume = " + newVolume); // uiThreadHandler.post(new Runnable() { // public void run() { // Do something here if necessary // } // }); } public void onPlayStatusChanged(boolean newStatus) throws RemoteException { isPlaying.set(newStatus); updatePlayPauseIcon(); } public void onTimeInSongChange(final int secondsIn, final int secondsTotal) throws RemoteException { SqueezerActivity.this.secondsIn = secondsIn; SqueezerActivity.this.secondsTotal = secondsTotal; uiThreadHandler.sendEmptyMessage(UPDATE_TIME); } }; }
Add a TODO for button handling.
src/com/danga/squeezer/SqueezerActivity.java
Add a TODO for button handling.
Java
apache-2.0
616f59ee63377e7a748a4a0f9692b4420037a55c
0
panzy/AndroidRecording
/* * Copyright (C) 2013 Steelkiwi Development, Julia Zudikova, Viacheslav Tyagotenkov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.skd.androidrecording.video; import android.annotation.SuppressLint; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Size; import android.os.Build; import android.view.Surface; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /* * Represents camera management helper class. * Holds method for setting camera display orientation. */ public class CameraHelper { public static int getAvailableCamerasCount() { return Camera.getNumberOfCameras(); } public static int getDefaultCameraID() { int camerasCnt = getAvailableCamerasCount(); int defaultCameraID = 0; CameraInfo cameraInfo = new CameraInfo(); for (int i=0; i <camerasCnt; i++) { Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { defaultCameraID = i; } } return defaultCameraID; } public static boolean isCameraFacingBack(int cameraID) { CameraInfo cameraInfo = new CameraInfo(); Camera.getCameraInfo(cameraID, cameraInfo); return (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK); } @SuppressLint("NewApi") public static List<Size> getCameraSupportedVideoSizes(android.hardware.Camera camera) { if ((Build.VERSION.SDK_INT >= 11) && (camera != null)) { if (camera.getParameters().getSupportedVideoSizes() != null) { return camera.getParameters().getSupportedVideoSizes(); } else { // Video sizes may be null, which indicates that all the supported // preview sizes are supported for video recording. HashSet<String> allSizesLiteral = new HashSet<>(); for (Camera.Size sz : camera.getParameters().getSupportedPreviewSizes()) { allSizesLiteral.add(String.format("%dx%d", sz.width, sz.height)); } // on Samsung Galaxy 3, the supported preview sizes are too many, // but it seems that not all of them can be used as recording video size. // the following set are used by the built-in camera app. Camera.Size[] preferredSizes = { camera.new Size(1920, 1080), camera.new Size(1280, 720), camera.new Size(720, 480), camera.new Size(640, 480), camera.new Size(320, 240) }; List<Size> result = new ArrayList<>(preferredSizes.length); for (Camera.Size sz : preferredSizes) { if (allSizesLiteral.contains(String.format("%dx%d", sz.width, sz.height))) result.add(sz); } return result; } } else { return null; } } public static int setCameraDisplayOrientation(int cameraId, android.hardware.Camera camera, int displayRotation) { Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(cameraId, info); int degrees = 0; switch (displayRotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int camRotationDegree = 0; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { camRotationDegree = (info.orientation + degrees) % 360; camRotationDegree = (360 - camRotationDegree) % 360; // compensate the mirror } else { camRotationDegree = (info.orientation - degrees + 360) % 360; } if (camera != null) { camera.setDisplayOrientation(camRotationDegree); } return camRotationDegree; } }
lib/src/com/skd/androidrecording/video/CameraHelper.java
/* * Copyright (C) 2013 Steelkiwi Development, Julia Zudikova, Viacheslav Tyagotenkov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.skd.androidrecording.video; import android.annotation.SuppressLint; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Size; import android.os.Build; import android.view.Surface; import java.util.List; /* * Represents camera management helper class. * Holds method for setting camera display orientation. */ public class CameraHelper { public static int getAvailableCamerasCount() { return Camera.getNumberOfCameras(); } public static int getDefaultCameraID() { int camerasCnt = getAvailableCamerasCount(); int defaultCameraID = 0; CameraInfo cameraInfo = new CameraInfo(); for (int i=0; i <camerasCnt; i++) { Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { defaultCameraID = i; } } return defaultCameraID; } public static boolean isCameraFacingBack(int cameraID) { CameraInfo cameraInfo = new CameraInfo(); Camera.getCameraInfo(cameraID, cameraInfo); return (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK); } @SuppressLint("NewApi") public static List<Size> getCameraSupportedVideoSizes(android.hardware.Camera camera) { if ((Build.VERSION.SDK_INT >= 11) && (camera != null)) { if (camera.getParameters().getSupportedVideoSizes() != null) { return camera.getParameters().getSupportedVideoSizes(); } else { // Video sizes may be null, which indicates that all the supported // preview sizes are supported for video recording. return camera.getParameters().getSupportedPreviewSizes(); } } else { return null; } } public static int setCameraDisplayOrientation(int cameraId, android.hardware.Camera camera, int displayRotation) { Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(cameraId, info); int degrees = 0; switch (displayRotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int camRotationDegree = 0; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { camRotationDegree = (info.orientation + degrees) % 360; camRotationDegree = (360 - camRotationDegree) % 360; // compensate the mirror } else { camRotationDegree = (info.orientation - degrees + 360) % 360; } if (camera != null) { camera.setDisplayOrientation(camRotationDegree); } return camRotationDegree; } }
filter video sizes
lib/src/com/skd/androidrecording/video/CameraHelper.java
filter video sizes
Java
apache-2.0
3402a856db4c21311b4a571a3085872e7511bc3b
0
leanddrot/IsisPlanEstudio,leanddrot/IsisPlanEstudio
package dom.planEstudio; import java.util.ArrayList; import java.util.List; import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Named; import org.apache.isis.applib.query.Query; @DomainService(menuOrder = "10", repositoryFor = Plan.class) public class PlanRepositorio { // {{ crearPlan (action) @MemberOrder(sequence = "1") public Plan crearPlan(final String descripcion) { Plan plan = container.newTransientInstance(Plan.class); plan.setDescripcion(descripcion); container.persistIfNotAlready(plan); return plan; } // }} // {{ listarPlanes (action) @MemberOrder(sequence = "1.2") public List<Plan> listarPlanes() { return container.allInstances(Plan.class); } // }} // {{ listarPlanes (action) @MemberOrder(sequence = "1.5") public Plan seleccionarUnPlan(Plan plan) { return plan; } // }} // region > agregarAnio // ////////////////////////////////////// @MemberOrder(sequence = "3") public Plan agregarAnio(final @Named("Plan") Plan plan, final @Named("") int anioNumero) { Anio nuevoAnio = new Anio(); nuevoAnio.setAnioNumero(anioNumero); plan.getAnioList().add(nuevoAnio); return plan; } public List<Integer> choices1AgregarAnio() { List<Integer> aniosDisponibles = new ArrayList<Integer>(); for (int i = 1; i < 9; i++) { aniosDisponibles.add(i); } return aniosDisponibles; } public String validateAgregarAnio(Plan plan, int anioNumero) { List<Anio> aniosList = plan.getAnioList(); for (Anio anio : aniosList) { if (anio.getAnioNumero() == anioNumero) { return "El año '" + anioNumero + "' ya fué creado"; } } return null; } // endRegion > agregarAnio // {{ EliminarPlan (action) @MemberOrder(sequence = "1") public String eliminarPlan(final @Named("Plan a eliminar") Plan plan) { String descripcion = plan.getDescripcion(); container.remove(plan); return "El plan de estudio '" + descripcion + "' ha sido Eliminado"; } // region > injected services // ////////////////////////////////////// @javax.inject.Inject DomainObjectContainer container; // endregion }
dom/src/main/java/dom/planEstudio/PlanRepositorio.java
package dom.planEstudio; import java.util.ArrayList; import java.util.List; import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Named; import org.apache.isis.applib.query.Query; @DomainService(menuOrder = "10", repositoryFor = Plan.class) public class PlanRepositorio { // {{ crearPlan (action) @MemberOrder(sequence = "1") public Plan crearPlan(final String descripcion) { Plan plan = container.newTransientInstance(Plan.class); plan.setDescripcion(descripcion); container.persistIfNotAlready(plan); return plan; } // }} // {{ listarPlanes (action) @MemberOrder(sequence = "1.2") public List<Plan> listarPlanes() { return container.allInstances(Plan.class); } // }} // {{ listarPlanes (action) @MemberOrder(sequence = "1.5") public Plan seleccionarUnPlan(Plan plan) { return plan; } // }} // region > agregarAnio // ////////////////////////////////////// @MemberOrder(sequence = "3") public Plan agregarAnio(final @Named("Plan") Plan plan, final @Named("") int anioNumero) { Anio nuevoAnio = new Anio(); nuevoAnio.setAnioNumero(anioNumero); plan.getAnioList().add(nuevoAnio); return plan; } public List<Integer> choices1AgregarAnio() { List<Integer> aniosDisponibles = new ArrayList<Integer>(); for (int i = 1; i < 9; i++) { aniosDisponibles.add(i); } return aniosDisponibles; } public String validateAgregarAnio(Plan plan, int anioNumero) { List<Anio> aniosList = plan.getAnioList(); for (Anio anio : aniosList) { if (anio.getAnioNumero() == anioNumero) { return "El año '" + anioNumero + "' ya fué creado"; } } return null; } // endRegion > agregarAnio // ////////////////////////////////////// // region > injected services // ////////////////////////////////////// @javax.inject.Inject DomainObjectContainer container; // endregion }
Agregado el metodo eliminar plan
dom/src/main/java/dom/planEstudio/PlanRepositorio.java
Agregado el metodo eliminar plan
Java
bsd-3-clause
7f2e252cc67379741d3d6d6bc1b6daac01f72d0c
0
mdcao/japsa,mdcao/japsa
package japsa.util; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.zip.GZIPOutputStream; import org.apache.commons.math3.linear.OpenMapRealMatrix; import org.apache.commons.math3.linear.SparseRealMatrix; import htsjdk.samtools.CigarElement; import htsjdk.samtools.SAMRecord; import japsa.seq.Sequence; import japsa.seq.SequenceOutputStream; import pal.distance.DistanceMatrix; import pal.misc.IdGroup; import pal.misc.SimpleIdGroup; import pal.tree.NeighborJoiningTree; import pal.tree.NodeUtils; public class TranscriptUtils { public static int overlap(int st1, int end1, int st2, int end2){ int minlen = Math.min(end1-st1, end2 - st2); int overlap = Math.min(end1-st2, end2 - st1); return Math.max(0, Math.min(minlen, overlap) +1); } public static int union(int st1, int end1, int st2, int end2, int overlap){ int len1 = end1 - st1; int len2 = end2 - st2; if(overlap<=0) { return len1+len2; }else{ int union = Math.max(end1-st2, end2 - st1); int maxlen = Math.max(len1, len2); return Math.max(union, maxlen)+1 - overlap; } } static String getString(int[] c) { StringBuffer sb = new StringBuffer(c[0]+""); for(int i=1; i<c.length;i++) { sb.append(",");sb.append(c[i]); } return sb.toString(); } static String getString(double[] c) { String formatstr = "%5.3g"; StringBuffer sb = new StringBuffer(String.format(formatstr,c[0]).trim()+""); for(int i=1; i<c.length;i++) { sb.append(",");sb.append(String.format(formatstr, c[i]).trim()); } return sb.toString(); } static String getString(String string, int num_sources2, boolean print_index) { StringBuffer sb = new StringBuffer(string); if(print_index) sb.append(0); for(int i=1; i<num_sources2;i++) { sb.append(",");sb.append(string); if(print_index)sb.append(i); } String res = sb.toString(); return res; } static double round2 = 100; static String[] nmes = "5_3:5_no3:no5_3:no5_no3".split(":"); public static class CigarClusters { final double thresh; CigarClusters(double thresh){ this.thresh = thresh; } public DistanceMatrix getDistanceMatrix( PrintWriter pw){ int len = l.size(); double[][] res = new double[len][]; String[] labels = new String[len]; for(int i=0; i<len; i++) { res[i] = new double[len]; CigarCluster cc = l.get(i); labels[i] = cc.id; res[i][i] =0; for(int j=0; j<i; j++) { CigarCluster cc_j = l.get(j); double dist = 1-cc.similarity(cc_j); res[i][j] = dist; res[j][i] = dist; } } for(int i=0; i<len; i++) { pw.print(labels[i]+","+l.get(i).index+","); pw.println(getString(res[i])); } IdGroup group = new SimpleIdGroup(labels); DistanceMatrix dm = new DistanceMatrix(res, group); return dm; } List<CigarCluster> l = new ArrayList<CigarCluster>(); public String matchCluster(CigarCluster c1, int index, int source_index, int num_sources) { String clusterID=""; double best_sc0=0; int best_index = -1; for (int i = 0; i < l.size(); i++) { double sc = l.get(i).similarity(c1,index, thresh); if(sc> best_sc0) { best_sc0 = sc; best_index = i; } } if (best_sc0 >= thresh) { CigarCluster clust = l.get(best_index); clust.merge(c1); clusterID = clust.id; // System.err.println("merged"); } else { CigarCluster newc = new CigarCluster(l.size()+"", index,num_sources); newc.addReadCount(source_index); newc.merge(c1); clusterID = newc.id; l.add(newc); System.err.println("new cluster " + best_sc0 + " " + best_index+" "+newc.id+" "+index); // System.err.println(l.size()); } return clusterID; } public void getConsensus(Annotation annot, Sequence refseq, PrintWriter[] exonP , PrintWriter[] transcriptsP, SequenceOutputStream[] seqFasta, PrintWriter[] clusterW, int[] depth, int num_sources) throws IOException{ int[] first_last = new int[2]; for(int i=0; i<exonP.length; i++){ exonP[i].println("ID,index,start,end"); transcriptsP[i].println("ID,index,start,end,startPos,endPos,totLen,countTotal,"+getString("count", num_sources,true)); } Collections.sort(l); int startPos = 0; for(int i=0; i<l.size(); i++) { CigarCluster cc = l.get(i); int[][] exons = cc.getExons( 0.3,10, depth, clusterW[cc.index]); String id = cc.id; String read_count = getString(cc.readCount); StringBuffer descline = new StringBuffer();//cc.index+","+read_count); StringBuffer subseq= new StringBuffer(); StringBuffer annotline = new StringBuffer(); int transcript_len =0; int endPos = startPos+cc.numPos; transcriptsP[cc.index].println(cc.id+","+cc.index+","+cc.start+","+cc.end+","+startPos+","+endPos+","+cc.totLen+","+cc.readCountSum+","+read_count); startPos =endPos; for(int j=0; j<exons.length; j++) { int start = exons[j][0]; int end = exons[j][1]; exonP[cc.index].println(id+","+cc.index+","+start+","+end+","+read_count); annotline.append(annot.calcORFOverlap(start, end, first_last, transcript_len)); int len = end-start+1; descline.append(";"); descline.append(start); descline.append("-"); descline.append(end); descline.append(","); descline.append(len); //descline.append("|");descline.append(annot.getInfo(first_last[0])); //descline.append("|");descline.append(annot.getInfo(first_last[1])); subseq.append(refseq.subSequence(start, end).toString()); //System.err.println(subseq.length()); //System.err.println(subseq); //System.err.println("h"); transcript_len += len; //seqline.append(subseq.toString()); } Sequence subseq1 = new Sequence(refseq.alphabet(),subseq.toString().toCharArray(), id); // subseq1.setName(id); descline.append(" "); descline.append(annotline); subseq1.setDesc(descline.toString()); subseq1.writeFasta(seqFasta[cc.index]); // seqFasta.println(idline.toString()); // seqFasta.println(seqline.toString()); } } } public static class CigarCluster implements Comparable{ final private int index; final String id; int start=0; int end=0; @Override public int compareTo(Object o) { CigarCluster ic1 = (CigarCluster)o; if(ic1.readCountSum==readCountSum) return 0; else return ic1.readCountSum<readCountSum ? -1 : 1; } public void addReadCount(int source_index) { readCount[source_index]++; this.readCountSum++; } public CigarCluster(String id, int index, int num_sources) { this.id = id; this.index = index; this.readCount = new int[num_sources]; } private SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); //coverate at high res public void clear(int source_index) { map.clear(); map100.clear(); Arrays.fill(readCount, 0); readCount[source_index]=1; readCountSum=1; start =0; end=0; } private SortedMap<Integer, Integer> map100 = new TreeMap<Integer, Integer>(); //coverage at low res (every 100bp) public void add(int round) { if(round<start) start =round; else if(round>end) end = round; int round1 = (int) Math.floor((double)round/round2); map.put(round, map.containsKey(round) ? map.get(round) + 1 : 1); map100.put(round1, map100.containsKey(round1) ? map100.get(round1) + 1 : 1); } public String toString() { return map.keySet().toString(); } public Iterator<Integer> keys() { return map.keySet().iterator(); } public Iterator<Integer> tailKeys(int st) { return map.tailMap(st).keySet().iterator(); } int getDepth(Integer i) { return this.map.containsKey(i) ? map.get(i) : 0; } int[][] exons; public int[][] getExons( double threshPerc, int numsteps, int[] depth, PrintWriter clusterW) { if(exons!=null) return exons; List<Integer> start1 = new ArrayList<Integer>(); List<Integer> end1 = new ArrayList<Integer>(); double thresh = (double) readCountSum*threshPerc; boolean in =false; Arrays.fill(depth, 0); numPos =0; totLen =0; boolean prev0 = start>1; boolean printPrev = false; for(int i=this.start; i<this.end; i++) { depth[i] = getDepth(i); if(depth[i]>0){ if(prev0 && !printPrev){ clusterW.println((i-1)+","+depth[i-1]+","+this.id); } numPos++; clusterW.println(i+","+depth[i]+","+this.id); prev0 = false; printPrev = true; }else if(!prev0){ clusterW.println(i+","+depth[i]+","+this.id); printPrev = true; prev0=true; }else{ printPrev = false; prev0 = true; } } outer: for(int i=start; i<=end; i++) { double dep = depth[i]; if(!in && dep>=thresh) { for(int j = 1; j<numsteps && i+j < depth.length; j++) { if(depth[i+j]<thresh) continue outer; // no longer jumping in } in = true; start1.add(i); } if(in && dep<thresh) { for(int j = 1; j<numsteps && i+j < depth.length; j++) { if(depth[i+j]>=thresh) continue outer; // no longer jumping out } in = false; end1.add(i-1); } } if(end1.size() < start1.size()) end1.add(end); exons = new int[end1.size()][]; for(int i=0; i<end1.size(); i++) { exons[i] = new int[] {start1.get(i), end1.get(i)}; totLen += end1.get(i) - start1.get(i)+1; } return exons; } int[] readCount; int readCountSum; int numPos =-1; int totLen = -1; /** if its going to be less than thresh we return zero */ public double similarity(CigarCluster c1,int index, double thresh) { if(this.index !=index) return 0; int overlap = overlap(c1.start,c1.end,start, end); if(overlap<0) return 0; else{ double union = union(c1.start, c1.end, start, end, overlap) ; if(overlap / union < thresh) return 0; } double sim = this.similarity(map100, c1.map100); if(sim<thresh ) return 0; else sim = this.similarity(map, c1.map); //System.err.println(highRes+" "+sim); return sim; } public static double similarity(int[][] exons1, int[][] exons2 ){ int overlap =0; int union =0; for(int i=0; i<exons1.length; i++){ int st1 = exons1[i][0]; int end1 = exons1[i][1]; for(int j=0; j<exons2.length; j++){ int st2 = exons2[j][0]; int end2 = exons2[j][1]; int overl = overlap(st1, end1,st2, end2); int unio = union(st1, end1,st2, end2, overl); overlap+=overl; union+= unio; } } return (double) overlap/(double) union; } public double exonSimilarity(CigarCluster c1){ return similarity(c1.exons, this.exons); } public double similarity(CigarCluster c1) { int overlap = overlap(c1.start, c1.end,start, end); if(overlap<=0) return 0; int union = union(c1.start, c1.end,start, end, overlap); double sim = (double) overlap/(double) union; if(sim < 0.5) return 0; double sim1 = this.similarity(map100, c1.map100); if(sim1<0.5) return sim1; else return this.similarity(map, c1.map); } public static double similarity(Map<Integer, Integer> map, Map<Integer, Integer> m1) { int intersection = 0; int union = map.size(); for (Iterator<Integer> it = m1.keySet().iterator(); it.hasNext();) { if (map.containsKey(it.next())) { intersection++; } else { union++; } } return ((double) intersection) / (double) union; } static int merge(Map<Integer, Integer> target, Map<Integer, Integer> source){ // int source_sum = sum(source); // int target_sum = sum(target); // int sum0 = source_sum+target_sum; Iterator<Entry<Integer, Integer>> it = source.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, Integer> entry = it.next(); Integer key = entry.getKey(); int curr = target.containsKey(key) ? target.get(key) : 0; int newv = curr + entry.getValue(); target.put(key, newv); } return sum(target); } static int sum(Map<Integer, Integer> source){ return source.values().stream() .reduce(0, Integer::sum); } public void merge(CigarCluster c1) { if(c1.start < start) start = c1.start; if(c1.end > end) end = c1.end; for(int i=0; i<this.readCount.length;i++) { readCount[i]+=c1.readCount[i]; } this.readCountSum+=c1.readCountSum; int sum1 = merge(map, c1.map); int sum2 = merge(map100,c1.map100); if(sum1!=sum2){ throw new RuntimeException("maps not concordant"); } } } public static class Annotation{ List<String> genes= new ArrayList<String>(); List<Integer> start = new ArrayList<Integer>(); List<Integer> end = new ArrayList<Integer>(); int[][] orfs; //Name,Type,Minimum,Maximum,Length,Direction,gene // 5'UTR,5'UTR,1,265,265,forward,none public Annotation(File f) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(f)) ; List<String> header = Arrays.asList(br.readLine().split(",")); int gene_ind = header.indexOf("gene"); int start_ind = header.indexOf("Minimum"); int end_ind = header.indexOf("Maximum"); String str = ""; while((str=br.readLine())!=null){ String[] line = str.split(","); String gene = line[gene_ind]; if(!gene.equals("none")) { genes.add(gene); int st = Integer.parseInt(line[start_ind]); int en = Integer.parseInt(line[end_ind]); start.add(st); end.add(en); } } br.close(); orfs = new int[start.size()][]; overlap = new double[start.size()]; orf_len = new int[start.size()]; for(int i=0; i<orf_len.length; i++) { orf_len[i] = end.get(i) - start.get(i)+1; orfs[i] = new int[] {start.get(i),end.get(i)}; } } /*public String getInfo(int i) { if(i<0 || overlap[i] <0) return "NA"; else return this.genes.get(i)+","+this.start_offset[i]+","+this.end_offset[i]; }*/ public final double[] overlap; public final int[] orf_len; //public final int[] start_offset; //relative start position of ORF // public final int[] end_offset; //relative end position of ORF public String calcORFOverlap(int start, int end, int[] first_last, int transcript_len) { //could consider correcting here to keep in-fram int first = -1; int last = -1; StringBuffer sb = new StringBuffer(); for(int i=0 ; i<orfs.length; i++) { int[] st_en = orfs[i]; overlap[i] = (double) overlap(start, end, st_en[0], st_en[1])/ (double)(st_en[1] - st_en[0] +1); if(overlap[i]>0) { if(first<0) first = i; last = i; sb.append(";"); sb.append(this.genes.get(i)); sb.append(","); sb.append(String.format( "%5.3g",overlap[i]).trim()); sb.append(","); sb.append(st_en[0] - start + transcript_len); // how far into read ORF starts; sb.append(","); sb.append(st_en[1] - start+transcript_len); // how far into read ORF ends } } first_last[0] =first; first_last[1] = last; return sb.toString(); } } public static class IdentityProfile1 { final File outfile, outfile1, outfile2, outfile3, outfile4, outfile5, outfile6, outfile7, outfile8; public IdentityProfile1(Sequence refSeq, File resDir, int num_sources, int genome_index, int round, boolean calculateCoExpression, double overlapThresh, int startThresh, int endThresh) throws IOException { //File readClusterFile = new File(outdir, "readclusters.txt.gz"); this.round = (double) round; this.num_sources = num_sources; this.coRefPositions = new CigarCluster("reuseable",0,num_sources); TranscriptUtils.round2 = 100.0/round; this.genome = refSeq; this.startThresh = startThresh; this.endThresh = endThresh; this.source_index = 0; this.calculateCoExpression = calculateCoExpression; outfile = new File(resDir,genome_index+ ".txt"); outfile1 = new File(resDir, genome_index+ "coref.txt"); outfile2 = new File(resDir, genome_index+"clusters.txt"); outfile3 = new File(resDir,genome_index+ "readToCluster.txt.gz"); outfile4 = new File(resDir,genome_index+ "exons.txt"); outfile5 = new File(resDir,genome_index+ "clusters.fa"); outfile6 = new File(resDir,genome_index+ "tree.txt.gz"); outfile7 = new File(resDir,genome_index+ "dist.txt.gz"); outfile8 = new File(resDir,genome_index+ "transcripts.txt"); readClusters = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile3)))); this.readClusters.println("readID,clusterID,index,source_index");//+clusterID+","+index+","+source_index); readClusters.println("readID,clusterId,type,source"); readClipped = 0; numDel = 0; numIns = 0; match = new int[refSeq.length()]; mismatch = new int[refSeq.length()]; refClipped = new int[refSeq.length()]; baseDel = new int[refSeq.length()]; baseIns = new int[refSeq.length()]; Arrays.fill(match, 0); Arrays.fill(mismatch, 0); Arrays.fill(baseDel, 0); Arrays.fill(baseIns, 0); Arrays.fill(refClipped, 0); refBase = 0; readBase = 0; // the number of bases from ref and read // following should be made more efficient Set<Integer> roundedPos = new HashSet<Integer>(); for (int i = 0; i < refSeq.length(); i++) { roundedPos.add(round(i)); } roundedPositions = roundedPos.toArray(new Integer[0]); this.depth = new int[roundedPos.size()]; /* * for(int i=0; i<roundedPositions.length; i++){ roundedPositions[i] = * 1+i*(int)round; } */ codepth = new SparseRealMatrix[nmes.length]; all_clusters =new CigarClusters(overlapThresh); if(this.calculateCoExpression) { for (int i = 0; i < this.codepth.length; i++) { codepth[i] = new OpenMapRealMatrix(roundedPositions.length, roundedPositions.length); } } } private int round(int pos) { int res = (int) Math.floor((double) pos / round); return res; } final int startThresh, endThresh; final double round ; private final boolean calculateCoExpression; final String[] nmes = "5_3:5_no3:no5_3:no5_no3".split(":"); public void processRefPositions(int startPos, int distToEnd, String id) { int index = 0; if (startPos < startThresh) index = distToEnd < endThresh ? 0 : 1; else index = distToEnd < endThresh ? 2 : 3; Iterator<Integer> it = coRefPositions.keys(); if(calculateCoExpression) { while (it.hasNext()) { Integer pos1 = it.next(); Iterator<Integer> it2 = coRefPositions.tailKeys(pos1); while (it2.hasNext()) { Integer pos2 = it2.next(); double value = codepth[index].getEntry(pos1, pos2); this.codepth[index].setEntry(pos1, pos2, value + 1); } } } // coRefPositions.index = index; String clusterID = this.all_clusters.matchCluster(coRefPositions,index, this.source_index, this.num_sources); // this also clears current cluster this.readClusters.println(id+","+clusterID+","+index+","+source_index); } public void addRefPositions(int position) { coRefPositions.add(round(position)); } public SparseRealMatrix[] codepth; private final CigarCluster coRefPositions; private CigarClusters all_clusters; private Integer[] roundedPositions;// , corefSum; private final int[] depth; // convenience matrix for depth public int[] match, mismatch, refClipped, baseDel, baseIns; public int numIns, numDel, readClipped, refBase, readBase; private final PrintWriter readClusters; private final Sequence genome; private final int num_sources; public int source_index; //source index public void updateSourceIndex(int i) { this.source_index = i; } public void print(PrintWriter pw, Sequence seq) { pw.println("pos,base,match,mismatch,refClipped,baseDel,baseIns"); for (int i = 0; i < match.length; i++) { pw.println((i + 1) + "," + seq.charAt(i) + "," + match[i] + "," + mismatch[i] + "," + refClipped[i] + "," + baseDel[i] + "," + baseIns[i]); } pw.flush(); } /*public void printClusters(File outfile1) throws IOException { PrintWriter pw = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile1)))); StringBuffer sb = new StringBuffer("pos,NA,"+getString("NA",num_sources,false)); for (int i = 0; i < this.roundedPositions.length; i++) { sb.append(","); sb.append(roundedPositions[i] * round + 1); } pw.println(sb.toString()); for (int i = 0; i < this.all_clusters.l.size(); i++) { this.all_clusters.l.get(i).print(pw); // pw.println(this.all_clusters.l.get(i).summary(this.roundedPositions)); } pw.close(); }*/ public void printCoRef(File outfile1) throws IOException { if(calculateCoExpression) { for (int index = 0; index < this.codepth.length; index++) { SparseRealMatrix cod = this.codepth[index]; if(cod==null) continue; File outfile1_ = new File(outfile1.getParentFile(), outfile1.getName() + "." + nmes[index] + ".gz"); PrintWriter pw = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile1_)))); int len = this.codepth[index].getRowDimension(); for (int i = 0; i < len; i++) { int row = i; // nonZeroRows.get(i); pw.print(roundedPositions[row] * round + 1); for (int j = 0; j < len; j++) { int col = j;// nonZeroRows.get(j); int val = col >= row ? (int) cod.getEntry(row, col) : 0; // (int) this.codepth[index].getEntry(col, row); pw.print(","); pw.print(val); } pw.println(); } pw.close(); } } } public void getConsensus(Annotation annot) throws IOException { int num_types = this.nmes.length; PrintWriter[] exonsP = new PrintWriter[num_types]; PrintWriter[] transcriptsP = new PrintWriter[num_types]; SequenceOutputStream[] seqFasta = new SequenceOutputStream[num_types]; PrintWriter[] clusterW = new PrintWriter[num_types]; for(int i=0; i<num_types; i++){ exonsP[i] =new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile4+"."+nmes[i]+".gz")))); seqFasta [i]= new SequenceOutputStream(new GZIPOutputStream(new FileOutputStream(outfile5+"."+nmes[i]+".gz"))); transcriptsP [i]= new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile8+"."+nmes[i]+".gz")))); clusterW[i]= new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile2+"."+nmes[i]+".gz")))); } this.all_clusters.getConsensus(annot, this.genome, exonsP, transcriptsP, seqFasta,clusterW, this.depth, this.num_sources); for(int i=0; i<num_types; i++){ clusterW[i].close(); exonsP[i].close(); seqFasta[i].close(); transcriptsP[i].close(); } } public void printTree() throws IOException{ PrintWriter treeP = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile6)))); PrintWriter distP = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile7)))); System.err.println("calculating distance matrix.."); DistanceMatrix dm = this.all_clusters.getDistanceMatrix( distP); System.err.println("..done"); NeighborJoiningTree tree = new NeighborJoiningTree(dm); //treeP.print(tree.toString()); NodeUtils.printNH(treeP, tree.getRoot(), true, false, 0, true); treeP.close(); distP.close(); } public void finalise() throws IOException{ this.readClusters.close(); IdentityProfile1 pr1 = this; PrintWriter pw = new PrintWriter(new FileWriter(outfile)); pr1.print(pw, genome); pw.close(); pr1.printCoRef(outfile1); // pr1.printClusters(outfile2); System.out.println("========================= TOTAL ============================"); } public void newRead(int source_index2) { this.coRefPositions.clear(source_index2); } } /** * Get the identity between a read sequence from a sam and a reference sequence * * @param refSeq * @param sam * @return */ public static void identity1(Sequence refSeq, Sequence readSeq, SAMRecord sam, IdentityProfile1 profile, int source_index) { int readPos = 0;// start from 0 int refPos = sam.getAlignmentStart() - 1;// convert to 0-based index //String id = sam.getHeader().getId(); String id = sam.getReadName(); profile.newRead(source_index); for (final CigarElement e : sam.getCigar().getCigarElements()) { final int length = e.getLength(); switch (e.getOperator()) { case H: // nothing todo profile.readClipped += length; break; // ignore hard clips case P: profile.readClipped += length; // pad is a kind of hard clipped ?? break; // ignore pads case S: // advance on the reference profile.readClipped += length; readPos += length; break; // soft clip read bases case N: // System.err.println(length); refPos += length; for (int i = 0; i < length && refPos + i < refSeq.length(); i++) { profile.refClipped[refPos + i] += 1; } // profile.refClipped += length; break; // reference skip case D:// deletion refPos += length; profile.refBase += length; for (int i = 0; i < length && refPos + i < refSeq.length(); i++) { profile.baseDel[refPos + i] += 1; } profile.numDel++; break; case I: readPos += length; profile.readBase += length; profile.baseIns[refPos] += length; profile.numIns++; break; case M: for (int i = 0; i < length && refPos + i < refSeq.length(); i++) { profile.addRefPositions(refPos + i); if (refSeq.getBase(refPos + i) == readSeq.getBase(readPos + i)) profile.match[refPos + i]++; else profile.mismatch[refPos + i]++; } profile.readBase += length; profile.refBase += length; readPos += length; refPos += length; break; case EQ: readPos += length; refPos += length; profile.addRefPositions(refPos); profile.readBase += length; profile.refBase += length; profile.match[refPos] += length; break; case X: readPos += length; refPos += length; profile.readBase += length; profile.refBase += length; profile.addRefPositions(refPos); profile.mismatch[refPos] += length; break; default: throw new IllegalStateException("Case statement didn't deal with cigar op: " + e.getOperator()); }// case } // for profile.processRefPositions(sam.getAlignmentStart(), refSeq.length() - sam.getAlignmentEnd(), id); // \return profile; } }
src/main/java/japsa/util/TranscriptUtils.java
package japsa.util; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.zip.GZIPOutputStream; import org.apache.commons.math3.linear.OpenMapRealMatrix; import org.apache.commons.math3.linear.SparseRealMatrix; import htsjdk.samtools.CigarElement; import htsjdk.samtools.SAMRecord; import japsa.seq.Sequence; import japsa.seq.SequenceOutputStream; import pal.distance.DistanceMatrix; import pal.misc.IdGroup; import pal.misc.SimpleIdGroup; import pal.tree.NeighborJoiningTree; import pal.tree.NodeUtils; public class TranscriptUtils { public static int overlap(int st1, int end1, int st2, int end2){ int minlen = Math.min(end1-st1, end2 - st2); int overlap = Math.min(end1-st2, end2 - st1); return Math.max(0, Math.min(minlen, overlap) +1); } public static int union(int st1, int end1, int st2, int end2, int overlap){ int len1 = end1 - st1; int len2 = end2 - st2; if(overlap<=0) { return len1+len2; }else{ int union = Math.max(end1-st2, end2 - st1); int maxlen = Math.max(len1, len2); return Math.max(union, maxlen)+1 - overlap; } } static String getString(int[] c) { StringBuffer sb = new StringBuffer(c[0]+""); for(int i=1; i<c.length;i++) { sb.append(",");sb.append(c[i]); } return sb.toString(); } static String getString(double[] c) { String formatstr = "%5.3g"; StringBuffer sb = new StringBuffer(String.format(formatstr,c[0]).trim()+""); for(int i=1; i<c.length;i++) { sb.append(",");sb.append(String.format(formatstr, c[i]).trim()); } return sb.toString(); } static String getString(String string, int num_sources2, boolean print_index) { StringBuffer sb = new StringBuffer(string); if(print_index) sb.append(0); for(int i=1; i<num_sources2;i++) { sb.append(",");sb.append(string); if(print_index)sb.append(i); } String res = sb.toString(); return res; } static double round2 = 100; static String[] nmes = "5_3:5_no3:no5_3:no5_no3".split(":"); public static class CigarClusters { final double thresh; CigarClusters(double thresh){ this.thresh = thresh; } public DistanceMatrix getDistanceMatrix( PrintWriter pw){ int len = l.size(); double[][] res = new double[len][]; String[] labels = new String[len]; for(int i=0; i<len; i++) { res[i] = new double[len]; CigarCluster cc = l.get(i); labels[i] = cc.id; res[i][i] =0; for(int j=0; j<i; j++) { CigarCluster cc_j = l.get(j); double dist = 1-cc.similarity(cc_j); res[i][j] = dist; res[j][i] = dist; } } for(int i=0; i<len; i++) { pw.print(labels[i]+","+l.get(i).index+","); pw.println(getString(res[i])); } IdGroup group = new SimpleIdGroup(labels); DistanceMatrix dm = new DistanceMatrix(res, group); return dm; } List<CigarCluster> l = new ArrayList<CigarCluster>(); public String matchCluster(CigarCluster c1, int index, int source_index, int num_sources) { String clusterID=""; double best_sc0=0; int best_index = -1; for (int i = 0; i < l.size(); i++) { double sc = l.get(i).similarity(c1,index, thresh); if(sc> best_sc0) { best_sc0 = sc; best_index = i; } } if (best_sc0 >= thresh) { CigarCluster clust = l.get(best_index); clust.merge(c1); clusterID = clust.id; // System.err.println("merged"); } else { CigarCluster newc = new CigarCluster(l.size()+"", index,num_sources); newc.addReadCount(source_index); newc.merge(c1); clusterID = newc.id; l.add(newc); System.err.println("new cluster " + best_sc0 + " " + best_index+" "+newc.id+" "+index); // System.err.println(l.size()); } return clusterID; } public void getConsensus(Annotation annot, Sequence refseq, PrintWriter[] exonP , PrintWriter[] transcriptsP, SequenceOutputStream[] seqFasta, PrintWriter[] clusterW, int[] depth, int num_sources) throws IOException{ int[] first_last = new int[2]; for(int i=0; i<exonP.length; i++){ exonP[i].println("ID,index,start,end"); transcriptsP[i].println("ID,index,start,end,startPos,endPos,totLen,countTotal,"+getString("count", num_sources,true)); } Collections.sort(l); int startPos = 0; for(int i=0; i<l.size(); i++) { CigarCluster cc = l.get(i); int[][] exons = cc.getExons( 0.3,10, depth, clusterW[cc.index]); String id = cc.id; String read_count = getString(cc.readCount); StringBuffer descline = new StringBuffer();//cc.index+","+read_count); StringBuffer subseq= new StringBuffer(); StringBuffer annotline = new StringBuffer(); int transcript_len =0; int endPos = startPos+cc.numPos; transcriptsP[cc.index].println(cc.id+","+cc.index+","+cc.start+","+cc.end+","+startPos+","+endPos+","+cc.totLen+","+cc.readCountSum+","+read_count); startPos =endPos; for(int j=0; j<exons.length; j++) { int start = exons[j][0]; int end = exons[j][1]; exonP[cc.index].println(id+","+cc.index+","+start+","+end+","+read_count); annotline.append(annot.calcORFOverlap(start, end, first_last, transcript_len)); int len = end-start+1; descline.append(";"); descline.append(start); descline.append("-"); descline.append(end); descline.append(","); descline.append(len); //descline.append("|");descline.append(annot.getInfo(first_last[0])); //descline.append("|");descline.append(annot.getInfo(first_last[1])); subseq.append(refseq.subSequence(start, end).toString()); //System.err.println(subseq.length()); //System.err.println(subseq); //System.err.println("h"); transcript_len += len; //seqline.append(subseq.toString()); } Sequence subseq1 = new Sequence(refseq.alphabet(),subseq.toString().toCharArray(), id); // subseq1.setName(id); descline.append(" "); descline.append(annotline); subseq1.setDesc(descline.toString()); subseq1.writeFasta(seqFasta[cc.index]); // seqFasta.println(idline.toString()); // seqFasta.println(seqline.toString()); } } } public static class CigarCluster implements Comparable{ final private int index; final String id; int start=0; int end=0; @Override public int compareTo(Object o) { CigarCluster ic1 = (CigarCluster)o; if(ic1.readCountSum==readCountSum) return 0; else return ic1.readCountSum<readCountSum ? -1 : 1; } public void addReadCount(int source_index) { readCount[source_index]++; this.readCountSum++; } public CigarCluster(String id, int index, int num_sources) { this.id = id; this.index = index; this.readCount = new int[num_sources]; } private SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); //coverate at high res public void clear(int source_index) { map.clear(); map100.clear(); Arrays.fill(readCount, 0); readCount[source_index]=1; readCountSum=1; start =0; end=0; } private SortedMap<Integer, Integer> map100 = new TreeMap<Integer, Integer>(); //coverage at low res (every 100bp) public void add(int round) { if(round<start) start =round; else if(round>end) end = round; int round1 = (int) Math.floor((double)round/round2); map.put(round, map.containsKey(round) ? map.get(round) + 1 : 1); map100.put(round1, map100.containsKey(round1) ? map100.get(round1) + 1 : 1); } public String toString() { return map.keySet().toString(); } public Iterator<Integer> keys() { return map.keySet().iterator(); } public Iterator<Integer> tailKeys(int st) { return map.tailMap(st).keySet().iterator(); } int getDepth(Integer i) { return this.map.containsKey(i) ? map.get(i) : 0; } int[][] exons; public int[][] getExons( double threshPerc, int numsteps, int[] depth, PrintWriter clusterW) { if(exons!=null) return exons; List<Integer> start1 = new ArrayList<Integer>(); List<Integer> end1 = new ArrayList<Integer>(); double thresh = (double) readCountSum*threshPerc; boolean in =false; Arrays.fill(depth, 0); numPos =0; totLen =0; for(int i=this.start; i<this.end; i++) { depth[i] = getDepth(i); if(depth[i]>0){ numPos++; clusterW.println(i+","+depth[i]+","+this.id); } } outer: for(int i=start; i<=end; i++) { double dep = depth[i]; if(!in && dep>=thresh) { for(int j = 1; j<numsteps && i+j < depth.length; j++) { if(depth[i+j]<thresh) continue outer; // no longer jumping in } in = true; start1.add(i); } if(in && dep<thresh) { for(int j = 1; j<numsteps && i+j < depth.length; j++) { if(depth[i+j]>=thresh) continue outer; // no longer jumping out } in = false; end1.add(i-1); } } if(end1.size() < start1.size()) end1.add(end); exons = new int[end1.size()][]; for(int i=0; i<end1.size(); i++) { exons[i] = new int[] {start1.get(i), end1.get(i)}; totLen += end1.get(i) - start1.get(i)+1; } return exons; } int[] readCount; int readCountSum; int numPos =-1; int totLen = -1; /** if its going to be less than thresh we return zero */ public double similarity(CigarCluster c1,int index, double thresh) { if(this.index !=index) return 0; int overlap = overlap(c1.start,c1.end,start, end); if(overlap<0) return 0; else{ double union = union(c1.start, c1.end, start, end, overlap) ; if(overlap / union < thresh) return 0; } double sim = this.similarity(map100, c1.map100); if(sim<thresh ) return 0; else sim = this.similarity(map, c1.map); //System.err.println(highRes+" "+sim); return sim; } public static double similarity(int[][] exons1, int[][] exons2 ){ int overlap =0; int union =0; for(int i=0; i<exons1.length; i++){ int st1 = exons1[i][0]; int end1 = exons1[i][1]; for(int j=0; j<exons2.length; j++){ int st2 = exons2[j][0]; int end2 = exons2[j][1]; int overl = overlap(st1, end1,st2, end2); int unio = union(st1, end1,st2, end2, overl); overlap+=overl; union+= unio; } } return (double) overlap/(double) union; } public double exonSimilarity(CigarCluster c1){ return similarity(c1.exons, this.exons); } public double similarity(CigarCluster c1) { int overlap = overlap(c1.start, c1.end,start, end); if(overlap<=0) return 0; int union = union(c1.start, c1.end,start, end, overlap); double sim = (double) overlap/(double) union; if(sim < 0.5) return 0; double sim1 = this.similarity(map100, c1.map100); if(sim1<0.5) return sim1; else return this.similarity(map, c1.map); } public static double similarity(Map<Integer, Integer> map, Map<Integer, Integer> m1) { int intersection = 0; int union = map.size(); for (Iterator<Integer> it = m1.keySet().iterator(); it.hasNext();) { if (map.containsKey(it.next())) { intersection++; } else { union++; } } return ((double) intersection) / (double) union; } static int merge(Map<Integer, Integer> target, Map<Integer, Integer> source){ // int source_sum = sum(source); // int target_sum = sum(target); // int sum0 = source_sum+target_sum; Iterator<Entry<Integer, Integer>> it = source.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, Integer> entry = it.next(); Integer key = entry.getKey(); int curr = target.containsKey(key) ? target.get(key) : 0; int newv = curr + entry.getValue(); target.put(key, newv); } return sum(target); } static int sum(Map<Integer, Integer> source){ return source.values().stream() .reduce(0, Integer::sum); } public void merge(CigarCluster c1) { if(c1.start < start) start = c1.start; if(c1.end > end) end = c1.end; for(int i=0; i<this.readCount.length;i++) { readCount[i]+=c1.readCount[i]; } this.readCountSum+=c1.readCountSum; int sum1 = merge(map, c1.map); int sum2 = merge(map100,c1.map100); if(sum1!=sum2){ throw new RuntimeException("maps not concordant"); } } } public static class Annotation{ List<String> genes= new ArrayList<String>(); List<Integer> start = new ArrayList<Integer>(); List<Integer> end = new ArrayList<Integer>(); int[][] orfs; //Name,Type,Minimum,Maximum,Length,Direction,gene // 5'UTR,5'UTR,1,265,265,forward,none public Annotation(File f) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(f)) ; List<String> header = Arrays.asList(br.readLine().split(",")); int gene_ind = header.indexOf("gene"); int start_ind = header.indexOf("Minimum"); int end_ind = header.indexOf("Maximum"); String str = ""; while((str=br.readLine())!=null){ String[] line = str.split(","); String gene = line[gene_ind]; if(!gene.equals("none")) { genes.add(gene); int st = Integer.parseInt(line[start_ind]); int en = Integer.parseInt(line[end_ind]); start.add(st); end.add(en); } } br.close(); orfs = new int[start.size()][]; overlap = new double[start.size()]; orf_len = new int[start.size()]; for(int i=0; i<orf_len.length; i++) { orf_len[i] = end.get(i) - start.get(i)+1; orfs[i] = new int[] {start.get(i),end.get(i)}; } } /*public String getInfo(int i) { if(i<0 || overlap[i] <0) return "NA"; else return this.genes.get(i)+","+this.start_offset[i]+","+this.end_offset[i]; }*/ public final double[] overlap; public final int[] orf_len; //public final int[] start_offset; //relative start position of ORF // public final int[] end_offset; //relative end position of ORF public String calcORFOverlap(int start, int end, int[] first_last, int transcript_len) { //could consider correcting here to keep in-fram int first = -1; int last = -1; StringBuffer sb = new StringBuffer(); for(int i=0 ; i<orfs.length; i++) { int[] st_en = orfs[i]; overlap[i] = (double) overlap(start, end, st_en[0], st_en[1])/ (double)(st_en[1] - st_en[0] +1); if(overlap[i]>0) { if(first<0) first = i; last = i; sb.append(";"); sb.append(this.genes.get(i)); sb.append(","); sb.append(String.format( "%5.3g",overlap[i]).trim()); sb.append(","); sb.append(st_en[0] - start + transcript_len); // how far into read ORF starts; sb.append(","); sb.append(st_en[1] - start+transcript_len); // how far into read ORF ends } } first_last[0] =first; first_last[1] = last; return sb.toString(); } } public static class IdentityProfile1 { final File outfile, outfile1, outfile2, outfile3, outfile4, outfile5, outfile6, outfile7, outfile8; public IdentityProfile1(Sequence refSeq, File resDir, int num_sources, int genome_index, int round, boolean calculateCoExpression, double overlapThresh, int startThresh, int endThresh) throws IOException { //File readClusterFile = new File(outdir, "readclusters.txt.gz"); this.round = (double) round; this.num_sources = num_sources; this.coRefPositions = new CigarCluster("reuseable",0,num_sources); TranscriptUtils.round2 = 100.0/round; this.genome = refSeq; this.startThresh = startThresh; this.endThresh = endThresh; this.source_index = 0; this.calculateCoExpression = calculateCoExpression; outfile = new File(resDir,genome_index+ ".txt"); outfile1 = new File(resDir, genome_index+ "coref.txt"); outfile2 = new File(resDir, genome_index+"clusters.txt"); outfile3 = new File(resDir,genome_index+ "readToCluster.txt.gz"); outfile4 = new File(resDir,genome_index+ "exons.txt"); outfile5 = new File(resDir,genome_index+ "clusters.fa"); outfile6 = new File(resDir,genome_index+ "tree.txt.gz"); outfile7 = new File(resDir,genome_index+ "dist.txt.gz"); outfile8 = new File(resDir,genome_index+ "transcripts.txt"); readClusters = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile3)))); this.readClusters.println("readID,clusterID,index,source_index");//+clusterID+","+index+","+source_index); readClusters.println("readID,clusterId,type,source"); readClipped = 0; numDel = 0; numIns = 0; match = new int[refSeq.length()]; mismatch = new int[refSeq.length()]; refClipped = new int[refSeq.length()]; baseDel = new int[refSeq.length()]; baseIns = new int[refSeq.length()]; Arrays.fill(match, 0); Arrays.fill(mismatch, 0); Arrays.fill(baseDel, 0); Arrays.fill(baseIns, 0); Arrays.fill(refClipped, 0); refBase = 0; readBase = 0; // the number of bases from ref and read // following should be made more efficient Set<Integer> roundedPos = new HashSet<Integer>(); for (int i = 0; i < refSeq.length(); i++) { roundedPos.add(round(i)); } roundedPositions = roundedPos.toArray(new Integer[0]); this.depth = new int[roundedPos.size()]; /* * for(int i=0; i<roundedPositions.length; i++){ roundedPositions[i] = * 1+i*(int)round; } */ codepth = new SparseRealMatrix[nmes.length]; all_clusters =new CigarClusters(overlapThresh); if(this.calculateCoExpression) { for (int i = 0; i < this.codepth.length; i++) { codepth[i] = new OpenMapRealMatrix(roundedPositions.length, roundedPositions.length); } } } private int round(int pos) { int res = (int) Math.floor((double) pos / round); return res; } final int startThresh, endThresh; final double round ; private final boolean calculateCoExpression; final String[] nmes = "5_3:5_no3:no5_3:no5_no3".split(":"); public void processRefPositions(int startPos, int distToEnd, String id) { int index = 0; if (startPos < startThresh) index = distToEnd < endThresh ? 0 : 1; else index = distToEnd < endThresh ? 2 : 3; Iterator<Integer> it = coRefPositions.keys(); if(calculateCoExpression) { while (it.hasNext()) { Integer pos1 = it.next(); Iterator<Integer> it2 = coRefPositions.tailKeys(pos1); while (it2.hasNext()) { Integer pos2 = it2.next(); double value = codepth[index].getEntry(pos1, pos2); this.codepth[index].setEntry(pos1, pos2, value + 1); } } } // coRefPositions.index = index; String clusterID = this.all_clusters.matchCluster(coRefPositions,index, this.source_index, this.num_sources); // this also clears current cluster this.readClusters.println(id+","+clusterID+","+index+","+source_index); } public void addRefPositions(int position) { coRefPositions.add(round(position)); } public SparseRealMatrix[] codepth; private final CigarCluster coRefPositions; private CigarClusters all_clusters; private Integer[] roundedPositions;// , corefSum; private final int[] depth; // convenience matrix for depth public int[] match, mismatch, refClipped, baseDel, baseIns; public int numIns, numDel, readClipped, refBase, readBase; private final PrintWriter readClusters; private final Sequence genome; private final int num_sources; public int source_index; //source index public void updateSourceIndex(int i) { this.source_index = i; } public void print(PrintWriter pw, Sequence seq) { pw.println("pos,base,match,mismatch,refClipped,baseDel,baseIns"); for (int i = 0; i < match.length; i++) { pw.println((i + 1) + "," + seq.charAt(i) + "," + match[i] + "," + mismatch[i] + "," + refClipped[i] + "," + baseDel[i] + "," + baseIns[i]); } pw.flush(); } /*public void printClusters(File outfile1) throws IOException { PrintWriter pw = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile1)))); StringBuffer sb = new StringBuffer("pos,NA,"+getString("NA",num_sources,false)); for (int i = 0; i < this.roundedPositions.length; i++) { sb.append(","); sb.append(roundedPositions[i] * round + 1); } pw.println(sb.toString()); for (int i = 0; i < this.all_clusters.l.size(); i++) { this.all_clusters.l.get(i).print(pw); // pw.println(this.all_clusters.l.get(i).summary(this.roundedPositions)); } pw.close(); }*/ public void printCoRef(File outfile1) throws IOException { if(calculateCoExpression) { for (int index = 0; index < this.codepth.length; index++) { SparseRealMatrix cod = this.codepth[index]; if(cod==null) continue; File outfile1_ = new File(outfile1.getParentFile(), outfile1.getName() + "." + nmes[index] + ".gz"); PrintWriter pw = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile1_)))); int len = this.codepth[index].getRowDimension(); for (int i = 0; i < len; i++) { int row = i; // nonZeroRows.get(i); pw.print(roundedPositions[row] * round + 1); for (int j = 0; j < len; j++) { int col = j;// nonZeroRows.get(j); int val = col >= row ? (int) cod.getEntry(row, col) : 0; // (int) this.codepth[index].getEntry(col, row); pw.print(","); pw.print(val); } pw.println(); } pw.close(); } } } public void getConsensus(Annotation annot) throws IOException { int num_types = this.nmes.length; PrintWriter[] exonsP = new PrintWriter[num_types]; PrintWriter[] transcriptsP = new PrintWriter[num_types]; SequenceOutputStream[] seqFasta = new SequenceOutputStream[num_types]; PrintWriter[] clusterW = new PrintWriter[num_types]; for(int i=0; i<num_types; i++){ exonsP[i] =new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile4+"."+nmes[i]+".gz")))); seqFasta [i]= new SequenceOutputStream(new GZIPOutputStream(new FileOutputStream(outfile5+"."+nmes[i]+".gz"))); transcriptsP [i]= new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile8+"."+nmes[i]+".gz")))); clusterW[i]= new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile2+"."+nmes[i]+".gz")))); } this.all_clusters.getConsensus(annot, this.genome, exonsP, transcriptsP, seqFasta,clusterW, this.depth, this.num_sources); for(int i=0; i<num_types; i++){ clusterW[i].close(); exonsP[i].close(); seqFasta[i].close(); transcriptsP[i].close(); } } public void printTree() throws IOException{ PrintWriter treeP = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile6)))); PrintWriter distP = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outfile7)))); System.err.println("calculating distance matrix.."); DistanceMatrix dm = this.all_clusters.getDistanceMatrix( distP); System.err.println("..done"); NeighborJoiningTree tree = new NeighborJoiningTree(dm); //treeP.print(tree.toString()); NodeUtils.printNH(treeP, tree.getRoot(), true, false, 0, true); treeP.close(); distP.close(); } public void finalise() throws IOException{ this.readClusters.close(); IdentityProfile1 pr1 = this; PrintWriter pw = new PrintWriter(new FileWriter(outfile)); pr1.print(pw, genome); pw.close(); pr1.printCoRef(outfile1); // pr1.printClusters(outfile2); System.out.println("========================= TOTAL ============================"); } public void newRead(int source_index2) { this.coRefPositions.clear(source_index2); } } /** * Get the identity between a read sequence from a sam and a reference sequence * * @param refSeq * @param sam * @return */ public static void identity1(Sequence refSeq, Sequence readSeq, SAMRecord sam, IdentityProfile1 profile, int source_index) { int readPos = 0;// start from 0 int refPos = sam.getAlignmentStart() - 1;// convert to 0-based index //String id = sam.getHeader().getId(); String id = sam.getReadName(); profile.newRead(source_index); for (final CigarElement e : sam.getCigar().getCigarElements()) { final int length = e.getLength(); switch (e.getOperator()) { case H: // nothing todo profile.readClipped += length; break; // ignore hard clips case P: profile.readClipped += length; // pad is a kind of hard clipped ?? break; // ignore pads case S: // advance on the reference profile.readClipped += length; readPos += length; break; // soft clip read bases case N: // System.err.println(length); refPos += length; for (int i = 0; i < length && refPos + i < refSeq.length(); i++) { profile.refClipped[refPos + i] += 1; } // profile.refClipped += length; break; // reference skip case D:// deletion refPos += length; profile.refBase += length; for (int i = 0; i < length && refPos + i < refSeq.length(); i++) { profile.baseDel[refPos + i] += 1; } profile.numDel++; break; case I: readPos += length; profile.readBase += length; profile.baseIns[refPos] += length; profile.numIns++; break; case M: for (int i = 0; i < length && refPos + i < refSeq.length(); i++) { profile.addRefPositions(refPos + i); if (refSeq.getBase(refPos + i) == readSeq.getBase(readPos + i)) profile.match[refPos + i]++; else profile.mismatch[refPos + i]++; } profile.readBase += length; profile.refBase += length; readPos += length; refPos += length; break; case EQ: readPos += length; refPos += length; profile.addRefPositions(refPos); profile.readBase += length; profile.refBase += length; profile.match[refPos] += length; break; case X: readPos += length; refPos += length; profile.readBase += length; profile.refBase += length; profile.addRefPositions(refPos); profile.mismatch[refPos] += length; break; default: throw new IllegalStateException("Case statement didn't deal with cigar op: " + e.getOperator()); }// case } // for profile.processRefPositions(sam.getAlignmentStart(), refSeq.length() - sam.getAlignmentEnd(), id); // \return profile; } }
update
src/main/java/japsa/util/TranscriptUtils.java
update
Java
bsd-3-clause
1f9d3ec3a0fced6c8c5832f4d24fb657596ff72f
0
Open-MBEE/MDK,Open-MBEE/MDK
/******************************************************************************* * Copyright (c) <2013>, California Institute of Technology ("Caltech"). * U.S. Government sponsorship acknowledged. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * - Neither the name of Caltech nor its operating division, the Jet Propulsion Laboratory, * nor the names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package gov.nasa.jpl.mbee.ems; import gov.nasa.jpl.mbee.lib.Utils; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.nomagic.magicdraw.core.Project; import com.nomagic.magicdraw.core.ProjectUtilities; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Comment; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceSpecification; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Package; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Slot; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ValueSpecification; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Extension; import com.nomagic.uml2.ext.magicdraw.mdprofiles.ProfileApplication; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype; public class ModelExporter { //private JSONObject elementHierarchy = new JSONObject(); private JSONObject elements = new JSONObject(); //private JSONArray roots = new JSONArray(); private List<Element> starts; private int depth; private boolean packageOnly; private Stereotype view = Utils.getViewStereotype(); private Stereotype viewpoint = Utils.getViewpointStereotype(); public ModelExporter(Project prj, int depth, boolean pkgOnly) { this.depth = depth; starts = new ArrayList<Element>(); for (Package pkg: prj.getModel().getNestedPackage()) { if (ProjectUtilities.isElementInAttachedProject(pkg)) continue;//check for module?? starts.add(pkg); } packageOnly = pkgOnly; } public ModelExporter(List<Element> roots, int depth, boolean pkgOnly) { this.depth = depth; this.starts = roots; packageOnly = pkgOnly; } public int getNumberOfElements() { return elements.size(); } @SuppressWarnings("unchecked") public JSONObject getResult() { for (Element e: starts) { addToElements(e, 1); //roots.add(e.getID()); } JSONObject result = new JSONObject(); //result.put("roots", roots); JSONArray elementss = new JSONArray(); elementss.addAll(elements.values()); result.put("elements", elementss); //result.put("elementHierarchy", elementHierarchy); return result; } @SuppressWarnings("unchecked") private boolean addToElements(Element e, int curdepth) { if (elements.containsKey(e.getID())) return true; if (//e instanceof ValueSpecification || !(e instanceof Package) && packageOnly || e instanceof Extension || e instanceof ProfileApplication) return false; if (ProjectUtilities.isElementInAttachedProject(e)) return false; if (e instanceof Comment && ExportUtility.isElementDocumentation((Comment)e)) return false; if (e instanceof InstanceSpecification && e.getOwnedElement().isEmpty()) return false; if (e instanceof Slot && ExportUtility.ignoreSlots.contains(((Slot)e).getDefiningFeature().getID())) return false; JSONObject elementInfo = new JSONObject(); ExportUtility.fillElement(e, elementInfo, view, viewpoint); elements.put(e.getID(), elementInfo); if ((depth != 0 && curdepth > depth) || curdepth == 0) return true; //JSONArray children = new JSONArray(); for (Element c: e.getOwnedElement()) { addToElements(c, curdepth+1); //children.add(c.getID()); } //elementHierarchy.put(e.getID(), children); return true; } }
src/main/java/gov/nasa/jpl/mbee/ems/ModelExporter.java
/******************************************************************************* * Copyright (c) <2013>, California Institute of Technology ("Caltech"). * U.S. Government sponsorship acknowledged. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * - Neither the name of Caltech nor its operating division, the Jet Propulsion Laboratory, * nor the names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package gov.nasa.jpl.mbee.ems; import gov.nasa.jpl.mbee.lib.Utils; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.nomagic.magicdraw.core.Project; import com.nomagic.magicdraw.core.ProjectUtilities; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Comment; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceSpecification; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Package; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Slot; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ValueSpecification; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Extension; import com.nomagic.uml2.ext.magicdraw.mdprofiles.ProfileApplication; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype; public class ModelExporter { //private JSONObject elementHierarchy = new JSONObject(); private JSONObject elements = new JSONObject(); //private JSONArray roots = new JSONArray(); private List<Element> starts; private int depth; private boolean packageOnly; private Stereotype view = Utils.getViewStereotype(); private Stereotype viewpoint = Utils.getViewpointStereotype(); public ModelExporter(Project prj, int depth, boolean pkgOnly) { this.depth = depth; starts = new ArrayList<Element>(); for (Package pkg: prj.getModel().getNestedPackage()) { if (ProjectUtilities.isElementInAttachedProject(pkg)) continue;//check for module?? starts.add(pkg); } packageOnly = pkgOnly; } public ModelExporter(List<Element> roots, int depth, boolean pkgOnly) { this.depth = depth; this.starts = roots; packageOnly = pkgOnly; } public int getNumberOfElements() { return elements.size(); } @SuppressWarnings("unchecked") public JSONObject getResult() { for (Element e: starts) { addToElements(e, 1); //roots.add(e.getID()); } JSONObject result = new JSONObject(); //result.put("roots", roots); JSONArray elementss = new JSONArray(); elementss.addAll(elements.values()); result.put("elements", elementss); //result.put("elementHierarchy", elementHierarchy); return result; } @SuppressWarnings("unchecked") private boolean addToElements(Element e, int curdepth) { if (elements.containsKey(e.getID())) return true; if (e instanceof ValueSpecification || !(e instanceof Package) && packageOnly || e instanceof Extension || e instanceof ProfileApplication) return false; if (ProjectUtilities.isElementInAttachedProject(e)) return false; if (e instanceof Comment && ExportUtility.isElementDocumentation((Comment)e)) return false; if (e instanceof InstanceSpecification && e.getOwnedElement().isEmpty()) return false; if (e instanceof Slot && ExportUtility.ignoreSlots.contains(((Slot)e).getDefiningFeature().getID())) return false; JSONObject elementInfo = new JSONObject(); ExportUtility.fillElement(e, elementInfo, view, viewpoint); elements.put(e.getID(), elementInfo); if ((depth != 0 && curdepth > depth) || curdepth == 0) return true; //JSONArray children = new JSONArray(); for (Element c: e.getOwnedElement()) { addToElements(c, curdepth+1); //children.add(c.getID()); } //elementHierarchy.put(e.getID(), children); return true; } }
allowing ValueSpecifications to be exported like other elements
src/main/java/gov/nasa/jpl/mbee/ems/ModelExporter.java
allowing ValueSpecifications to be exported like other elements
Java
bsd-3-clause
c9f840d005fe478a50a209dc30991fcb8d222636
0
interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl
/* $Id$ */ package ibis.connect; import ibis.util.TypedProperties; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Enumeration; import java.util.Hashtable; import java.util.Map; import java.util.StringTokenizer; import org.apache.log4j.Logger; /** * A generalized SocketFactory which supports the normal client/server connection * scheme and brokered connections through a control link. */ public class IbisSocketFactory { private static IbisSocketFactory staticFactory; static Logger logger = ibis.util.GetLogger.getLogger(IbisSocketFactory.class.getName()); /** * Map which converts a SocketType nicknames into the class name which * implements it. */ private static Hashtable nicknames = new Hashtable(); private static final String DEFAULT_CLIENT_SERVER = "PlainTCP"; private static final String DEFAULT_BROKERED = "AnyTCP"; private static ClientServerSocketFactory clientServerSocketFactory = null; private static BrokeredSocketFactory brokeredSocketFactory = null; private static BrokeredSocketFactory parallelBaseSocketFactory = null; protected IbisSocketFactory() { logger.info("IbisSocketFactory: starting configuration."); // init types table declareNickname("PlainTCP", "ibis.connect.plainSocketFactories.PlainTCPSocketFactory"); declareNickname("NIOTCP", "ibis.connect.plainSocketFactories.NIOTCPSocketFactory"); declareNickname("TCPSplice", "ibis.connect.tcpSplicing.TCPSpliceSocketFactory"); declareNickname("RoutedMessages", "ibis.connect.routedMessages.RoutedMessagesSocketFactory"); declareNickname("ParallelStreams", "ibis.connect.parallelStreams.ParallelStreamsSocketFactory"); declareNickname("NIOParallelStreams", "ibis.connect.NIOParallelStreams.NIOParallelStreamsSocketFactory"); declareNickname("PortRange", "ibis.connect.plainSocketFactories.PortRangeSocketFactory"); declareNickname("SSL", "ibis.connect.plainSocketFactories.SSLSocketType"); declareNickname("AnyTCP", "ibis.connect.plainSocketFactories.AnyBrokeredTCPSocketFactory"); // Declare new nicknames here. String dataLinksProperty = TypedProperties .stringProperty(ConnectionProperties.DATA_LINKS); if (dataLinksProperty == null) { dataLinksProperty = DEFAULT_BROKERED; } String controlLinksProperty = TypedProperties .stringProperty(ConnectionProperties.CONTROL_LINKS); if (controlLinksProperty == null) { controlLinksProperty = DEFAULT_CLIENT_SERVER; } String parallelBaseType = null; StringTokenizer st = new StringTokenizer(dataLinksProperty, " ,\t\n\r\f"); String s = st.nextToken(); if (s.equalsIgnoreCase("ParallelStreams") || s.equalsIgnoreCase("NIOParallelStreams")) { // ParallelStreams has an underlying brokered socket type. String tmp = s; parallelBaseType = st.nextToken(); if (parallelBaseType == null) { if (tmp.equalsIgnoreCase("ParallelStreams")) { parallelBaseType = "PlainTCP"; } else { parallelBaseType = "NIOTCP"; } } dataLinksProperty = tmp; } brokeredSocketFactory = loadBrokeredSocketType(dataLinksProperty); if (brokeredSocketFactory == null) { throw new Error("no brokered socket type found!"); } if (parallelBaseType != null) { parallelBaseSocketFactory = loadBrokeredSocketType(parallelBaseType); if (parallelBaseSocketFactory == null) { throw new Error( "no brokered socket type for parallel streams found!"); } } clientServerSocketFactory = loadSocketType(controlLinksProperty); if (clientServerSocketFactory == null) { throw new Error("no client-server socket type found!"); } logger.info("client-server links: " + clientServerSocketFactory.getClass()); logger.info("brokered links: " + brokeredSocketFactory.getClass()); if (parallelBaseType != null) { logger.info("base links for parallel streams: " + parallelBaseSocketFactory.getClass()); } } public static IbisSocketFactory getFactory() { if (staticFactory == null) { staticFactory = new IbisSocketFactory(); } return staticFactory; } private void declareNickname(String nickname, String className) { nicknames.put(nickname.toLowerCase(), className); } /* * loads a SocketType into the factory name: a nickname from the 'nicknames' * hashtable, or a fully-qualified class name which extends SocketType */ private synchronized ClientServerSocketFactory loadSocketType( String socketType) { ClientServerSocketFactory t = null; String className = (String) nicknames.get(socketType.toLowerCase()); Class c = null; if (className == null) { className = socketType; } try { c = Class.forName(className); } catch (Exception e) { logger.error("IbisSocketFactory: socket type " + socketType + " not found."); logger.error(" known types are:"); Enumeration i = nicknames.keys(); while (i.hasMoreElements()) { logger.error((String) i.nextElement()); } throw new Error("IbisSocketFactory: class not found: " + className, e); } try { t = (ClientServerSocketFactory) c.newInstance(); logger.info("Registering socket type: " + t.getClass()); logger.info(" class name: " + t.getClass().getName()); } catch (Exception e) { logger.error("IbisSocketFactory: Socket type constructor " + className + " got exception:", e); logger.error("IbisSocketFactory: loadSocketType returns null"); } return t; } private synchronized BrokeredSocketFactory loadBrokeredSocketType( String socketType) { BrokeredSocketFactory f = null; try { f = (BrokeredSocketFactory) loadSocketType(socketType); } catch (Exception e) { logger.info("SocketFactory: SocketType " + f.getClass() + " does not support brokered connection " + "establishment."); throw new Error(e); } return f; } public BrokeredSocketFactory getBrokeredType() { return brokeredSocketFactory; } public BrokeredSocketFactory getParallelStreamsBaseType() { return parallelBaseSocketFactory; } // Bootstrap client sockets: Socket(addr, port); public IbisSocket createClientSocket(InetAddress addr, int port, Map properties) throws IOException { logger.info("create client socket: " + addr + " type = " + clientServerSocketFactory); return createClientSocket(addr, port, null, 0, 0, properties); } /** * Client Socket creator method with a timeout. Creates a client socket and * connects it to the the specified Inetaddress and port. * * @param addr * the IP address * @param port * the port * @param timeoutMillis * if < 0, throw exception on failure. If 0, retry until success. * if > 0, block at most <code>timeoutMillis</code> * milliseconds. * @param properties * socket properties. * @exception IOException * is thrown when the socket was not properly created within * this time. * @return the socket created. */ public IbisSocket createClientSocket(InetAddress addr, int port, Map properties, int timeout) throws IOException { logger.info("create client socket: " + addr + " type = " + clientServerSocketFactory); return createClientSocket(addr, port, null, 0, timeout, properties); } /** * Client Socket creator method with a timeout. Creates a client socket and * connects it to the the specified Inetaddress and port. Some hosts have * multiple local IP addresses. If the specified <code>localIP</code> * address is <code>null</code>, this method tries to bind to the first * of this machine's IP addresses. Otherwise, it uses the specified address. * * @param dest * the IP address * @param port * the port * @param localIP * the local IP address, or <code>null</code> * @param localPort * the local port to bind to, 0 means any port * @param timeoutMillis * if < 0, throw exception on failure. If 0, retry until success. * if > 0, block at most <code>timeoutMillis</code> * milliseconds. * @exception IOException * is thrown when the socket was not properly created within * this time. * @return the socket created. */ public IbisSocket createClientSocket(InetAddress dest, int port, InetAddress localIP, int localPort, int timeoutMillis, Map properties) throws IOException { logger.info("create client socket: " + dest + " type = " + clientServerSocketFactory); if (timeoutMillis == 0) { while (true) { try { return clientServerSocketFactory .createClientSocket(dest, port, localIP, localPort, timeoutMillis, properties); } catch (Exception e) { logger.info(e); } try { Thread.sleep(1000); } catch (Exception e) { // ignore } } } else if (timeoutMillis < 0) { return clientServerSocketFactory.createClientSocket(dest, port, localIP, localPort, 0, properties); } return clientServerSocketFactory.createClientSocket(dest, port, localIP, localPort, timeoutMillis, properties); } public IbisServerSocket createServerSocket(int port, int backlog, InetAddress addr, Map properties) throws IOException { return clientServerSocketFactory.createServerSocket( new InetSocketAddress(addr, port), backlog, properties); } public IbisServerSocket createServerSocket(int port, InetAddress localAddress, boolean retry, Map properties) throws IOException { return createServerSocket(port, localAddress, 50, retry, properties); } /** * Simple ServerSocket creator method. Creates a server socket that will * accept connections on the specified port, on the specified local address. * If the specified address is <code>null</code>, the first of this * machine's IP addresses is chosen. * * @param port * the local TCP port, or 0, in which case a free port is chosen. * @param localAddress * the local Inetaddress the server will bind to, or * <code>null</code>. * @param retry * when <code>true</code>, the method blocks until the socket * is successfuly created. * @return the server socket created. * @exception IOException * when the socket could not be created for some reason. */ public IbisServerSocket createServerSocket(int port, InetAddress localAddress, int backlog, boolean retry, Map properties) throws IOException { boolean connected = false; IbisServerSocket s = null; int localPort; while (!connected) { try { logger.info("Creating new ServerSocket on " + localAddress + ":" + port); s = createServerSocket(port, backlog, localAddress, properties); logger.info("DONE, with port = " + s.getLocalPort()); connected = true; } catch (IOException e1) { if (!retry) { throw e1; } logger.info("ServerSocket connect to " + port + " failed: " + e1 + "; retrying"); try { Thread.sleep(1000); } catch (InterruptedException e2) { // don't care } } } return s; } public IbisSocket createBrokeredSocket(InputStream in, OutputStream out, boolean hintIsServer, Map properties) throws IOException { logger.info("SocketFactory: creating brokered socket- hint=" + hintIsServer + "; type=" + brokeredSocketFactory.getClass()); return brokeredSocketFactory.createBrokeredSocket(in, out, hintIsServer, properties); } }
src/ibis/connect/IbisSocketFactory.java
/* $Id$ */ package ibis.connect; import ibis.util.TypedProperties; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Enumeration; import java.util.Hashtable; import java.util.Map; import java.util.StringTokenizer; import org.apache.log4j.Logger; /** * A generalized SocketFactory which supports the normal client/server connection * scheme and brokered connections through a control link. */ public class IbisSocketFactory { private static IbisSocketFactory staticFactory; static Logger logger = ibis.util.GetLogger.getLogger(IbisSocketFactory.class.getName()); /** * Map which converts a SocketType nicknames into the class name which * implements it. */ private static Hashtable nicknames = new Hashtable(); private static final String DEFAULT_CLIENT_SERVER = "PlainTCP"; private static final String DEFAULT_BROKERED = "AnyTCP"; private static ClientServerSocketFactory clientServerSocketFactory = null; private static BrokeredSocketFactory brokeredSocketFactory = null; private static BrokeredSocketFactory parallelBaseSocketFactory = null; protected IbisSocketFactory() { logger.info("IbisSocketFactory: starting configuration."); // init types table declareNickname("PlainTCP", "ibis.connect.plainSocketFactories.PlainTCPSocketFactory"); declareNickname("NIOTCP", "ibis.connect.plainSocketFactories.NIOTCPSocketFactory"); declareNickname("TCPSplice", "ibis.connect.tcpSplicing.TCPSpliceSocketFactory"); declareNickname("RoutedMessages", "ibis.connect.routedMessages.RoutedMessagesSocketFactory"); declareNickname("ParallelStreams", "ibis.connect.parallelStreams.ParallelStreamsSocketFactory"); declareNickname("NIOParallelStreams", "ibis.connect.NIOParallelStreams.NIOParallelStreamsSocketFactory"); declareNickname("PortRange", "ibis.connect.plainSocketFactories.PortRangeSocketFactory"); declareNickname("SSL", "ibis.connect.plainSocketFactories.SSLSocketType"); declareNickname("AnyTCP", "ibis.connect.plainSocketFactories.AnyBrokeredTCPSocketFactory"); // Declare new nicknames here. String dataLinksProperty = TypedProperties .stringProperty(ConnectionProperties.DATA_LINKS); if (dataLinksProperty == null) { dataLinksProperty = DEFAULT_BROKERED; } String controlLinksProperty = TypedProperties .stringProperty(ConnectionProperties.CONTROL_LINKS); if (controlLinksProperty == null) { controlLinksProperty = DEFAULT_CLIENT_SERVER; } String parallelBaseType = null; StringTokenizer st = new StringTokenizer(dataLinksProperty, " ,\t\n\r\f"); String s = st.nextToken(); if (s.equalsIgnoreCase("ParallelStreams") || s.equalsIgnoreCase("NIOParallelStreams")) { // ParallelStreams has an underlying brokered socket type. String tmp = s; parallelBaseType = st.nextToken(); if (parallelBaseType == null) { if (tmp.equalsIgnoreCase("ParallelStreams")) { parallelBaseType = "PlainTCP"; } else { parallelBaseType = "NIOTCP"; } } dataLinksProperty = tmp; } brokeredSocketFactory = loadBrokeredSocketType(dataLinksProperty); if (brokeredSocketFactory == null) { throw new Error("no brokered socket type found!"); } if (parallelBaseType != null) { parallelBaseSocketFactory = loadBrokeredSocketType(parallelBaseType); if (parallelBaseSocketFactory == null) { throw new Error( "no brokered socket type for parallel streams found!"); } } clientServerSocketFactory = loadSocketType(controlLinksProperty); if (clientServerSocketFactory == null) { throw new Error("no client-server socket type found!"); } logger.info("client-server links: " + clientServerSocketFactory.getClass()); logger.info("brokered links: " + brokeredSocketFactory.getClass()); if (parallelBaseType != null) { logger.info("base links for parallel streams: " + parallelBaseSocketFactory.getClass()); } } public static IbisSocketFactory getFactory() { if (staticFactory == null) { staticFactory = new IbisSocketFactory(); } return staticFactory; } private void declareNickname(String nickname, String className) { nicknames.put(nickname.toLowerCase(), className); } /* * loads a SocketType into the factory name: a nickname from the 'nicknames' * hashtable, or a fully-qualified class name which extends SocketType */ private synchronized ClientServerSocketFactory loadSocketType( String socketType) { ClientServerSocketFactory t = null; String className = (String) nicknames.get(socketType.toLowerCase()); Class c = null; if (className == null) { className = socketType; } try { c = Class.forName(className); } catch (Exception e) { logger.error("IbisSocketFactory: socket type " + socketType + " not found."); logger.error(" known types are:"); Enumeration i = nicknames.keys(); while (i.hasMoreElements()) { logger.error((String) i.nextElement()); } throw new Error("IbisSocketFactory: class not found: " + className, e); } try { t = (ClientServerSocketFactory) c.newInstance(); logger.info("Registering socket type: " + t.getClass()); logger.info(" class name: " + t.getClass().getName()); } catch (Exception e) { logger.error("IbisSocketFactory: Socket type constructor " + className + " got exception:", e); logger.error("IbisSocketFactory: loadSocketType returns null"); } return t; } private synchronized BrokeredSocketFactory loadBrokeredSocketType( String socketType) { BrokeredSocketFactory f = null; try { f = (BrokeredSocketFactory) loadSocketType(socketType); } catch (Exception e) { logger.info("SocketFactory: SocketType " + f.getClass() + " does not support brokered connection " + "establishment."); throw new Error(e); } return f; } public BrokeredSocketFactory getBrokeredType() { return brokeredSocketFactory; } public BrokeredSocketFactory getParallelStreamsBaseType() { return parallelBaseSocketFactory; } // Bootstrap client sockets: Socket(addr, port); public IbisSocket createClientSocket(InetAddress addr, int port, Map properties) throws IOException { logger.info("create client socket: " + addr + " type = " + clientServerSocketFactory); return createClientSocket(addr, port, null, 0, 0, properties); } /** * client Socket creator method with a timeout. Creates a client socket and * connects it to the the specified Inetaddress and port. Some hosts have * multiple local IP addresses. If the specified <code>localIP</code> * address is <code>null</code>, this method tries to bind to the first * of this machine's IP addresses. Otherwise, it uses the specified address. * * @param dest * the IP address * @param port * the port * @param localIP * the local IP address, or <code>null</code> * @param localPort * the local port to bind to, 0 means any port * @param timeoutMillis * if < 0, throw exception on failure. If 0, retry until success. * if > 0, block at most <code>timeoutMillis</code> * milliseconds. * @exception IOException * is thrown when the socket was not properly created within * this time. * @return the socket created. */ public IbisSocket createClientSocket(InetAddress dest, int port, InetAddress localIP, int localPort, int timeoutMillis, Map properties) throws IOException { logger.info("create client socket: " + dest + " type = " + clientServerSocketFactory); if (timeoutMillis == 0) { while (true) { try { return clientServerSocketFactory .createClientSocket(dest, port, localIP, localPort, timeoutMillis, properties); } catch (Exception e) { logger.info(e); } try { Thread.sleep(1000); } catch (Exception e) { // ignore } } } else if (timeoutMillis < 0) { return clientServerSocketFactory.createClientSocket(dest, port, localIP, localPort, 0, properties); } return clientServerSocketFactory.createClientSocket(dest, port, localIP, localPort, timeoutMillis, properties); } public IbisServerSocket createServerSocket(int port, int backlog, InetAddress addr, Map properties) throws IOException { return clientServerSocketFactory.createServerSocket( new InetSocketAddress(addr, port), backlog, properties); } public IbisServerSocket createServerSocket(int port, InetAddress localAddress, boolean retry, Map properties) throws IOException { return createServerSocket(port, localAddress, 50, retry, properties); } /** * Simple ServerSocket creator method. Creates a server socket that will * accept connections on the specified port, on the specified local address. * If the specified address is <code>null</code>, the first of this * machine's IP addresses is chosen. * * @param port * the local TCP port, or 0, in which case a free port is chosen. * @param localAddress * the local Inetaddress the server will bind to, or * <code>null</code>. * @param retry * when <code>true</code>, the method blocks until the socket * is successfuly created. * @return the server socket created. * @exception IOException * when the socket could not be created for some reason. */ public IbisServerSocket createServerSocket(int port, InetAddress localAddress, int backlog, boolean retry, Map properties) throws IOException { boolean connected = false; IbisServerSocket s = null; int localPort; while (!connected) { try { logger.info("Creating new ServerSocket on " + localAddress + ":" + port); s = createServerSocket(port, backlog, localAddress, properties); logger.info("DONE, with port = " + s.getLocalPort()); connected = true; } catch (IOException e1) { if (!retry) { throw e1; } logger.info("ServerSocket connect to " + port + " failed: " + e1 + "; retrying"); try { Thread.sleep(1000); } catch (InterruptedException e2) { // don't care } } } return s; } public IbisSocket createBrokeredSocket(InputStream in, OutputStream out, boolean hintIsServer, Map properties) throws IOException { logger.info("SocketFactory: creating brokered socket- hint=" + hintIsServer + "; type=" + brokeredSocketFactory.getClass()); return brokeredSocketFactory.createBrokeredSocket(in, out, hintIsServer, properties); } }
Added simple createClientSocket with timeout git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@3056 aaf88347-d911-0410-b711-e54d386773bb
src/ibis/connect/IbisSocketFactory.java
Added simple createClientSocket with timeout
Java
bsd-3-clause
0fac5ce133022ac154094137950c7d060cea6362
0
ericvergnaud/antlr4,worsht/antlr4,wjkohnen/antlr4,Pursuit92/antlr4,joshids/antlr4,krzkaczor/antlr4,Pursuit92/antlr4,joshids/antlr4,chandler14362/antlr4,Distrotech/antlr4,parrt/antlr4,worsht/antlr4,Pursuit92/antlr4,Pursuit92/antlr4,ericvergnaud/antlr4,joshids/antlr4,parrt/antlr4,chandler14362/antlr4,chandler14362/antlr4,joshids/antlr4,lncosie/antlr4,chienjchienj/antlr4,cooperra/antlr4,wjkohnen/antlr4,wjkohnen/antlr4,Pursuit92/antlr4,krzkaczor/antlr4,Pursuit92/antlr4,parrt/antlr4,lncosie/antlr4,Pursuit92/antlr4,joshids/antlr4,jvanzyl/antlr4,antlr/antlr4,antlr/antlr4,chienjchienj/antlr4,krzkaczor/antlr4,chienjchienj/antlr4,chandler14362/antlr4,sidhart/antlr4,sidhart/antlr4,Distrotech/antlr4,antlr/antlr4,Distrotech/antlr4,joshids/antlr4,antlr/antlr4,sidhart/antlr4,supriyantomaftuh/antlr4,sidhart/antlr4,wjkohnen/antlr4,worsht/antlr4,lncosie/antlr4,ericvergnaud/antlr4,worsht/antlr4,ericvergnaud/antlr4,krzkaczor/antlr4,Pursuit92/antlr4,lncosie/antlr4,hce/antlr4,cooperra/antlr4,supriyantomaftuh/antlr4,mcanthony/antlr4,ericvergnaud/antlr4,chandler14362/antlr4,chandler14362/antlr4,lncosie/antlr4,cooperra/antlr4,chandler14362/antlr4,supriyantomaftuh/antlr4,mcanthony/antlr4,cooperra/antlr4,antlr/antlr4,deveshg/antlr4,antlr/antlr4,joshids/antlr4,jvanzyl/antlr4,chienjchienj/antlr4,chandler14362/antlr4,parrt/antlr4,jvanzyl/antlr4,jvanzyl/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,parrt/antlr4,hce/antlr4,parrt/antlr4,wjkohnen/antlr4,cocosli/antlr4,mcanthony/antlr4,chandler14362/antlr4,hce/antlr4,krzkaczor/antlr4,joshids/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,wjkohnen/antlr4,cocosli/antlr4,Distrotech/antlr4,Distrotech/antlr4,ericvergnaud/antlr4,mcanthony/antlr4,cocosli/antlr4,Pursuit92/antlr4,supriyantomaftuh/antlr4,cocosli/antlr4,antlr/antlr4,sidhart/antlr4,hce/antlr4,wjkohnen/antlr4,parrt/antlr4,mcanthony/antlr4,antlr/antlr4,ericvergnaud/antlr4,wjkohnen/antlr4,parrt/antlr4,chienjchienj/antlr4,wjkohnen/antlr4,worsht/antlr4,parrt/antlr4,antlr/antlr4,supriyantomaftuh/antlr4
/* * [The "BSD license"] * Copyright (c) 2012 Terence Parr * Copyright (c) 2012 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.antlr.v4.test; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BailErrorStrategy; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.DefaultErrorStrategy; import org.antlr.v4.runtime.DiagnosticErrorListener; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenSource; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.atn.ATN; import org.antlr.v4.runtime.atn.ATNConfig; import org.antlr.v4.runtime.atn.ATNConfigSet; import org.antlr.v4.runtime.atn.LexerATNSimulator; import org.antlr.v4.runtime.atn.ParserATNSimulator; import org.antlr.v4.runtime.atn.PredictionContextCache; import org.antlr.v4.runtime.atn.PredictionMode; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.dfa.DFAState; import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.misc.Nullable; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeListener; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.CRC32; import java.util.zip.Checksum; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class TestPerformance extends BaseTest { /** * Parse all java files under this package within the JDK_SOURCE_ROOT * (environment variable or property defined on the Java command line). */ private static final String TOP_PACKAGE = "java.lang"; /** * {@code true} to load java files from sub-packages of * {@link #TOP_PACKAGE}. */ private static final boolean RECURSIVE = true; /** * {@code true} to read all source files from disk into memory before * starting the parse. The default value is {@code true} to help prevent * drive speed from affecting the performance results. This value may be set * to {@code false} to support parsing large input sets which would not * otherwise fit into memory. */ private static final boolean PRELOAD_SOURCES = true; /** * The encoding to use when reading source files. */ private static final String ENCODING = "UTF-8"; /** * The maximum number of files to parse in a single iteration. */ private static final int MAX_FILES_PER_PARSE_ITERATION = Integer.MAX_VALUE; /** * {@code true} to call {@link Collections#shuffle} on the list of input * files before the first parse iteration. */ private static final boolean SHUFFLE_FILES_AT_START = false; /** * {@code true} to call {@link Collections#shuffle} before each parse * iteration <em>after</em> the first. */ private static final boolean SHUFFLE_FILES_AFTER_ITERATIONS = false; /** * The instance of {@link Random} passed when calling * {@link Collections#shuffle}. */ private static final Random RANDOM = new Random(); /** * {@code true} to use the Java grammar with expressions in the v4 * left-recursive syntax (Java-LR.g4). {@code false} to use the standard * grammar (Java.g4). In either case, the grammar is renamed in the * temporary directory to Java.g4 before compiling. */ private static final boolean USE_LR_GRAMMAR = true; /** * {@code true} to specify the {@code -Xforce-atn} option when generating * the grammar, forcing all decisions in {@code JavaParser} to be handled by * {@link ParserATNSimulator#adaptivePredict}. */ private static final boolean FORCE_ATN = false; /** * {@code true} to specify the {@code -atn} option when generating the * grammar. This will cause ANTLR to export the ATN for each decision as a * DOT (GraphViz) file. */ private static final boolean EXPORT_ATN_GRAPHS = true; /** * {@code true} to specify the {@code -XdbgST} option when generating the * grammar. */ private static final boolean DEBUG_TEMPLATES = false; /** * {@code true} to specify the {@code -XdbgSTWait} option when generating the * grammar. */ private static final boolean DEBUG_TEMPLATES_WAIT = DEBUG_TEMPLATES; /** * {@code true} to delete temporary (generated and compiled) files when the * test completes. */ private static final boolean DELETE_TEMP_FILES = true; /** * {@code true} to call {@link System#gc} and then wait for 5 seconds at the * end of the test to make it easier for a profiler to grab a heap dump at * the end of the test run. */ private static final boolean PAUSE_FOR_HEAP_DUMP = false; /** * Parse each file with {@code JavaParser.compilationUnit}. */ private static final boolean RUN_PARSER = true; /** * {@code true} to use {@link BailErrorStrategy}, {@code false} to use * {@link DefaultErrorStrategy}. */ private static final boolean BAIL_ON_ERROR = false; /** * {@code true} to compute a checksum for verifying consistency across * optimizations and multiple passes. */ private static final boolean COMPUTE_CHECKSUM = true; /** * This value is passed to {@link Parser#setBuildParseTree}. */ private static final boolean BUILD_PARSE_TREES = false; /** * Use * {@link ParseTreeWalker#DEFAULT}{@code .}{@link ParseTreeWalker#walk walk} * with the {@code JavaParserBaseListener} to show parse tree walking * overhead. If {@link #BUILD_PARSE_TREES} is {@code false}, the listener * will instead be called during the parsing process via * {@link Parser#addParseListener}. */ private static final boolean BLANK_LISTENER = false; /** * Shows the number of {@link DFAState} and {@link ATNConfig} instances in * the DFA cache at the end of each pass. If {@link #REUSE_LEXER_DFA} and/or * {@link #REUSE_PARSER_DFA} are false, the corresponding instance numbers * will only apply to one file (the last file if {@link #NUMBER_OF_THREADS} * is 0, otherwise the last file which was parsed on the first thread). */ private static final boolean SHOW_DFA_STATE_STATS = true; /** * If {@code true}, the DFA state statistics report includes a breakdown of * the number of DFA states contained in each decision (with rule names). */ private static final boolean DETAILED_DFA_STATE_STATS = true; /** * Specify the {@link PredictionMode} used by the * {@link ParserATNSimulator}. If {@link #TWO_STAGE_PARSING} is * {@code true}, this value only applies to the second stage, as the first * stage will always use {@link PredictionMode#SLL}. */ private static final PredictionMode PREDICTION_MODE = PredictionMode.LL; private static final boolean TWO_STAGE_PARSING = true; private static final boolean SHOW_CONFIG_STATS = false; /** * If {@code true}, detailed statistics for the number of DFA edges were * taken while parsing each file, as well as the number of DFA edges which * required on-the-fly computation. */ private static final boolean COMPUTE_TRANSITION_STATS = false; /** * If {@code true}, the transition statistics will be adjusted to a running * total before reporting the final results. */ private static final boolean TRANSITION_RUNNING_AVERAGE = false; /** * If {@code true}, transition statistics will be weighted according to the * total number of transitions taken during the parsing of each file. */ private static final boolean TRANSITION_WEIGHTED_AVERAGE = false; /** * If {@code true}, after each pass a summary of the time required to parse * each file will be printed. */ private static final boolean COMPUTE_TIMING_STATS = false; /** * If {@code true}, the timing statistics for {@link #COMPUTE_TIMING_STATS} * will be cumulative (i.e. the time reported for the <em>n</em>th file will * be the total time required to parse the first <em>n</em> files). */ private static final boolean TIMING_CUMULATIVE = false; /** * If {@code true}, the timing statistics will include the parser only. This * flag allows for targeted measurements, and helps eliminate variance when * {@link #PRELOAD_SOURCES} is {@code false}. * <p/> * This flag has no impact when {@link #RUN_PARSER} is {@code false}. */ private static final boolean TIME_PARSE_ONLY = false; private static final boolean REPORT_SYNTAX_ERRORS = true; private static final boolean REPORT_AMBIGUITIES = false; private static final boolean REPORT_FULL_CONTEXT = false; private static final boolean REPORT_CONTEXT_SENSITIVITY = REPORT_FULL_CONTEXT; /** * If {@code true}, a single {@code JavaLexer} will be used, and * {@link Lexer#setInputStream} will be called to initialize it for each * source file. Otherwise, a new instance will be created for each file. */ private static final boolean REUSE_LEXER = false; /** * If {@code true}, a single DFA will be used for lexing which is shared * across all threads and files. Otherwise, each file will be lexed with its * own DFA which is accomplished by creating one ATN instance per thread and * clearing its DFA cache before lexing each file. */ private static final boolean REUSE_LEXER_DFA = true; /** * If {@code true}, a single {@code JavaParser} will be used, and * {@link Parser#setInputStream} will be called to initialize it for each * source file. Otherwise, a new instance will be created for each file. */ private static final boolean REUSE_PARSER = false; /** * If {@code true}, a single DFA will be used for parsing which is shared * across all threads and files. Otherwise, each file will be parsed with * its own DFA which is accomplished by creating one ATN instance per thread * and clearing its DFA cache before parsing each file. */ private static final boolean REUSE_PARSER_DFA = true; /** * If {@code true}, the shared lexer and parser are reset after each pass. * If {@code false}, all passes after the first will be fully "warmed up", * which makes them faster and can compare them to the first warm-up pass, * but it will not distinguish bytecode load/JIT time from warm-up time * during the first pass. */ private static final boolean CLEAR_DFA = false; /** * Total number of passes to make over the source. */ private static final int PASSES = 4; /** * This option controls the granularity of multi-threaded parse operations. * If {@code true}, the parsing operation will be parallelized across files; * otherwise the parsing will be parallelized across multiple iterations. */ private static final boolean FILE_GRANULARITY = false; /** * Number of parser threads to use. */ private static final int NUMBER_OF_THREADS = 1; private static final Lexer[] sharedLexers = new Lexer[NUMBER_OF_THREADS]; private static final Parser[] sharedParsers = new Parser[NUMBER_OF_THREADS]; private static final ParseTreeListener[] sharedListeners = new ParseTreeListener[NUMBER_OF_THREADS]; private static final long[][] totalTransitionsPerFile; private static final long[][] computedTransitionsPerFile; static { if (COMPUTE_TRANSITION_STATS) { totalTransitionsPerFile = new long[PASSES][]; computedTransitionsPerFile = new long[PASSES][]; } else { totalTransitionsPerFile = null; computedTransitionsPerFile = null; } } private static final long[][] timePerFile; private static final int[][] tokensPerFile; static { if (COMPUTE_TIMING_STATS) { timePerFile = new long[PASSES][]; tokensPerFile = new int[PASSES][]; } else { timePerFile = null; tokensPerFile = null; } } private final AtomicIntegerArray tokenCount = new AtomicIntegerArray(PASSES); @Test //@org.junit.Ignore public void compileJdk() throws IOException, InterruptedException, ExecutionException { String jdkSourceRoot = getSourceRoot("JDK"); assertTrue("The JDK_SOURCE_ROOT environment variable must be set for performance testing.", jdkSourceRoot != null && !jdkSourceRoot.isEmpty()); compileJavaParser(USE_LR_GRAMMAR); final String lexerName = "JavaLexer"; final String parserName = "JavaParser"; final String listenerName = "JavaBaseListener"; final String entryPoint = "compilationUnit"; final ParserFactory factory = getParserFactory(lexerName, parserName, listenerName, entryPoint); if (!TOP_PACKAGE.isEmpty()) { jdkSourceRoot = jdkSourceRoot + '/' + TOP_PACKAGE.replace('.', '/'); } File directory = new File(jdkSourceRoot); assertTrue(directory.isDirectory()); FilenameFilter filesFilter = FilenameFilters.extension(".java", false); FilenameFilter directoriesFilter = FilenameFilters.ALL_FILES; final List<InputDescriptor> sources = loadSources(directory, filesFilter, directoriesFilter, RECURSIVE); for (int i = 0; i < PASSES; i++) { if (COMPUTE_TRANSITION_STATS) { totalTransitionsPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)]; computedTransitionsPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)]; } if (COMPUTE_TIMING_STATS) { timePerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)]; tokensPerFile[i] = new int[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)]; } } System.out.format("Located %d source files.%n", sources.size()); System.out.print(getOptionsDescription(TOP_PACKAGE)); ExecutorService executorService = Executors.newFixedThreadPool(FILE_GRANULARITY ? 1 : NUMBER_OF_THREADS, new NumberedThreadFactory()); List<Future<?>> passResults = new ArrayList<Future<?>>(); passResults.add(executorService.submit(new Runnable() { @Override public void run() { try { parse1(0, factory, sources, SHUFFLE_FILES_AT_START); } catch (InterruptedException ex) { Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); } } })); for (int i = 0; i < PASSES - 1; i++) { final int currentPass = i + 1; passResults.add(executorService.submit(new Runnable() { @Override public void run() { if (CLEAR_DFA) { int index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber(); if (sharedLexers.length > 0 && sharedLexers[index] != null) { ATN atn = sharedLexers[index].getATN(); for (int j = 0; j < sharedLexers[index].getInterpreter().decisionToDFA.length; j++) { sharedLexers[index].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j); } } if (sharedParsers.length > 0 && sharedParsers[index] != null) { ATN atn = sharedParsers[index].getATN(); for (int j = 0; j < sharedParsers[index].getInterpreter().decisionToDFA.length; j++) { sharedParsers[index].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j); } } if (FILE_GRANULARITY) { Arrays.fill(sharedLexers, null); Arrays.fill(sharedParsers, null); } } try { parse2(currentPass, factory, sources, SHUFFLE_FILES_AFTER_ITERATIONS); } catch (InterruptedException ex) { Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); } } })); } for (Future<?> passResult : passResults) { passResult.get(); } executorService.shutdown(); executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); if (COMPUTE_TRANSITION_STATS) { computeTransitionStatistics(); } if (COMPUTE_TIMING_STATS) { computeTimingStatistics(); } sources.clear(); if (PAUSE_FOR_HEAP_DUMP) { System.gc(); System.out.println("Pausing before application exit."); try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); } } } /** * Compute and print ATN/DFA transition statistics. */ private void computeTransitionStatistics() { if (TRANSITION_RUNNING_AVERAGE) { for (int i = 0; i < PASSES; i++) { long[] data = computedTransitionsPerFile[i]; for (int j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } data = totalTransitionsPerFile[i]; for (int j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } } } long[] sumNum = new long[totalTransitionsPerFile[0].length]; long[] sumDen = new long[totalTransitionsPerFile[0].length]; double[] sumNormalized = new double[totalTransitionsPerFile[0].length]; for (int i = 0; i < PASSES; i++) { long[] num = computedTransitionsPerFile[i]; long[] den = totalTransitionsPerFile[i]; for (int j = 0; j < den.length; j++) { sumNum[j] += num[j]; sumDen[j] += den[j]; sumNormalized[j] += (double)num[j] / (double)den[j]; } } double[] weightedAverage = new double[totalTransitionsPerFile[0].length]; double[] average = new double[totalTransitionsPerFile[0].length]; for (int i = 0; i < average.length; i++) { weightedAverage[i] = (double)sumNum[i] / (double)sumDen[i]; average[i] = sumNormalized[i] / PASSES; } double[] low95 = new double[totalTransitionsPerFile[0].length]; double[] high95 = new double[totalTransitionsPerFile[0].length]; double[] low67 = new double[totalTransitionsPerFile[0].length]; double[] high67 = new double[totalTransitionsPerFile[0].length]; double[] stddev = new double[totalTransitionsPerFile[0].length]; for (int i = 0; i < stddev.length; i++) { double[] points = new double[PASSES]; for (int j = 0; j < PASSES; j++) { points[j] = ((double)computedTransitionsPerFile[j][i] / (double)totalTransitionsPerFile[j][i]); } Arrays.sort(points); final double averageValue = TRANSITION_WEIGHTED_AVERAGE ? weightedAverage[i] : average[i]; double value = 0; for (int j = 0; j < PASSES; j++) { double diff = points[j] - averageValue; value += diff * diff; } int ignoreCount95 = (int)Math.round(PASSES * (1 - 0.95) / 2.0); int ignoreCount67 = (int)Math.round(PASSES * (1 - 0.667) / 2.0); low95[i] = points[ignoreCount95]; high95[i] = points[points.length - 1 - ignoreCount95]; low67[i] = points[ignoreCount67]; high67[i] = points[points.length - 1 - ignoreCount67]; stddev[i] = Math.sqrt(value / PASSES); } System.out.format("File\tAverage\tStd. Dev.\t95%% Low\t95%% High\t66.7%% Low\t66.7%% High%n"); for (int i = 0; i < stddev.length; i++) { final double averageValue = TRANSITION_WEIGHTED_AVERAGE ? weightedAverage[i] : average[i]; System.out.format("%d\t%e\t%e\t%e\t%e\t%e\t%e%n", i + 1, averageValue, stddev[i], averageValue - low95[i], high95[i] - averageValue, averageValue - low67[i], high67[i] - averageValue); } } /** * Compute and print timing statistics. */ private void computeTimingStatistics() { if (TIMING_CUMULATIVE) { for (int i = 0; i < PASSES; i++) { long[] data = timePerFile[i]; for (int j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } int[] data2 = tokensPerFile[i]; for (int j = 0; j < data2.length - 1; j++) { data2[j + 1] += data2[j]; } } } final int fileCount = timePerFile[0].length; double[] sum = new double[fileCount]; for (int i = 0; i < PASSES; i++) { long[] data = timePerFile[i]; int[] tokenData = tokensPerFile[i]; for (int j = 0; j < data.length; j++) { sum[j] += (double)data[j] / (double)tokenData[j]; } } double[] average = new double[fileCount]; for (int i = 0; i < average.length; i++) { average[i] = sum[i] / PASSES; } double[] low95 = new double[fileCount]; double[] high95 = new double[fileCount]; double[] low67 = new double[fileCount]; double[] high67 = new double[fileCount]; double[] stddev = new double[fileCount]; for (int i = 0; i < stddev.length; i++) { double[] points = new double[PASSES]; for (int j = 0; j < PASSES; j++) { points[j] = (double)timePerFile[j][i] / (double)tokensPerFile[j][i]; } Arrays.sort(points); final double averageValue = average[i]; double value = 0; for (int j = 0; j < PASSES; j++) { double diff = points[j] - averageValue; value += diff * diff; } int ignoreCount95 = (int)Math.round(PASSES * (1 - 0.95) / 2.0); int ignoreCount67 = (int)Math.round(PASSES * (1 - 0.667) / 2.0); low95[i] = points[ignoreCount95]; high95[i] = points[points.length - 1 - ignoreCount95]; low67[i] = points[ignoreCount67]; high67[i] = points[points.length - 1 - ignoreCount67]; stddev[i] = Math.sqrt(value / PASSES); } System.out.format("File\tAverage\tStd. Dev.\t95%% Low\t95%% High\t66.7%% Low\t66.7%% High%n"); for (int i = 0; i < stddev.length; i++) { final double averageValue = average[i]; System.out.format("%d\t%e\t%e\t%e\t%e\t%e\t%e%n", i + 1, averageValue, stddev[i], averageValue - low95[i], high95[i] - averageValue, averageValue - low67[i], high67[i] - averageValue); } } private String getSourceRoot(String prefix) { String sourceRoot = System.getenv(prefix+"_SOURCE_ROOT"); if (sourceRoot == null) { sourceRoot = System.getProperty(prefix+"_SOURCE_ROOT"); } return sourceRoot; } @Override protected void eraseTempDir() { if (DELETE_TEMP_FILES) { super.eraseTempDir(); } } public static String getOptionsDescription(String topPackage) { StringBuilder builder = new StringBuilder(); builder.append("Input="); if (topPackage.isEmpty()) { builder.append("*"); } else { builder.append(topPackage).append(".*"); } builder.append(", Grammar=").append(USE_LR_GRAMMAR ? "LR" : "Standard"); builder.append(", ForceAtn=").append(FORCE_ATN); builder.append(newline); builder.append("Op=Lex").append(RUN_PARSER ? "+Parse" : " only"); builder.append(", Strategy=").append(BAIL_ON_ERROR ? BailErrorStrategy.class.getSimpleName() : DefaultErrorStrategy.class.getSimpleName()); builder.append(", BuildParseTree=").append(BUILD_PARSE_TREES); builder.append(", WalkBlankListener=").append(BLANK_LISTENER); builder.append(newline); builder.append("Lexer=").append(REUSE_LEXER ? "setInputStream" : "newInstance"); builder.append(", Parser=").append(REUSE_PARSER ? "setInputStream" : "newInstance"); builder.append(", AfterPass=").append(CLEAR_DFA ? "newInstance" : "setInputStream"); builder.append(newline); return builder.toString(); } /** * This method is separate from {@link #parse2} so the first pass can be distinguished when analyzing * profiler results. */ protected void parse1(int currentPass, ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException { if (FILE_GRANULARITY) { System.gc(); } parseSources(currentPass, factory, sources, shuffleSources); } /** * This method is separate from {@link #parse1} so the first pass can be distinguished when analyzing * profiler results. */ protected void parse2(int currentPass, ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException { if (FILE_GRANULARITY) { System.gc(); } parseSources(currentPass, factory, sources, shuffleSources); } protected List<InputDescriptor> loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive) { List<InputDescriptor> result = new ArrayList<InputDescriptor>(); loadSources(directory, filesFilter, directoriesFilter, recursive, result); return result; } protected void loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive, Collection<InputDescriptor> result) { assert directory.isDirectory(); File[] sources = directory.listFiles(filesFilter); for (File file : sources) { if (!file.isFile()) { continue; } result.add(new InputDescriptor(file.getAbsolutePath())); } if (recursive) { File[] children = directory.listFiles(directoriesFilter); for (File child : children) { if (child.isDirectory()) { loadSources(child, filesFilter, directoriesFilter, true, result); } } } } int configOutputSize = 0; @SuppressWarnings("unused") protected void parseSources(final int currentPass, final ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException { if (shuffleSources) { List<InputDescriptor> sourcesList = new ArrayList<InputDescriptor>(sources); synchronized (RANDOM) { Collections.shuffle(sourcesList, RANDOM); } sources = sourcesList; } long startTime = System.nanoTime(); tokenCount.set(currentPass, 0); int inputSize = 0; int inputCount = 0; Collection<Future<FileParseResult>> results = new ArrayList<Future<FileParseResult>>(); ExecutorService executorService; if (FILE_GRANULARITY) { executorService = Executors.newFixedThreadPool(FILE_GRANULARITY ? NUMBER_OF_THREADS : 1, new NumberedThreadFactory()); } else { executorService = Executors.newSingleThreadExecutor(new FixedThreadNumberFactory(((NumberedThread)Thread.currentThread()).getThreadNumber())); } for (InputDescriptor inputDescriptor : sources) { if (inputCount >= MAX_FILES_PER_PARSE_ITERATION) { break; } final CharStream input = inputDescriptor.getInputStream(); input.seek(0); inputSize += input.size(); inputCount++; Future<FileParseResult> futureChecksum = executorService.submit(new Callable<FileParseResult>() { @Override public FileParseResult call() { // this incurred a great deal of overhead and was causing significant variations in performance results. //System.out.format("Parsing file %s\n", input.getSourceName()); try { return factory.parseFile(input, currentPass, ((NumberedThread)Thread.currentThread()).getThreadNumber()); } catch (IllegalStateException ex) { ex.printStackTrace(System.err); } catch (Throwable t) { t.printStackTrace(System.err); } return null; } }); results.add(futureChecksum); } Checksum checksum = new CRC32(); int currentIndex = -1; for (Future<FileParseResult> future : results) { currentIndex++; int fileChecksum = 0; try { FileParseResult fileResult = future.get(); if (COMPUTE_TRANSITION_STATS) { totalTransitionsPerFile[currentPass][currentIndex] = fileResult.parserTotalTransitions; computedTransitionsPerFile[currentPass][currentIndex] = fileResult.parserComputedTransitions; } if (COMPUTE_TIMING_STATS) { timePerFile[currentPass][currentIndex] = fileResult.endTime - fileResult.startTime; tokensPerFile[currentPass][currentIndex] = fileResult.tokenCount; } fileChecksum = fileResult.checksum; } catch (ExecutionException ex) { Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); } if (COMPUTE_CHECKSUM) { updateChecksum(checksum, fileChecksum); } } executorService.shutdown(); executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); System.out.format("%d. Total parse time for %d files (%d KB, %d tokens, checksum 0x%8X): %.0fms%n", currentPass + 1, inputCount, inputSize / 1024, tokenCount.get(currentPass), COMPUTE_CHECKSUM ? checksum.getValue() : 0, (double)(System.nanoTime() - startTime) / 1000000.0); if (sharedLexers.length > 0) { int index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber(); Lexer lexer = sharedLexers[index]; final LexerATNSimulator lexerInterpreter = lexer.getInterpreter(); final DFA[] modeToDFA = lexerInterpreter.decisionToDFA; if (SHOW_DFA_STATE_STATS) { int states = 0; int configs = 0; Set<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>(); for (int i = 0; i < modeToDFA.length; i++) { DFA dfa = modeToDFA[i]; if (dfa == null) { continue; } states += dfa.states.size(); for (DFAState state : dfa.states.values()) { configs += state.configs.size(); uniqueConfigs.addAll(state.configs); } } System.out.format("There are %d lexer DFAState instances, %d configs (%d unique).%n", states, configs, uniqueConfigs.size()); if (DETAILED_DFA_STATE_STATS) { System.out.format("\tMode\tStates\tConfigs\tMode%n"); for (int i = 0; i < modeToDFA.length; i++) { DFA dfa = modeToDFA[i]; if (dfa == null || dfa.states.isEmpty()) { continue; } int modeConfigs = 0; for (DFAState state : dfa.states.values()) { modeConfigs += state.configs.size(); } String modeName = lexer.getModeNames()[i]; System.out.format("\t%d\t%d\t%d\t%s%n", dfa.decision, dfa.states.size(), modeConfigs, modeName); } } } } if (RUN_PARSER && sharedParsers.length > 0) { int index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber(); Parser parser = sharedParsers[index]; // make sure the individual DFAState objects actually have unique ATNConfig arrays final ParserATNSimulator interpreter = parser.getInterpreter(); final DFA[] decisionToDFA = interpreter.decisionToDFA; if (SHOW_DFA_STATE_STATS) { int states = 0; int configs = 0; Set<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>(); for (int i = 0; i < decisionToDFA.length; i++) { DFA dfa = decisionToDFA[i]; if (dfa == null) { continue; } states += dfa.states.size(); for (DFAState state : dfa.states.values()) { configs += state.configs.size(); uniqueConfigs.addAll(state.configs); } } System.out.format("There are %d parser DFAState instances, %d configs (%d unique).%n", states, configs, uniqueConfigs.size()); if (DETAILED_DFA_STATE_STATS) { System.out.format("\tDecision\tStates\tConfigs\tRule%n"); for (int i = 0; i < decisionToDFA.length; i++) { DFA dfa = decisionToDFA[i]; if (dfa == null || dfa.states.isEmpty()) { continue; } int decisionConfigs = 0; for (DFAState state : dfa.states.values()) { decisionConfigs += state.configs.size(); } String ruleName = parser.getRuleNames()[parser.getATN().decisionToState.get(dfa.decision).ruleIndex]; System.out.format("\t%d\t%d\t%d\t%s%n", dfa.decision, dfa.states.size(), decisionConfigs, ruleName); } } } int localDfaCount = 0; int globalDfaCount = 0; int localConfigCount = 0; int globalConfigCount = 0; int[] contextsInDFAState = new int[0]; for (int i = 0; i < decisionToDFA.length; i++) { DFA dfa = decisionToDFA[i]; if (dfa == null) { continue; } if (SHOW_CONFIG_STATS) { for (DFAState state : dfa.states.keySet()) { if (state.configs.size() >= contextsInDFAState.length) { contextsInDFAState = Arrays.copyOf(contextsInDFAState, state.configs.size() + 1); } if (state.isAcceptState) { boolean hasGlobal = false; for (ATNConfig config : state.configs) { if (config.reachesIntoOuterContext > 0) { globalConfigCount++; hasGlobal = true; } else { localConfigCount++; } } if (hasGlobal) { globalDfaCount++; } else { localDfaCount++; } } contextsInDFAState[state.configs.size()]++; } } } if (SHOW_CONFIG_STATS && currentPass == 0) { System.out.format(" DFA accept states: %d total, %d with only local context, %d with a global context%n", localDfaCount + globalDfaCount, localDfaCount, globalDfaCount); System.out.format(" Config stats: %d total, %d local, %d global%n", localConfigCount + globalConfigCount, localConfigCount, globalConfigCount); if (SHOW_DFA_STATE_STATS) { for (int i = 0; i < contextsInDFAState.length; i++) { if (contextsInDFAState[i] != 0) { System.out.format(" %d configs = %d%n", i, contextsInDFAState[i]); } } } } } if (COMPUTE_TIMING_STATS) { System.out.format("File\tTokens\tTime%n"); for (int i = 0; i< timePerFile[currentPass].length; i++) { System.out.format("%d\t%d\t%d%n", i + 1, tokensPerFile[currentPass][i], timePerFile[currentPass][i]); } } } protected void compileJavaParser(boolean leftRecursive) throws IOException { String grammarFileName = "Java.g4"; String sourceName = leftRecursive ? "Java-LR.g4" : "Java.g4"; String body = load(sourceName, null); List<String> extraOptions = new ArrayList<String>(); extraOptions.add("-Werror"); if (FORCE_ATN) { extraOptions.add("-Xforce-atn"); } if (EXPORT_ATN_GRAPHS) { extraOptions.add("-atn"); } if (DEBUG_TEMPLATES) { extraOptions.add("-XdbgST"); if (DEBUG_TEMPLATES_WAIT) { extraOptions.add("-XdbgSTWait"); } } extraOptions.add("-visitor"); String[] extraOptionsArray = extraOptions.toArray(new String[extraOptions.size()]); boolean success = rawGenerateAndBuildRecognizer(grammarFileName, body, "JavaParser", "JavaLexer", true, extraOptionsArray); assertTrue(success); } protected String load(String fileName, @Nullable String encoding) throws IOException { if ( fileName==null ) { return null; } String fullFileName = getClass().getPackage().getName().replace('.', '/') + '/' + fileName; int size = 65000; InputStreamReader isr; InputStream fis = getClass().getClassLoader().getResourceAsStream(fullFileName); if ( encoding!=null ) { isr = new InputStreamReader(fis, encoding); } else { isr = new InputStreamReader(fis); } try { char[] data = new char[size]; int n = isr.read(data); return new String(data, 0, n); } finally { isr.close(); } } private static void updateChecksum(Checksum checksum, int value) { checksum.update((value) & 0xFF); checksum.update((value >>> 8) & 0xFF); checksum.update((value >>> 16) & 0xFF); checksum.update((value >>> 24) & 0xFF); } private static void updateChecksum(Checksum checksum, Token token) { if (token == null) { checksum.update(0); return; } updateChecksum(checksum, token.getStartIndex()); updateChecksum(checksum, token.getStopIndex()); updateChecksum(checksum, token.getLine()); updateChecksum(checksum, token.getCharPositionInLine()); updateChecksum(checksum, token.getType()); updateChecksum(checksum, token.getChannel()); } protected ParserFactory getParserFactory(String lexerName, String parserName, String listenerName, final String entryPoint) { try { ClassLoader loader = new URLClassLoader(new URL[] { new File(tmpdir).toURI().toURL() }, ClassLoader.getSystemClassLoader()); final Class<? extends Lexer> lexerClass = loader.loadClass(lexerName).asSubclass(Lexer.class); final Class<? extends Parser> parserClass = loader.loadClass(parserName).asSubclass(Parser.class); final Class<? extends ParseTreeListener> listenerClass = loader.loadClass(listenerName).asSubclass(ParseTreeListener.class); final Constructor<? extends Lexer> lexerCtor = lexerClass.getConstructor(CharStream.class); final Constructor<? extends Parser> parserCtor = parserClass.getConstructor(TokenStream.class); // construct initial instances of the lexer and parser to deserialize their ATNs TokenSource tokenSource = lexerCtor.newInstance(new ANTLRInputStream("")); parserCtor.newInstance(new CommonTokenStream(tokenSource)); return new ParserFactory() { @Override public FileParseResult parseFile(CharStream input, int currentPass, int thread) { final Checksum checksum = new CRC32(); final long startTime = System.nanoTime(); assert thread >= 0 && thread < NUMBER_OF_THREADS; try { ParseTreeListener listener = sharedListeners[thread]; if (listener == null) { listener = listenerClass.newInstance(); sharedListeners[thread] = listener; } Lexer lexer = sharedLexers[thread]; if (REUSE_LEXER && lexer != null) { lexer.setInputStream(input); } else { Lexer previousLexer = lexer; lexer = lexerCtor.newInstance(input); DFA[] decisionToDFA = (FILE_GRANULARITY || previousLexer == null ? lexer : previousLexer).getInterpreter().decisionToDFA; if (!REUSE_LEXER_DFA || (!FILE_GRANULARITY && previousLexer == null)) { decisionToDFA = new DFA[decisionToDFA.length]; } if (COMPUTE_TRANSITION_STATS) { lexer.setInterpreter(new StatisticsLexerATNSimulator(lexer, lexer.getATN(), decisionToDFA, lexer.getInterpreter().getSharedContextCache())); } else if (!REUSE_LEXER_DFA) { lexer.setInterpreter(new LexerATNSimulator(lexer, lexer.getATN(), decisionToDFA, lexer.getInterpreter().getSharedContextCache())); } sharedLexers[thread] = lexer; } if (lexer.getInterpreter().decisionToDFA[0] == null) { ATN atn = lexer.getATN(); for (int i = 0; i < lexer.getInterpreter().decisionToDFA.length; i++) { lexer.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i); } } CommonTokenStream tokens = new CommonTokenStream(lexer); tokens.fill(); tokenCount.addAndGet(currentPass, tokens.size()); if (COMPUTE_CHECKSUM) { for (Token token : tokens.getTokens()) { updateChecksum(checksum, token); } } if (!RUN_PARSER) { return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), null, tokens.size(), startTime, lexer, null); } final long parseStartTime = System.nanoTime(); Parser parser = sharedParsers[thread]; if (REUSE_PARSER && parser != null) { parser.setInputStream(tokens); } else { Parser previousParser = parser; parser = parserCtor.newInstance(tokens); DFA[] decisionToDFA = (FILE_GRANULARITY || previousParser == null ? parser : previousParser).getInterpreter().decisionToDFA; if (!REUSE_PARSER_DFA || (!FILE_GRANULARITY && previousParser == null)) { decisionToDFA = new DFA[decisionToDFA.length]; } if (COMPUTE_TRANSITION_STATS) { parser.setInterpreter(new StatisticsParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache())); } else if (!REUSE_PARSER_DFA) { parser.setInterpreter(new ParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache())); } sharedParsers[thread] = parser; } parser.removeErrorListeners(); if (!TWO_STAGE_PARSING) { parser.addErrorListener(DescriptiveErrorListener.INSTANCE); parser.addErrorListener(new SummarizingDiagnosticErrorListener()); } if (parser.getInterpreter().decisionToDFA[0] == null) { ATN atn = parser.getATN(); for (int i = 0; i < parser.getInterpreter().decisionToDFA.length; i++) { parser.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i); } } parser.getInterpreter().setPredictionMode(TWO_STAGE_PARSING ? PredictionMode.SLL : PREDICTION_MODE); parser.setBuildParseTree(BUILD_PARSE_TREES); if (!BUILD_PARSE_TREES && BLANK_LISTENER) { parser.addParseListener(listener); } if (BAIL_ON_ERROR || TWO_STAGE_PARSING) { parser.setErrorHandler(new BailErrorStrategy()); } Method parseMethod = parserClass.getMethod(entryPoint); Object parseResult; ParseTreeListener checksumParserListener = null; try { if (COMPUTE_CHECKSUM) { checksumParserListener = new ChecksumParseTreeListener(checksum); parser.addParseListener(checksumParserListener); } parseResult = parseMethod.invoke(parser); } catch (InvocationTargetException ex) { if (!TWO_STAGE_PARSING) { throw ex; } String sourceName = tokens.getSourceName(); sourceName = sourceName != null && !sourceName.isEmpty() ? sourceName+": " : ""; System.err.println(sourceName+"Forced to retry with full context."); if (!(ex.getCause() instanceof ParseCancellationException)) { throw ex; } tokens.reset(); if (REUSE_PARSER && parser != null) { parser.setInputStream(tokens); } else { Parser previousParser = parser; parser = parserCtor.newInstance(tokens); DFA[] decisionToDFA = previousParser.getInterpreter().decisionToDFA; if (COMPUTE_TRANSITION_STATS) { parser.setInterpreter(new StatisticsParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache())); } else if (!REUSE_PARSER_DFA) { parser.setInterpreter(new ParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache())); } sharedParsers[thread] = parser; } parser.removeErrorListeners(); parser.addErrorListener(DescriptiveErrorListener.INSTANCE); parser.addErrorListener(new SummarizingDiagnosticErrorListener()); parser.getInterpreter().setPredictionMode(PredictionMode.LL); parser.setBuildParseTree(BUILD_PARSE_TREES); if (!BUILD_PARSE_TREES && BLANK_LISTENER) { parser.addParseListener(listener); } if (BAIL_ON_ERROR) { parser.setErrorHandler(new BailErrorStrategy()); } parseResult = parseMethod.invoke(parser); } finally { if (checksumParserListener != null) { parser.removeParseListener(checksumParserListener); } } assertThat(parseResult, instanceOf(ParseTree.class)); if (BUILD_PARSE_TREES && BLANK_LISTENER) { ParseTreeWalker.DEFAULT.walk(listener, (ParseTree)parseResult); } return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), (ParseTree)parseResult, tokens.size(), TIME_PARSE_ONLY ? parseStartTime : startTime, lexer, parser); } catch (Exception e) { if (!REPORT_SYNTAX_ERRORS && e instanceof ParseCancellationException) { return new FileParseResult("unknown", (int)checksum.getValue(), null, 0, startTime, null, null); } e.printStackTrace(System.out); throw new IllegalStateException(e); } } }; } catch (Exception e) { e.printStackTrace(System.out); Assert.fail(e.getMessage()); throw new IllegalStateException(e); } } protected interface ParserFactory { FileParseResult parseFile(CharStream input, int currentPass, int thread); } protected static class FileParseResult { public final String sourceName; public final int checksum; public final ParseTree parseTree; public final int tokenCount; public final long startTime; public final long endTime; public final int lexerDFASize; public final long lexerTotalTransitions; public final long lexerComputedTransitions; public final int parserDFASize; public final long parserTotalTransitions; public final long parserComputedTransitions; public FileParseResult(String sourceName, int checksum, @Nullable ParseTree parseTree, int tokenCount, long startTime, Lexer lexer, Parser parser) { this.sourceName = sourceName; this.checksum = checksum; this.parseTree = parseTree; this.tokenCount = tokenCount; this.startTime = startTime; this.endTime = System.nanoTime(); if (lexer != null) { LexerATNSimulator interpreter = lexer.getInterpreter(); if (interpreter instanceof StatisticsLexerATNSimulator) { lexerTotalTransitions = ((StatisticsLexerATNSimulator)interpreter).totalTransitions; lexerComputedTransitions = ((StatisticsLexerATNSimulator)interpreter).computedTransitions; } else { lexerTotalTransitions = 0; lexerComputedTransitions = 0; } int dfaSize = 0; for (DFA dfa : interpreter.decisionToDFA) { if (dfa != null) { dfaSize += dfa.states.size(); } } lexerDFASize = dfaSize; } else { lexerDFASize = 0; lexerTotalTransitions = 0; lexerComputedTransitions = 0; } if (parser != null) { ParserATNSimulator interpreter = parser.getInterpreter(); if (interpreter instanceof StatisticsParserATNSimulator) { parserTotalTransitions = ((StatisticsParserATNSimulator)interpreter).totalTransitions; parserComputedTransitions = ((StatisticsParserATNSimulator)interpreter).computedTransitions; } else { parserTotalTransitions = 0; parserComputedTransitions = 0; } int dfaSize = 0; for (DFA dfa : interpreter.decisionToDFA) { if (dfa != null) { dfaSize += dfa.states.size(); } } parserDFASize = dfaSize; } else { parserDFASize = 0; parserTotalTransitions = 0; parserComputedTransitions = 0; } } } private static class StatisticsLexerATNSimulator extends LexerATNSimulator { public long totalTransitions; public long computedTransitions; public StatisticsLexerATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { super(atn, decisionToDFA, sharedContextCache); } public StatisticsLexerATNSimulator(Lexer recog, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { super(recog, atn, decisionToDFA, sharedContextCache); } @Override protected DFAState getExistingTargetState(DFAState s, int t) { totalTransitions++; return super.getExistingTargetState(s, t); } @Override protected DFAState computeTargetState(CharStream input, DFAState s, int t) { computedTransitions++; return super.computeTargetState(input, s, t); } } private static class StatisticsParserATNSimulator extends ParserATNSimulator { public long totalTransitions; public long computedTransitions; public StatisticsParserATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { super(atn, decisionToDFA, sharedContextCache); } public StatisticsParserATNSimulator(Parser parser, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { super(parser, atn, decisionToDFA, sharedContextCache); } @Override protected DFAState getExistingTargetState(DFAState previousD, int t) { totalTransitions++; return super.getExistingTargetState(previousD, t); } @Override protected DFAState computeTargetState(DFA dfa, DFAState previousD, int t) { computedTransitions++; return super.computeTargetState(dfa, previousD, t); } } private static class DescriptiveErrorListener extends BaseErrorListener { public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { if (!REPORT_SYNTAX_ERRORS) { return; } String sourceName = recognizer.getInputStream().getSourceName(); if (!sourceName.isEmpty()) { sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine); } System.err.println(sourceName+"line "+line+":"+charPositionInLine+" "+msg); } } private static class SummarizingDiagnosticErrorListener extends DiagnosticErrorListener { @Override public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet ambigAlts, ATNConfigSet configs) { if (!REPORT_AMBIGUITIES) { return; } super.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, ambigAlts, configs); } @Override public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, ATNConfigSet configs) { if (!REPORT_FULL_CONTEXT) { return; } super.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, configs); } @Override public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, ATNConfigSet configs) { if (!REPORT_CONTEXT_SENSITIVITY) { return; } super.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, configs); } } protected static final class FilenameFilters { public static final FilenameFilter ALL_FILES = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return true; } }; public static FilenameFilter extension(String extension) { return extension(extension, true); } public static FilenameFilter extension(String extension, boolean caseSensitive) { return new FileExtensionFilenameFilter(extension, caseSensitive); } public static FilenameFilter name(String filename) { return name(filename, true); } public static FilenameFilter name(String filename, boolean caseSensitive) { return new FileNameFilenameFilter(filename, caseSensitive); } public static FilenameFilter all(FilenameFilter... filters) { return new AllFilenameFilter(filters); } public static FilenameFilter any(FilenameFilter... filters) { return new AnyFilenameFilter(filters); } public static FilenameFilter none(FilenameFilter... filters) { return not(any(filters)); } public static FilenameFilter not(FilenameFilter filter) { return new NotFilenameFilter(filter); } private FilenameFilters() { } protected static class FileExtensionFilenameFilter implements FilenameFilter { private final String extension; private final boolean caseSensitive; public FileExtensionFilenameFilter(String extension, boolean caseSensitive) { if (!extension.startsWith(".")) { extension = '.' + extension; } this.extension = extension; this.caseSensitive = caseSensitive; } @Override public boolean accept(File dir, String name) { if (caseSensitive) { return name.endsWith(extension); } else { return name.toLowerCase().endsWith(extension); } } } protected static class FileNameFilenameFilter implements FilenameFilter { private final String filename; private final boolean caseSensitive; public FileNameFilenameFilter(String filename, boolean caseSensitive) { this.filename = filename; this.caseSensitive = caseSensitive; } @Override public boolean accept(File dir, String name) { if (caseSensitive) { return name.equals(filename); } else { return name.toLowerCase().equals(filename); } } } protected static class AllFilenameFilter implements FilenameFilter { private final FilenameFilter[] filters; public AllFilenameFilter(FilenameFilter[] filters) { this.filters = filters; } @Override public boolean accept(File dir, String name) { for (FilenameFilter filter : filters) { if (!filter.accept(dir, name)) { return false; } } return true; } } protected static class AnyFilenameFilter implements FilenameFilter { private final FilenameFilter[] filters; public AnyFilenameFilter(FilenameFilter[] filters) { this.filters = filters; } @Override public boolean accept(File dir, String name) { for (FilenameFilter filter : filters) { if (filter.accept(dir, name)) { return true; } } return false; } } protected static class NotFilenameFilter implements FilenameFilter { private final FilenameFilter filter; public NotFilenameFilter(FilenameFilter filter) { this.filter = filter; } @Override public boolean accept(File dir, String name) { return !filter.accept(dir, name); } } } protected static class NumberedThread extends Thread { private final int threadNumber; public NumberedThread(Runnable target, int threadNumber) { super(target); this.threadNumber = threadNumber; } public final int getThreadNumber() { return threadNumber; } } protected static class NumberedThreadFactory implements ThreadFactory { private final AtomicInteger nextThread = new AtomicInteger(); @Override public Thread newThread(Runnable r) { int threadNumber = nextThread.getAndIncrement(); assert threadNumber < NUMBER_OF_THREADS; return new NumberedThread(r, threadNumber); } } protected static class FixedThreadNumberFactory implements ThreadFactory { private final int threadNumber; public FixedThreadNumberFactory(int threadNumber) { this.threadNumber = threadNumber; } @Override public Thread newThread(Runnable r) { assert threadNumber < NUMBER_OF_THREADS; return new NumberedThread(r, threadNumber); } } protected static class ChecksumParseTreeListener implements ParseTreeListener { private static final int VISIT_TERMINAL = 1; private static final int VISIT_ERROR_NODE = 2; private static final int ENTER_RULE = 3; private static final int EXIT_RULE = 4; private final Checksum checksum; public ChecksumParseTreeListener(Checksum checksum) { this.checksum = checksum; } @Override public void visitTerminal(TerminalNode node) { checksum.update(VISIT_TERMINAL); updateChecksum(checksum, node.getSymbol()); } @Override public void visitErrorNode(ErrorNode node) { checksum.update(VISIT_ERROR_NODE); updateChecksum(checksum, node.getSymbol()); } @Override public void enterEveryRule(ParserRuleContext ctx) { checksum.update(ENTER_RULE); updateChecksum(checksum, ctx.getRuleIndex()); updateChecksum(checksum, ctx.getStart()); } @Override public void exitEveryRule(ParserRuleContext ctx) { checksum.update(EXIT_RULE); updateChecksum(checksum, ctx.getRuleIndex()); updateChecksum(checksum, ctx.getStop()); } } protected static final class InputDescriptor { private final String source; private Reference<CloneableANTLRFileStream> inputStream; public InputDescriptor(@NotNull String source) { this.source = source; if (PRELOAD_SOURCES) { getInputStream(); } } @NotNull public synchronized CharStream getInputStream() { CloneableANTLRFileStream stream = inputStream != null ? inputStream.get() : null; if (stream == null) { try { stream = new CloneableANTLRFileStream(source, ENCODING); } catch (IOException ex) { throw new RuntimeException(ex); } if (PRELOAD_SOURCES) { inputStream = new StrongReference<CloneableANTLRFileStream>(stream); } else { inputStream = new SoftReference<CloneableANTLRFileStream>(stream); } } return stream.createCopy(); } } protected static class CloneableANTLRFileStream extends ANTLRFileStream { public CloneableANTLRFileStream(String fileName, String encoding) throws IOException { super(fileName, encoding); } public ANTLRInputStream createCopy() { ANTLRInputStream stream = new ANTLRInputStream(this.data, this.n); stream.name = this.getSourceName(); return stream; } } public static class StrongReference<T> extends WeakReference<T> { public final T referent; public StrongReference(T referent) { super(referent); this.referent = referent; } @Override public T get() { return referent; } } }
tool/test/org/antlr/v4/test/TestPerformance.java
/* * [The "BSD license"] * Copyright (c) 2012 Terence Parr * Copyright (c) 2012 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.antlr.v4.test; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BailErrorStrategy; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.DefaultErrorStrategy; import org.antlr.v4.runtime.DiagnosticErrorListener; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenSource; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.atn.ATN; import org.antlr.v4.runtime.atn.ATNConfig; import org.antlr.v4.runtime.atn.ATNConfigSet; import org.antlr.v4.runtime.atn.LexerATNSimulator; import org.antlr.v4.runtime.atn.ParserATNSimulator; import org.antlr.v4.runtime.atn.PredictionContextCache; import org.antlr.v4.runtime.atn.PredictionMode; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.dfa.DFAState; import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.misc.Nullable; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeListener; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.CRC32; import java.util.zip.Checksum; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class TestPerformance extends BaseTest { /** * Parse all java files under this package within the JDK_SOURCE_ROOT * (environment variable or property defined on the Java command line). */ private static final String TOP_PACKAGE = "java.lang"; /** * {@code true} to load java files from sub-packages of * {@link #TOP_PACKAGE}. */ private static final boolean RECURSIVE = true; /** * {@code true} to read all source files from disk into memory before * starting the parse. The default value is {@code true} to help prevent * drive speed from affecting the performance results. This value may be set * to {@code false} to support parsing large input sets which would not * otherwise fit into memory. */ private static final boolean PRELOAD_SOURCES = true; /** * The encoding to use when reading source files. */ private static final String ENCODING = "UTF-8"; /** * The maximum number of files to parse in a single iteration. */ private static final int MAX_FILES_PER_PARSE_ITERATION = Integer.MAX_VALUE; /** * {@code true} to call {@link Collections#shuffle} on the list of input * files before the first parse iteration. */ private static final boolean SHUFFLE_FILES_AT_START = false; /** * {@code true} to call {@link Collections#shuffle} before each parse * iteration <em>after</em> the first. */ private static final boolean SHUFFLE_FILES_AFTER_ITERATIONS = false; /** * The instance of {@link Random} passed when calling * {@link Collections#shuffle}. */ private static final Random RANDOM = new Random(); /** * {@code true} to use the Java grammar with expressions in the v4 * left-recursive syntax (Java-LR.g4). {@code false} to use the standard * grammar (Java.g4). In either case, the grammar is renamed in the * temporary directory to Java.g4 before compiling. */ private static final boolean USE_LR_GRAMMAR = true; /** * {@code true} to specify the {@code -Xforce-atn} option when generating * the grammar, forcing all decisions in {@code JavaParser} to be handled by * {@link ParserATNSimulator#adaptivePredict}. */ private static final boolean FORCE_ATN = false; /** * {@code true} to specify the {@code -atn} option when generating the * grammar. This will cause ANTLR to export the ATN for each decision as a * DOT (GraphViz) file. */ private static final boolean EXPORT_ATN_GRAPHS = true; /** * {@code true} to specify the {@code -XdbgST} option when generating the * grammar. */ private static final boolean DEBUG_TEMPLATES = false; /** * {@code true} to specify the {@code -XdbgSTWait} option when generating the * grammar. */ private static final boolean DEBUG_TEMPLATES_WAIT = DEBUG_TEMPLATES; /** * {@code true} to delete temporary (generated and compiled) files when the * test completes. */ private static final boolean DELETE_TEMP_FILES = true; /** * {@code true} to call {@link System#gc} and then wait for 5 seconds at the * end of the test to make it easier for a profiler to grab a heap dump at * the end of the test run. */ private static final boolean PAUSE_FOR_HEAP_DUMP = false; /** * Parse each file with {@code JavaParser.compilationUnit}. */ private static final boolean RUN_PARSER = true; /** * {@code true} to use {@link BailErrorStrategy}, {@code false} to use * {@link DefaultErrorStrategy}. */ private static final boolean BAIL_ON_ERROR = false; /** * {@code true} to compute a checksum for verifying consistency across * optimizations and multiple passes. */ private static final boolean COMPUTE_CHECKSUM = true; /** * This value is passed to {@link Parser#setBuildParseTree}. */ private static final boolean BUILD_PARSE_TREES = false; /** * Use * {@link ParseTreeWalker#DEFAULT}{@code .}{@link ParseTreeWalker#walk walk} * with the {@code JavaParserBaseListener} to show parse tree walking * overhead. If {@link #BUILD_PARSE_TREES} is {@code false}, the listener * will instead be called during the parsing process via * {@link Parser#addParseListener}. */ private static final boolean BLANK_LISTENER = false; /** * Shows the number of {@link DFAState} and {@link ATNConfig} instances in * the DFA cache at the end of each pass. If {@link #REUSE_LEXER_DFA} and/or * {@link #REUSE_PARSER_DFA} are false, the corresponding instance numbers * will only apply to one file (the last file if {@link #NUMBER_OF_THREADS} * is 0, otherwise the last file which was parsed on the first thread). */ private static final boolean SHOW_DFA_STATE_STATS = true; /** * If {@code true}, the DFA state statistics report includes a breakdown of * the number of DFA states contained in each decision (with rule names). */ private static final boolean DETAILED_DFA_STATE_STATS = true; /** * Specify the {@link PredictionMode} used by the * {@link ParserATNSimulator}. If {@link #TWO_STAGE_PARSING} is * {@code true}, this value only applies to the second stage, as the first * stage will always use {@link PredictionMode#SLL}. */ private static final PredictionMode PREDICTION_MODE = PredictionMode.LL; private static final boolean TWO_STAGE_PARSING = true; private static final boolean SHOW_CONFIG_STATS = false; /** * If {@code true}, detailed statistics for the number of DFA edges were * taken while parsing each file, as well as the number of DFA edges which * required on-the-fly computation. */ private static final boolean COMPUTE_TRANSITION_STATS = false; /** * If {@code true}, the transition statistics will be adjusted to a running * total before reporting the final results. */ private static final boolean TRANSITION_RUNNING_AVERAGE = false; /** * If {@code true}, transition statistics will be weighted according to the * total number of transitions taken during the parsing of each file. */ private static final boolean TRANSITION_WEIGHTED_AVERAGE = false; /** * If {@code true}, after each pass a summary of the time required to parse * each file will be printed. */ private static final boolean COMPUTE_TIMING_STATS = false; /** * If {@code true}, the timing statistics for {@link #COMPUTE_TIMING_STATS} * will be cumulative (i.e. the time reported for the <em>n</em>th file will * be the total time required to parse the first <em>n</em> files). */ private static final boolean TIMING_CUMULATIVE = false; /** * If {@code true}, the timing statistics will include the parser only. This * flag allows for targeted measurements, and helps eliminate variance when * {@link #PRELOAD_SOURCES} is {@code false}. * <p/> * This flag has no impact when {@link #RUN_PARSER} is {@code false}. */ private static final boolean TIME_PARSE_ONLY = false; private static final boolean REPORT_SYNTAX_ERRORS = true; private static final boolean REPORT_AMBIGUITIES = false; private static final boolean REPORT_FULL_CONTEXT = false; private static final boolean REPORT_CONTEXT_SENSITIVITY = REPORT_FULL_CONTEXT; /** * If {@code true}, a single {@code JavaLexer} will be used, and * {@link Lexer#setInputStream} will be called to initialize it for each * source file. Otherwise, a new instance will be created for each file. */ private static final boolean REUSE_LEXER = false; /** * If {@code true}, a single DFA will be used for lexing which is shared * across all threads and files. Otherwise, each file will be lexed with its * own DFA which is accomplished by creating one ATN instance per thread and * clearing its DFA cache before lexing each file. */ private static final boolean REUSE_LEXER_DFA = true; /** * If {@code true}, a single {@code JavaParser} will be used, and * {@link Parser#setInputStream} will be called to initialize it for each * source file. Otherwise, a new instance will be created for each file. */ private static final boolean REUSE_PARSER = false; /** * If {@code true}, a single DFA will be used for parsing which is shared * across all threads and files. Otherwise, each file will be parsed with * its own DFA which is accomplished by creating one ATN instance per thread * and clearing its DFA cache before parsing each file. */ private static final boolean REUSE_PARSER_DFA = true; /** * If {@code true}, the shared lexer and parser are reset after each pass. * If {@code false}, all passes after the first will be fully "warmed up", * which makes them faster and can compare them to the first warm-up pass, * but it will not distinguish bytecode load/JIT time from warm-up time * during the first pass. */ private static final boolean CLEAR_DFA = false; /** * Total number of passes to make over the source. */ private static final int PASSES = 4; /** * This option controls the granularity of multi-threaded parse operations. * If {@code true}, the parsing operation will be parallelized across files; * otherwise the parsing will be parallelized across multiple iterations. */ private static final boolean FILE_GRANULARITY = false; /** * Number of parser threads to use. */ private static final int NUMBER_OF_THREADS = 1; private static final Lexer[] sharedLexers = new Lexer[NUMBER_OF_THREADS]; private static final Parser[] sharedParsers = new Parser[NUMBER_OF_THREADS]; private static final ParseTreeListener[] sharedListeners = new ParseTreeListener[NUMBER_OF_THREADS]; private static final long[][] totalTransitionsPerFile; private static final long[][] computedTransitionsPerFile; static { if (COMPUTE_TRANSITION_STATS) { totalTransitionsPerFile = new long[PASSES][]; computedTransitionsPerFile = new long[PASSES][]; } else { totalTransitionsPerFile = null; computedTransitionsPerFile = null; } } private static final long[][] timePerFile; private static final int[][] tokensPerFile; static { if (COMPUTE_TIMING_STATS) { timePerFile = new long[PASSES][]; tokensPerFile = new int[PASSES][]; } else { timePerFile = null; tokensPerFile = null; } } private final AtomicIntegerArray tokenCount = new AtomicIntegerArray(PASSES); @Test //@org.junit.Ignore public void compileJdk() throws IOException, InterruptedException, ExecutionException { String jdkSourceRoot = getSourceRoot("JDK"); assertTrue("The JDK_SOURCE_ROOT environment variable must be set for performance testing.", jdkSourceRoot != null && !jdkSourceRoot.isEmpty()); compileJavaParser(USE_LR_GRAMMAR); final String lexerName = "JavaLexer"; final String parserName = "JavaParser"; final String listenerName = "JavaBaseListener"; final String entryPoint = "compilationUnit"; final ParserFactory factory = getParserFactory(lexerName, parserName, listenerName, entryPoint); if (!TOP_PACKAGE.isEmpty()) { jdkSourceRoot = jdkSourceRoot + '/' + TOP_PACKAGE.replace('.', '/'); } File directory = new File(jdkSourceRoot); assertTrue(directory.isDirectory()); FilenameFilter filesFilter = FilenameFilters.extension(".java", false); FilenameFilter directoriesFilter = FilenameFilters.ALL_FILES; final List<InputDescriptor> sources = loadSources(directory, filesFilter, directoriesFilter, RECURSIVE); for (int i = 0; i < PASSES; i++) { if (COMPUTE_TRANSITION_STATS) { totalTransitionsPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)]; computedTransitionsPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)]; } if (COMPUTE_TIMING_STATS) { timePerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)]; tokensPerFile[i] = new int[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)]; } } System.out.format("Located %d source files.%n", sources.size()); System.out.print(getOptionsDescription(TOP_PACKAGE)); ExecutorService executorService = Executors.newFixedThreadPool(FILE_GRANULARITY ? 1 : NUMBER_OF_THREADS, new NumberedThreadFactory()); List<Future<?>> passResults = new ArrayList<Future<?>>(); passResults.add(executorService.submit(new Runnable() { @Override public void run() { try { parse1(0, factory, sources, SHUFFLE_FILES_AT_START); } catch (InterruptedException ex) { Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); } } })); for (int i = 0; i < PASSES - 1; i++) { final int currentPass = i + 1; passResults.add(executorService.submit(new Runnable() { @Override public void run() { if (CLEAR_DFA) { int index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber(); if (sharedLexers.length > 0 && sharedLexers[index] != null) { ATN atn = sharedLexers[index].getATN(); for (int j = 0; j < sharedLexers[index].getInterpreter().decisionToDFA.length; j++) { sharedLexers[index].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j); } } if (sharedParsers.length > 0 && sharedParsers[index] != null) { ATN atn = sharedParsers[index].getATN(); for (int j = 0; j < sharedParsers[index].getInterpreter().decisionToDFA.length; j++) { sharedParsers[index].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j); } } if (FILE_GRANULARITY) { Arrays.fill(sharedLexers, null); Arrays.fill(sharedParsers, null); } } try { parse2(currentPass, factory, sources, SHUFFLE_FILES_AFTER_ITERATIONS); } catch (InterruptedException ex) { Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); } } })); } for (Future<?> passResult : passResults) { passResult.get(); } executorService.shutdown(); executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); if (COMPUTE_TRANSITION_STATS) { computeTransitionStatistics(); } if (COMPUTE_TIMING_STATS) { computeTimingStatistics(); } sources.clear(); if (PAUSE_FOR_HEAP_DUMP) { System.gc(); System.out.println("Pausing before application exit."); try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); } } } /** * Compute and print ATN/DFA transition statistics. */ private void computeTransitionStatistics() { if (TRANSITION_RUNNING_AVERAGE) { for (int i = 0; i < PASSES; i++) { long[] data = computedTransitionsPerFile[i]; for (int j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } data = totalTransitionsPerFile[i]; for (int j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } } } long[] sumNum = new long[totalTransitionsPerFile[0].length]; long[] sumDen = new long[totalTransitionsPerFile[0].length]; double[] sumNormalized = new double[totalTransitionsPerFile[0].length]; for (int i = 0; i < PASSES; i++) { long[] num = computedTransitionsPerFile[i]; long[] den = totalTransitionsPerFile[i]; for (int j = 0; j < den.length; j++) { sumNum[j] += num[j]; sumDen[j] += den[j]; sumNormalized[j] += (double)num[j] / (double)den[j]; } } double[] weightedAverage = new double[totalTransitionsPerFile[0].length]; double[] average = new double[totalTransitionsPerFile[0].length]; for (int i = 0; i < average.length; i++) { weightedAverage[i] = (double)sumNum[i] / (double)sumDen[i]; average[i] = sumNormalized[i] / PASSES; } double[] low95 = new double[totalTransitionsPerFile[0].length]; double[] high95 = new double[totalTransitionsPerFile[0].length]; double[] low67 = new double[totalTransitionsPerFile[0].length]; double[] high67 = new double[totalTransitionsPerFile[0].length]; double[] stddev = new double[totalTransitionsPerFile[0].length]; for (int i = 0; i < stddev.length; i++) { double[] points = new double[PASSES]; for (int j = 0; j < PASSES; j++) { points[j] = ((double)computedTransitionsPerFile[j][i] / (double)totalTransitionsPerFile[j][i]); } Arrays.sort(points); final double averageValue = TRANSITION_WEIGHTED_AVERAGE ? weightedAverage[i] : average[i]; double value = 0; for (int j = 0; j < PASSES; j++) { double diff = points[j] - averageValue; value += diff * diff; } int ignoreCount95 = (int)Math.round(PASSES * (1 - 0.95) / 2.0); int ignoreCount67 = (int)Math.round(PASSES * (1 - 0.667) / 2.0); low95[i] = points[ignoreCount95]; high95[i] = points[points.length - 1 - ignoreCount95]; low67[i] = points[ignoreCount67]; high67[i] = points[points.length - 1 - ignoreCount67]; stddev[i] = Math.sqrt(value / PASSES); } System.out.format("File\tAverage\tStd. Dev.\t95%% Low\t95%% High\t66.7%% Low\t66.7%% High%n"); for (int i = 0; i < stddev.length; i++) { final double averageValue = TRANSITION_WEIGHTED_AVERAGE ? weightedAverage[i] : average[i]; System.out.format("%d\t%e\t%e\t%e\t%e\t%e\t%e%n", i + 1, averageValue, stddev[i], averageValue - low95[i], high95[i] - averageValue, averageValue - low67[i], high67[i] - averageValue); } } /** * Compute and print timing statistics. */ private void computeTimingStatistics() { if (TIMING_CUMULATIVE) { for (int i = 0; i < PASSES; i++) { long[] data = timePerFile[i]; for (int j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } int[] data2 = tokensPerFile[i]; for (int j = 0; j < data2.length - 1; j++) { data2[j + 1] += data2[j]; } } } final int fileCount = timePerFile[0].length; double[] sum = new double[fileCount]; for (int i = 0; i < PASSES; i++) { long[] data = timePerFile[i]; int[] tokenData = tokensPerFile[i]; for (int j = 0; j < data.length; j++) { sum[j] += (double)data[j] / (double)tokenData[j]; } } double[] average = new double[fileCount]; for (int i = 0; i < average.length; i++) { average[i] = sum[i] / PASSES; } double[] low95 = new double[fileCount]; double[] high95 = new double[fileCount]; double[] low67 = new double[fileCount]; double[] high67 = new double[fileCount]; double[] stddev = new double[fileCount]; for (int i = 0; i < stddev.length; i++) { double[] points = new double[PASSES]; for (int j = 0; j < PASSES; j++) { points[j] = (double)timePerFile[j][i] / (double)tokensPerFile[j][i]; } Arrays.sort(points); final double averageValue = average[i]; double value = 0; for (int j = 0; j < PASSES; j++) { double diff = points[j] - averageValue; value += diff * diff; } int ignoreCount95 = (int)Math.round(PASSES * (1 - 0.95) / 2.0); int ignoreCount67 = (int)Math.round(PASSES * (1 - 0.667) / 2.0); low95[i] = points[ignoreCount95]; high95[i] = points[points.length - 1 - ignoreCount95]; low67[i] = points[ignoreCount67]; high67[i] = points[points.length - 1 - ignoreCount67]; stddev[i] = Math.sqrt(value / PASSES); } System.out.format("File\tAverage\tStd. Dev.\t95%% Low\t95%% High\t66.7%% Low\t66.7%% High%n"); for (int i = 0; i < stddev.length; i++) { final double averageValue = average[i]; System.out.format("%d\t%e\t%e\t%e\t%e\t%e\t%e%n", i + 1, averageValue, stddev[i], averageValue - low95[i], high95[i] - averageValue, averageValue - low67[i], high67[i] - averageValue); } } private String getSourceRoot(String prefix) { String sourceRoot = System.getenv(prefix+"_SOURCE_ROOT"); if (sourceRoot == null) { sourceRoot = System.getProperty(prefix+"_SOURCE_ROOT"); } return sourceRoot; } @Override protected void eraseTempDir() { if (DELETE_TEMP_FILES) { super.eraseTempDir(); } } public static String getOptionsDescription(String topPackage) { StringBuilder builder = new StringBuilder(); builder.append("Input="); if (topPackage.isEmpty()) { builder.append("*"); } else { builder.append(topPackage).append(".*"); } builder.append(", Grammar=").append(USE_LR_GRAMMAR ? "LR" : "Standard"); builder.append(", ForceAtn=").append(FORCE_ATN); builder.append(newline); builder.append("Op=Lex").append(RUN_PARSER ? "+Parse" : " only"); builder.append(", Strategy=").append(BAIL_ON_ERROR ? BailErrorStrategy.class.getSimpleName() : DefaultErrorStrategy.class.getSimpleName()); builder.append(", BuildParseTree=").append(BUILD_PARSE_TREES); builder.append(", WalkBlankListener=").append(BLANK_LISTENER); builder.append(newline); builder.append("Lexer=").append(REUSE_LEXER ? "setInputStream" : "newInstance"); builder.append(", Parser=").append(REUSE_PARSER ? "setInputStream" : "newInstance"); builder.append(", AfterPass=").append(CLEAR_DFA ? "newInstance" : "setInputStream"); builder.append(newline); return builder.toString(); } /** * This method is separate from {@link #parse2} so the first pass can be distinguished when analyzing * profiler results. */ protected void parse1(int currentPass, ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException { if (FILE_GRANULARITY) { System.gc(); } parseSources(currentPass, factory, sources, shuffleSources); } /** * This method is separate from {@link #parse1} so the first pass can be distinguished when analyzing * profiler results. */ protected void parse2(int currentPass, ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException { if (FILE_GRANULARITY) { System.gc(); } parseSources(currentPass, factory, sources, shuffleSources); } protected List<InputDescriptor> loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive) { List<InputDescriptor> result = new ArrayList<InputDescriptor>(); loadSources(directory, filesFilter, directoriesFilter, recursive, result); return result; } protected void loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive, Collection<InputDescriptor> result) { assert directory.isDirectory(); File[] sources = directory.listFiles(filesFilter); for (File file : sources) { if (!file.isFile()) { continue; } result.add(new InputDescriptor(file.getAbsolutePath())); } if (recursive) { File[] children = directory.listFiles(directoriesFilter); for (File child : children) { if (child.isDirectory()) { loadSources(child, filesFilter, directoriesFilter, true, result); } } } } int configOutputSize = 0; @SuppressWarnings("unused") protected void parseSources(final int currentPass, final ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException { if (shuffleSources) { List<InputDescriptor> sourcesList = new ArrayList<InputDescriptor>(sources); synchronized (RANDOM) { Collections.shuffle(sourcesList, RANDOM); } sources = sourcesList; } long startTime = System.currentTimeMillis(); tokenCount.set(currentPass, 0); int inputSize = 0; int inputCount = 0; Collection<Future<FileParseResult>> results = new ArrayList<Future<FileParseResult>>(); ExecutorService executorService; if (FILE_GRANULARITY) { executorService = Executors.newFixedThreadPool(FILE_GRANULARITY ? NUMBER_OF_THREADS : 1, new NumberedThreadFactory()); } else { executorService = Executors.newSingleThreadExecutor(new FixedThreadNumberFactory(((NumberedThread)Thread.currentThread()).getThreadNumber())); } for (InputDescriptor inputDescriptor : sources) { if (inputCount >= MAX_FILES_PER_PARSE_ITERATION) { break; } final CharStream input = inputDescriptor.getInputStream(); input.seek(0); inputSize += input.size(); inputCount++; Future<FileParseResult> futureChecksum = executorService.submit(new Callable<FileParseResult>() { @Override public FileParseResult call() { // this incurred a great deal of overhead and was causing significant variations in performance results. //System.out.format("Parsing file %s\n", input.getSourceName()); try { return factory.parseFile(input, currentPass, ((NumberedThread)Thread.currentThread()).getThreadNumber()); } catch (IllegalStateException ex) { ex.printStackTrace(System.err); } catch (Throwable t) { t.printStackTrace(System.err); } return null; } }); results.add(futureChecksum); } Checksum checksum = new CRC32(); int currentIndex = -1; for (Future<FileParseResult> future : results) { currentIndex++; int fileChecksum = 0; try { FileParseResult fileResult = future.get(); if (COMPUTE_TRANSITION_STATS) { totalTransitionsPerFile[currentPass][currentIndex] = fileResult.parserTotalTransitions; computedTransitionsPerFile[currentPass][currentIndex] = fileResult.parserComputedTransitions; } if (COMPUTE_TIMING_STATS) { timePerFile[currentPass][currentIndex] = fileResult.endTime - fileResult.startTime; tokensPerFile[currentPass][currentIndex] = fileResult.tokenCount; } fileChecksum = fileResult.checksum; } catch (ExecutionException ex) { Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); } if (COMPUTE_CHECKSUM) { updateChecksum(checksum, fileChecksum); } } executorService.shutdown(); executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); System.out.format("%d. Total parse time for %d files (%d KB, %d tokens, checksum 0x%8X): %dms%n", currentPass + 1, inputCount, inputSize / 1024, tokenCount.get(currentPass), COMPUTE_CHECKSUM ? checksum.getValue() : 0, System.currentTimeMillis() - startTime); if (sharedLexers.length > 0) { int index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber(); Lexer lexer = sharedLexers[index]; final LexerATNSimulator lexerInterpreter = lexer.getInterpreter(); final DFA[] modeToDFA = lexerInterpreter.decisionToDFA; if (SHOW_DFA_STATE_STATS) { int states = 0; int configs = 0; Set<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>(); for (int i = 0; i < modeToDFA.length; i++) { DFA dfa = modeToDFA[i]; if (dfa == null) { continue; } states += dfa.states.size(); for (DFAState state : dfa.states.values()) { configs += state.configs.size(); uniqueConfigs.addAll(state.configs); } } System.out.format("There are %d lexer DFAState instances, %d configs (%d unique).%n", states, configs, uniqueConfigs.size()); if (DETAILED_DFA_STATE_STATS) { System.out.format("\tMode\tStates\tConfigs\tMode%n"); for (int i = 0; i < modeToDFA.length; i++) { DFA dfa = modeToDFA[i]; if (dfa == null || dfa.states.isEmpty()) { continue; } int modeConfigs = 0; for (DFAState state : dfa.states.values()) { modeConfigs += state.configs.size(); } String modeName = lexer.getModeNames()[i]; System.out.format("\t%d\t%d\t%d\t%s%n", dfa.decision, dfa.states.size(), modeConfigs, modeName); } } } } if (RUN_PARSER && sharedParsers.length > 0) { int index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber(); Parser parser = sharedParsers[index]; // make sure the individual DFAState objects actually have unique ATNConfig arrays final ParserATNSimulator interpreter = parser.getInterpreter(); final DFA[] decisionToDFA = interpreter.decisionToDFA; if (SHOW_DFA_STATE_STATS) { int states = 0; int configs = 0; Set<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>(); for (int i = 0; i < decisionToDFA.length; i++) { DFA dfa = decisionToDFA[i]; if (dfa == null) { continue; } states += dfa.states.size(); for (DFAState state : dfa.states.values()) { configs += state.configs.size(); uniqueConfigs.addAll(state.configs); } } System.out.format("There are %d parser DFAState instances, %d configs (%d unique).%n", states, configs, uniqueConfigs.size()); if (DETAILED_DFA_STATE_STATS) { System.out.format("\tDecision\tStates\tConfigs\tRule%n"); for (int i = 0; i < decisionToDFA.length; i++) { DFA dfa = decisionToDFA[i]; if (dfa == null || dfa.states.isEmpty()) { continue; } int decisionConfigs = 0; for (DFAState state : dfa.states.values()) { decisionConfigs += state.configs.size(); } String ruleName = parser.getRuleNames()[parser.getATN().decisionToState.get(dfa.decision).ruleIndex]; System.out.format("\t%d\t%d\t%d\t%s%n", dfa.decision, dfa.states.size(), decisionConfigs, ruleName); } } } int localDfaCount = 0; int globalDfaCount = 0; int localConfigCount = 0; int globalConfigCount = 0; int[] contextsInDFAState = new int[0]; for (int i = 0; i < decisionToDFA.length; i++) { DFA dfa = decisionToDFA[i]; if (dfa == null) { continue; } if (SHOW_CONFIG_STATS) { for (DFAState state : dfa.states.keySet()) { if (state.configs.size() >= contextsInDFAState.length) { contextsInDFAState = Arrays.copyOf(contextsInDFAState, state.configs.size() + 1); } if (state.isAcceptState) { boolean hasGlobal = false; for (ATNConfig config : state.configs) { if (config.reachesIntoOuterContext > 0) { globalConfigCount++; hasGlobal = true; } else { localConfigCount++; } } if (hasGlobal) { globalDfaCount++; } else { localDfaCount++; } } contextsInDFAState[state.configs.size()]++; } } } if (SHOW_CONFIG_STATS && currentPass == 0) { System.out.format(" DFA accept states: %d total, %d with only local context, %d with a global context%n", localDfaCount + globalDfaCount, localDfaCount, globalDfaCount); System.out.format(" Config stats: %d total, %d local, %d global%n", localConfigCount + globalConfigCount, localConfigCount, globalConfigCount); if (SHOW_DFA_STATE_STATS) { for (int i = 0; i < contextsInDFAState.length; i++) { if (contextsInDFAState[i] != 0) { System.out.format(" %d configs = %d%n", i, contextsInDFAState[i]); } } } } } if (COMPUTE_TIMING_STATS) { System.out.format("File\tTokens\tTime%n"); for (int i = 0; i< timePerFile[currentPass].length; i++) { System.out.format("%d\t%d\t%d%n", i + 1, tokensPerFile[currentPass][i], timePerFile[currentPass][i]); } } } protected void compileJavaParser(boolean leftRecursive) throws IOException { String grammarFileName = "Java.g4"; String sourceName = leftRecursive ? "Java-LR.g4" : "Java.g4"; String body = load(sourceName, null); List<String> extraOptions = new ArrayList<String>(); extraOptions.add("-Werror"); if (FORCE_ATN) { extraOptions.add("-Xforce-atn"); } if (EXPORT_ATN_GRAPHS) { extraOptions.add("-atn"); } if (DEBUG_TEMPLATES) { extraOptions.add("-XdbgST"); if (DEBUG_TEMPLATES_WAIT) { extraOptions.add("-XdbgSTWait"); } } extraOptions.add("-visitor"); String[] extraOptionsArray = extraOptions.toArray(new String[extraOptions.size()]); boolean success = rawGenerateAndBuildRecognizer(grammarFileName, body, "JavaParser", "JavaLexer", true, extraOptionsArray); assertTrue(success); } protected String load(String fileName, @Nullable String encoding) throws IOException { if ( fileName==null ) { return null; } String fullFileName = getClass().getPackage().getName().replace('.', '/') + '/' + fileName; int size = 65000; InputStreamReader isr; InputStream fis = getClass().getClassLoader().getResourceAsStream(fullFileName); if ( encoding!=null ) { isr = new InputStreamReader(fis, encoding); } else { isr = new InputStreamReader(fis); } try { char[] data = new char[size]; int n = isr.read(data); return new String(data, 0, n); } finally { isr.close(); } } private static void updateChecksum(Checksum checksum, int value) { checksum.update((value) & 0xFF); checksum.update((value >>> 8) & 0xFF); checksum.update((value >>> 16) & 0xFF); checksum.update((value >>> 24) & 0xFF); } private static void updateChecksum(Checksum checksum, Token token) { if (token == null) { checksum.update(0); return; } updateChecksum(checksum, token.getStartIndex()); updateChecksum(checksum, token.getStopIndex()); updateChecksum(checksum, token.getLine()); updateChecksum(checksum, token.getCharPositionInLine()); updateChecksum(checksum, token.getType()); updateChecksum(checksum, token.getChannel()); } protected ParserFactory getParserFactory(String lexerName, String parserName, String listenerName, final String entryPoint) { try { ClassLoader loader = new URLClassLoader(new URL[] { new File(tmpdir).toURI().toURL() }, ClassLoader.getSystemClassLoader()); final Class<? extends Lexer> lexerClass = loader.loadClass(lexerName).asSubclass(Lexer.class); final Class<? extends Parser> parserClass = loader.loadClass(parserName).asSubclass(Parser.class); final Class<? extends ParseTreeListener> listenerClass = loader.loadClass(listenerName).asSubclass(ParseTreeListener.class); final Constructor<? extends Lexer> lexerCtor = lexerClass.getConstructor(CharStream.class); final Constructor<? extends Parser> parserCtor = parserClass.getConstructor(TokenStream.class); // construct initial instances of the lexer and parser to deserialize their ATNs TokenSource tokenSource = lexerCtor.newInstance(new ANTLRInputStream("")); parserCtor.newInstance(new CommonTokenStream(tokenSource)); return new ParserFactory() { @Override public FileParseResult parseFile(CharStream input, int currentPass, int thread) { final Checksum checksum = new CRC32(); final long startTime = System.nanoTime(); assert thread >= 0 && thread < NUMBER_OF_THREADS; try { ParseTreeListener listener = sharedListeners[thread]; if (listener == null) { listener = listenerClass.newInstance(); sharedListeners[thread] = listener; } Lexer lexer = sharedLexers[thread]; if (REUSE_LEXER && lexer != null) { lexer.setInputStream(input); } else { Lexer previousLexer = lexer; lexer = lexerCtor.newInstance(input); DFA[] decisionToDFA = (FILE_GRANULARITY || previousLexer == null ? lexer : previousLexer).getInterpreter().decisionToDFA; if (!REUSE_LEXER_DFA || (!FILE_GRANULARITY && previousLexer == null)) { decisionToDFA = new DFA[decisionToDFA.length]; } if (COMPUTE_TRANSITION_STATS) { lexer.setInterpreter(new StatisticsLexerATNSimulator(lexer, lexer.getATN(), decisionToDFA, lexer.getInterpreter().getSharedContextCache())); } else if (!REUSE_LEXER_DFA) { lexer.setInterpreter(new LexerATNSimulator(lexer, lexer.getATN(), decisionToDFA, lexer.getInterpreter().getSharedContextCache())); } sharedLexers[thread] = lexer; } if (lexer.getInterpreter().decisionToDFA[0] == null) { ATN atn = lexer.getATN(); for (int i = 0; i < lexer.getInterpreter().decisionToDFA.length; i++) { lexer.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i); } } CommonTokenStream tokens = new CommonTokenStream(lexer); tokens.fill(); tokenCount.addAndGet(currentPass, tokens.size()); if (COMPUTE_CHECKSUM) { for (Token token : tokens.getTokens()) { updateChecksum(checksum, token); } } if (!RUN_PARSER) { return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), null, tokens.size(), startTime, lexer, null); } final long parseStartTime = System.nanoTime(); Parser parser = sharedParsers[thread]; if (REUSE_PARSER && parser != null) { parser.setInputStream(tokens); } else { Parser previousParser = parser; parser = parserCtor.newInstance(tokens); DFA[] decisionToDFA = (FILE_GRANULARITY || previousParser == null ? parser : previousParser).getInterpreter().decisionToDFA; if (!REUSE_PARSER_DFA || (!FILE_GRANULARITY && previousParser == null)) { decisionToDFA = new DFA[decisionToDFA.length]; } if (COMPUTE_TRANSITION_STATS) { parser.setInterpreter(new StatisticsParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache())); } else if (!REUSE_PARSER_DFA) { parser.setInterpreter(new ParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache())); } sharedParsers[thread] = parser; } parser.removeErrorListeners(); if (!TWO_STAGE_PARSING) { parser.addErrorListener(DescriptiveErrorListener.INSTANCE); parser.addErrorListener(new SummarizingDiagnosticErrorListener()); } if (parser.getInterpreter().decisionToDFA[0] == null) { ATN atn = parser.getATN(); for (int i = 0; i < parser.getInterpreter().decisionToDFA.length; i++) { parser.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i); } } parser.getInterpreter().setPredictionMode(TWO_STAGE_PARSING ? PredictionMode.SLL : PREDICTION_MODE); parser.setBuildParseTree(BUILD_PARSE_TREES); if (!BUILD_PARSE_TREES && BLANK_LISTENER) { parser.addParseListener(listener); } if (BAIL_ON_ERROR || TWO_STAGE_PARSING) { parser.setErrorHandler(new BailErrorStrategy()); } Method parseMethod = parserClass.getMethod(entryPoint); Object parseResult; ParseTreeListener checksumParserListener = null; try { if (COMPUTE_CHECKSUM) { checksumParserListener = new ChecksumParseTreeListener(checksum); parser.addParseListener(checksumParserListener); } parseResult = parseMethod.invoke(parser); } catch (InvocationTargetException ex) { if (!TWO_STAGE_PARSING) { throw ex; } String sourceName = tokens.getSourceName(); sourceName = sourceName != null && !sourceName.isEmpty() ? sourceName+": " : ""; System.err.println(sourceName+"Forced to retry with full context."); if (!(ex.getCause() instanceof ParseCancellationException)) { throw ex; } tokens.reset(); if (REUSE_PARSER && parser != null) { parser.setInputStream(tokens); } else { Parser previousParser = parser; parser = parserCtor.newInstance(tokens); DFA[] decisionToDFA = previousParser.getInterpreter().decisionToDFA; if (COMPUTE_TRANSITION_STATS) { parser.setInterpreter(new StatisticsParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache())); } else if (!REUSE_PARSER_DFA) { parser.setInterpreter(new ParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache())); } sharedParsers[thread] = parser; } parser.removeErrorListeners(); parser.addErrorListener(DescriptiveErrorListener.INSTANCE); parser.addErrorListener(new SummarizingDiagnosticErrorListener()); parser.getInterpreter().setPredictionMode(PredictionMode.LL); parser.setBuildParseTree(BUILD_PARSE_TREES); if (!BUILD_PARSE_TREES && BLANK_LISTENER) { parser.addParseListener(listener); } if (BAIL_ON_ERROR) { parser.setErrorHandler(new BailErrorStrategy()); } parseResult = parseMethod.invoke(parser); } finally { if (checksumParserListener != null) { parser.removeParseListener(checksumParserListener); } } assertThat(parseResult, instanceOf(ParseTree.class)); if (BUILD_PARSE_TREES && BLANK_LISTENER) { ParseTreeWalker.DEFAULT.walk(listener, (ParseTree)parseResult); } return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), (ParseTree)parseResult, tokens.size(), TIME_PARSE_ONLY ? parseStartTime : startTime, lexer, parser); } catch (Exception e) { if (!REPORT_SYNTAX_ERRORS && e instanceof ParseCancellationException) { return new FileParseResult("unknown", (int)checksum.getValue(), null, 0, startTime, null, null); } e.printStackTrace(System.out); throw new IllegalStateException(e); } } }; } catch (Exception e) { e.printStackTrace(System.out); Assert.fail(e.getMessage()); throw new IllegalStateException(e); } } protected interface ParserFactory { FileParseResult parseFile(CharStream input, int currentPass, int thread); } protected static class FileParseResult { public final String sourceName; public final int checksum; public final ParseTree parseTree; public final int tokenCount; public final long startTime; public final long endTime; public final int lexerDFASize; public final long lexerTotalTransitions; public final long lexerComputedTransitions; public final int parserDFASize; public final long parserTotalTransitions; public final long parserComputedTransitions; public FileParseResult(String sourceName, int checksum, @Nullable ParseTree parseTree, int tokenCount, long startTime, Lexer lexer, Parser parser) { this.sourceName = sourceName; this.checksum = checksum; this.parseTree = parseTree; this.tokenCount = tokenCount; this.startTime = startTime; this.endTime = System.nanoTime(); if (lexer != null) { LexerATNSimulator interpreter = lexer.getInterpreter(); if (interpreter instanceof StatisticsLexerATNSimulator) { lexerTotalTransitions = ((StatisticsLexerATNSimulator)interpreter).totalTransitions; lexerComputedTransitions = ((StatisticsLexerATNSimulator)interpreter).computedTransitions; } else { lexerTotalTransitions = 0; lexerComputedTransitions = 0; } int dfaSize = 0; for (DFA dfa : interpreter.decisionToDFA) { if (dfa != null) { dfaSize += dfa.states.size(); } } lexerDFASize = dfaSize; } else { lexerDFASize = 0; lexerTotalTransitions = 0; lexerComputedTransitions = 0; } if (parser != null) { ParserATNSimulator interpreter = parser.getInterpreter(); if (interpreter instanceof StatisticsParserATNSimulator) { parserTotalTransitions = ((StatisticsParserATNSimulator)interpreter).totalTransitions; parserComputedTransitions = ((StatisticsParserATNSimulator)interpreter).computedTransitions; } else { parserTotalTransitions = 0; parserComputedTransitions = 0; } int dfaSize = 0; for (DFA dfa : interpreter.decisionToDFA) { if (dfa != null) { dfaSize += dfa.states.size(); } } parserDFASize = dfaSize; } else { parserDFASize = 0; parserTotalTransitions = 0; parserComputedTransitions = 0; } } } private static class StatisticsLexerATNSimulator extends LexerATNSimulator { public long totalTransitions; public long computedTransitions; public StatisticsLexerATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { super(atn, decisionToDFA, sharedContextCache); } public StatisticsLexerATNSimulator(Lexer recog, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { super(recog, atn, decisionToDFA, sharedContextCache); } @Override protected DFAState getExistingTargetState(DFAState s, int t) { totalTransitions++; return super.getExistingTargetState(s, t); } @Override protected DFAState computeTargetState(CharStream input, DFAState s, int t) { computedTransitions++; return super.computeTargetState(input, s, t); } } private static class StatisticsParserATNSimulator extends ParserATNSimulator { public long totalTransitions; public long computedTransitions; public StatisticsParserATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { super(atn, decisionToDFA, sharedContextCache); } public StatisticsParserATNSimulator(Parser parser, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { super(parser, atn, decisionToDFA, sharedContextCache); } @Override protected DFAState getExistingTargetState(DFAState previousD, int t) { totalTransitions++; return super.getExistingTargetState(previousD, t); } @Override protected DFAState computeTargetState(DFA dfa, DFAState previousD, int t) { computedTransitions++; return super.computeTargetState(dfa, previousD, t); } } private static class DescriptiveErrorListener extends BaseErrorListener { public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { if (!REPORT_SYNTAX_ERRORS) { return; } String sourceName = recognizer.getInputStream().getSourceName(); if (!sourceName.isEmpty()) { sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine); } System.err.println(sourceName+"line "+line+":"+charPositionInLine+" "+msg); } } private static class SummarizingDiagnosticErrorListener extends DiagnosticErrorListener { @Override public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet ambigAlts, ATNConfigSet configs) { if (!REPORT_AMBIGUITIES) { return; } super.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, ambigAlts, configs); } @Override public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, ATNConfigSet configs) { if (!REPORT_FULL_CONTEXT) { return; } super.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, configs); } @Override public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, ATNConfigSet configs) { if (!REPORT_CONTEXT_SENSITIVITY) { return; } super.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, configs); } } protected static final class FilenameFilters { public static final FilenameFilter ALL_FILES = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return true; } }; public static FilenameFilter extension(String extension) { return extension(extension, true); } public static FilenameFilter extension(String extension, boolean caseSensitive) { return new FileExtensionFilenameFilter(extension, caseSensitive); } public static FilenameFilter name(String filename) { return name(filename, true); } public static FilenameFilter name(String filename, boolean caseSensitive) { return new FileNameFilenameFilter(filename, caseSensitive); } public static FilenameFilter all(FilenameFilter... filters) { return new AllFilenameFilter(filters); } public static FilenameFilter any(FilenameFilter... filters) { return new AnyFilenameFilter(filters); } public static FilenameFilter none(FilenameFilter... filters) { return not(any(filters)); } public static FilenameFilter not(FilenameFilter filter) { return new NotFilenameFilter(filter); } private FilenameFilters() { } protected static class FileExtensionFilenameFilter implements FilenameFilter { private final String extension; private final boolean caseSensitive; public FileExtensionFilenameFilter(String extension, boolean caseSensitive) { if (!extension.startsWith(".")) { extension = '.' + extension; } this.extension = extension; this.caseSensitive = caseSensitive; } @Override public boolean accept(File dir, String name) { if (caseSensitive) { return name.endsWith(extension); } else { return name.toLowerCase().endsWith(extension); } } } protected static class FileNameFilenameFilter implements FilenameFilter { private final String filename; private final boolean caseSensitive; public FileNameFilenameFilter(String filename, boolean caseSensitive) { this.filename = filename; this.caseSensitive = caseSensitive; } @Override public boolean accept(File dir, String name) { if (caseSensitive) { return name.equals(filename); } else { return name.toLowerCase().equals(filename); } } } protected static class AllFilenameFilter implements FilenameFilter { private final FilenameFilter[] filters; public AllFilenameFilter(FilenameFilter[] filters) { this.filters = filters; } @Override public boolean accept(File dir, String name) { for (FilenameFilter filter : filters) { if (!filter.accept(dir, name)) { return false; } } return true; } } protected static class AnyFilenameFilter implements FilenameFilter { private final FilenameFilter[] filters; public AnyFilenameFilter(FilenameFilter[] filters) { this.filters = filters; } @Override public boolean accept(File dir, String name) { for (FilenameFilter filter : filters) { if (filter.accept(dir, name)) { return true; } } return false; } } protected static class NotFilenameFilter implements FilenameFilter { private final FilenameFilter filter; public NotFilenameFilter(FilenameFilter filter) { this.filter = filter; } @Override public boolean accept(File dir, String name) { return !filter.accept(dir, name); } } } protected static class NumberedThread extends Thread { private final int threadNumber; public NumberedThread(Runnable target, int threadNumber) { super(target); this.threadNumber = threadNumber; } public final int getThreadNumber() { return threadNumber; } } protected static class NumberedThreadFactory implements ThreadFactory { private final AtomicInteger nextThread = new AtomicInteger(); @Override public Thread newThread(Runnable r) { int threadNumber = nextThread.getAndIncrement(); assert threadNumber < NUMBER_OF_THREADS; return new NumberedThread(r, threadNumber); } } protected static class FixedThreadNumberFactory implements ThreadFactory { private final int threadNumber; public FixedThreadNumberFactory(int threadNumber) { this.threadNumber = threadNumber; } @Override public Thread newThread(Runnable r) { assert threadNumber < NUMBER_OF_THREADS; return new NumberedThread(r, threadNumber); } } protected static class ChecksumParseTreeListener implements ParseTreeListener { private static final int VISIT_TERMINAL = 1; private static final int VISIT_ERROR_NODE = 2; private static final int ENTER_RULE = 3; private static final int EXIT_RULE = 4; private final Checksum checksum; public ChecksumParseTreeListener(Checksum checksum) { this.checksum = checksum; } @Override public void visitTerminal(TerminalNode node) { checksum.update(VISIT_TERMINAL); updateChecksum(checksum, node.getSymbol()); } @Override public void visitErrorNode(ErrorNode node) { checksum.update(VISIT_ERROR_NODE); updateChecksum(checksum, node.getSymbol()); } @Override public void enterEveryRule(ParserRuleContext ctx) { checksum.update(ENTER_RULE); updateChecksum(checksum, ctx.getRuleIndex()); updateChecksum(checksum, ctx.getStart()); } @Override public void exitEveryRule(ParserRuleContext ctx) { checksum.update(EXIT_RULE); updateChecksum(checksum, ctx.getRuleIndex()); updateChecksum(checksum, ctx.getStop()); } } protected static final class InputDescriptor { private final String source; private Reference<CloneableANTLRFileStream> inputStream; public InputDescriptor(@NotNull String source) { this.source = source; if (PRELOAD_SOURCES) { getInputStream(); } } @NotNull public synchronized CharStream getInputStream() { CloneableANTLRFileStream stream = inputStream != null ? inputStream.get() : null; if (stream == null) { try { stream = new CloneableANTLRFileStream(source, ENCODING); } catch (IOException ex) { throw new RuntimeException(ex); } if (PRELOAD_SOURCES) { inputStream = new StrongReference<CloneableANTLRFileStream>(stream); } else { inputStream = new SoftReference<CloneableANTLRFileStream>(stream); } } return stream.createCopy(); } } protected static class CloneableANTLRFileStream extends ANTLRFileStream { public CloneableANTLRFileStream(String fileName, String encoding) throws IOException { super(fileName, encoding); } public ANTLRInputStream createCopy() { ANTLRInputStream stream = new ANTLRInputStream(this.data, this.n); stream.name = this.getSourceName(); return stream; } } public static class StrongReference<T> extends WeakReference<T> { public final T referent; public StrongReference(T referent) { super(referent); this.referent = referent; } @Override public T get() { return referent; } } }
Use System.nanoTime for more precise timing results
tool/test/org/antlr/v4/test/TestPerformance.java
Use System.nanoTime for more precise timing results
Java
bsd-3-clause
80af37a8f685cdc021e82a61fb7fbcc1789f0eb3
0
AlexRNL/Commons
package com.alexrnl.commons.gui.swing; import java.awt.Component; import java.awt.Frame; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.UnsupportedLookAndFeelException; import com.alexrnl.commons.error.ExceptionUtils; import com.alexrnl.commons.translation.AbstractDialog; import com.alexrnl.commons.translation.GUIElement; import com.alexrnl.commons.translation.Translator; import com.alexrnl.commons.utils.StringUtils; /** * Utility class for Swing related methods.<br /> * @author Alex */ public final class SwingUtils { /** Logger */ private static Logger lg = Logger.getLogger(SwingUtils.class.getName()); /** * Constructor #1.<br /> * Default private constructor. */ private SwingUtils () { super(); } /** * Sets the look and feel of the application.<br /> * Update all frames and pack them to update * @param lookAndFeelName * the name of the look and feel to set. * @return <code>true</code> if the new look and feel was successfully set. */ public static boolean setLookAndFeel (final String lookAndFeelName) { boolean lookAndFeelApplied = false; for (final LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) { if (lg.isLoggable(Level.FINE)) { lg.fine(laf.getName()); } if (laf.getName().equals(lookAndFeelName)) { try { UIManager.setLookAndFeel(laf.getClassName()); if (lg.isLoggable(Level.FINE)) { lg.fine("Look and feel properly setted (" + laf.getName() + ")."); } lookAndFeelApplied = true; } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { lg.warning("Could not set the look and feel " + laf.getName() + ": " + ExceptionUtils.display(e)); lookAndFeelApplied = false; } } } // Applying changes to application if (lookAndFeelApplied) { for (final Frame frame : Frame.getFrames()) { SwingUtilities.updateComponentTreeUI(frame); } } else { lg.warning("Could not find (or set) the look and feel " + lookAndFeelName + ". Using default look and feel."); } return lookAndFeelApplied; } /** * Return the message of a dialog with the parameters included, if the message contained some. * @param translator * the translator to use for displaying the text. * @param dialog * the dialog to use. * @param maxLine * the maximum length allowed on a line. * @return the message to display. */ private static String getMessage (final Translator translator, final AbstractDialog dialog, final int maxLine) { return StringUtils.splitInLinesHTML(translator.get(dialog.message(), dialog.getParameters()), maxLine); } /** * Show the dialog with translation picked from the dialog specified. * @param parent * the parent window (may be <code>null</code>). * @param translator * the translator to use for displaying the text. * @param dialog * the key to the translations to use. * @param type * the type of the dialog. Generally, {@link JOptionPane#ERROR_MESSAGE error}, * {@link JOptionPane#WARNING_MESSAGE warning}, {@link JOptionPane#INFORMATION_MESSAGE * information}, {@link JOptionPane#QUESTION_MESSAGE question} or * {@link JOptionPane#PLAIN_MESSAGE plain} message. * @param maxLine * the maximum length allowed on a line. * @see JOptionPane#showMessageDialog(Component, Object, String, int, javax.swing.Icon) */ public static void showMessageDialog (final Component parent, final Translator translator, final AbstractDialog dialog, final int type, final int maxLine) { JOptionPane.showMessageDialog(parent, getMessage(translator, dialog, maxLine), translator.get(dialog.title()), type); } /** * Show a confirmation dialog to the user.<br/> * @param parent * the parent component. * @param translator * the translator to use for displaying the text. * @param dialog * the dialog to display. * @param maxLine * the maximum length allowed on a line. * @return <code>true</code> if the use confirmed the dialog (clicked 'yes'). */ public static boolean askConfirmation (final Component parent, final Translator translator, final AbstractDialog dialog, final int maxLine) { final int choice = JOptionPane.showConfirmDialog(parent, getMessage(translator, dialog, maxLine), translator.get(dialog.title()), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); return choice == JOptionPane.YES_OPTION; } /** * Ask the user to choose an element from a list.<br /> * The elements of the list will be translated using their {@link Object#toString()} method.<br /> * The collection provided should not contain identical object or identical text translations. * @param <T> * the type of element the dialog offers. * @param parent * the parent component. * @param translator * the translator to use for displaying the text. * @param dialog * the dialog to display. * @param elements * the elements to display in the list. * @param maxLine * the maximum length allowed on a line. * @return the selected element, or <code>null</code> if user canceled. */ public static <T> T askChoice (final Component parent, final Translator translator, final AbstractDialog dialog, final Collection<T> elements, final int maxLine) { if (elements == null || elements.isEmpty()) { lg.warning("Cannot display a dialog for choices with an null or empty list"); throw new IllegalArgumentException("Cannot display input dialog with null or empty list"); } // Map element and their translation, final Map<String, T> translationMap = new LinkedHashMap<>(elements.size()); for (final T t : elements) { translationMap.put(translator.get(t.toString()), t); } final String choice = (String) JOptionPane.showInputDialog(parent, getMessage(translator, dialog, maxLine), translator.get(dialog.title()), JOptionPane.QUESTION_MESSAGE, null, translationMap.keySet().toArray(new Object[0]), translationMap.keySet().iterator().next()); if (lg.isLoggable(Level.FINE)) { lg.fine("The user has choose " + choice); } return translationMap.get(choice); } /** * Creates a {@link JMenuItem} based on the parameters provided.<br /> * <ul> * <li>Set a mnemonic (using the character following the {@link Translator#MNEMONIC_MARK} defined).</li> * <li>Set the shortcut define in the translation file.</li> * <li>Set the listener specified.</li> * <li>Set the tool tip.</li> * </ul> * @param translator * the translator to use for displaying the text. * @param element * the element to use to build the JMenuItem (use text and accelerator). * @param actionListener * the listener to add on the menu item. * @return the menu item created. * @see #getMenu(Translator, String) */ public static JMenuItem getMenuItem (final Translator translator, final GUIElement element, final ActionListener actionListener) { final JMenuItem item = new JMenuItem(); installMnemonics(translator, item, element.getText()); // Set shortcut if (translator.has(element.getShortcut())) { final String shortcut = translator.get(element.getShortcut()); item.setAccelerator(KeyStroke.getKeyStroke(shortcut)); } // Set listener if (actionListener != null) { item.addActionListener(actionListener); } // Set tool tip if (translator.has(element.getToolTip())) { final String toolTip = translator.get(element.getToolTip()); item.setToolTipText(toolTip); } return item; } /** * Creates a {@link JMenu} based on the text provided.<br /> * @param translator * the translator to use for displaying the text. * @param element * the translation key to use. * @return a menu parsed to retrieve the Mnemonic, if set. */ public static JMenu getMenu (final Translator translator, final String element) { final JMenu menu = new JMenu(); installMnemonics(translator, menu, element); return menu; } /** * Install the text and the mnemonics on the specified menu component.<br /> * @param translator * the translator to use for displaying the text. * @param menu * the menu item to initialize. * @param key * the translation key to use. */ private static void installMnemonics (final Translator translator, final JMenuItem menu, final String key) { String text = translator.get(key); final int mnemonicIndex = text.indexOf(Translator.MNEMONIC_MARK); if (mnemonicIndex == text.length() - 1) { lg.warning("Mnemonic mark at the end of the translation, cannot set mnemonic"); menu.setText(text.substring(0, mnemonicIndex)); } else if (mnemonicIndex > -1) { text = text.substring(0, mnemonicIndex) + text.substring(mnemonicIndex + 1); menu.setText(text); menu.setMnemonic(KeyEvent.getExtendedKeyCodeForChar(text.charAt(mnemonicIndex))); } else { menu.setText(text); } } }
src/main/java/com/alexrnl/commons/gui/swing/SwingUtils.java
package com.alexrnl.commons.gui.swing; import java.awt.Component; import java.awt.Frame; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.UnsupportedLookAndFeelException; import com.alexrnl.commons.error.ExceptionUtils; import com.alexrnl.commons.translation.AbstractDialog; import com.alexrnl.commons.translation.GUIElement; import com.alexrnl.commons.translation.Translator; import com.alexrnl.commons.utils.StringUtils; /** * Utility class for Swing related methods.<br /> * @author Alex */ public final class SwingUtils { /** Logger */ private static Logger lg = Logger.getLogger(SwingUtils.class.getName()); /** * Constructor #1.<br /> * Default private constructor. */ private SwingUtils () { super(); } /** * Sets the look and feel of the application.<br /> * Update all frames and pack them to update * @param lookAndFeelName * the name of the look and feel to set. * @return <code>true</code> if the new look and feel was successfully set. */ public static boolean setLookAndFeel (final String lookAndFeelName) { boolean lookAndFeelApplied = false; for (final LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) { if (lg.isLoggable(Level.FINE)) { lg.fine(laf.getName()); } if (laf.getName().equals(lookAndFeelName)) { try { UIManager.setLookAndFeel(laf.getClassName()); if (lg.isLoggable(Level.FINE)) { lg.fine("Look and feel properly setted (" + laf.getName() + ")."); } lookAndFeelApplied = true; } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { lg.warning("Could not set the look and feel " + laf.getName() + ": " + ExceptionUtils.display(e)); lookAndFeelApplied = false; } } } // Applying changes to application if (lookAndFeelApplied) { for (final Frame frame : Frame.getFrames()) { SwingUtilities.updateComponentTreeUI(frame); } } else { lg.warning("Could not find (or set) the look and feel " + lookAndFeelName + ". Using default look and feel."); } return lookAndFeelApplied; } /** * Return the message of a dialog with the parameters included, if the message contained some. * @param translator * the translator to use for displaying the text. * @param dialog * the dialog to use. * @param maxLine * the maximum length allowed on a line. * @return the message to display. */ private static String getMessage (final Translator translator, final AbstractDialog dialog, final int maxLine) { return StringUtils.splitInLinesHTML(translator.get(dialog.message(), dialog.getParameters()), maxLine); } /** * Show the dialog with translation picked from the dialog specified. * @param parent * the parent window (may be <code>null</code>). * @param translator * the translator to use for displaying the text. * @param dialog * the key to the translations to use. * @param type * the type of the dialog. Generally, {@link JOptionPane#ERROR_MESSAGE error}, * {@link JOptionPane#WARNING_MESSAGE warning}, {@link JOptionPane#INFORMATION_MESSAGE * information}, {@link JOptionPane#QUESTION_MESSAGE question} or * {@link JOptionPane#PLAIN_MESSAGE plain} message. * @param maxLine * the maximum length allowed on a line. * @see JOptionPane#showMessageDialog(Component, Object, String, int, javax.swing.Icon) */ public static void showMessageDialog (final Component parent, final Translator translator, final AbstractDialog dialog, final int type, final int maxLine) { JOptionPane.showMessageDialog(parent, getMessage(translator, dialog, maxLine), translator.get(dialog.title()), type); } /** * Show a confirmation dialog to the user.<br/> * @param parent * the parent component. * @param translator * the translator to use for displaying the text. * @param dialog * the dialog to display. * @param maxLine * the maximum length allowed on a line. * @return <code>true</code> if the use confirmed the dialog (clicked 'yes'). */ public static boolean askConfirmation (final Component parent, final Translator translator, final AbstractDialog dialog, final int maxLine) { final int choice = JOptionPane.showConfirmDialog(parent, getMessage(translator, dialog, maxLine), translator.get(dialog.title()), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); return choice == JOptionPane.YES_OPTION; } /** * Ask the user to choose an element from a list.<br /> * The elements of the list will be translated using their {@link Object#toString()} method.<br /> * The collection provided should not contain identical object or identical text translations. * @param <T> * the type of element the dialog offers. * @param parent * the parent component. * @param translator * the translator to use for displaying the text. * @param dialog * the dialog to display. * @param elements * the elements to display in the list. * @param maxLine * the maximum length allowed on a line. * @return the selected element, or <code>null</code> if user canceled. */ public static <T> T askChoice (final Component parent, final Translator translator, final AbstractDialog dialog, final Collection<T> elements, final int maxLine) { if (elements == null || elements.isEmpty()) { lg.warning("Cannot display a dialog for choices with an null or empty list"); throw new IllegalArgumentException("Cannot display input dialog with null or empty list"); } // Map element and their translation, final Map<String, T> translationMap = new LinkedHashMap<>(elements.size()); for (final T t : elements) { translationMap.put(translator.get(t.toString()), t); } final String choice = (String) JOptionPane.showInputDialog(parent, getMessage(translator, dialog, maxLine), translator.get(dialog.title()), JOptionPane.QUESTION_MESSAGE, null, translationMap.keySet().toArray(new Object[0]), translationMap.keySet().iterator().next()); if (lg.isLoggable(Level.FINE)) { lg.fine("The user has choose " + choice); } return translationMap.get(choice); } /** * Creates a {@link JMenuItem} based on the parameters provided.<br /> * <ul> * <li>Set a mnemonic (using the character following the {@link Translator#MNEMONIC_MARK} defined).</li> * <li>Set the shortcut define in the translation file.</li> * <li>Set the listener specified.</li> * <li>Set the tool tip.</li> * </ul> * @param translator * the translator to use for displaying the text. * @param element * the element to use to build the JMenuItem (use text and accelerator). * @param actionListener * the listener to add on the menu item. * @return the menu item created. * @see #getMenu(Translator, String) */ public static JMenuItem getMenuItem (final Translator translator, final GUIElement element, final ActionListener actionListener) { final JMenuItem item = new JMenuItem(); installMnemonics(translator, item, element.getText()); // Set shortcut if (translator.has(element.getShortcut())) { final String shortcut = translator.get(element.getShortcut()); item.setAccelerator(KeyStroke.getKeyStroke(shortcut)); } // Set listener if (actionListener != null) { item.addActionListener(actionListener); } // Set tool tip if (translator.has(element.getToolTip())) { final String toolTip = translator.get(element.getToolTip()); item.setToolTipText(toolTip); } return item; } /** * Creates a {@link JMenu} based on the text provided.<br /> * @param translator * the translator to use for displaying the text. * @param element * the translation key to use. * @return a menu parsed to retrieve the Mnemonic, if set. */ public static JMenu getMenu (final Translator translator, final String element) { final JMenu menu = new JMenu(); installMnemonics(translator, menu, element); return menu; } /** * Install the text and the mnemonics on the specified menu component.<br /> * @param translator * the translator to use for displaying the text. * @param menu * the menu item to initialize. * @param key * the translation key to use. */ private static void installMnemonics (final Translator translator, final JMenuItem menu, final String key) { String text = translator.get(key); final int mnemonicIndex = text.indexOf(Translator.MNEMONIC_MARK); if (mnemonicIndex > -1) { text = text.substring(0, mnemonicIndex) + text.substring(mnemonicIndex + 1); menu.setText(text); menu.setMnemonic(KeyEvent.getExtendedKeyCodeForChar(text.charAt(mnemonicIndex))); } else { menu.setText(text); } } }
Add protection if the mnemonic character is at the end of the translation
src/main/java/com/alexrnl/commons/gui/swing/SwingUtils.java
Add protection if the mnemonic character is at the end of the translation
Java
bsd-3-clause
7f37082fe11ca377945fb36b3f07aaa3fb8fc347
0
muloem/xins,muloem/xins,muloem/xins
/* * $Id$ * * Copyright 2003-2005 Wanadoo Nederland B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.tests.server; import java.io.File; import java.io.StringReader; import java.util.List; import java.util.Random; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.xins.common.collections.BasicPropertyReader; import org.xins.common.http.HTTPCallRequest; import org.xins.common.http.HTTPCallResult; import org.xins.common.http.HTTPServiceCaller; import org.xins.common.service.TargetDescriptor; import org.xins.common.text.FastStringBuffer; import org.xins.common.text.HexConverter; import org.xins.common.text.ParseException; import org.xins.common.xml.Element; import org.xins.common.xml.ElementParser; /** * Tests for XINS call convention. * * @version $Revision$ $Date$ * @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>) */ public class CallingConventionTests extends TestCase { //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- /** * Returns a test suite with all test cases defined by this class. * * @return * the test suite, never <code>null</code>. */ public static Test suite() { return new TestSuite(CallingConventionTests.class); } //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- /** * The random number generator. */ private final static Random RANDOM = new Random(); //------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------- /** * Constructs a new <code>CallingConventionTests</code> test suite with * the specified name. The name will be passed to the superconstructor. * * @param name * the name for this test suite. */ public CallingConventionTests(String name) { super(name); } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Tests the standard calling convention which should be the default. */ public void testStandardCallingConvention1() throws Throwable { callResultCodeStandard(null); } /** * Tests the standard calling convention. */ public void testStandardCallingConvention2() throws Throwable { callResultCodeStandard("_xins-std"); } /** * Tests with an unknown calling convention. */ public void testInvalidCallingConvention() throws Throwable { TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/", 2000); BasicPropertyReader params = new BasicPropertyReader(); params.set("_function", "ResultCode"); params.set("inputText", "blablabla"); params.set("_convention", "_xins-bla"); HTTPCallRequest request = new HTTPCallRequest(params); HTTPServiceCaller caller = new HTTPServiceCaller(descriptor); HTTPCallResult result = caller.call(request); assertEquals(400, result.getStatusCode()); } /** * Calls the ResultCode function and expect the standard calling convention back. * * @param convention * the name of the calling convention parameter, or <code>null</code> * if no calling convention parameter should be sent. * * @throw Throwable * if anything goes wrong. */ public void callResultCodeStandard(String convention) throws Throwable { FastStringBuffer buffer = new FastStringBuffer(16); HexConverter.toHexString(buffer, RANDOM.nextLong()); String randomFive = buffer.toString().substring(0, 5); Element result1 = callResultCode(convention, randomFive); assertNull("The method returned an error code for the first call: " + result1.getAttribute("errorcode"), result1.getAttribute("errorcode")); assertNull("The method returned a code attribute for the first call: " + result1.getAttribute("code"), result1.getAttribute("code")); assertNull("The method returned a success attribute for the first call: " + result1.getAttribute("success"), result1.getAttribute("success")); Element result2 = callResultCode(convention, randomFive); assertNotNull("The method did not return an error code for the second call.", result2.getAttribute("errorcode")); assertNull("The method returned a code attribute for the second call: " + result2.getAttribute("code"), result2.getAttribute("code")); assertNull("The method returned a success attribute for the second call: " + result2.getAttribute("success"), result2.getAttribute("success")); } /** * Tests the old style calling convention. */ public void testOldCallingConvention1() throws Throwable { FastStringBuffer buffer = new FastStringBuffer(16); HexConverter.toHexString(buffer, RANDOM.nextLong()); String randomFive = buffer.toString().substring(0, 5); Element result1 = callResultCode("_xins-old", randomFive); assertNull("The method returned an error code for the first call: " + result1.getAttribute("errorcode"), result1.getAttribute("errorcode")); assertNull("The method returned a code attribute for the first call: " + result1.getAttribute("code"), result1.getAttribute("code")); assertNotNull("The method did not return a success attribute for the first call.", result1.getAttribute("success")); Element result2 = callResultCode("_xins-old", randomFive); assertNotNull("The method did not return an error code for the second call.", result2.getAttribute("errorcode")); assertNotNull("The method did not return a code attribute for the second call.", result2.getAttribute("code")); assertNotNull("The method did not return a success attribute for the second call.", result2.getAttribute("success")); assertEquals("The code and errorcode are different.", result2.getAttribute("code"), result2.getAttribute("errorcode")); } /** * Call the ResultCode function with the specified calling convention. * * @param convention * the name of the calling convention parameter, or <code>null</code> * if no calling convention parameter should be sent. * * @param inputText * the value of the parameter to send as input. * * @return * the parsed result as an Element. * * @throw Throwable * if anything goes wrong. */ private Element callResultCode(String convention, String inputText) throws Throwable { TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/allinone/", 2000); BasicPropertyReader params = new BasicPropertyReader(); params.set("_function", "ResultCode"); params.set("inputText", inputText); if (convention != null) { params.set("_convention", convention); } HTTPCallRequest request = new HTTPCallRequest(params); HTTPServiceCaller caller = new HTTPServiceCaller(descriptor); HTTPCallResult result = caller.call(request); byte[] data = result.getData(); ElementParser parser = new ElementParser(); return parser.parse(new StringReader(new String(data))); } /** * Test the XML calling convention. */ public void testXMLCallingConvention() throws Throwable { FastStringBuffer buffer = new FastStringBuffer(16); HexConverter.toHexString(buffer, RANDOM.nextLong()); String randomFive = buffer.toString().substring(0, 5); // Successful call postXMLRequest(randomFive, true); // Unsuccessful call postXMLRequest(randomFive, false); } /** * Posts XML request. * * @param randomFive * A randomly generated String. * @param success * <code>true</code> if the expected result should be successfal, * <code>false</code> otherwise. * * @throws Exception * If anything goes wrong. */ private void postXMLRequest(String randomFive, boolean success) throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xml"; String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<request function=\"ResultCode\">" + " <param name=\"inputText\">" + randomFive + "</param>" + "</request>"; Element result = postXML(destination, data); assertEquals("result", result.getLocalName()); if (success) { assertNull("The method returned an error code: " + result.getAttribute("errorcode"), result.getAttribute("errorcode")); } else { assertNotNull("The method did not return an error code for the second call: " + result.getAttribute("errorcode"), result.getAttribute("errorcode")); assertEquals("AlreadySet", result.getAttribute("errorcode")); } assertNull("The method returned a code attribute: " + result.getAttribute("code"), result.getAttribute("code")); assertNull("The method returned a success attribute.", result.getAttribute("success")); List child = result.getChildElements(); assertEquals(1, child.size()); Element param = (Element) child.get(0); assertEquals("param", param.getLocalName()); if (success) { assertEquals("outputText", param.getAttribute("name")); assertEquals(randomFive + " added.", param.getText()); } else { assertEquals("count", param.getAttribute("name")); assertEquals("1", param.getText()); } } /** * Tests the XSLT calling convention. */ public void testXSLTCallingConvention() throws Throwable { String html = getHTMLVersion(false); assertTrue("The returned data is not an HTML file.", html.startsWith("<html>")); assertTrue("Incorrect HTML data returned.", html.indexOf("XINS version") != -1); String html2 = getHTMLVersion(true); assertTrue("The returned data is not an HTML file.", html2.startsWith("<html>")); assertTrue("Incorrect HTML data returned.", html2.indexOf("API version") != -1); } private String getHTMLVersion(boolean useTemplateParam) throws Exception { TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/", 2000); BasicPropertyReader params = new BasicPropertyReader(); params.set("_function", "_GetVersion"); params.set("_convention", "_xins-xslt"); if (useTemplateParam) { String userDir = new File(System.getProperty("user.dir")).toURL().toString(); params.set("_template", userDir + "src/tests/getVersion2.xslt"); } HTTPCallRequest request = new HTTPCallRequest(params); HTTPServiceCaller caller = new HTTPServiceCaller(descriptor); HTTPCallResult result = caller.call(request); return result.getString(); } /** * Tests the SOAP calling convention. */ public void testSOAPCallingConvention() throws Throwable { FastStringBuffer buffer = new FastStringBuffer(16); HexConverter.toHexString(buffer, RANDOM.nextLong()); String randomFive = buffer.toString().substring(0, 5); // Successful call postSOAPRequest(randomFive, true); // Unsuccessful call postSOAPRequest(randomFive, false); } /** * Posts SOAP request. * * @param randomFive * A randomly generated String. * @param success * <code>true</code> if the expected result should be successfal, * <code>false</code> otherwise. * * @throws Exception * If anything goes wrong. */ private void postSOAPRequest(String randomFive, boolean success) throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap"; String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" + " <soap:Body>" + " <ns0:ResultCodeRequest>" + " <inputText>" + randomFive + "</inputText>" + " </ns0:ResultCodeRequest>" + " </soap:Body>" + "</soap:Envelope>"; Element result = postXML(destination, data); assertEquals("Envelope", result.getLocalName()); assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size()); assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size()); Element bodyElem = (Element) result.getChildElements("Body").get(0); if (success) { assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("ResultCodeResponse").size()); Element responseElem = (Element) bodyElem.getChildElements("ResultCodeResponse").get(0); assertEquals("Incorrect number of \"outputText\" elements.", 1, responseElem.getChildElements("outputText").size()); Element outputTextElem = (Element) responseElem.getChildElements("outputText").get(0); assertEquals("Incorrect returned text", randomFive + " added.", outputTextElem.getText()); } else { assertEquals("Incorrect number of \"Fault\" elements.", 1, bodyElem.getChildElements("Fault").size()); Element faultElem = (Element) bodyElem.getChildElements("Fault").get(0); assertEquals("Incorrect number of \"faultcode\" elements.", 1, faultElem.getChildElements("faultcode").size()); Element faultCodeElem = (Element) faultElem.getChildElements("faultcode").get(0); assertEquals("Incorrect faultcode text", "soap:Server", faultCodeElem.getText()); assertEquals("Incorrect number of \"faultstring\" elements.", 1, faultElem.getChildElements("faultstring").size()); Element faultStringElem = (Element) faultElem.getChildElements("faultstring").get(0); assertEquals("Incorrect faultstring text", "AlreadySet", faultStringElem.getText()); } } /** * Tests the SOAP calling convention for the type convertion. */ public void testSOAPCallingConvention2() throws Throwable { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap"; String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" + " <soap:Body>" + " <ns0:SimpleTypesRequest>" + " <inputBoolean>0</inputBoolean>" + " <inputByte>0</inputByte>" + " <inputInt>0</inputInt>" + " <inputLong>0</inputLong>" + " <inputFloat>1.0</inputFloat>" + " <inputText>0</inputText>" + " </ns0:SimpleTypesRequest>" + " </soap:Body>" + "</soap:Envelope>"; Element result = postXML(destination, data); assertEquals("Envelope", result.getLocalName()); assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size()); assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size()); Element bodyElem = (Element) result.getChildElements("Body").get(0); assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("SimpleTypesResponse").size()); } /** * Tests the SOAP calling convention with a data section. */ public void testSOAPCallingConvention3() throws Throwable { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap"; String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" + " <soap:Body>" + " <ns0:DataSection3Request>" + " <data>" + " <address company=\"McDo\" postcode=\"1234\" />" + " <address company=\"Drill\" postcode=\"4567\" />" + " </data>" + " </ns0:DataSection3Request>" + " </soap:Body>" + "</soap:Envelope>"; Element result = postXML(destination, data); assertEquals("Envelope", result.getLocalName()); assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size()); assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size()); Element bodyElem = (Element) result.getChildElements("Body").get(0); assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("DataSection3Response").size()); } /** * Tests the XML-RPC calling convention with an incomplete request. */ public void testXMLRPCCallingConvention() throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc"; // Send an incorrect request String data = "<?xml version=\"1.0\"?>" + "<methodCall>" + " <methodName>SimpleTypes</methodName>" + " <params>" + " <param><value><struct><member>" + " <name>inputBoolean</name>" + " <value><boolean>0</boolean></value>" + " </member></struct></value></param>" + " </params>" + "</methodCall>"; Element result = postXML(destination, data); assertEquals("methodResponse", result.getLocalName()); Element faultElem = getUniqueChild(result, "fault"); Element valueElem = getUniqueChild(faultElem, "value"); Element structElem = getUniqueChild(valueElem, "struct"); Element member1 = (Element) structElem.getChildElements("member").get(0); Element member1Name = getUniqueChild(member1, "name"); assertEquals("faultCode", member1Name.getText()); Element member1Value = getUniqueChild(member1, "value"); Element member1IntValue = getUniqueChild(member1Value, "int"); assertEquals("3", member1IntValue.getText()); Element member2 = (Element) structElem.getChildElements("member").get(1); Element member2Name = getUniqueChild(member2, "name"); assertEquals("faultString", member2Name.getText()); Element member2Value = getUniqueChild(member2, "value"); Element member2StringValue = getUniqueChild(member2Value, "string"); assertEquals("_InvalidRequest", member2StringValue.getText()); } /** * Tests the XML-RPC calling convention for a successful result. */ public void testXMLRPCCallingConvention2() throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc"; // Send a correct request String data = "<?xml version=\"1.0\"?>" + "<methodCall>" + " <methodName>SimpleTypes</methodName>" + " <params>" + " <param><value><struct><member>" + " <name>inputBoolean</name>" + " <value><boolean>1</boolean></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputByte</name>" + " <value><i4>0</i4></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputInt</name>" + " <value><i4>50</i4></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputLong</name>" + " <value><string>123456460</string></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputFloat</name>" + " <value><double>3.14159265</double></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputText</name>" + " <value><string>Hello World!</string></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputDate</name>" + " <value><dateTime.iso8601>19980717T14:08:55</dateTime.iso8601></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputTimestamp</name>" + " <value><dateTime.iso8601>19980817T15:08:55</dateTime.iso8601></value>" + " </member></struct></value></param>" + " </params>" + "</methodCall>"; Element result = postXML(destination, data); assertEquals("methodResponse", result.getLocalName()); Element paramsElem = getUniqueChild(result, "params"); Element paramElem = getUniqueChild(paramsElem, "param"); Element valueElem = getUniqueChild(paramElem, "value"); Element structElem = getUniqueChild(valueElem, "struct"); } /** * Tests the XML-RPC calling convention for a data section. */ public void testXMLRPCCallingConvention3() throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc"; // Send a correct request String data = "<?xml version=\"1.0\"?>" + "<methodCall>" + " <methodName>DataSection3</methodName>" + " <params>" + " <param><value><struct><member>" + " <name>inputText</name>" + " <value><string>hello</string></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>data</name>" + " <value><array><data>" + " <value><struct><member>" + " <name>address</name>" + " <value><string></string></value>" + " </member>" + " <member>" + " <name>company</name>" + " <value><string>MyCompany</string></value>" + " </member>" + " <member>" + " <name>postcode</name>" + " <value><string>72650</string></value>" + " </member></struct></value>" + " </data></array></value>" + " </member></struct></value></param>" + " </params>" + "</methodCall>"; Element result = postXML(destination, data); assertEquals("methodResponse", result.getLocalName()); Element paramsElem = getUniqueChild(result, "params"); Element paramElem = getUniqueChild(paramsElem, "param"); Element valueElem = getUniqueChild(paramElem, "value"); Element structElem = getUniqueChild(valueElem, "struct"); } /** * Test the custom calling convention. */ /*public void testCustomCallingConvention() throws Exception { URL url = new URL("http://localhost:8080/?query=hello%20Custom"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); assertEquals(200, connection.getResponseCode()); URL url2 = new URL("http://localhost:8080/?query=hello%20Custom&_convention=xins-tests"); HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection(); connection2.connect(); assertEquals(400, connection2.getResponseCode()); }*/ /** * Posts the XML data the the given destination. * * @param destination * the destination where the XML has to be posted. * @param data * the XML to post. * * @return * the returned XML already parsed. * * @throw Exception * if anything goes wrong. */ private Element postXML(String destination, String data) throws Exception { PostMethod post = new PostMethod(destination); post.setRequestHeader("Content-Type", "text/xml; charset=UTF-8"); post.setRequestBody(data); HttpClient client = new HttpClient(); client.setConnectionTimeout(5000); client.setTimeout(5000); try { int code = client.executeMethod(post); byte[] returnedData = post.getResponseBody(); ElementParser parser = new ElementParser(); String content = new String(returnedData); System.err.println("content: " + content); Element result = parser.parse(new StringReader(content)); return result; } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } } /** * Gets the unique child of the element. * * @param parentElement * the parent element, cannot be <code>null</code>. * * @param elementName * the name of the child element to get, or <code>null</code> if the * parent have a unique child. * * @throws InvalidRequestException * if no child was found or more than one child was found. */ private Element getUniqueChild(Element parentElement, String elementName) throws ParseException { List childList = null; if (elementName == null) { childList = parentElement.getChildElements(); } else { childList = parentElement.getChildElements(elementName); } if (childList.size() == 0) { throw new ParseException("No \"" + elementName + "\" children found in the \"" + parentElement.getLocalName() + "\" element of the XML-RPC request."); } else if (childList.size() > 1) { throw new ParseException("More than one \"" + elementName + "\" children found in the \"" + parentElement.getLocalName() + "\" element of the XML-RPC request."); } return (Element) childList.get(0); } }
src/tests/org/xins/tests/server/CallingConventionTests.java
/* * $Id$ * * Copyright 2003-2005 Wanadoo Nederland B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.tests.server; import java.io.File; import java.io.StringReader; import java.util.List; import java.util.Random; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.xins.common.collections.BasicPropertyReader; import org.xins.common.http.HTTPCallRequest; import org.xins.common.http.HTTPCallResult; import org.xins.common.http.HTTPServiceCaller; import org.xins.common.service.TargetDescriptor; import org.xins.common.text.FastStringBuffer; import org.xins.common.text.HexConverter; import org.xins.common.text.ParseException; import org.xins.common.xml.Element; import org.xins.common.xml.ElementParser; /** * Tests for XINS call convention. * * @version $Revision$ $Date$ * @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>) */ public class CallingConventionTests extends TestCase { //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- /** * Returns a test suite with all test cases defined by this class. * * @return * the test suite, never <code>null</code>. */ public static Test suite() { return new TestSuite(CallingConventionTests.class); } //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- /** * The random number generator. */ private final static Random RANDOM = new Random(); //------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------- /** * Constructs a new <code>CallingConventionTests</code> test suite with * the specified name. The name will be passed to the superconstructor. * * @param name * the name for this test suite. */ public CallingConventionTests(String name) { super(name); } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Tests the standard calling convention which should be the default. */ public void testStandardCallingConvention1() throws Throwable { callResultCodeStandard(null); } /** * Tests the standard calling convention. */ public void testStandardCallingConvention2() throws Throwable { callResultCodeStandard("_xins-std"); } /** * Tests with an unknown calling convention. */ public void testInvalidCallingConvention() throws Throwable { TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/", 2000); BasicPropertyReader params = new BasicPropertyReader(); params.set("_function", "ResultCode"); params.set("inputText", "blablabla"); params.set("_convention", "_xins-bla"); HTTPCallRequest request = new HTTPCallRequest(params); HTTPServiceCaller caller = new HTTPServiceCaller(descriptor); HTTPCallResult result = caller.call(request); assertEquals(400, result.getStatusCode()); } /** * Calls the ResultCode function and expect the standard calling convention back. * * @param convention * the name of the calling convention parameter, or <code>null</code> * if no calling convention parameter should be sent. * * @throw Throwable * if anything goes wrong. */ public void callResultCodeStandard(String convention) throws Throwable { FastStringBuffer buffer = new FastStringBuffer(16); HexConverter.toHexString(buffer, RANDOM.nextLong()); String randomFive = buffer.toString().substring(0, 5); Element result1 = callResultCode(convention, randomFive); assertNull("The method returned an error code for the first call: " + result1.getAttribute("errorcode"), result1.getAttribute("errorcode")); assertNull("The method returned a code attribute for the first call: " + result1.getAttribute("code"), result1.getAttribute("code")); assertNull("The method returned a success attribute for the first call: " + result1.getAttribute("success"), result1.getAttribute("success")); Element result2 = callResultCode(convention, randomFive); assertNotNull("The method did not return an error code for the second call.", result2.getAttribute("errorcode")); assertNull("The method returned a code attribute for the second call: " + result2.getAttribute("code"), result2.getAttribute("code")); assertNull("The method returned a success attribute for the second call: " + result2.getAttribute("success"), result2.getAttribute("success")); } /** * Tests the old style calling convention. */ public void testOldCallingConvention1() throws Throwable { FastStringBuffer buffer = new FastStringBuffer(16); HexConverter.toHexString(buffer, RANDOM.nextLong()); String randomFive = buffer.toString().substring(0, 5); Element result1 = callResultCode("_xins-old", randomFive); assertNull("The method returned an error code for the first call: " + result1.getAttribute("errorcode"), result1.getAttribute("errorcode")); assertNull("The method returned a code attribute for the first call: " + result1.getAttribute("code"), result1.getAttribute("code")); assertNotNull("The method did not return a success attribute for the first call.", result1.getAttribute("success")); Element result2 = callResultCode("_xins-old", randomFive); assertNotNull("The method did not return an error code for the second call.", result2.getAttribute("errorcode")); assertNotNull("The method did not return a code attribute for the second call.", result2.getAttribute("code")); assertNotNull("The method did not return a success attribute for the second call.", result2.getAttribute("success")); assertEquals("The code and errorcode are different.", result2.getAttribute("code"), result2.getAttribute("errorcode")); } /** * Call the ResultCode function with the specified calling convention. * * @param convention * the name of the calling convention parameter, or <code>null</code> * if no calling convention parameter should be sent. * * @param inputText * the value of the parameter to send as input. * * @return * the parsed result as an Element. * * @throw Throwable * if anything goes wrong. */ private Element callResultCode(String convention, String inputText) throws Throwable { TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/allinone/", 2000); BasicPropertyReader params = new BasicPropertyReader(); params.set("_function", "ResultCode"); params.set("inputText", inputText); if (convention != null) { params.set("_convention", convention); } HTTPCallRequest request = new HTTPCallRequest(params); HTTPServiceCaller caller = new HTTPServiceCaller(descriptor); HTTPCallResult result = caller.call(request); byte[] data = result.getData(); ElementParser parser = new ElementParser(); return parser.parse(new StringReader(new String(data))); } /** * Test the XML calling convention. */ public void testXMLCallingConvention() throws Throwable { FastStringBuffer buffer = new FastStringBuffer(16); HexConverter.toHexString(buffer, RANDOM.nextLong()); String randomFive = buffer.toString().substring(0, 5); // Successful call postXMLRequest(randomFive, true); // Unsuccessful call postXMLRequest(randomFive, false); } /** * Posts XML request. * * @param randomFive * A randomly generated String. * @param success * <code>true</code> if the expected result should be successfal, * <code>false</code> otherwise. * * @throws Exception * If anything goes wrong. */ private void postXMLRequest(String randomFive, boolean success) throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xml"; String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<request>" + " <param name=\"_function\">ResultCode</param>" + " <param name=\"inputText\">" + randomFive + "</param>" + "</request>"; Element result = postXML(destination, data); assertEquals("result", result.getLocalName()); if (success) { assertNull("The method returned an error code: " + result.getAttribute("errorcode"), result.getAttribute("errorcode")); } else { assertNotNull("The method did not return an error code for the second call: " + result.getAttribute("errorcode"), result.getAttribute("errorcode")); assertEquals("AlreadySet", result.getAttribute("errorcode")); } assertNull("The method returned a code attribute: " + result.getAttribute("code"), result.getAttribute("code")); assertNull("The method returned a success attribute.", result.getAttribute("success")); List child = result.getChildElements(); assertEquals(1, child.size()); Element param = (Element) child.get(0); assertEquals("param", param.getLocalName()); if (success) { assertEquals("outputText", param.getAttribute("name")); assertEquals(randomFive + " added.", param.getText()); } else { assertEquals("count", param.getAttribute("name")); assertEquals("1", param.getText()); } } /** * Tests the XSLT calling convention. */ public void testXSLTCallingConvention() throws Throwable { String html = getHTMLVersion(false); assertTrue("The returned data is not an HTML file.", html.startsWith("<html>")); assertTrue("Incorrect HTML data returned.", html.indexOf("XINS version") != -1); String html2 = getHTMLVersion(true); assertTrue("The returned data is not an HTML file.", html2.startsWith("<html>")); assertTrue("Incorrect HTML data returned.", html2.indexOf("API version") != -1); } private String getHTMLVersion(boolean useTemplateParam) throws Exception { TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/", 2000); BasicPropertyReader params = new BasicPropertyReader(); params.set("_function", "_GetVersion"); params.set("_convention", "_xins-xslt"); if (useTemplateParam) { String userDir = new File(System.getProperty("user.dir")).toURL().toString(); params.set("_template", userDir + "src/tests/getVersion2.xslt"); } HTTPCallRequest request = new HTTPCallRequest(params); HTTPServiceCaller caller = new HTTPServiceCaller(descriptor); HTTPCallResult result = caller.call(request); return result.getString(); } /** * Tests the SOAP calling convention. */ public void testSOAPCallingConvention() throws Throwable { FastStringBuffer buffer = new FastStringBuffer(16); HexConverter.toHexString(buffer, RANDOM.nextLong()); String randomFive = buffer.toString().substring(0, 5); // Successful call postSOAPRequest(randomFive, true); // Unsuccessful call postSOAPRequest(randomFive, false); } /** * Posts SOAP request. * * @param randomFive * A randomly generated String. * @param success * <code>true</code> if the expected result should be successfal, * <code>false</code> otherwise. * * @throws Exception * If anything goes wrong. */ private void postSOAPRequest(String randomFive, boolean success) throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap"; String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" + " <soap:Body>" + " <ns0:ResultCodeRequest>" + " <inputText>" + randomFive + "</inputText>" + " </ns0:ResultCodeRequest>" + " </soap:Body>" + "</soap:Envelope>"; Element result = postXML(destination, data); assertEquals("Envelope", result.getLocalName()); assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size()); assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size()); Element bodyElem = (Element) result.getChildElements("Body").get(0); if (success) { assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("ResultCodeResponse").size()); Element responseElem = (Element) bodyElem.getChildElements("ResultCodeResponse").get(0); assertEquals("Incorrect number of \"outputText\" elements.", 1, responseElem.getChildElements("outputText").size()); Element outputTextElem = (Element) responseElem.getChildElements("outputText").get(0); assertEquals("Incorrect returned text", randomFive + " added.", outputTextElem.getText()); } else { assertEquals("Incorrect number of \"Fault\" elements.", 1, bodyElem.getChildElements("Fault").size()); Element faultElem = (Element) bodyElem.getChildElements("Fault").get(0); assertEquals("Incorrect number of \"faultcode\" elements.", 1, faultElem.getChildElements("faultcode").size()); Element faultCodeElem = (Element) faultElem.getChildElements("faultcode").get(0); assertEquals("Incorrect faultcode text", "soap:Server", faultCodeElem.getText()); assertEquals("Incorrect number of \"faultstring\" elements.", 1, faultElem.getChildElements("faultstring").size()); Element faultStringElem = (Element) faultElem.getChildElements("faultstring").get(0); assertEquals("Incorrect faultstring text", "AlreadySet", faultStringElem.getText()); } } /** * Tests the SOAP calling convention for the type convertion. */ public void testSOAPCallingConvention2() throws Throwable { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap"; String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" + " <soap:Body>" + " <ns0:SimpleTypesRequest>" + " <inputBoolean>0</inputBoolean>" + " <inputByte>0</inputByte>" + " <inputInt>0</inputInt>" + " <inputLong>0</inputLong>" + " <inputFloat>1.0</inputFloat>" + " <inputText>0</inputText>" + " </ns0:SimpleTypesRequest>" + " </soap:Body>" + "</soap:Envelope>"; Element result = postXML(destination, data); assertEquals("Envelope", result.getLocalName()); assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size()); assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size()); Element bodyElem = (Element) result.getChildElements("Body").get(0); assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("SimpleTypesResponse").size()); } /** * Tests the SOAP calling convention with a data section. */ public void testSOAPCallingConvention3() throws Throwable { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap"; String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" + " <soap:Body>" + " <ns0:DataSection3Request>" + " <data>" + " <address company=\"McDo\" postcode=\"1234\" />" + " <address company=\"Drill\" postcode=\"4567\" />" + " </data>" + " </ns0:DataSection3Request>" + " </soap:Body>" + "</soap:Envelope>"; Element result = postXML(destination, data); assertEquals("Envelope", result.getLocalName()); assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size()); assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size()); Element bodyElem = (Element) result.getChildElements("Body").get(0); assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("DataSection3Response").size()); } /** * Tests the XML-RPC calling convention with an incomplete request. */ public void testXMLRPCCallingConvention() throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc"; // Send an incorrect request String data = "<?xml version=\"1.0\"?>" + "<methodCall>" + " <methodName>SimpleTypes</methodName>" + " <params>" + " <param><value><struct><member>" + " <name>inputBoolean</name>" + " <value><boolean>0</boolean></value>" + " </member></struct></value></param>" + " </params>" + "</methodCall>"; Element result = postXML(destination, data); assertEquals("methodResponse", result.getLocalName()); Element faultElem = getUniqueChild(result, "fault"); Element valueElem = getUniqueChild(faultElem, "value"); Element structElem = getUniqueChild(valueElem, "struct"); Element member1 = (Element) structElem.getChildElements("member").get(0); Element member1Name = getUniqueChild(member1, "name"); assertEquals("faultCode", member1Name.getText()); Element member1Value = getUniqueChild(member1, "value"); Element member1IntValue = getUniqueChild(member1Value, "int"); assertEquals("3", member1IntValue.getText()); Element member2 = (Element) structElem.getChildElements("member").get(1); Element member2Name = getUniqueChild(member2, "name"); assertEquals("faultString", member2Name.getText()); Element member2Value = getUniqueChild(member2, "value"); Element member2StringValue = getUniqueChild(member2Value, "string"); assertEquals("_InvalidRequest", member2StringValue.getText()); } /** * Tests the XML-RPC calling convention for a successful result. */ public void testXMLRPCCallingConvention2() throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc"; // Send a correct request String data = "<?xml version=\"1.0\"?>" + "<methodCall>" + " <methodName>SimpleTypes</methodName>" + " <params>" + " <param><value><struct><member>" + " <name>inputBoolean</name>" + " <value><boolean>1</boolean></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputByte</name>" + " <value><i4>0</i4></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputInt</name>" + " <value><i4>50</i4></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputLong</name>" + " <value><string>123456460</string></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputFloat</name>" + " <value><double>3.14159265</double></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputText</name>" + " <value><string>Hello World!</string></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputDate</name>" + " <value><dateTime.iso8601>19980717T14:08:55</dateTime.iso8601></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>inputTimestamp</name>" + " <value><dateTime.iso8601>19980817T15:08:55</dateTime.iso8601></value>" + " </member></struct></value></param>" + " </params>" + "</methodCall>"; Element result = postXML(destination, data); assertEquals("methodResponse", result.getLocalName()); Element paramsElem = getUniqueChild(result, "params"); Element paramElem = getUniqueChild(paramsElem, "param"); Element valueElem = getUniqueChild(paramElem, "value"); Element structElem = getUniqueChild(valueElem, "struct"); } /** * Tests the XML-RPC calling convention for a data section. */ public void testXMLRPCCallingConvention3() throws Exception { String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc"; // Send a correct request String data = "<?xml version=\"1.0\"?>" + "<methodCall>" + " <methodName>DataSection3</methodName>" + " <params>" + " <param><value><struct><member>" + " <name>inputText</name>" + " <value><string>hello</string></value>" + " </member></struct></value></param>" + " <param><value><struct><member>" + " <name>data</name>" + " <value><array><data>" + " <value><struct><member>" + " <name>address</name>" + " <value><string></string></value>" + " </member>" + " <member>" + " <name>company</name>" + " <value><string>MyCompany</string></value>" + " </member>" + " <member>" + " <name>postcode</name>" + " <value><string>72650</string></value>" + " </member></struct></value>" + " </data></array></value>" + " </member></struct></value></param>" + " </params>" + "</methodCall>"; Element result = postXML(destination, data); assertEquals("methodResponse", result.getLocalName()); Element paramsElem = getUniqueChild(result, "params"); Element paramElem = getUniqueChild(paramsElem, "param"); Element valueElem = getUniqueChild(paramElem, "value"); Element structElem = getUniqueChild(valueElem, "struct"); } /** * Test the custom calling convention. */ /*public void testCustomCallingConvention() throws Exception { URL url = new URL("http://localhost:8080/?query=hello%20Custom"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); assertEquals(200, connection.getResponseCode()); URL url2 = new URL("http://localhost:8080/?query=hello%20Custom&_convention=xins-tests"); HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection(); connection2.connect(); assertEquals(400, connection2.getResponseCode()); }*/ /** * Posts the XML data the the given destination. * * @param destination * the destination where the XML has to be posted. * @param data * the XML to post. * * @return * the returned XML already parsed. * * @throw Exception * if anything goes wrong. */ private Element postXML(String destination, String data) throws Exception { PostMethod post = new PostMethod(destination); post.setRequestHeader("Content-Type", "text/xml; charset=UTF-8"); post.setRequestBody(data); HttpClient client = new HttpClient(); client.setConnectionTimeout(5000); client.setTimeout(5000); try { int code = client.executeMethod(post); byte[] returnedData = post.getResponseBody(); ElementParser parser = new ElementParser(); String content = new String(returnedData); System.err.println("content: " + content); Element result = parser.parse(new StringReader(content)); return result; } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } } /** * Gets the unique child of the element. * * @param parentElement * the parent element, cannot be <code>null</code>. * * @param elementName * the name of the child element to get, or <code>null</code> if the * parent have a unique child. * * @throws InvalidRequestException * if no child was found or more than one child was found. */ private Element getUniqueChild(Element parentElement, String elementName) throws ParseException { List childList = null; if (elementName == null) { childList = parentElement.getChildElements(); } else { childList = parentElement.getChildElements(elementName); } if (childList.size() == 0) { throw new ParseException("No \"" + elementName + "\" children found in the \"" + parentElement.getLocalName() + "\" element of the XML-RPC request."); } else if (childList.size() > 1) { throw new ParseException("More than one \"" + elementName + "\" children found in the \"" + parentElement.getLocalName() + "\" element of the XML-RPC request."); } return (Element) childList.get(0); } }
- Fixed SF.net bug #1382438: XMLCallingConvention does not match the specifications.
src/tests/org/xins/tests/server/CallingConventionTests.java
- Fixed SF.net bug #1382438: XMLCallingConvention does not match the specifications.
Java
mit
0a122218a5bfb2d3c97998c8ae365019dd3d198c
0
FIRST-Team-339/2017
package org.usfirst.frc.team339.Utils; import org.usfirst.frc.team339.HardwareInterfaces.KilroyCamera; import org.usfirst.frc.team339.HardwareInterfaces.UltraSonic; import org.usfirst.frc.team339.HardwareInterfaces.transmission.TransmissionFourWheel; import org.usfirst.frc.team339.HardwareInterfaces.transmission.TransmissionMecanum; import org.usfirst.frc.team339.Vision.ImageProcessor; import edu.wpi.first.wpilibj.Encoder; /** * This class allows us to drive semi-autonomously, and is to be implemented * with a transmission using Tank or Mecanum drive, as well as a camera * and an image processor. * * @author Ryan McGee * */ public class Drive { private TransmissionMecanum transmissionMecanum = null; private TransmissionFourWheel transmissionFourWheel = null; private ImageProcessor imageProcessor = null; private KilroyCamera camera = null; private Encoder rightFrontEncoder = null; private Encoder rightRearEncoder = null; private Encoder leftFrontEncoder = null; private Encoder leftRearEncoder = null; private boolean isUsingEncoders = false; private boolean isUsingUltrasonics = false; private UltraSonic leftUlt = null; private UltraSonic rightUlt = null; /** * Creates an instance of the Drive class, with a mecanum drive system. * If this is called, the mecanum versions of each method are used. * * @param transmissionMecanum * The transmission to be input * @param camera * The camera we want to use for image saving * @param imageProcessor * The processor we want to use for aiming and aligning */ public Drive (TransmissionMecanum transmissionMecanum, KilroyCamera camera, ImageProcessor imageProcessor) { this.transmissionMecanum = transmissionMecanum; this.transmissionType = TransmissionType.MECANUM; this.camera = camera; this.imageProcessor = imageProcessor; } /** * Creates an instance of the Drive class, with a mecanum drive system. * If this is called, the mecanum versions of each method are used. * * @param transmissionMecanum * The transmission to be input * @param camera * The camera we want to use for image saving * @param imageProcessor * The processor we want to use for aiming and aligning * @param rightFrontEncoder * The front right encoder * @param rightRearEncoder * The back right encoder * @param leftFrontEncoder * The front left encoder * @param leftRearEncoder * The back left encoder * @param leftUlt * The ultrasonic on the left side of the robot * @param rightUlt * The ultrasonic on the right side of the robot */ public Drive (TransmissionMecanum transmissionMecanum, KilroyCamera camera, ImageProcessor imageProcessor, Encoder rightFrontEncoder, Encoder rightRearEncoder, Encoder leftFrontEncoder, Encoder leftRearEncoder, UltraSonic leftUlt, UltraSonic rightUlt) { this(transmissionMecanum, camera, imageProcessor); this.initEncoders(leftFrontEncoder, rightFrontEncoder, leftRearEncoder, rightRearEncoder); this.rightUlt = rightUlt; this.leftUlt = leftUlt; isUsingUltrasonics = true; } /** * Creates an instance of the Drive class, with a tank drive system. * If this is called, the tank versions of each method are used. * * @param transmissionFourWheel * The transmission to be input * @param camera * The camera we want to use for image saving * @param imageProcessor * The processor we want to use for aiming and aligning */ public Drive (TransmissionFourWheel transmissionFourWheel, KilroyCamera camera, ImageProcessor imageProcessor) { this.transmissionFourWheel = transmissionFourWheel; this.transmissionType = TransmissionType.TANK; this.camera = camera; this.imageProcessor = imageProcessor; } /** * Creates an instance of the Drive class, with a Tank drive system. * If this is called, the Tank versions of each method are used. * * @param transmissionFourWheel * The transmission to be input * @param camera * The camera we want to use for image saving * @param imageProcessor * The processor we want to use for aiming and aligning * @param rightFrontEncoder * The front right encoder * @param rightRearEncoder * The back right encoder * @param leftFrontEncoder * The front left encoder * @param leftRearEncoder * The back left encoder * @param leftUlt * The ultrasonic on the left side of the robot * @param rightUlt * The ultrasonic on the right side of the robot */ public Drive (TransmissionFourWheel transmissionFourWheel, KilroyCamera camera, ImageProcessor imageProcessor, Encoder leftFrontEncoder, Encoder rightFrontEncoder, Encoder leftRearEncoder, Encoder rightRearEncoder, UltraSonic leftUlt, UltraSonic rightUlt) { this(transmissionFourWheel, camera, imageProcessor); this.initEncoders(leftFrontEncoder, rightFrontEncoder, leftRearEncoder, rightRearEncoder); this.leftUlt = leftUlt; this.rightUlt = rightUlt; isUsingUltrasonics = true; } /** * Initializes all the encoders. Is called in the constructor and can * be called outside the class. * * @param _leftFrontEncoder * The front left encoder * @param _rightFrontEncoder * The front right encoder * @param _leftRearEncoder * The back left encoder * @param _rightRearEncoder * The back right encoder */ public void initEncoders (Encoder _leftFrontEncoder, Encoder _rightFrontEncoder, Encoder _leftRearEncoder, Encoder _rightRearEncoder) { isUsingEncoders = true; this.leftFrontEncoder = _leftFrontEncoder; this.rightFrontEncoder = _rightFrontEncoder; this.leftRearEncoder = _leftRearEncoder; this.rightRearEncoder = _rightRearEncoder; this.setEncoderDistancePerPulse(DEFAULT_DISTANCE_PER_PULSE); } /** * Gets the averaged distance out of the four encoders * * @return averaged distance after driving forwards */ public double getAveragedEncoderValues () { return (this.getLeftFrontEncoderDistance() + this.getRightFrontEncoderDistance() + this.getLeftRearEncoderDistance() + this.getRightRearEncoderDistance()) / 4.0; } // TODO Test this /** * Drives a distance given. To drive backwards, give negative speed, not * negative distance. * * @param inches * How far we want to go * @param speed * How fast we want to go there * @return Whether or not we have finished driving yet */ public boolean driveInches (double inches, double speed) { // Again, we don't know why it's going backwards... if (firstTimeDriveInches) { this.resetEncoders(); firstTimeDriveInches = false; } if (Math.abs(this.getAveragedEncoderValues()) >= Math.abs(inches)) { if (this.transmissionType == TransmissionType.MECANUM) this.transmissionMecanum.drive(0.0, 0.0, 0.0, 0, 0); else this.transmissionFourWheel.drive(0.0, 0.0); firstTimeDriveInches = true; return true; } if (this.transmissionType == TransmissionType.MECANUM) this.transmissionMecanum.drive(speed, 0.0, 0.0, 0, 0); else this.transmissionFourWheel.drive(-speed, -speed); return false; } private boolean firstTimeDriveInches = true; /** * Aligns to the low dual targets for the gear peg. This finds the * average of the two targets, divides by the resolution of the camera * (to make it relative coordinates) and compares it to the given * value defined as relativeCenter. * * @author Ryan McGee * * @param relativeCenter * The "center" of the camera, the value we want to align to. * @param movementSpeed * The speed we want the motors to run at * @param deadband * The "happy" value; the method will say "I am aligned!" when we are * in this range. * @return Whether or not we are aligned to the center yet. */ public AlignReturnType alignToGear (double relativeCenter, double movementSpeed, double deadband) { imageProcessor.processImage(); if (imageProcessor.getNthSizeBlob(1) != null) switch (this.transmissionType) { case TANK: double distanceToCenter = imageProcessor .getPositionOfRobotToGear( imageProcessor.getNthSizeBlob(0), imageProcessor.getNthSizeBlob(1), relativeCenter); System.out .println("Distance to center: " + distanceToCenter); System.out.println("Deadband: " + (10.0 / this.camera.getHorizontalResolution())); if (distanceToCenter == Double.MAX_VALUE) { transmissionFourWheel.drive(0.0, 0.0); return AlignReturnType.NO_BLOBS; } if (Math.abs(distanceToCenter) <= deadband) { transmissionFourWheel.drive(0.0, 0.0); return AlignReturnType.ALIGNED; } else if (distanceToCenter > 0) { transmissionFourWheel.drive(movementSpeed, -movementSpeed); } else if (distanceToCenter < 0) { transmissionFourWheel.drive(-movementSpeed, movementSpeed); } break; case MECANUM: break; default: break; } return AlignReturnType.MISALIGNED; } // TODO we need to test this!! /** * Aligns to the gear peg WHILE driving towards it. If the transmission type * is Mecanum, it will STRAFE while moving forwards. If it is tank drive * mode, it will adjust each side's speed accordingly. * * @param driveSpeed * The speed we will drive forwards * @param alignVar * If it is tank drive, this will be the speed it aligns. * If it is in mecanum drive, this is the angle added on. * @param deadband * If the camera's center is in this deadband, we are 'aligned'. * @param relativeCenter * Where we want the center of the robot to be * @param distanceToTarget * What we want the distance to the wall from the bumper * to be when we stop aligning * @return Whether or not we are aligned, close enough, misaligned, or see no * blobs. */ public AlignReturnType strafeToGear (double driveSpeed, double alignVar, double deadband, double relativeCenter, int distanceToTarget) { // If we have no blobs, return so. if (this.imageProcessor.getNthSizeBlob(1) == null) return AlignReturnType.NO_BLOBS; // If we don't have any ultrasonics in the constructor, stop aligning. if (this.isUsingUltrasonics == false) return AlignReturnType.ALIGNED; double distanceToCenter = this.imageProcessor .getPositionOfRobotToGear( this.imageProcessor.getNthSizeBlob(0), this.imageProcessor.getNthSizeBlob(1), relativeCenter); if (Math.abs(distanceToCenter) < deadband) { if ((this.leftUlt .getOffsetDistanceFromNearestBummper() + this.rightUlt.getOffsetDistanceFromNearestBummper()) / 2.0 <= distanceToTarget) return AlignReturnType.CLOSE_ENOUGH; if (this.transmissionType == TransmissionType.MECANUM) transmissionMecanum.drive(driveSpeed, 0.0, 0.0, 0, 0); else if (this.transmissionType == TransmissionType.TANK) transmissionFourWheel.drive(driveSpeed, driveSpeed); return AlignReturnType.ALIGNED; } if (distanceToCenter > 0) { if (this.transmissionType == TransmissionType.MECANUM) this.transmissionMecanum.drive(driveSpeed, alignVar, 0, 0, 0); else if (this.transmissionType == TransmissionType.TANK) this.transmissionFourWheel.drive(driveSpeed - alignVar, driveSpeed + alignVar); } else if (distanceToCenter < 0) { if (this.transmissionType == TransmissionType.MECANUM) this.transmissionMecanum.drive(driveSpeed, -alignVar, 0.0, 0, 0); else if (this.transmissionType == TransmissionType.TANK) this.transmissionFourWheel.drive(driveSpeed + alignVar, driveSpeed - alignVar); } return AlignReturnType.MISALIGNED; } /** * Tells us how any aligning method returned. * * @author Ryan McGee * */ public static enum AlignReturnType { /** * No blobs are present */ NO_BLOBS, /** * We are now aligned with the target */ ALIGNED, /** * We are not aligned with the target, keep aligning */ MISALIGNED, /** * Only used if we are using an ultrasonic */ CLOSE_ENOUGH } public void strafeStraight (double inches) { resetEncoders(); double rightFrontSpeed = inches; double rightRearSpeed = inches; double leftFrontSpeed = inches; double leftRearSpeed = inches; } /** * @return the distance the front left encoder has driven based on the * distance per pulse set earlier. */ public double getLeftFrontEncoderDistance () { return this.leftFrontEncoder.getDistance(); } /** * @return the distance the front right encoder has driven based on the * distance per pulse set earlier. */ public double getRightFrontEncoderDistance () { return this.rightFrontEncoder.getDistance(); } /** * @return the distance the back left encoder has driven based on the * distance per pulse set earlier. */ public double getLeftRearEncoderDistance () { return this.leftRearEncoder.getDistance(); } /** * @return the distance the back rear encoder has driven based on the * distance per pulse set earlier. */ public double getRightRearEncoderDistance () { return this.rightRearEncoder.getDistance(); } /** * Sets the value multiplied by to get an accurate distance we have driven * * @param value * Distance per pulse */ public void setEncoderDistancePerPulse (double value) { this.leftFrontEncoder.setDistancePerPulse(value); this.rightFrontEncoder.setDistancePerPulse(value); this.leftRearEncoder.setDistancePerPulse(value); this.rightRearEncoder.setDistancePerPulse(value); } /** * Resets all encoders back to 0 'distance units' driven */ public void resetEncoders () { this.leftFrontEncoder.reset(); this.rightFrontEncoder.reset(); this.leftRearEncoder.reset(); this.rightRearEncoder.reset(); } /** * Rotates the robot by degrees. * * @param degrees * Number of degrees to rotate by. Negative if left, positive if * right. * @return Whether or not we have finished turning yet. */ public boolean turnDegrees (double degrees) { if (firstAlign) { this.resetEncoders(); this.firstAlign = false; } // We do not know why, but the robot by default turns opposite what we want. double adjustedDegrees = -degrees; if (!isUsingEncoders) { this.firstAlign = true; return true; } double angleInRadians = Math.toRadians(Math.abs(degrees)); double leftSideAverage = Math .abs(this.getLeftFrontEncoderDistance() + this.getLeftRearEncoderDistance()) / 2.0; double rightSideAverage = Math .abs(this.getRightFrontEncoderDistance() + this.getRightRearEncoderDistance()) / 2.0; // If the arc length is equal to the amount driven, we finish if (rightSideAverage >= angleInRadians * turningCircleRadius || leftSideAverage >= angleInRadians * turningCircleRadius) { this.firstAlign = true; return true; } // Rotate if not if (adjustedDegrees < 0) { if (transmissionType == TransmissionType.TANK) transmissionFourWheel.drive(rotateSpeed, -rotateSpeed); else transmissionMecanum.drive(0.0, 0.0, -rotateSpeed, 0, 0); } else if (adjustedDegrees > 0) { if (transmissionType == TransmissionType.TANK) transmissionFourWheel.drive(-rotateSpeed, rotateSpeed); else transmissionMecanum.drive(0.0, 0.0, rotateSpeed, 0, 0); } return false; } private double rotateSpeed = .6; /** * Gets how fast we are rotating in turnDegrees * * @return rotation speed */ public double getRotateSpeed () { return this.rotateSpeed; } /** * Sets how fast we should rotate in turnDegrees * * @param speed * rotation speed */ public void setRotateSpeed (double speed) { this.rotateSpeed = speed; } private double turningCircleRadius = 11; /** * Gets the radius of the circle that the robot rotates around * * @return Radius in inches */ public double getTurningCircleRadius () { return turningCircleRadius; } /** * Sets the radius of the circlie that the robot rotates around * * @param radius * Radius in inches */ public void setTurningCircleRadius (double radius) { this.turningCircleRadius = radius; } private boolean firstAlign = true; /** * The type of transmission we are using. Is set in the constructor. * * @author Ryan McGee * */ public static enum TransmissionType { /** * Tank drive */ TANK, /** * Mecanum drive */ MECANUM } // ===================================================================== // Constants // ===================================================================== private TransmissionType transmissionType = null; /** * The value that the getDistance is multiplied by to get an accurate * distance. */ private static final double DEFAULT_DISTANCE_PER_PULSE = 1.0 / 12.9375; }
src/org/usfirst/frc/team339/Utils/Drive.java
package org.usfirst.frc.team339.Utils; import org.usfirst.frc.team339.HardwareInterfaces.KilroyCamera; import org.usfirst.frc.team339.HardwareInterfaces.UltraSonic; import org.usfirst.frc.team339.HardwareInterfaces.transmission.TransmissionFourWheel; import org.usfirst.frc.team339.HardwareInterfaces.transmission.TransmissionMecanum; import org.usfirst.frc.team339.Vision.ImageProcessor; import edu.wpi.first.wpilibj.Encoder; /** * This class allows us to drive semi-autonomously, and is to be implemented * with a transmission using Tank or Mecanum drive, as well as a camera * and an image processor. * * @author Ryan McGee * */ public class Drive { private TransmissionMecanum transmissionMecanum = null; private TransmissionFourWheel transmissionFourWheel = null; private ImageProcessor imageProcessor = null; private KilroyCamera camera = null; private Encoder rightFrontEncoder = null; private Encoder rightRearEncoder = null; private Encoder leftFrontEncoder = null; private Encoder leftRearEncoder = null; private boolean isUsingEncoders = false; private boolean isUsingUltrasonics = false; private UltraSonic leftUlt = null; private UltraSonic rightUlt = null; /** * Creates an instance of the Drive class, with a mecanum drive system. * If this is called, the mecanum versions of each method are used. * * @param transmissionMecanum * The transmission to be input * @param camera * The camera we want to use for image saving * @param imageProcessor * The processor we want to use for aiming and aligning */ public Drive (TransmissionMecanum transmissionMecanum, KilroyCamera camera, ImageProcessor imageProcessor) { this.transmissionMecanum = transmissionMecanum; this.transmissionType = TransmissionType.MECANUM; this.camera = camera; this.imageProcessor = imageProcessor; } /** * Creates an instance of the Drive class, with a mecanum drive system. * If this is called, the mecanum versions of each method are used. * * @param transmissionMecanum * The transmission to be input * @param camera * The camera we want to use for image saving * @param imageProcessor * The processor we want to use for aiming and aligning * @param rightFrontEncoder * The front right encoder * @param rightRearEncoder * The back right encoder * @param leftFrontEncoder * The front left encoder * @param leftRearEncoder * The back left encoder * @param leftUlt * The ultrasonic on the left side of the robot * @param rightUlt * The ultrasonic on the right side of the robot */ public Drive (TransmissionMecanum transmissionMecanum, KilroyCamera camera, ImageProcessor imageProcessor, Encoder rightFrontEncoder, Encoder rightRearEncoder, Encoder leftFrontEncoder, Encoder leftRearEncoder, UltraSonic leftUlt, UltraSonic rightUlt) { this(transmissionMecanum, camera, imageProcessor); this.initEncoders(leftFrontEncoder, rightFrontEncoder, leftRearEncoder, rightRearEncoder); this.rightUlt = rightUlt; this.leftUlt = leftUlt; isUsingUltrasonics = true; } /** * Creates an instance of the Drive class, with a tank drive system. * If this is called, the tank versions of each method are used. * * @param transmissionFourWheel * The transmission to be input * @param camera * The camera we want to use for image saving * @param imageProcessor * The processor we want to use for aiming and aligning */ public Drive (TransmissionFourWheel transmissionFourWheel, KilroyCamera camera, ImageProcessor imageProcessor) { this.transmissionFourWheel = transmissionFourWheel; this.transmissionType = TransmissionType.TANK; this.camera = camera; this.imageProcessor = imageProcessor; } /** * Creates an instance of the Drive class, with a Tank drive system. * If this is called, the Tank versions of each method are used. * * @param transmissionFourWheel * The transmission to be input * @param camera * The camera we want to use for image saving * @param imageProcessor * The processor we want to use for aiming and aligning * @param rightFrontEncoder * The front right encoder * @param rightRearEncoder * The back right encoder * @param leftFrontEncoder * The front left encoder * @param leftRearEncoder * The back left encoder * @param leftUlt * The ultrasonic on the left side of the robot * @param rightUlt * The ultrasonic on the right side of the robot */ public Drive (TransmissionFourWheel transmissionFourWheel, KilroyCamera camera, ImageProcessor imageProcessor, Encoder leftFrontEncoder, Encoder rightFrontEncoder, Encoder leftRearEncoder, Encoder rightRearEncoder, UltraSonic leftUlt, UltraSonic rightUlt) { this(transmissionFourWheel, camera, imageProcessor); this.initEncoders(leftFrontEncoder, rightFrontEncoder, leftRearEncoder, rightRearEncoder); this.leftUlt = leftUlt; this.rightUlt = rightUlt; isUsingUltrasonics = true; } /** * Initializes all the encoders. Is called in the constructor and can * be called outside the class. * * @param _leftFrontEncoder * The front left encoder * @param _rightFrontEncoder * The front right encoder * @param _leftRearEncoder * The back left encoder * @param _rightRearEncoder * The back right encoder */ public void initEncoders (Encoder _leftFrontEncoder, Encoder _rightFrontEncoder, Encoder _leftRearEncoder, Encoder _rightRearEncoder) { isUsingEncoders = true; this.leftFrontEncoder = _leftFrontEncoder; this.rightFrontEncoder = _rightFrontEncoder; this.leftRearEncoder = _leftRearEncoder; this.rightRearEncoder = _rightRearEncoder; this.setEncoderDistancePerPulse(DEFAULT_DISTANCE_PER_PULSE); } /** * Gets the averaged distance out of the four encoders * * @return averaged distance after driving forwards */ public double getAveragedEncoderValues () { return (this.getLeftFrontEncoderDistance() + this.getRightFrontEncoderDistance() + this.getLeftRearEncoderDistance() + this.getRightRearEncoderDistance()) / 4.0; } // TODO Test this /** * Drives a distance given. To drive backwards, give negative speed, not * negative distance. * * @param inches * How far we want to go * @param speed * How fast we want to go there * @return Whether or not we have finished driving yet */ public boolean driveInches (double inches, double speed) { // Again, we don't know why it's going backwards... if (firstTimeDriveInches) { this.resetEncoders(); firstTimeDriveInches = false; } if (Math.abs(this.getAveragedEncoderValues()) >= Math.abs(inches)) { if (this.transmissionType == TransmissionType.MECANUM) this.transmissionMecanum.drive(0.0, 0.0, 0.0, 0, 0); else this.transmissionFourWheel.drive(0.0, 0.0); firstTimeDriveInches = true; return true; } if (this.transmissionType == TransmissionType.MECANUM) this.transmissionMecanum.drive(speed, 0.0, 0.0, 0, 0); else this.transmissionFourWheel.drive(-speed, -speed); return false; } private boolean firstTimeDriveInches = true; /** * Aligns to the low dual targets for the gear peg. This finds the * average of the two targets, divides by the resolution of the camera * (to make it relative coordinates) and compares it to the given * value defined as relativeCenter. * * @author Ryan McGee * * @param relativeCenter * The "center" of the camera, the value we want to align to. * @param movementSpeed * The speed we want the motors to run at * @param deadband * The "happy" value; the method will say "I am aligned!" when we are * in this range. * @return Whether or not we are aligned to the center yet. */ public AlignReturnType alignToGear (double relativeCenter, double movementSpeed, double deadband) { imageProcessor.processImage(); if (imageProcessor.getNthSizeBlob(1) != null) switch (this.transmissionType) { case TANK: double distanceToCenter = imageProcessor .getPositionOfRobotToGear( imageProcessor.getNthSizeBlob(0), imageProcessor.getNthSizeBlob(1), relativeCenter); System.out .println("Distance to center: " + distanceToCenter); System.out.println("Deadband: " + (10.0 / this.camera.getHorizontalResolution())); if (distanceToCenter == Double.MAX_VALUE) { transmissionFourWheel.drive(0.0, 0.0); return AlignReturnType.NO_BLOBS; } if (Math.abs(distanceToCenter) <= deadband) { transmissionFourWheel.drive(0.0, 0.0); return AlignReturnType.ALIGNED; } else if (distanceToCenter > 0) { transmissionFourWheel.drive(movementSpeed, -movementSpeed); } else if (distanceToCenter < 0) { transmissionFourWheel.drive(-movementSpeed, movementSpeed); } break; case MECANUM: break; default: break; } return AlignReturnType.MISALIGNED; } // TODO we need to test this!! /** * Aligns to the gear peg WHILE driving towards it. If the transmission type * is Mecanum, it will STRAFE while moving forwards. If it is tank drive * mode, it will adjust each side's speed accordingly. * * @param driveSpeed * The speed we will drive forwards * @param alignVar * If it is tank drive, this will be the speed it aligns. * If it is in mecanum drive, this is the angle added on. * @param deadband * If the camera's center is in this deadband, we are 'aligned'. * @param relativeCenter * Where we want the center of the robot to be * @param distanceToTarget * What we want the distance to the wall from the bumper * to be when we stop aligning * @return Whether or not we are aligned, close enough, misaligned, or see no * blobs. */ public AlignReturnType strafeToGear (double driveSpeed, double alignVar, double deadband, double relativeCenter, int distanceToTarget) { // If we have no blobs, return so. if (this.imageProcessor.getNthSizeBlob(1) == null) return AlignReturnType.NO_BLOBS; // If we don't have any ultrasonics in the constructor, stop aligning. if (this.isUsingUltrasonics == false) return AlignReturnType.ALIGNED; double distanceToCenter = this.imageProcessor .getPositionOfRobotToGear( this.imageProcessor.getNthSizeBlob(0), this.imageProcessor.getNthSizeBlob(1), relativeCenter); if (Math.abs(distanceToCenter) < deadband) { if ((this.leftUlt .getOffsetDistanceFromNearestBummper() + this.rightUlt.getOffsetDistanceFromNearestBummper()) / 2.0 <= distanceToTarget) return AlignReturnType.CLOSE_ENOUGH; if (this.transmissionType == TransmissionType.MECANUM) transmissionMecanum.drive(driveSpeed, 0.0, 0.0, 0, 0); else if (this.transmissionType == TransmissionType.TANK) transmissionFourWheel.drive(driveSpeed, driveSpeed); return AlignReturnType.ALIGNED; } if (distanceToCenter > 0) { if (this.transmissionType == TransmissionType.MECANUM) this.transmissionMecanum.drive(driveSpeed, alignVar, 0, 0, 0); else if (this.transmissionType == TransmissionType.TANK) this.transmissionFourWheel.drive(driveSpeed - alignVar, driveSpeed + alignVar); } else if (distanceToCenter < 0) { if (this.transmissionType == TransmissionType.MECANUM) this.transmissionMecanum.drive(driveSpeed, -alignVar, 0.0, 0, 0); else if (this.transmissionType == TransmissionType.TANK) this.transmissionFourWheel.drive(driveSpeed + alignVar, driveSpeed - alignVar); } return AlignReturnType.MISALIGNED; } /** * Tells us how any aligning method returned. * * @author Ryan McGee * */ public static enum AlignReturnType { /** * No blobs are present */ NO_BLOBS, /** * We are now aligned with the target */ ALIGNED, /** * We are not aligned with the target, keep aligning */ MISALIGNED, /** * Only used if we are using an ultrasonic */ CLOSE_ENOUGH } /** * @return the distance the front left encoder has driven based on the * distance per pulse set earlier. */ public double getLeftFrontEncoderDistance () { return this.leftFrontEncoder.getDistance(); } /** * @return the distance the front right encoder has driven based on the * distance per pulse set earlier. */ public double getRightFrontEncoderDistance () { return this.rightFrontEncoder.getDistance(); } /** * @return the distance the back left encoder has driven based on the * distance per pulse set earlier. */ public double getLeftRearEncoderDistance () { return this.leftRearEncoder.getDistance(); } /** * @return the distance the back rear encoder has driven based on the * distance per pulse set earlier. */ public double getRightRearEncoderDistance () { return this.rightRearEncoder.getDistance(); } /** * Sets the value multiplied by to get an accurate distance we have driven * * @param value * Distance per pulse */ public void setEncoderDistancePerPulse (double value) { this.leftFrontEncoder.setDistancePerPulse(value); this.rightFrontEncoder.setDistancePerPulse(value); this.leftRearEncoder.setDistancePerPulse(value); this.rightRearEncoder.setDistancePerPulse(value); } /** * Resets all encoders back to 0 'distance units' driven */ public void resetEncoders () { this.leftFrontEncoder.reset(); this.rightFrontEncoder.reset(); this.leftRearEncoder.reset(); this.rightRearEncoder.reset(); } /** * Rotates the robot by degrees. * * @param degrees * Number of degrees to rotate by. Negative if left, positive if * right. * @return Whether or not we have finished turning yet. */ public boolean turnDegrees (double degrees) { if (firstAlign) { this.resetEncoders(); this.firstAlign = false; } // We do not know why, but the robot by default turns opposite what we want. double adjustedDegrees = -degrees; if (!isUsingEncoders) { this.firstAlign = true; return true; } double angleInRadians = Math.toRadians(Math.abs(degrees)); double leftSideAverage = Math .abs(this.getLeftFrontEncoderDistance() + this.getLeftRearEncoderDistance()) / 2.0; double rightSideAverage = Math .abs(this.getRightFrontEncoderDistance() + this.getRightRearEncoderDistance()) / 2.0; // If the arc length is equal to the amount driven, we finish if (rightSideAverage >= angleInRadians * turningCircleRadius || leftSideAverage >= angleInRadians * turningCircleRadius) { this.firstAlign = true; return true; } // Rotate if not if (adjustedDegrees < 0) { if (transmissionType == TransmissionType.TANK) transmissionFourWheel.drive(rotateSpeed, -rotateSpeed); else transmissionMecanum.drive(0.0, 0.0, -rotateSpeed, 0, 0); } else if (adjustedDegrees > 0) { if (transmissionType == TransmissionType.TANK) transmissionFourWheel.drive(-rotateSpeed, rotateSpeed); else transmissionMecanum.drive(0.0, 0.0, rotateSpeed, 0, 0); } return false; } private double rotateSpeed = .6; /** * Gets how fast we are rotating in turnDegrees * * @return rotation speed */ public double getRotateSpeed () { return this.rotateSpeed; } /** * Sets how fast we should rotate in turnDegrees * * @param speed * rotation speed */ public void setRotateSpeed (double speed) { this.rotateSpeed = speed; } private double turningCircleRadius = 11; /** * Gets the radius of the circle that the robot rotates around * * @return Radius in inches */ public double getTurningCircleRadius () { return turningCircleRadius; } /** * Sets the radius of the circlie that the robot rotates around * * @param radius * Radius in inches */ public void setTurningCircleRadius (double radius) { this.turningCircleRadius = radius; } private boolean firstAlign = true; /** * The type of transmission we are using. Is set in the constructor. * * @author Ryan McGee * */ public static enum TransmissionType { /** * Tank drive */ TANK, /** * Mecanum drive */ MECANUM } // ===================================================================== // Constants // ===================================================================== private TransmissionType transmissionType = null; /** * The value that the getDistance is multiplied by to get an accurate * distance. */ private static final double DEFAULT_DISTANCE_PER_PULSE = 1.0 / 12.9375; }
Began writing strafe straight
src/org/usfirst/frc/team339/Utils/Drive.java
Began writing strafe straight
Java
mit
5ea1f8d1e5285fe44d0480c64933f044c6727a09
0
Adyen/adyen-hybris,Adyen/adyen-hybris,Adyen/adyen-hybris
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.factory; import com.adyen.builders.terminal.TerminalAPIRequestBuilder; import com.adyen.enums.VatCategory; import com.adyen.model.AbstractPaymentRequest; import com.adyen.model.Address; import com.adyen.model.Amount; import com.adyen.model.BrowserInfo; import com.adyen.model.Installments; import com.adyen.model.Name; import com.adyen.model.PaymentRequest; import com.adyen.model.PaymentRequest3d; import com.adyen.model.additionalData.InvoiceLine; import com.adyen.model.applicationinfo.ApplicationInfo; import com.adyen.model.applicationinfo.CommonField; import com.adyen.model.applicationinfo.ExternalPlatform; import com.adyen.model.checkout.DefaultPaymentMethodDetails; import com.adyen.model.checkout.LineItem; import com.adyen.model.checkout.PaymentMethodDetails; import com.adyen.model.checkout.PaymentsDetailsRequest; import com.adyen.model.checkout.PaymentsRequest; import com.adyen.model.modification.CancelOrRefundRequest; import com.adyen.model.modification.CaptureRequest; import com.adyen.model.modification.RefundRequest; import com.adyen.model.nexo.AmountsReq; import com.adyen.model.nexo.DocumentQualifierType; import com.adyen.model.nexo.MessageCategoryType; import com.adyen.model.nexo.MessageReference; import com.adyen.model.nexo.PaymentTransaction; import com.adyen.model.nexo.SaleData; import com.adyen.model.nexo.TransactionIdentification; import com.adyen.model.nexo.TransactionStatusRequest; import com.adyen.model.recurring.DisableRequest; import com.adyen.model.recurring.Recurring; import com.adyen.model.recurring.RecurringDetailsRequest; import com.adyen.model.terminal.SaleToAcquirerData; import com.adyen.model.terminal.TerminalAPIRequest; import com.adyen.util.Util; import com.adyen.v6.enums.AdyenCardTypeEnum; import com.adyen.v6.enums.RecurringContractMode; import com.adyen.v6.model.RequestInfo; import com.google.gson.Gson; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.commercefacades.order.data.OrderEntryData; import de.hybris.platform.commercefacades.user.data.AddressData; import de.hybris.platform.commercefacades.user.data.CountryData; import de.hybris.platform.commerceservices.enums.CustomerType; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.config.ConfigurationService; import de.hybris.platform.util.TaxValue; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Currency; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import static com.adyen.v6.constants.Adyenv6coreConstants.AFTERPAY; import static com.adyen.v6.constants.Adyenv6coreConstants.CARD_TYPE_DEBIT; import static com.adyen.v6.constants.Adyenv6coreConstants.ISSUER_PAYMENT_METHODS; import static com.adyen.v6.constants.Adyenv6coreConstants.KLARNA; import static com.adyen.v6.constants.Adyenv6coreConstants.OPENINVOICE_METHODS_API; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_FACILPAY_PREFIX; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PIX; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_SEPA_DIRECTDEBIT; import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_NAME; import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_VERSION; public class AdyenRequestFactory { private ConfigurationService configurationService; private static final Logger LOG = Logger.getLogger(AdyenRequestFactory.class); private static final String PLATFORM_NAME = "Hybris"; private static final String PLATFORM_VERSION_PROPERTY = "build.version.api"; private static final String IS_3DS2_ALLOWED_PROPERTY = "is3DS2allowed"; private static final String ALLOW_3DS2_PROPERTY = "allow3DS2"; private static final String OVERWRITE_BRAND_PROPERTY = "overwriteBrand"; private static final List<String> CVC_OPTIONAL_BRANDS = Arrays.asList(AdyenCardTypeEnum.BCMC.getCode(), AdyenCardTypeEnum.MAESTRO.getCode()); public PaymentRequest3d create3DAuthorizationRequest(final String merchantAccount, final HttpServletRequest request, final String md, final String paRes) { return createBasePaymentRequest(new PaymentRequest3d(), request, merchantAccount).set3DRequestData(md, paRes); } @Deprecated public PaymentRequest createAuthorizationRequest(final String merchantAccount, final CartData cartData, final HttpServletRequest request, final CustomerModel customerModel, final RecurringContractMode recurringContractMode) { String amount = String.valueOf(cartData.getTotalPrice().getValue()); String currency = cartData.getTotalPrice().getCurrencyIso(); String reference = cartData.getCode(); PaymentRequest paymentRequest = createBasePaymentRequest(new PaymentRequest(), request, merchantAccount).reference(reference).setAmountData(amount, currency); // set shopper details if (customerModel != null) { paymentRequest.setShopperReference(customerModel.getCustomerID()); paymentRequest.setShopperEmail(customerModel.getContactEmail()); } // set recurring contract if (customerModel != null && PAYMENT_METHOD_CC.equals(cartData.getAdyenPaymentMethod())) { Recurring recurring = getRecurringContractType(recurringContractMode, cartData.getAdyenRememberTheseDetails()); paymentRequest.setRecurring(recurring); } // if address details are provided added it into the request if (cartData.getDeliveryAddress() != null) { Address deliveryAddress = setAddressData(cartData.getDeliveryAddress()); paymentRequest.setDeliveryAddress(deliveryAddress); } if (cartData.getPaymentInfo().getBillingAddress() != null) { // set PhoneNumber if it is provided if (cartData.getPaymentInfo().getBillingAddress().getPhone() != null && ! cartData.getPaymentInfo().getBillingAddress().getPhone().isEmpty()) { paymentRequest.setTelephoneNumber(cartData.getPaymentInfo().getBillingAddress().getPhone()); } Address billingAddress = setAddressData(cartData.getPaymentInfo().getBillingAddress()); paymentRequest.setBillingAddress(billingAddress); } // OpenInvoice add required additional data if (OPENINVOICE_METHODS_API.contains(cartData.getAdyenPaymentMethod()) || PAYMENT_METHOD_PAYPAL.contains(cartData.getAdyenPaymentMethod())) { paymentRequest.selectedBrand(cartData.getAdyenPaymentMethod()); setOpenInvoiceData(paymentRequest, cartData, customerModel); paymentRequest.setShopperName(getShopperNameFromAddress(cartData.getDeliveryAddress())); } return paymentRequest; } public PaymentsDetailsRequest create3DPaymentsRequest(final String paymentData, final String md, final String paRes) { PaymentsDetailsRequest paymentsDetailsRequest = new PaymentsDetailsRequest(); paymentsDetailsRequest.set3DRequestData(md, paRes, paymentData); return paymentsDetailsRequest; } public PaymentsDetailsRequest create3DS2PaymentsRequest(final String paymentData, final String token, String type) { PaymentsDetailsRequest paymentsDetailsRequest = new PaymentsDetailsRequest(); if (type.equals("fingerprint")) { paymentsDetailsRequest.setFingerPrint(token, paymentData); } else if (type.equals("challenge")) { paymentsDetailsRequest.setChallengeResult(token, paymentData); } return paymentsDetailsRequest; } public PaymentsRequest createPaymentsRequest(final String merchantAccount, final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel, final RecurringContractMode recurringContractMode, final Boolean guestUserTokenizationEnabled) { PaymentsRequest paymentsRequest = new PaymentsRequest(); String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); if (adyenPaymentMethod == null) { throw new IllegalArgumentException("Payment method is null"); } //Update payment request for generic information for all payment method types updatePaymentRequest(merchantAccount, cartData, requestInfo, customerModel, paymentsRequest); Boolean is3DS2allowed = is3DS2Allowed(); //For credit cards if (PAYMENT_METHOD_CC.equals(adyenPaymentMethod)) { if (CARD_TYPE_DEBIT.equals(cartData.getAdyenCardType())) { updatePaymentRequestForDC(paymentsRequest, cartData, recurringContractMode); } else { updatePaymentRequestForCC(paymentsRequest, cartData, recurringContractMode); } if (is3DS2allowed) { paymentsRequest = enhanceForThreeDS2(paymentsRequest, cartData); } if (customerModel != null && customerModel.getType() == CustomerType.GUEST && guestUserTokenizationEnabled) { paymentsRequest.setEnableOneClick(false); } } //For one click else if (adyenPaymentMethod.indexOf(PAYMENT_METHOD_ONECLICK) == 0) { String selectedReference = cartData.getAdyenSelectedReference(); if (selectedReference != null && ! selectedReference.isEmpty()) { paymentsRequest.addOneClickData(selectedReference, cartData.getAdyenEncryptedSecurityCode()); String cardBrand = cartData.getAdyenCardBrand(); if (cardBrand != null && CVC_OPTIONAL_BRANDS.contains(cardBrand)) { DefaultPaymentMethodDetails paymentMethodDetails = (DefaultPaymentMethodDetails) (paymentsRequest.getPaymentMethod()); paymentMethodDetails.setType(cardBrand); paymentsRequest.setPaymentMethod(paymentMethodDetails); } } if (is3DS2allowed) { paymentsRequest = enhanceForThreeDS2(paymentsRequest, cartData); } } //Set Boleto parameters else if (cartData.getAdyenPaymentMethod().indexOf(PAYMENT_METHOD_BOLETO) == 0) { setBoletoData(paymentsRequest, cartData); } else if (PAYMENT_METHOD_SEPA_DIRECTDEBIT.equals(cartData.getAdyenPaymentMethod())) { setSepaDirectDebitData(paymentsRequest, cartData); } //For alternate payment methods like iDeal, Paypal etc. else { updatePaymentRequestForAlternateMethod(paymentsRequest, cartData); } ApplicationInfo applicationInfo = updateApplicationInfoEcom(paymentsRequest.getApplicationInfo()); paymentsRequest.setApplicationInfo(applicationInfo); paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); paymentsRequest.setRedirectFromIssuerMethod(RequestMethod.POST.toString()); paymentsRequest.setRedirectToIssuerMethod(RequestMethod.POST.toString()); return paymentsRequest; } public PaymentsRequest createPaymentsRequest(final String merchantAccount, final CartData cartData, final PaymentMethodDetails paymentMethodDetails, final RequestInfo requestInfo, final CustomerModel customerModel) { PaymentsRequest paymentsRequest = new PaymentsRequest(); updatePaymentRequest(merchantAccount, cartData, requestInfo, customerModel, paymentsRequest); paymentsRequest.setPaymentMethod(paymentMethodDetails); paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); ApplicationInfo applicationInfo = updateApplicationInfoEcom(paymentsRequest.getApplicationInfo()); paymentsRequest.setApplicationInfo(applicationInfo); return paymentsRequest; } public PaymentsRequest enhanceForThreeDS2(PaymentsRequest paymentsRequest, CartData cartData) { if (paymentsRequest.getAdditionalData() == null) { paymentsRequest.setAdditionalData(new HashMap<>()); } paymentsRequest.getAdditionalData().put(ALLOW_3DS2_PROPERTY, is3DS2Allowed().toString()); paymentsRequest.setChannel(PaymentsRequest.ChannelEnum.WEB); BrowserInfo browserInfo = new Gson().fromJson(cartData.getAdyenBrowserInfo(), BrowserInfo.class); browserInfo = updateBrowserInfoFromRequest(browserInfo, paymentsRequest); paymentsRequest.setBrowserInfo(browserInfo); return paymentsRequest; } public BrowserInfo updateBrowserInfoFromRequest(BrowserInfo browserInfo, PaymentsRequest paymentsRequest) { if (browserInfo != null) { browserInfo.setUserAgent(paymentsRequest.getBrowserInfo().getUserAgent()); browserInfo.setAcceptHeader(paymentsRequest.getBrowserInfo().getAcceptHeader()); } return browserInfo; } public ApplicationInfo updateApplicationInfoEcom(ApplicationInfo applicationInfo) { updateApplicationInfoPos(applicationInfo); CommonField adyenPaymentSource = new CommonField(); adyenPaymentSource.setName(PLUGIN_NAME); adyenPaymentSource.setVersion(PLUGIN_VERSION); applicationInfo.setAdyenPaymentSource(adyenPaymentSource); return applicationInfo; } public ApplicationInfo updateApplicationInfoPos(ApplicationInfo applicationInfo) { if (applicationInfo == null) { applicationInfo = new ApplicationInfo(); } ExternalPlatform externalPlatform = new ExternalPlatform(); externalPlatform.setName(PLATFORM_NAME); externalPlatform.setVersion(getPlatformVersion()); applicationInfo.setExternalPlatform(externalPlatform); CommonField merchantApplication = new CommonField(); merchantApplication.setName(PLUGIN_NAME); merchantApplication.setVersion(PLUGIN_VERSION); applicationInfo.setMerchantApplication(merchantApplication); return applicationInfo; } private void updatePaymentRequest(final String merchantAccount, final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel, PaymentsRequest paymentsRequest) { //Get details from CartData to set in PaymentRequest. String amount = String.valueOf(cartData.getTotalPrice().getValue()); String currency = cartData.getTotalPrice().getCurrencyIso(); String reference = cartData.getCode(); AddressData billingAddress = cartData.getPaymentInfo() != null ? cartData.getPaymentInfo().getBillingAddress() : null; AddressData deliveryAddress = cartData.getDeliveryAddress(); //Get details from HttpServletRequest to set in PaymentRequest. String userAgent = requestInfo.getUserAgent(); String acceptHeader = requestInfo.getAcceptHeader(); String shopperIP = requestInfo.getShopperIp(); String origin = requestInfo.getOrigin(); String shopperLocale = requestInfo.getShopperLocale(); paymentsRequest.setAmountData(amount, currency) .reference(reference) .merchantAccount(merchantAccount) .addBrowserInfoData(userAgent, acceptHeader) .shopperIP(shopperIP) .origin(origin) .shopperLocale(shopperLocale) .setCountryCode(getCountryCode(cartData)); // set shopper details from CustomerModel. if (customerModel != null) { paymentsRequest.setShopperReference(customerModel.getCustomerID()); paymentsRequest.setShopperEmail(customerModel.getContactEmail()); } // if address details are provided, set it to the PaymentRequest if (deliveryAddress != null) { paymentsRequest.setDeliveryAddress(setAddressData(deliveryAddress)); } if (billingAddress != null) { paymentsRequest.setBillingAddress(setAddressData(billingAddress)); // set PhoneNumber if it is provided String phone = billingAddress.getPhone(); if (phone != null && ! phone.isEmpty()) { paymentsRequest.setTelephoneNumber(phone); } } if (PAYMENT_METHOD_PIX.equals(cartData.getAdyenPaymentMethod())) { setPixData(paymentsRequest, cartData); } } private void updatePaymentRequestForCC(PaymentsRequest paymentsRequest, CartData cartData, RecurringContractMode recurringContractMode) { Recurring recurringContract = getRecurringContractType(recurringContractMode); Recurring.ContractEnum contractEnum = null; if (recurringContract != null) { contractEnum = recurringContract.getContract(); } paymentsRequest.setEnableRecurring(false); paymentsRequest.setEnableOneClick(false); String encryptedCardNumber = cartData.getAdyenEncryptedCardNumber(); String encryptedExpiryMonth = cartData.getAdyenEncryptedExpiryMonth(); String encryptedExpiryYear = cartData.getAdyenEncryptedExpiryYear(); if (cartData.getAdyenInstallments() != null) { Installments installmentObj = new Installments(); installmentObj.setValue(cartData.getAdyenInstallments()); paymentsRequest.setInstallments(installmentObj); } if (! StringUtils.isEmpty(encryptedCardNumber) && ! StringUtils.isEmpty(encryptedExpiryMonth) && ! StringUtils.isEmpty(encryptedExpiryYear)) { paymentsRequest.addEncryptedCardData(encryptedCardNumber, encryptedExpiryMonth, encryptedExpiryYear, cartData.getAdyenEncryptedSecurityCode(), cartData.getAdyenCardHolder()); } if (Recurring.ContractEnum.ONECLICK_RECURRING == contractEnum) { paymentsRequest.setEnableRecurring(true); if(cartData.getAdyenRememberTheseDetails()) { paymentsRequest.setEnableOneClick(true); } } else if (Recurring.ContractEnum.ONECLICK == contractEnum && cartData.getAdyenRememberTheseDetails() ) { paymentsRequest.setEnableOneClick(true); } else if (Recurring.ContractEnum.RECURRING == contractEnum) { paymentsRequest.setEnableRecurring(true); } // Set storeDetails parameter when shopper selected to have his card details stored if (cartData.getAdyenRememberTheseDetails()) { DefaultPaymentMethodDetails paymentMethodDetails = (DefaultPaymentMethodDetails) paymentsRequest.getPaymentMethod(); paymentMethodDetails.setStoreDetails(true); } } private void updatePaymentRequestForDC(PaymentsRequest paymentsRequest, CartData cartData, RecurringContractMode recurringContractMode) { Recurring recurringContract = getRecurringContractType(recurringContractMode); Recurring.ContractEnum contractEnum = null; if (recurringContract != null) { contractEnum = recurringContract.getContract(); } paymentsRequest.setEnableRecurring(false); paymentsRequest.setEnableOneClick(false); String encryptedCardNumber = cartData.getAdyenEncryptedCardNumber(); String encryptedExpiryMonth = cartData.getAdyenEncryptedExpiryMonth(); String encryptedExpiryYear = cartData.getAdyenEncryptedExpiryYear(); if ((Recurring.ContractEnum.ONECLICK_RECURRING == contractEnum || Recurring.ContractEnum.ONECLICK == contractEnum) && cartData.getAdyenRememberTheseDetails()) { paymentsRequest.setEnableOneClick(true); } if (! StringUtils.isEmpty(encryptedCardNumber) && ! StringUtils.isEmpty(encryptedExpiryMonth) && ! StringUtils.isEmpty(encryptedExpiryYear)) { paymentsRequest.addEncryptedCardData(encryptedCardNumber, encryptedExpiryMonth, encryptedExpiryYear, cartData.getAdyenEncryptedSecurityCode(), cartData.getAdyenCardHolder()); } // Set storeDetails parameter when shopper selected to have his card details stored if (cartData.getAdyenRememberTheseDetails()) { DefaultPaymentMethodDetails paymentMethodDetails = (DefaultPaymentMethodDetails) paymentsRequest.getPaymentMethod(); paymentMethodDetails.setStoreDetails(true); } String cardBrand = cartData.getAdyenCardBrand(); paymentsRequest.putAdditionalDataItem(OVERWRITE_BRAND_PROPERTY, "true"); paymentsRequest.getPaymentMethod().setType(cardBrand); } private void updatePaymentRequestForAlternateMethod(PaymentsRequest paymentsRequest, CartData cartData) { String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); DefaultPaymentMethodDetails paymentMethod = new DefaultPaymentMethodDetails(); paymentsRequest.setPaymentMethod(paymentMethod); paymentMethod.setType(adyenPaymentMethod); paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); if (ISSUER_PAYMENT_METHODS.contains(adyenPaymentMethod)) { paymentMethod.setIssuer(cartData.getAdyenIssuerId()); } else if (adyenPaymentMethod.startsWith(KLARNA) || adyenPaymentMethod.startsWith(PAYMENT_METHOD_FACILPAY_PREFIX) || OPENINVOICE_METHODS_API.contains(adyenPaymentMethod)) { setOpenInvoiceData(paymentsRequest, cartData); } else if (adyenPaymentMethod.equals(PAYMENT_METHOD_PAYPAL) && cartData.getDeliveryAddress() != null) { Name shopperName = getShopperNameFromAddress(cartData.getDeliveryAddress()); paymentsRequest.setShopperName(shopperName); } } private String getCountryCode(CartData cartData) { //Identify country code based on shopper's delivery address String countryCode = ""; AddressData billingAddressData = cartData.getPaymentInfo() != null ? cartData.getPaymentInfo().getBillingAddress() : null; if (billingAddressData != null) { CountryData billingCountry = billingAddressData.getCountry(); if (billingCountry != null) { countryCode = billingCountry.getIsocode(); } } else { AddressData deliveryAddressData = cartData.getDeliveryAddress(); if (deliveryAddressData != null) { CountryData deliveryCountry = deliveryAddressData.getCountry(); if (deliveryCountry != null) { countryCode = deliveryCountry.getIsocode(); } } } return countryCode; } public CaptureRequest createCaptureRequest(final String merchantAccount, final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) { CaptureRequest request = new CaptureRequest().fillAmount(String.valueOf(amount), currency.getCurrencyCode()) .merchantAccount(merchantAccount) .originalReference(authReference) .reference(merchantReference); updateApplicationInfoEcom(request.getApplicationInfo()); return request; } public CancelOrRefundRequest createCancelOrRefundRequest(final String merchantAccount, final String authReference, final String merchantReference) { CancelOrRefundRequest request = new CancelOrRefundRequest().merchantAccount(merchantAccount).originalReference(authReference).reference(merchantReference); updateApplicationInfoEcom(request.getApplicationInfo()); return request; } public RefundRequest createRefundRequest(final String merchantAccount, final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) { RefundRequest request = new RefundRequest().fillAmount(String.valueOf(amount), currency.getCurrencyCode()) .merchantAccount(merchantAccount) .originalReference(authReference) .reference(merchantReference); updateApplicationInfoEcom(request.getApplicationInfo()); return request; } public RecurringDetailsRequest createListRecurringDetailsRequest(final String merchantAccount, final String customerId) { return new RecurringDetailsRequest().merchantAccount(merchantAccount).shopperReference(customerId).selectOneClickContract(); } /** * Creates a request to disable a recurring contract */ public DisableRequest createDisableRequest(final String merchantAccount, final String customerId, final String recurringReference) { return new DisableRequest().merchantAccount(merchantAccount).shopperReference(customerId).recurringDetailReference(recurringReference); } private <T extends AbstractPaymentRequest> T createBasePaymentRequest(T abstractPaymentRequest, HttpServletRequest request, final String merchantAccount) { String userAgent = request.getHeader("User-Agent"); String acceptHeader = request.getHeader("Accept"); String shopperIP = request.getRemoteAddr(); abstractPaymentRequest.merchantAccount(merchantAccount).setBrowserInfoData(userAgent, acceptHeader).shopperIP(shopperIP); return abstractPaymentRequest; } public TerminalAPIRequest createTerminalAPIRequestForStatus(final CartData cartData, String originalServiceId) { TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest(); transactionStatusRequest.setReceiptReprintFlag(true); MessageReference messageReference = new MessageReference(); messageReference.setMessageCategory(MessageCategoryType.PAYMENT); messageReference.setSaleID(cartData.getStore()); messageReference.setServiceID(originalServiceId); transactionStatusRequest.setMessageReference(messageReference); transactionStatusRequest.getDocumentQualifier().add(DocumentQualifierType.CASHIER_RECEIPT); transactionStatusRequest.getDocumentQualifier().add(DocumentQualifierType.CUSTOMER_RECEIPT); String serviceId = Long.toString(System.currentTimeMillis() % 10000000000L); TerminalAPIRequestBuilder builder = new TerminalAPIRequestBuilder(cartData.getStore(), serviceId, cartData.getAdyenTerminalId()); builder.withTransactionStatusRequest(transactionStatusRequest); return builder.build(); } public TerminalAPIRequest createTerminalAPIRequest(final CartData cartData, CustomerModel customer, RecurringContractMode recurringContractMode, String serviceId) throws Exception { com.adyen.model.nexo.PaymentRequest paymentRequest = new com.adyen.model.nexo.PaymentRequest(); SaleData saleData = new SaleData(); TransactionIdentification transactionIdentification = new TransactionIdentification(); transactionIdentification.setTransactionID(cartData.getCode()); XMLGregorianCalendar timestamp = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()); transactionIdentification.setTimeStamp(timestamp); saleData.setSaleTransactionID(transactionIdentification); //Set recurring contract, if exists if(customer != null) { String shopperReference = customer.getCustomerID(); String shopperEmail = customer.getContactEmail(); Recurring recurringContract = getRecurringContractType(recurringContractMode); SaleToAcquirerData saleToAcquirerData = new SaleToAcquirerData(); if (recurringContract != null && StringUtils.isNotEmpty(shopperReference) && StringUtils.isNotEmpty(shopperEmail)) { saleToAcquirerData.setShopperEmail(shopperEmail); saleToAcquirerData.setShopperReference(shopperReference); saleToAcquirerData.setRecurringContract(recurringContract.getContract().toString()); } updateApplicationInfoPos(saleToAcquirerData.getApplicationInfo()); saleData.setSaleToAcquirerData(saleToAcquirerData); } paymentRequest.setSaleData(saleData); PaymentTransaction paymentTransaction = new PaymentTransaction(); AmountsReq amountsReq = new AmountsReq(); amountsReq.setCurrency(cartData.getTotalPrice().getCurrencyIso()); amountsReq.setRequestedAmount(cartData.getTotalPrice().getValue()); paymentTransaction.setAmountsReq(amountsReq); paymentRequest.setPaymentTransaction(paymentTransaction); TerminalAPIRequestBuilder builder = new TerminalAPIRequestBuilder(cartData.getStore(), serviceId, cartData.getAdyenTerminalId()); builder.withPaymentRequest(paymentRequest); return builder.build(); } /** * Set Address Data into API */ private Address setAddressData(AddressData addressData) { Address address = new Address(); // set defaults because all fields are required into the API address.setCity("NA"); address.setCountry("NA"); address.setHouseNumberOrName("NA"); address.setPostalCode("NA"); address.setStateOrProvince("NA"); address.setStreet("NA"); // set the actual values if they are available if (addressData.getTown() != null && ! addressData.getTown().isEmpty()) { address.setCity(addressData.getTown()); } if (addressData.getCountry() != null && ! addressData.getCountry().getIsocode().isEmpty()) { address.setCountry(addressData.getCountry().getIsocode()); } if (addressData.getLine1() != null && ! addressData.getLine1().isEmpty()) { address.setStreet(addressData.getLine1()); } if (addressData.getLine2() != null && ! addressData.getLine2().isEmpty()) { address.setHouseNumberOrName(addressData.getLine2()); } if (addressData.getPostalCode() != null && ! address.getPostalCode().isEmpty()) { address.setPostalCode(addressData.getPostalCode()); } //State value will be updated later for boleto in boleto specific method. if (addressData.getRegion() != null && StringUtils.isNotEmpty(addressData.getRegion().getIsocodeShort())) { address.setStateOrProvince(addressData.getRegion().getIsocodeShort()); } else if (addressData.getRegion() != null && StringUtils.isNotEmpty(addressData.getRegion().getIsocode())) { address.setStateOrProvince(addressData.getRegion().getIsocode()); } return address; } /** * Return Recurring object from RecurringContractMode */ private Recurring getRecurringContractType(RecurringContractMode recurringContractMode) { Recurring recurringContract = new Recurring(); //If recurring contract is disabled, return null if (recurringContractMode == null || RecurringContractMode.NONE.equals(recurringContractMode)) { return null; } String recurringMode = recurringContractMode.getCode(); Recurring.ContractEnum contractEnum = Recurring.ContractEnum.valueOf(recurringMode); recurringContract.contract(contractEnum); return recurringContract; } /** * Return the recurringContract. If the user did not want to save the card don't send it as ONECLICK */ private Recurring getRecurringContractType(RecurringContractMode recurringContractMode, final Boolean enableOneClick) { Recurring recurringContract = getRecurringContractType(recurringContractMode); //If recurring contract is disabled, return null if (recurringContract == null) { return null; } // if user want to save his card use the configured recurring contract type if (enableOneClick != null && enableOneClick) { return recurringContract; } Recurring.ContractEnum contractEnum = recurringContract.getContract(); /* * If save card is not checked do the folllowing changes: * NONE => NONE * ONECLICK => NONE * ONECLICK,RECURRING => RECURRING * RECURRING => RECURRING */ if (Recurring.ContractEnum.ONECLICK_RECURRING.equals(contractEnum) || Recurring.ContractEnum.RECURRING.equals(contractEnum)) { return recurringContract.contract(Recurring.ContractEnum.RECURRING); } return null; } /** * Get shopper name and gender */ private Name getShopperNameFromAddress(AddressData addressData) { Name shopperName = new Name(); shopperName.setFirstName(addressData.getFirstName()); shopperName.setLastName(addressData.getLastName()); shopperName.setGender(Name.GenderEnum.UNKNOWN); if (addressData.getTitleCode() != null && ! addressData.getTitleCode().isEmpty()) { if (addressData.getTitleCode().equals("mrs") || addressData.getTitleCode().equals("miss") || addressData.getTitleCode().equals("ms")) { shopperName.setGender(Name.GenderEnum.FEMALE); } else { shopperName.setGender(Name.GenderEnum.MALE); } } return shopperName; } /** * Set the required fields for using the OpenInvoice API * <p> * To deprecate when RatePay is natively implemented */ public void setOpenInvoiceData(PaymentRequest paymentRequest, CartData cartData, final CustomerModel customerModel) { // set date of birth if (cartData.getAdyenDob() != null) { paymentRequest.setDateOfBirth(cartData.getAdyenDob()); } if (cartData.getAdyenSocialSecurityNumber() != null && ! cartData.getAdyenSocialSecurityNumber().isEmpty()) { paymentRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); } if (cartData.getAdyenDfValue() != null && ! cartData.getAdyenDfValue().isEmpty()) { paymentRequest.setDeviceFingerprint(cartData.getAdyenDfValue()); } // set the invoice lines List<InvoiceLine> invoiceLines = new ArrayList(); String currency = cartData.getTotalPrice().getCurrencyIso(); for (OrderEntryData entry : cartData.getEntries()) { // Use totalPrice because the basePrice does include tax as well if you have configured this to be calculated in the price BigDecimal pricePerItem = entry.getTotalPrice().getValue().divide(new BigDecimal(entry.getQuantity())); String description = "NA"; if (entry.getProduct().getName() != null && ! entry.getProduct().getName().equals("")) { description = entry.getProduct().getName(); } // Tax of total price (included quantity) Double tax = entry.getTaxValues().stream().map(taxValue -> taxValue.getAppliedValue()).reduce(0.0, (x, y) -> x = x + y); // Calculate Tax per quantitiy if (tax > 0) { tax = tax / entry.getQuantity().intValue(); } // Calculate price without tax Amount itemAmountWithoutTax = Util.createAmount(pricePerItem.subtract(new BigDecimal(tax)), currency); Double percentage = entry.getTaxValues().stream().map(taxValue -> taxValue.getValue()).reduce(0.0, (x, y) -> x = x + y) * 100; InvoiceLine invoiceLine = new InvoiceLine(); invoiceLine.setCurrencyCode(currency); invoiceLine.setDescription(description); /* * The price for one item in the invoice line, represented in minor units. * The due amount for the item, VAT excluded. */ invoiceLine.setItemAmount(itemAmountWithoutTax.getValue()); // The VAT due for one item in the invoice line, represented in minor units. invoiceLine.setItemVATAmount(Util.createAmount(BigDecimal.valueOf(tax), currency).getValue()); // The VAT percentage for one item in the invoice line, represented in minor units. invoiceLine.setItemVatPercentage(percentage.longValue()); // The country-specific VAT category a product falls under. Allowed values: (High,Low,None) invoiceLine.setVatCategory(VatCategory.NONE); // An unique id for this item. Required for RatePay if the description of each item is not unique. if (! entry.getProduct().getCode().isEmpty()) { invoiceLine.setItemId(entry.getProduct().getCode()); } invoiceLine.setNumberOfItems(entry.getQuantity().intValue()); if (entry.getProduct() != null && ! entry.getProduct().getCode().isEmpty()) { invoiceLine.setItemId(entry.getProduct().getCode()); } if (entry.getProduct() != null && ! entry.getProduct().getCode().isEmpty()) { invoiceLine.setItemId(entry.getProduct().getCode()); } LOG.debug("InvoiceLine Product:" + invoiceLine.toString()); invoiceLines.add(invoiceLine); } // Add delivery costs if (cartData.getDeliveryCost() != null) { InvoiceLine invoiceLine = new InvoiceLine(); invoiceLine.setCurrencyCode(currency); invoiceLine.setDescription("Delivery Costs"); Amount deliveryAmount = Util.createAmount(cartData.getDeliveryCost().getValue().toString(), currency); invoiceLine.setItemAmount(deliveryAmount.getValue()); invoiceLine.setItemVATAmount(new Long("0")); invoiceLine.setItemVatPercentage(new Long("0")); invoiceLine.setVatCategory(VatCategory.NONE); invoiceLine.setNumberOfItems(1); LOG.debug("InvoiceLine DeliveryCosts:" + invoiceLine.toString()); invoiceLines.add(invoiceLine); } paymentRequest.setInvoiceLines(invoiceLines); } /* * Set the required fields for using the OpenInvoice API */ public void setOpenInvoiceData(PaymentsRequest paymentsRequest, CartData cartData) { paymentsRequest.setShopperName(getShopperNameFromAddress(cartData.getDeliveryAddress())); // set date of birth if (cartData.getAdyenDob() != null) { paymentsRequest.setDateOfBirth(cartData.getAdyenDob()); } if (cartData.getAdyenSocialSecurityNumber() != null && ! cartData.getAdyenSocialSecurityNumber().isEmpty()) { paymentsRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); } if (cartData.getAdyenDfValue() != null && ! cartData.getAdyenDfValue().isEmpty()) { paymentsRequest.setDeviceFingerprint(cartData.getAdyenDfValue()); } if (AFTERPAY.equals(cartData.getAdyenPaymentMethod())) { paymentsRequest.setShopperEmail(cartData.getAdyenShopperEmail()); paymentsRequest.setTelephoneNumber(cartData.getAdyenShopperTelephone()); paymentsRequest.setShopperName(getAfterPayShopperName(cartData)); } // set the invoice lines List<LineItem> invoiceLines = new ArrayList<>(); String currency = cartData.getTotalPrice().getCurrencyIso(); for (OrderEntryData entry : cartData.getEntries()) { if (entry.getQuantity() == 0L) { // skip zero quantities continue; } // Use totalPrice because the basePrice does include tax as well if you have configured this to be calculated in the price BigDecimal pricePerItem = entry.getTotalPrice().getValue().divide(new BigDecimal(entry.getQuantity())); String description = "NA"; if (entry.getProduct().getName() != null && ! entry.getProduct().getName().isEmpty()) { description = entry.getProduct().getName(); } // Tax of total price (included quantity) Double tax = entry.getTaxValues().stream().map(TaxValue::getAppliedValue).reduce(0.0, (x, y) -> x + y); // Calculate Tax per quantitiy if (tax > 0) { tax = tax / entry.getQuantity().intValue(); } // Calculate price without tax Amount itemAmountWithoutTax = Util.createAmount(pricePerItem.subtract(new BigDecimal(tax)), currency); Double percentage = entry.getTaxValues().stream().map(TaxValue::getValue).reduce(0.0, (x, y) -> x + y) * 100; LineItem invoiceLine = new LineItem(); invoiceLine.setDescription(description); /* * The price for one item in the invoice line, represented in minor units. * The due amount for the item, VAT excluded. */ invoiceLine.setAmountExcludingTax(itemAmountWithoutTax.getValue()); // The VAT due for one item in the invoice line, represented in minor units. invoiceLine.setTaxAmount(Util.createAmount(BigDecimal.valueOf(tax), currency).getValue()); // The VAT percentage for one item in the invoice line, represented in minor units. invoiceLine.setTaxPercentage(percentage.longValue()); // The country-specific VAT category a product falls under. Allowed values: (High,Low,None) invoiceLine.setTaxCategory(LineItem.TaxCategoryEnum.NONE); invoiceLine.setQuantity(entry.getQuantity()); if (entry.getProduct() != null && ! entry.getProduct().getCode().isEmpty()) { invoiceLine.setId(entry.getProduct().getCode()); } LOG.debug("InvoiceLine Product:" + invoiceLine.toString()); invoiceLines.add(invoiceLine); } // Add delivery costs if (cartData.getDeliveryCost() != null) { LineItem invoiceLine = new LineItem(); invoiceLine.setDescription("Delivery Costs"); Amount deliveryAmount = Util.createAmount(cartData.getDeliveryCost().getValue().toString(), currency); invoiceLine.setAmountExcludingTax(deliveryAmount.getValue()); invoiceLine.setTaxAmount(new Long("0")); invoiceLine.setTaxPercentage(new Long("0")); invoiceLine.setTaxCategory(LineItem.TaxCategoryEnum.NONE); invoiceLine.setQuantity(1L); LOG.debug("InvoiceLine DeliveryCosts:" + invoiceLine.toString()); invoiceLines.add(invoiceLine); } paymentsRequest.setLineItems(invoiceLines); } private Name getAfterPayShopperName(CartData cartData) { Name name = new Name(); name.setFirstName(cartData.getAdyenFirstName()); name.setLastName(cartData.getAdyenLastName()); name.gender(Name.GenderEnum.valueOf(cartData.getAdyenShopperGender())); return name; } /** * Set Boleto payment request data */ private void setBoletoData(PaymentsRequest paymentsRequest, CartData cartData) { DefaultPaymentMethodDetails paymentMethodDetails = (DefaultPaymentMethodDetails) (paymentsRequest.getPaymentMethod()); if (paymentMethodDetails == null) { paymentMethodDetails = new DefaultPaymentMethodDetails(); } paymentMethodDetails.setType(PAYMENT_METHOD_BOLETO_SANTANDER); paymentsRequest.setPaymentMethod(paymentMethodDetails); paymentsRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); Name shopperName = new Name(); shopperName.setFirstName(cartData.getAdyenFirstName()); shopperName.setLastName(cartData.getAdyenLastName()); paymentsRequest.setShopperName(shopperName); if (paymentsRequest.getBillingAddress() != null) { String stateOrProvinceBilling = paymentsRequest.getBillingAddress().getStateOrProvince(); if (! StringUtils.isEmpty(stateOrProvinceBilling) && stateOrProvinceBilling.length() > 2) { String shortStateOrProvince = stateOrProvinceBilling.substring(stateOrProvinceBilling.length() - 2); paymentsRequest.getBillingAddress().setStateOrProvince(shortStateOrProvince); } } if (paymentsRequest.getDeliveryAddress() != null) { String stateOrProvinceDelivery = paymentsRequest.getDeliveryAddress().getStateOrProvince(); if (! StringUtils.isEmpty(stateOrProvinceDelivery) && stateOrProvinceDelivery.length() > 2) { String shortStateOrProvince = stateOrProvinceDelivery.substring(stateOrProvinceDelivery.length() - 2); paymentsRequest.getDeliveryAddress().setStateOrProvince(shortStateOrProvince); } } } private void setSepaDirectDebitData(PaymentsRequest paymentRequest, CartData cartData) { DefaultPaymentMethodDetails paymentMethodDetails = new DefaultPaymentMethodDetails(); paymentMethodDetails.setSepaOwnerName(cartData.getAdyenSepaOwnerName()); paymentMethodDetails.setSepaIbanNumber(cartData.getAdyenSepaIbanNumber()); paymentMethodDetails.setType(PAYMENT_METHOD_SEPA_DIRECTDEBIT); paymentRequest.setPaymentMethod(paymentMethodDetails); } private void setPixData(PaymentsRequest paymentsRequest, CartData cartData) { Name shopperName = new Name(); shopperName.setFirstName(cartData.getAdyenFirstName()); shopperName.setLastName(cartData.getAdyenLastName()); paymentsRequest.setShopperName(shopperName); paymentsRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); List<LineItem> invoiceLines = new ArrayList<>(); for (OrderEntryData entry : cartData.getEntries()) { if (entry.getQuantity() == 0L) { // skip zero quantities continue; } BigDecimal productAmountIncludingTax = entry.getBasePrice().getValue(); String productName = "NA"; if (entry.getProduct().getName() != null && !entry.getProduct().getName().isEmpty()) { productName = entry.getProduct().getName(); } LineItem lineItem = new LineItem(); lineItem.setAmountIncludingTax(productAmountIncludingTax.longValue()); lineItem.setId(productName); invoiceLines.add(lineItem); } paymentsRequest.setLineItems(invoiceLines); } private String getPlatformVersion() { return getConfigurationService().getConfiguration().getString(PLATFORM_VERSION_PROPERTY); } private Boolean is3DS2Allowed() { Configuration configuration = getConfigurationService().getConfiguration(); boolean is3DS2AllowedValue = false; if (configuration.containsKey(IS_3DS2_ALLOWED_PROPERTY)) { is3DS2AllowedValue = configuration.getBoolean(IS_3DS2_ALLOWED_PROPERTY); } return is3DS2AllowedValue; } public ConfigurationService getConfigurationService() { return configurationService; } public void setConfigurationService(ConfigurationService configurationService) { this.configurationService = configurationService; } }
adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Hybris Extension * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.v6.factory; import com.adyen.util.Util; import com.adyen.builders.terminal.TerminalAPIRequestBuilder; import com.adyen.enums.VatCategory; import com.adyen.model.AbstractPaymentRequest; import com.adyen.model.Address; import com.adyen.model.Amount; import com.adyen.model.BrowserInfo; import com.adyen.model.Installments; import com.adyen.model.Name; import com.adyen.model.PaymentRequest; import com.adyen.model.PaymentRequest3d; import com.adyen.model.additionalData.InvoiceLine; import com.adyen.model.applicationinfo.ApplicationInfo; import com.adyen.model.applicationinfo.CommonField; import com.adyen.model.applicationinfo.ExternalPlatform; import com.adyen.model.checkout.DefaultPaymentMethodDetails; import com.adyen.model.checkout.LineItem; import com.adyen.model.checkout.PaymentMethodDetails; import com.adyen.model.checkout.PaymentsDetailsRequest; import com.adyen.model.checkout.PaymentsRequest; import com.adyen.model.modification.CancelOrRefundRequest; import com.adyen.model.modification.CaptureRequest; import com.adyen.model.modification.RefundRequest; import com.adyen.model.nexo.AmountsReq; import com.adyen.model.nexo.DocumentQualifierType; import com.adyen.model.nexo.MessageCategoryType; import com.adyen.model.nexo.MessageReference; import com.adyen.model.nexo.PaymentTransaction; import com.adyen.model.nexo.SaleData; import com.adyen.model.nexo.TransactionIdentification; import com.adyen.model.nexo.TransactionStatusRequest; import com.adyen.model.recurring.DisableRequest; import com.adyen.model.recurring.Recurring; import com.adyen.model.recurring.RecurringDetailsRequest; import com.adyen.model.terminal.SaleToAcquirerData; import com.adyen.model.terminal.TerminalAPIRequest; import com.adyen.v6.enums.AdyenCardTypeEnum; import com.adyen.v6.enums.RecurringContractMode; import com.adyen.v6.model.RequestInfo; import com.google.gson.Gson; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.commercefacades.order.data.OrderEntryData; import de.hybris.platform.commercefacades.user.data.AddressData; import de.hybris.platform.commercefacades.user.data.CountryData; import de.hybris.platform.commerceservices.enums.CustomerType; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.config.ConfigurationService; import de.hybris.platform.util.TaxValue; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Currency; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import static com.adyen.v6.constants.Adyenv6coreConstants.AFTERPAY; import static com.adyen.v6.constants.Adyenv6coreConstants.CARD_TYPE_DEBIT; import static com.adyen.v6.constants.Adyenv6coreConstants.ISSUER_PAYMENT_METHODS; import static com.adyen.v6.constants.Adyenv6coreConstants.KLARNA; import static com.adyen.v6.constants.Adyenv6coreConstants.OPENINVOICE_METHODS_API; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_FACILPAY_PREFIX; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PIX; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_SEPA_DIRECTDEBIT; import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_NAME; import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_VERSION; public class AdyenRequestFactory { private ConfigurationService configurationService; private static final Logger LOG = Logger.getLogger(AdyenRequestFactory.class); private static final String PLATFORM_NAME = "Hybris"; private static final String PLATFORM_VERSION_PROPERTY = "build.version.api"; private static final String IS_3DS2_ALLOWED_PROPERTY = "is3DS2allowed"; private static final String ALLOW_3DS2_PROPERTY = "allow3DS2"; private static final String OVERWRITE_BRAND_PROPERTY = "overwriteBrand"; private static final List<String> CVC_OPTIONAL_BRANDS = Arrays.asList(AdyenCardTypeEnum.BCMC.getCode(), AdyenCardTypeEnum.MAESTRO.getCode()); public PaymentRequest3d create3DAuthorizationRequest(final String merchantAccount, final HttpServletRequest request, final String md, final String paRes) { return createBasePaymentRequest(new PaymentRequest3d(), request, merchantAccount).set3DRequestData(md, paRes); } @Deprecated public PaymentRequest createAuthorizationRequest(final String merchantAccount, final CartData cartData, final HttpServletRequest request, final CustomerModel customerModel, final RecurringContractMode recurringContractMode) { String amount = String.valueOf(cartData.getTotalPrice().getValue()); String currency = cartData.getTotalPrice().getCurrencyIso(); String reference = cartData.getCode(); PaymentRequest paymentRequest = createBasePaymentRequest(new PaymentRequest(), request, merchantAccount).reference(reference).setAmountData(amount, currency); // set shopper details if (customerModel != null) { paymentRequest.setShopperReference(customerModel.getCustomerID()); paymentRequest.setShopperEmail(customerModel.getContactEmail()); } // set recurring contract if (customerModel != null && PAYMENT_METHOD_CC.equals(cartData.getAdyenPaymentMethod())) { Recurring recurring = getRecurringContractType(recurringContractMode, cartData.getAdyenRememberTheseDetails()); paymentRequest.setRecurring(recurring); } // if address details are provided added it into the request if (cartData.getDeliveryAddress() != null) { Address deliveryAddress = setAddressData(cartData.getDeliveryAddress()); paymentRequest.setDeliveryAddress(deliveryAddress); } if (cartData.getPaymentInfo().getBillingAddress() != null) { // set PhoneNumber if it is provided if (cartData.getPaymentInfo().getBillingAddress().getPhone() != null && ! cartData.getPaymentInfo().getBillingAddress().getPhone().isEmpty()) { paymentRequest.setTelephoneNumber(cartData.getPaymentInfo().getBillingAddress().getPhone()); } Address billingAddress = setAddressData(cartData.getPaymentInfo().getBillingAddress()); paymentRequest.setBillingAddress(billingAddress); } // OpenInvoice add required additional data if (OPENINVOICE_METHODS_API.contains(cartData.getAdyenPaymentMethod()) || PAYMENT_METHOD_PAYPAL.contains(cartData.getAdyenPaymentMethod())) { paymentRequest.selectedBrand(cartData.getAdyenPaymentMethod()); setOpenInvoiceData(paymentRequest, cartData, customerModel); paymentRequest.setShopperName(getShopperNameFromAddress(cartData.getDeliveryAddress())); } return paymentRequest; } public PaymentsDetailsRequest create3DPaymentsRequest(final String paymentData, final String md, final String paRes) { PaymentsDetailsRequest paymentsDetailsRequest = new PaymentsDetailsRequest(); paymentsDetailsRequest.set3DRequestData(md, paRes, paymentData); return paymentsDetailsRequest; } public PaymentsDetailsRequest create3DS2PaymentsRequest(final String paymentData, final String token, String type) { PaymentsDetailsRequest paymentsDetailsRequest = new PaymentsDetailsRequest(); if (type.equals("fingerprint")) { paymentsDetailsRequest.setFingerPrint(token, paymentData); } else if (type.equals("challenge")) { paymentsDetailsRequest.setChallengeResult(token, paymentData); } return paymentsDetailsRequest; } public PaymentsRequest createPaymentsRequest(final String merchantAccount, final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel, final RecurringContractMode recurringContractMode, final Boolean guestUserTokenizationEnabled) { PaymentsRequest paymentsRequest = new PaymentsRequest(); String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); if (adyenPaymentMethod == null) { throw new IllegalArgumentException("Payment method is null"); } //Update payment request for generic information for all payment method types updatePaymentRequest(merchantAccount, cartData, requestInfo, customerModel, paymentsRequest); Boolean is3DS2allowed = is3DS2Allowed(); //For credit cards if (PAYMENT_METHOD_CC.equals(adyenPaymentMethod)) { if (CARD_TYPE_DEBIT.equals(cartData.getAdyenCardType())) { updatePaymentRequestForDC(paymentsRequest, cartData, recurringContractMode); } else { updatePaymentRequestForCC(paymentsRequest, cartData, recurringContractMode); } if (is3DS2allowed) { paymentsRequest = enhanceForThreeDS2(paymentsRequest, cartData); } if (customerModel != null && customerModel.getType() == CustomerType.GUEST && guestUserTokenizationEnabled) { paymentsRequest.setEnableOneClick(false); } } //For one click else if (adyenPaymentMethod.indexOf(PAYMENT_METHOD_ONECLICK) == 0) { String selectedReference = cartData.getAdyenSelectedReference(); if (selectedReference != null && ! selectedReference.isEmpty()) { paymentsRequest.addOneClickData(selectedReference, cartData.getAdyenEncryptedSecurityCode()); String cardBrand = cartData.getAdyenCardBrand(); if (cardBrand != null && CVC_OPTIONAL_BRANDS.contains(cardBrand)) { DefaultPaymentMethodDetails paymentMethodDetails = (DefaultPaymentMethodDetails) (paymentsRequest.getPaymentMethod()); paymentMethodDetails.setType(cardBrand); paymentsRequest.setPaymentMethod(paymentMethodDetails); } } if (is3DS2allowed) { paymentsRequest = enhanceForThreeDS2(paymentsRequest, cartData); } } //Set Boleto parameters else if (cartData.getAdyenPaymentMethod().indexOf(PAYMENT_METHOD_BOLETO) == 0) { setBoletoData(paymentsRequest, cartData); } else if (PAYMENT_METHOD_SEPA_DIRECTDEBIT.equals(cartData.getAdyenPaymentMethod())) { setSepaDirectDebitData(paymentsRequest, cartData); } else if (PAYMENT_METHOD_PIX.equals(cartData.getAdyenPaymentMethod())) { setPixData(paymentsRequest, cartData); } //For alternate payment methods like iDeal, Paypal etc. else { updatePaymentRequestForAlternateMethod(paymentsRequest, cartData); } ApplicationInfo applicationInfo = updateApplicationInfoEcom(paymentsRequest.getApplicationInfo()); paymentsRequest.setApplicationInfo(applicationInfo); paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); paymentsRequest.setRedirectFromIssuerMethod(RequestMethod.POST.toString()); paymentsRequest.setRedirectToIssuerMethod(RequestMethod.POST.toString()); return paymentsRequest; } public PaymentsRequest createPaymentsRequest(final String merchantAccount, final CartData cartData, final PaymentMethodDetails paymentMethodDetails, final RequestInfo requestInfo, final CustomerModel customerModel) { PaymentsRequest paymentsRequest = new PaymentsRequest(); updatePaymentRequest(merchantAccount, cartData, requestInfo, customerModel, paymentsRequest); paymentsRequest.setPaymentMethod(paymentMethodDetails); paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); ApplicationInfo applicationInfo = updateApplicationInfoEcom(paymentsRequest.getApplicationInfo()); paymentsRequest.setApplicationInfo(applicationInfo); return paymentsRequest; } public PaymentsRequest enhanceForThreeDS2(PaymentsRequest paymentsRequest, CartData cartData) { if (paymentsRequest.getAdditionalData() == null) { paymentsRequest.setAdditionalData(new HashMap<>()); } paymentsRequest.getAdditionalData().put(ALLOW_3DS2_PROPERTY, is3DS2Allowed().toString()); paymentsRequest.setChannel(PaymentsRequest.ChannelEnum.WEB); BrowserInfo browserInfo = new Gson().fromJson(cartData.getAdyenBrowserInfo(), BrowserInfo.class); browserInfo = updateBrowserInfoFromRequest(browserInfo, paymentsRequest); paymentsRequest.setBrowserInfo(browserInfo); return paymentsRequest; } public BrowserInfo updateBrowserInfoFromRequest(BrowserInfo browserInfo, PaymentsRequest paymentsRequest) { if (browserInfo != null) { browserInfo.setUserAgent(paymentsRequest.getBrowserInfo().getUserAgent()); browserInfo.setAcceptHeader(paymentsRequest.getBrowserInfo().getAcceptHeader()); } return browserInfo; } public ApplicationInfo updateApplicationInfoEcom(ApplicationInfo applicationInfo) { updateApplicationInfoPos(applicationInfo); CommonField adyenPaymentSource = new CommonField(); adyenPaymentSource.setName(PLUGIN_NAME); adyenPaymentSource.setVersion(PLUGIN_VERSION); applicationInfo.setAdyenPaymentSource(adyenPaymentSource); return applicationInfo; } public ApplicationInfo updateApplicationInfoPos(ApplicationInfo applicationInfo) { if (applicationInfo == null) { applicationInfo = new ApplicationInfo(); } ExternalPlatform externalPlatform = new ExternalPlatform(); externalPlatform.setName(PLATFORM_NAME); externalPlatform.setVersion(getPlatformVersion()); applicationInfo.setExternalPlatform(externalPlatform); CommonField merchantApplication = new CommonField(); merchantApplication.setName(PLUGIN_NAME); merchantApplication.setVersion(PLUGIN_VERSION); applicationInfo.setMerchantApplication(merchantApplication); return applicationInfo; } private void updatePaymentRequest(final String merchantAccount, final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel, PaymentsRequest paymentsRequest) { //Get details from CartData to set in PaymentRequest. String amount = String.valueOf(cartData.getTotalPrice().getValue()); String currency = cartData.getTotalPrice().getCurrencyIso(); String reference = cartData.getCode(); AddressData billingAddress = cartData.getPaymentInfo() != null ? cartData.getPaymentInfo().getBillingAddress() : null; AddressData deliveryAddress = cartData.getDeliveryAddress(); //Get details from HttpServletRequest to set in PaymentRequest. String userAgent = requestInfo.getUserAgent(); String acceptHeader = requestInfo.getAcceptHeader(); String shopperIP = requestInfo.getShopperIp(); String origin = requestInfo.getOrigin(); String shopperLocale = requestInfo.getShopperLocale(); paymentsRequest.setAmountData(amount, currency) .reference(reference) .merchantAccount(merchantAccount) .addBrowserInfoData(userAgent, acceptHeader) .shopperIP(shopperIP) .origin(origin) .shopperLocale(shopperLocale) .setCountryCode(getCountryCode(cartData)); // set shopper details from CustomerModel. if (customerModel != null) { paymentsRequest.setShopperReference(customerModel.getCustomerID()); paymentsRequest.setShopperEmail(customerModel.getContactEmail()); } // if address details are provided, set it to the PaymentRequest if (deliveryAddress != null) { paymentsRequest.setDeliveryAddress(setAddressData(deliveryAddress)); } if (billingAddress != null) { paymentsRequest.setBillingAddress(setAddressData(billingAddress)); // set PhoneNumber if it is provided String phone = billingAddress.getPhone(); if (phone != null && ! phone.isEmpty()) { paymentsRequest.setTelephoneNumber(phone); } } } private void updatePaymentRequestForCC(PaymentsRequest paymentsRequest, CartData cartData, RecurringContractMode recurringContractMode) { Recurring recurringContract = getRecurringContractType(recurringContractMode); Recurring.ContractEnum contractEnum = null; if (recurringContract != null) { contractEnum = recurringContract.getContract(); } paymentsRequest.setEnableRecurring(false); paymentsRequest.setEnableOneClick(false); String encryptedCardNumber = cartData.getAdyenEncryptedCardNumber(); String encryptedExpiryMonth = cartData.getAdyenEncryptedExpiryMonth(); String encryptedExpiryYear = cartData.getAdyenEncryptedExpiryYear(); if (cartData.getAdyenInstallments() != null) { Installments installmentObj = new Installments(); installmentObj.setValue(cartData.getAdyenInstallments()); paymentsRequest.setInstallments(installmentObj); } if (! StringUtils.isEmpty(encryptedCardNumber) && ! StringUtils.isEmpty(encryptedExpiryMonth) && ! StringUtils.isEmpty(encryptedExpiryYear)) { paymentsRequest.addEncryptedCardData(encryptedCardNumber, encryptedExpiryMonth, encryptedExpiryYear, cartData.getAdyenEncryptedSecurityCode(), cartData.getAdyenCardHolder()); } if (Recurring.ContractEnum.ONECLICK_RECURRING == contractEnum) { paymentsRequest.setEnableRecurring(true); if(cartData.getAdyenRememberTheseDetails()) { paymentsRequest.setEnableOneClick(true); } } else if (Recurring.ContractEnum.ONECLICK == contractEnum && cartData.getAdyenRememberTheseDetails() ) { paymentsRequest.setEnableOneClick(true); } else if (Recurring.ContractEnum.RECURRING == contractEnum) { paymentsRequest.setEnableRecurring(true); } // Set storeDetails parameter when shopper selected to have his card details stored if (cartData.getAdyenRememberTheseDetails()) { DefaultPaymentMethodDetails paymentMethodDetails = (DefaultPaymentMethodDetails) paymentsRequest.getPaymentMethod(); paymentMethodDetails.setStoreDetails(true); } } private void updatePaymentRequestForDC(PaymentsRequest paymentsRequest, CartData cartData, RecurringContractMode recurringContractMode) { Recurring recurringContract = getRecurringContractType(recurringContractMode); Recurring.ContractEnum contractEnum = null; if (recurringContract != null) { contractEnum = recurringContract.getContract(); } paymentsRequest.setEnableRecurring(false); paymentsRequest.setEnableOneClick(false); String encryptedCardNumber = cartData.getAdyenEncryptedCardNumber(); String encryptedExpiryMonth = cartData.getAdyenEncryptedExpiryMonth(); String encryptedExpiryYear = cartData.getAdyenEncryptedExpiryYear(); if ((Recurring.ContractEnum.ONECLICK_RECURRING == contractEnum || Recurring.ContractEnum.ONECLICK == contractEnum) && cartData.getAdyenRememberTheseDetails()) { paymentsRequest.setEnableOneClick(true); } if (! StringUtils.isEmpty(encryptedCardNumber) && ! StringUtils.isEmpty(encryptedExpiryMonth) && ! StringUtils.isEmpty(encryptedExpiryYear)) { paymentsRequest.addEncryptedCardData(encryptedCardNumber, encryptedExpiryMonth, encryptedExpiryYear, cartData.getAdyenEncryptedSecurityCode(), cartData.getAdyenCardHolder()); } // Set storeDetails parameter when shopper selected to have his card details stored if (cartData.getAdyenRememberTheseDetails()) { DefaultPaymentMethodDetails paymentMethodDetails = (DefaultPaymentMethodDetails) paymentsRequest.getPaymentMethod(); paymentMethodDetails.setStoreDetails(true); } String cardBrand = cartData.getAdyenCardBrand(); paymentsRequest.putAdditionalDataItem(OVERWRITE_BRAND_PROPERTY, "true"); paymentsRequest.getPaymentMethod().setType(cardBrand); } private void updatePaymentRequestForAlternateMethod(PaymentsRequest paymentsRequest, CartData cartData) { String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); DefaultPaymentMethodDetails paymentMethod = new DefaultPaymentMethodDetails(); paymentsRequest.setPaymentMethod(paymentMethod); paymentMethod.setType(adyenPaymentMethod); paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); if (ISSUER_PAYMENT_METHODS.contains(adyenPaymentMethod)) { paymentMethod.setIssuer(cartData.getAdyenIssuerId()); } else if (adyenPaymentMethod.startsWith(KLARNA) || adyenPaymentMethod.startsWith(PAYMENT_METHOD_FACILPAY_PREFIX) || OPENINVOICE_METHODS_API.contains(adyenPaymentMethod)) { setOpenInvoiceData(paymentsRequest, cartData); } else if (adyenPaymentMethod.equals(PAYMENT_METHOD_PAYPAL) && cartData.getDeliveryAddress() != null) { Name shopperName = getShopperNameFromAddress(cartData.getDeliveryAddress()); paymentsRequest.setShopperName(shopperName); } } private String getCountryCode(CartData cartData) { //Identify country code based on shopper's delivery address String countryCode = ""; AddressData billingAddressData = cartData.getPaymentInfo() != null ? cartData.getPaymentInfo().getBillingAddress() : null; if (billingAddressData != null) { CountryData billingCountry = billingAddressData.getCountry(); if (billingCountry != null) { countryCode = billingCountry.getIsocode(); } } else { AddressData deliveryAddressData = cartData.getDeliveryAddress(); if (deliveryAddressData != null) { CountryData deliveryCountry = deliveryAddressData.getCountry(); if (deliveryCountry != null) { countryCode = deliveryCountry.getIsocode(); } } } return countryCode; } public CaptureRequest createCaptureRequest(final String merchantAccount, final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) { CaptureRequest request = new CaptureRequest().fillAmount(String.valueOf(amount), currency.getCurrencyCode()) .merchantAccount(merchantAccount) .originalReference(authReference) .reference(merchantReference); updateApplicationInfoEcom(request.getApplicationInfo()); return request; } public CancelOrRefundRequest createCancelOrRefundRequest(final String merchantAccount, final String authReference, final String merchantReference) { CancelOrRefundRequest request = new CancelOrRefundRequest().merchantAccount(merchantAccount).originalReference(authReference).reference(merchantReference); updateApplicationInfoEcom(request.getApplicationInfo()); return request; } public RefundRequest createRefundRequest(final String merchantAccount, final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) { RefundRequest request = new RefundRequest().fillAmount(String.valueOf(amount), currency.getCurrencyCode()) .merchantAccount(merchantAccount) .originalReference(authReference) .reference(merchantReference); updateApplicationInfoEcom(request.getApplicationInfo()); return request; } public RecurringDetailsRequest createListRecurringDetailsRequest(final String merchantAccount, final String customerId) { return new RecurringDetailsRequest().merchantAccount(merchantAccount).shopperReference(customerId).selectOneClickContract(); } /** * Creates a request to disable a recurring contract */ public DisableRequest createDisableRequest(final String merchantAccount, final String customerId, final String recurringReference) { return new DisableRequest().merchantAccount(merchantAccount).shopperReference(customerId).recurringDetailReference(recurringReference); } private <T extends AbstractPaymentRequest> T createBasePaymentRequest(T abstractPaymentRequest, HttpServletRequest request, final String merchantAccount) { String userAgent = request.getHeader("User-Agent"); String acceptHeader = request.getHeader("Accept"); String shopperIP = request.getRemoteAddr(); abstractPaymentRequest.merchantAccount(merchantAccount).setBrowserInfoData(userAgent, acceptHeader).shopperIP(shopperIP); return abstractPaymentRequest; } public TerminalAPIRequest createTerminalAPIRequestForStatus(final CartData cartData, String originalServiceId) { TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest(); transactionStatusRequest.setReceiptReprintFlag(true); MessageReference messageReference = new MessageReference(); messageReference.setMessageCategory(MessageCategoryType.PAYMENT); messageReference.setSaleID(cartData.getStore()); messageReference.setServiceID(originalServiceId); transactionStatusRequest.setMessageReference(messageReference); transactionStatusRequest.getDocumentQualifier().add(DocumentQualifierType.CASHIER_RECEIPT); transactionStatusRequest.getDocumentQualifier().add(DocumentQualifierType.CUSTOMER_RECEIPT); String serviceId = Long.toString(System.currentTimeMillis() % 10000000000L); TerminalAPIRequestBuilder builder = new TerminalAPIRequestBuilder(cartData.getStore(), serviceId, cartData.getAdyenTerminalId()); builder.withTransactionStatusRequest(transactionStatusRequest); return builder.build(); } public TerminalAPIRequest createTerminalAPIRequest(final CartData cartData, CustomerModel customer, RecurringContractMode recurringContractMode, String serviceId) throws Exception { com.adyen.model.nexo.PaymentRequest paymentRequest = new com.adyen.model.nexo.PaymentRequest(); SaleData saleData = new SaleData(); TransactionIdentification transactionIdentification = new TransactionIdentification(); transactionIdentification.setTransactionID(cartData.getCode()); XMLGregorianCalendar timestamp = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()); transactionIdentification.setTimeStamp(timestamp); saleData.setSaleTransactionID(transactionIdentification); //Set recurring contract, if exists if(customer != null) { String shopperReference = customer.getCustomerID(); String shopperEmail = customer.getContactEmail(); Recurring recurringContract = getRecurringContractType(recurringContractMode); SaleToAcquirerData saleToAcquirerData = new SaleToAcquirerData(); if (recurringContract != null && StringUtils.isNotEmpty(shopperReference) && StringUtils.isNotEmpty(shopperEmail)) { saleToAcquirerData.setShopperEmail(shopperEmail); saleToAcquirerData.setShopperReference(shopperReference); saleToAcquirerData.setRecurringContract(recurringContract.getContract().toString()); } updateApplicationInfoPos(saleToAcquirerData.getApplicationInfo()); saleData.setSaleToAcquirerData(saleToAcquirerData); } paymentRequest.setSaleData(saleData); PaymentTransaction paymentTransaction = new PaymentTransaction(); AmountsReq amountsReq = new AmountsReq(); amountsReq.setCurrency(cartData.getTotalPrice().getCurrencyIso()); amountsReq.setRequestedAmount(cartData.getTotalPrice().getValue()); paymentTransaction.setAmountsReq(amountsReq); paymentRequest.setPaymentTransaction(paymentTransaction); TerminalAPIRequestBuilder builder = new TerminalAPIRequestBuilder(cartData.getStore(), serviceId, cartData.getAdyenTerminalId()); builder.withPaymentRequest(paymentRequest); return builder.build(); } /** * Set Address Data into API */ private Address setAddressData(AddressData addressData) { Address address = new Address(); // set defaults because all fields are required into the API address.setCity("NA"); address.setCountry("NA"); address.setHouseNumberOrName("NA"); address.setPostalCode("NA"); address.setStateOrProvince("NA"); address.setStreet("NA"); // set the actual values if they are available if (addressData.getTown() != null && ! addressData.getTown().isEmpty()) { address.setCity(addressData.getTown()); } if (addressData.getCountry() != null && ! addressData.getCountry().getIsocode().isEmpty()) { address.setCountry(addressData.getCountry().getIsocode()); } if (addressData.getLine1() != null && ! addressData.getLine1().isEmpty()) { address.setStreet(addressData.getLine1()); } if (addressData.getLine2() != null && ! addressData.getLine2().isEmpty()) { address.setHouseNumberOrName(addressData.getLine2()); } if (addressData.getPostalCode() != null && ! address.getPostalCode().isEmpty()) { address.setPostalCode(addressData.getPostalCode()); } //State value will be updated later for boleto in boleto specific method. if (addressData.getRegion() != null && StringUtils.isNotEmpty(addressData.getRegion().getIsocodeShort())) { address.setStateOrProvince(addressData.getRegion().getIsocodeShort()); } else if (addressData.getRegion() != null && StringUtils.isNotEmpty(addressData.getRegion().getIsocode())) { address.setStateOrProvince(addressData.getRegion().getIsocode()); } return address; } /** * Return Recurring object from RecurringContractMode */ private Recurring getRecurringContractType(RecurringContractMode recurringContractMode) { Recurring recurringContract = new Recurring(); //If recurring contract is disabled, return null if (recurringContractMode == null || RecurringContractMode.NONE.equals(recurringContractMode)) { return null; } String recurringMode = recurringContractMode.getCode(); Recurring.ContractEnum contractEnum = Recurring.ContractEnum.valueOf(recurringMode); recurringContract.contract(contractEnum); return recurringContract; } /** * Return the recurringContract. If the user did not want to save the card don't send it as ONECLICK */ private Recurring getRecurringContractType(RecurringContractMode recurringContractMode, final Boolean enableOneClick) { Recurring recurringContract = getRecurringContractType(recurringContractMode); //If recurring contract is disabled, return null if (recurringContract == null) { return null; } // if user want to save his card use the configured recurring contract type if (enableOneClick != null && enableOneClick) { return recurringContract; } Recurring.ContractEnum contractEnum = recurringContract.getContract(); /* * If save card is not checked do the folllowing changes: * NONE => NONE * ONECLICK => NONE * ONECLICK,RECURRING => RECURRING * RECURRING => RECURRING */ if (Recurring.ContractEnum.ONECLICK_RECURRING.equals(contractEnum) || Recurring.ContractEnum.RECURRING.equals(contractEnum)) { return recurringContract.contract(Recurring.ContractEnum.RECURRING); } return null; } /** * Get shopper name and gender */ private Name getShopperNameFromAddress(AddressData addressData) { Name shopperName = new Name(); shopperName.setFirstName(addressData.getFirstName()); shopperName.setLastName(addressData.getLastName()); shopperName.setGender(Name.GenderEnum.UNKNOWN); if (addressData.getTitleCode() != null && ! addressData.getTitleCode().isEmpty()) { if (addressData.getTitleCode().equals("mrs") || addressData.getTitleCode().equals("miss") || addressData.getTitleCode().equals("ms")) { shopperName.setGender(Name.GenderEnum.FEMALE); } else { shopperName.setGender(Name.GenderEnum.MALE); } } return shopperName; } /** * Set the required fields for using the OpenInvoice API * <p> * To deprecate when RatePay is natively implemented */ public void setOpenInvoiceData(PaymentRequest paymentRequest, CartData cartData, final CustomerModel customerModel) { // set date of birth if (cartData.getAdyenDob() != null) { paymentRequest.setDateOfBirth(cartData.getAdyenDob()); } if (cartData.getAdyenSocialSecurityNumber() != null && ! cartData.getAdyenSocialSecurityNumber().isEmpty()) { paymentRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); } if (cartData.getAdyenDfValue() != null && ! cartData.getAdyenDfValue().isEmpty()) { paymentRequest.setDeviceFingerprint(cartData.getAdyenDfValue()); } // set the invoice lines List<InvoiceLine> invoiceLines = new ArrayList(); String currency = cartData.getTotalPrice().getCurrencyIso(); for (OrderEntryData entry : cartData.getEntries()) { // Use totalPrice because the basePrice does include tax as well if you have configured this to be calculated in the price BigDecimal pricePerItem = entry.getTotalPrice().getValue().divide(new BigDecimal(entry.getQuantity())); String description = "NA"; if (entry.getProduct().getName() != null && ! entry.getProduct().getName().equals("")) { description = entry.getProduct().getName(); } // Tax of total price (included quantity) Double tax = entry.getTaxValues().stream().map(taxValue -> taxValue.getAppliedValue()).reduce(0.0, (x, y) -> x = x + y); // Calculate Tax per quantitiy if (tax > 0) { tax = tax / entry.getQuantity().intValue(); } // Calculate price without tax Amount itemAmountWithoutTax = Util.createAmount(pricePerItem.subtract(new BigDecimal(tax)), currency); Double percentage = entry.getTaxValues().stream().map(taxValue -> taxValue.getValue()).reduce(0.0, (x, y) -> x = x + y) * 100; InvoiceLine invoiceLine = new InvoiceLine(); invoiceLine.setCurrencyCode(currency); invoiceLine.setDescription(description); /* * The price for one item in the invoice line, represented in minor units. * The due amount for the item, VAT excluded. */ invoiceLine.setItemAmount(itemAmountWithoutTax.getValue()); // The VAT due for one item in the invoice line, represented in minor units. invoiceLine.setItemVATAmount(Util.createAmount(BigDecimal.valueOf(tax), currency).getValue()); // The VAT percentage for one item in the invoice line, represented in minor units. invoiceLine.setItemVatPercentage(percentage.longValue()); // The country-specific VAT category a product falls under. Allowed values: (High,Low,None) invoiceLine.setVatCategory(VatCategory.NONE); // An unique id for this item. Required for RatePay if the description of each item is not unique. if (! entry.getProduct().getCode().isEmpty()) { invoiceLine.setItemId(entry.getProduct().getCode()); } invoiceLine.setNumberOfItems(entry.getQuantity().intValue()); if (entry.getProduct() != null && ! entry.getProduct().getCode().isEmpty()) { invoiceLine.setItemId(entry.getProduct().getCode()); } if (entry.getProduct() != null && ! entry.getProduct().getCode().isEmpty()) { invoiceLine.setItemId(entry.getProduct().getCode()); } LOG.debug("InvoiceLine Product:" + invoiceLine.toString()); invoiceLines.add(invoiceLine); } // Add delivery costs if (cartData.getDeliveryCost() != null) { InvoiceLine invoiceLine = new InvoiceLine(); invoiceLine.setCurrencyCode(currency); invoiceLine.setDescription("Delivery Costs"); Amount deliveryAmount = Util.createAmount(cartData.getDeliveryCost().getValue().toString(), currency); invoiceLine.setItemAmount(deliveryAmount.getValue()); invoiceLine.setItemVATAmount(new Long("0")); invoiceLine.setItemVatPercentage(new Long("0")); invoiceLine.setVatCategory(VatCategory.NONE); invoiceLine.setNumberOfItems(1); LOG.debug("InvoiceLine DeliveryCosts:" + invoiceLine.toString()); invoiceLines.add(invoiceLine); } paymentRequest.setInvoiceLines(invoiceLines); } /* * Set the required fields for using the OpenInvoice API */ public void setOpenInvoiceData(PaymentsRequest paymentsRequest, CartData cartData) { paymentsRequest.setShopperName(getShopperNameFromAddress(cartData.getDeliveryAddress())); // set date of birth if (cartData.getAdyenDob() != null) { paymentsRequest.setDateOfBirth(cartData.getAdyenDob()); } if (cartData.getAdyenSocialSecurityNumber() != null && ! cartData.getAdyenSocialSecurityNumber().isEmpty()) { paymentsRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); } if (cartData.getAdyenDfValue() != null && ! cartData.getAdyenDfValue().isEmpty()) { paymentsRequest.setDeviceFingerprint(cartData.getAdyenDfValue()); } if (AFTERPAY.equals(cartData.getAdyenPaymentMethod())) { paymentsRequest.setShopperEmail(cartData.getAdyenShopperEmail()); paymentsRequest.setTelephoneNumber(cartData.getAdyenShopperTelephone()); paymentsRequest.setShopperName(getAfterPayShopperName(cartData)); } // set the invoice lines List<LineItem> invoiceLines = new ArrayList<>(); String currency = cartData.getTotalPrice().getCurrencyIso(); for (OrderEntryData entry : cartData.getEntries()) { if (entry.getQuantity() == 0L) { // skip zero quantities continue; } // Use totalPrice because the basePrice does include tax as well if you have configured this to be calculated in the price BigDecimal pricePerItem = entry.getTotalPrice().getValue().divide(new BigDecimal(entry.getQuantity())); String description = "NA"; if (entry.getProduct().getName() != null && ! entry.getProduct().getName().isEmpty()) { description = entry.getProduct().getName(); } // Tax of total price (included quantity) Double tax = entry.getTaxValues().stream().map(TaxValue::getAppliedValue).reduce(0.0, (x, y) -> x + y); // Calculate Tax per quantitiy if (tax > 0) { tax = tax / entry.getQuantity().intValue(); } // Calculate price without tax Amount itemAmountWithoutTax = Util.createAmount(pricePerItem.subtract(new BigDecimal(tax)), currency); Double percentage = entry.getTaxValues().stream().map(TaxValue::getValue).reduce(0.0, (x, y) -> x + y) * 100; LineItem invoiceLine = new LineItem(); invoiceLine.setDescription(description); /* * The price for one item in the invoice line, represented in minor units. * The due amount for the item, VAT excluded. */ invoiceLine.setAmountExcludingTax(itemAmountWithoutTax.getValue()); // The VAT due for one item in the invoice line, represented in minor units. invoiceLine.setTaxAmount(Util.createAmount(BigDecimal.valueOf(tax), currency).getValue()); // The VAT percentage for one item in the invoice line, represented in minor units. invoiceLine.setTaxPercentage(percentage.longValue()); // The country-specific VAT category a product falls under. Allowed values: (High,Low,None) invoiceLine.setTaxCategory(LineItem.TaxCategoryEnum.NONE); invoiceLine.setQuantity(entry.getQuantity()); if (entry.getProduct() != null && ! entry.getProduct().getCode().isEmpty()) { invoiceLine.setId(entry.getProduct().getCode()); } LOG.debug("InvoiceLine Product:" + invoiceLine.toString()); invoiceLines.add(invoiceLine); } // Add delivery costs if (cartData.getDeliveryCost() != null) { LineItem invoiceLine = new LineItem(); invoiceLine.setDescription("Delivery Costs"); Amount deliveryAmount = Util.createAmount(cartData.getDeliveryCost().getValue().toString(), currency); invoiceLine.setAmountExcludingTax(deliveryAmount.getValue()); invoiceLine.setTaxAmount(new Long("0")); invoiceLine.setTaxPercentage(new Long("0")); invoiceLine.setTaxCategory(LineItem.TaxCategoryEnum.NONE); invoiceLine.setQuantity(1L); LOG.debug("InvoiceLine DeliveryCosts:" + invoiceLine.toString()); invoiceLines.add(invoiceLine); } paymentsRequest.setLineItems(invoiceLines); } private Name getAfterPayShopperName(CartData cartData) { Name name = new Name(); name.setFirstName(cartData.getAdyenFirstName()); name.setLastName(cartData.getAdyenLastName()); name.gender(Name.GenderEnum.valueOf(cartData.getAdyenShopperGender())); return name; } /** * Set Boleto payment request data */ private void setBoletoData(PaymentsRequest paymentsRequest, CartData cartData) { DefaultPaymentMethodDetails paymentMethodDetails = (DefaultPaymentMethodDetails) (paymentsRequest.getPaymentMethod()); if (paymentMethodDetails == null) { paymentMethodDetails = new DefaultPaymentMethodDetails(); } paymentMethodDetails.setType(PAYMENT_METHOD_BOLETO_SANTANDER); paymentsRequest.setPaymentMethod(paymentMethodDetails); paymentsRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); Name shopperName = new Name(); shopperName.setFirstName(cartData.getAdyenFirstName()); shopperName.setLastName(cartData.getAdyenLastName()); paymentsRequest.setShopperName(shopperName); if (paymentsRequest.getBillingAddress() != null) { String stateOrProvinceBilling = paymentsRequest.getBillingAddress().getStateOrProvince(); if (! StringUtils.isEmpty(stateOrProvinceBilling) && stateOrProvinceBilling.length() > 2) { String shortStateOrProvince = stateOrProvinceBilling.substring(stateOrProvinceBilling.length() - 2); paymentsRequest.getBillingAddress().setStateOrProvince(shortStateOrProvince); } } if (paymentsRequest.getDeliveryAddress() != null) { String stateOrProvinceDelivery = paymentsRequest.getDeliveryAddress().getStateOrProvince(); if (! StringUtils.isEmpty(stateOrProvinceDelivery) && stateOrProvinceDelivery.length() > 2) { String shortStateOrProvince = stateOrProvinceDelivery.substring(stateOrProvinceDelivery.length() - 2); paymentsRequest.getDeliveryAddress().setStateOrProvince(shortStateOrProvince); } } } private void setSepaDirectDebitData(PaymentsRequest paymentRequest, CartData cartData) { DefaultPaymentMethodDetails paymentMethodDetails = new DefaultPaymentMethodDetails(); paymentMethodDetails.setSepaOwnerName(cartData.getAdyenSepaOwnerName()); paymentMethodDetails.setSepaIbanNumber(cartData.getAdyenSepaIbanNumber()); paymentMethodDetails.setType(PAYMENT_METHOD_SEPA_DIRECTDEBIT); paymentRequest.setPaymentMethod(paymentMethodDetails); } private void setPixData(PaymentsRequest paymentsRequest, CartData cartData) { Name shopperName = new Name(); shopperName.setFirstName(cartData.getAdyenFirstName()); shopperName.setLastName(cartData.getAdyenLastName()); paymentsRequest.setShopperName(shopperName); paymentsRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); } private String getPlatformVersion() { return getConfigurationService().getConfiguration().getString(PLATFORM_VERSION_PROPERTY); } private Boolean is3DS2Allowed() { Configuration configuration = getConfigurationService().getConfiguration(); boolean is3DS2AllowedValue = false; if (configuration.containsKey(IS_3DS2_ALLOWED_PROPERTY)) { is3DS2AllowedValue = configuration.getBoolean(IS_3DS2_ALLOWED_PROPERTY); } return is3DS2AllowedValue; } public ConfigurationService getConfigurationService() { return configurationService; } public void setConfigurationService(ConfigurationService configurationService) { this.configurationService = configurationService; } }
PW-4089 Added line item in the payment request.
adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java
PW-4089 Added line item in the payment request.
Java
mit
ea45d42fc7afa5f0b40a7e774a58c0545492ee55
0
simplyianm/albkit
package pw.ian.albkit; import pw.ian.albkit.command.CommandHandler; import pw.ian.albkit.command.Commands; import org.bukkit.Server; import org.bukkit.event.Listener; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.ServicesManager; import org.bukkit.plugin.java.JavaPlugin; /** * A base plugin class which makes creating new plugins more convenient, as it * removes the necessity to initialise server, plugin manager and services * manager variables as well as providing an easy way to register listeners * * @author Ollie */ public abstract class AlbPlugin extends JavaPlugin { protected Server server; protected PluginManager pluginMgr; protected ServicesManager servicesMgr; public abstract void onEnable(); /** * Initialises variables etc for this plugin. Should be called at the start * of the onEnable() implementation in extensions of this class */ protected void init() { server = getServer(); pluginMgr = server.getPluginManager(); servicesMgr = server.getServicesManager(); } /** * Registers the given listener to this JavaPlugin object * * @param listener The Listener to register */ protected void register(final Listener listener) { pluginMgr.registerEvents(listener, this); } /** * Registers the given CommandHandler to a command with the given name * * @param name The name to register the command to * @param handler The CommandHandler to register for the command */ protected void register(final String name, final CommandHandler handler) { Commands.registerCommand(this, name, handler); } /** * Registers the given CommandHandler * * @param handler The CommandHandler to register */ protected void register(final CommandHandler handler) { register(handler.getName(), handler); } }
src/main/java/pw/ian/albkit/AlbPlugin.java
package pw.ian.albkit; import org.bukkit.Server; import org.bukkit.event.Listener; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.ServicesManager; import org.bukkit.plugin.java.JavaPlugin; /** * A base plugin class which makes creating new plugins more convenient, as it * removes the necessity to initialise server, plugin manager and services * manager variables as well as providing an easy way to register listeners * * @author Ollie */ public abstract class AlbPlugin extends JavaPlugin { protected Server server; protected PluginManager pluginMgr; protected ServicesManager servicesMgr; public abstract void onEnable(); /** * Initialises variables etc for this plugin. Should be called at the start * of the onEnable() implementation in extensions of this class */ protected void init() { server = getServer(); pluginMgr = server.getPluginManager(); servicesMgr = server.getServicesManager(); } /** * Registers the given listener to this JavaPlugin object * * @param listener The Listener to register */ protected void register(final Listener listener) { pluginMgr.registerEvents(listener, this); } }
Add utility command registration methods
src/main/java/pw/ian/albkit/AlbPlugin.java
Add utility command registration methods
Java
mit
e9813bd3379dac4b1af6c135e948bbac2e432c29
0
ajohnston9/ciscorouter
package ciscoroutertool.gui; import ciscoroutertool.config.ConfigurationManager; import ciscoroutertool.scanner.FullReport; import ciscoroutertool.scanner.ScanManager; import ciscoroutertool.settings.SettingsManager; import ciscoroutertool.utils.Host; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import java.io.File; import java.util.ArrayList; import java.util.Vector; /** * Runs the Main GUI and acts as a portal to the rest of the application * @version 0.01ALPHA * @author Andrew H. Johnston */ public class MainGUI extends javax.swing.JFrame implements ScanLauncherParent { /** * Default Serial ID */ private static final long serialVersionUID = 1L; /** * Filter that will only show configuration (XML) files in the open dialog. */ private final FileNameExtensionFilter filter = new FileNameExtensionFilter("Configuration File", "xml"); /** * The file dialog used to open/save files */ private final JFileChooser fc = new JFileChooser(); /** * The object that allows the app to access and store settings */ public final static SettingsManager settingsManager = new SettingsManager(); /** * The "Please Wait" dialog that displays while scanning */ private final ScanningDialog scanning = new ScanningDialog(); /** * The list of hosts to be scanned */ private static final ArrayList<Host> hosts = new ArrayList<>(); /** * The current row of the table we are filling */ private int currentRow = 0; /** * Creates new form MainGUI */ public MainGUI() { initComponents(); System.out.println(System.getProperty("user.dir")); fc.setFileFilter(filter); if (settingsManager.requiresAuth()) { AuthDialog auth = new AuthDialog(); auth.setVisible(true); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); currentConfTable = new javax.swing.JTable(); lblConfTable = new javax.swing.JLabel(); btnAddDevice = new javax.swing.JButton(); btnRunScan = new javax.swing.JToggleButton(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); menuOpenConfig = new javax.swing.JMenuItem(); menuSaveConfig = new javax.swing.JMenuItem(); menuRunScan = new javax.swing.JMenuItem(); menuClose = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); menuAddDevice = new javax.swing.JMenuItem(); menuSecurityChange = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Crest Security Cisco Router Testing Tool"); currentConfTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Scan", "IP Address", "Scan Type" } ) { Class[] types = new Class [] { java.lang.Boolean.class, java.lang.Object.class, java.lang.Object.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); currentConfTable.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(currentConfTable); if (currentConfTable.getColumnModel().getColumnCount() > 0) { currentConfTable.getColumnModel().getColumn(0).setMinWidth(80); currentConfTable.getColumnModel().getColumn(0).setPreferredWidth(80); currentConfTable.getColumnModel().getColumn(0).setMaxWidth(80); } lblConfTable.setText("Current Configuration: "); btnAddDevice.setText("Add New Device..."); btnAddDevice.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddDeviceActionPerformed(evt); } }); btnRunScan.setText("Run Scan..."); btnRunScan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRunScanActionPerformed(evt); } }); fileMenu.setText("File"); menuOpenConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); menuOpenConfig.setText("Open..."); menuOpenConfig.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuOpenConfigActionPerformed(evt); } }); fileMenu.add(menuOpenConfig); menuSaveConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); menuSaveConfig.setText("Save..."); menuSaveConfig.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuSaveConfigActionPerformed(evt); } }); fileMenu.add(menuSaveConfig); menuRunScan.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK)); menuRunScan.setText("Run"); fileMenu.add(menuRunScan); menuClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK)); menuClose.setText("Close..."); menuClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuCloseActionPerformed(evt); } }); fileMenu.add(menuClose); menuBar.add(fileMenu); editMenu.setText("Edit"); menuAddDevice.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); menuAddDevice.setText("Add a Device.."); menuAddDevice.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuAddDeviceActionPerformed(evt); } }); editMenu.add(menuAddDevice); menuSecurityChange.setText("Enable/Disable Security"); menuSecurityChange.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuSecurityChangeActionPerformed(evt); } }); editMenu.add(menuSecurityChange); menuBar.add(editMenu); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 649, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblConfTable, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(btnAddDevice) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnRunScan))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(lblConfTable, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddDevice) .addComponent(btnRunScan)) .addContainerGap(143, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Handles the opening of previously saved scanning configurations * @param evt The ActionEvent object with relevant data */ private void menuOpenConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuOpenConfigActionPerformed int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); ConfigurationManager manager = new ConfigurationManager(f); ArrayList<Host> configHosts = manager.getAllHosts(); hosts.addAll(configHosts); for(Host h : hosts) { this.updateTable(h); } } }//GEN-LAST:event_menuOpenConfigActionPerformed /** * Show the box that allows for the setting of a password * @param evt The ActionEvent object with relevant data */ private void menuSecurityChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuSecurityChangeActionPerformed SecurityDialog secDialog = new SecurityDialog(); secDialog.setVisible(true); }//GEN-LAST:event_menuSecurityChangeActionPerformed /** * Allows the user to close the application * @param evt The ActionEvent object with relevant data */ private void menuCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCloseActionPerformed int confirm = JOptionPane.showConfirmDialog(this, "Are you sure you'd like to quit?", "Quit the Application", JOptionPane.YES_NO_OPTION); if (confirm == JOptionPane.YES_OPTION) { System.exit(0); } //Otherwise do nothing }//GEN-LAST:event_menuCloseActionPerformed /** * Opens the window to allow a new device to be added to the current scan * configuration. * @param evt The ActionEvent object with relevant data */ private void menuAddDeviceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuAddDeviceActionPerformed this.openNewDeviceDialog(); }//GEN-LAST:event_menuAddDeviceActionPerformed /** * Opens the window to allow a new device to be added to the current scan * configuration. * @param evt The ActionEvent object with relevant data */ private void btnAddDeviceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddDeviceActionPerformed this.openNewDeviceDialog(); }//GEN-LAST:event_btnAddDeviceActionPerformed /** * Opens the new device dialog with all relevant parameters */ private void openNewDeviceDialog() { NewDeviceDialog device = new NewDeviceDialog(this); device.setVisible(true); } /** * Runs a scan on the selected hosts. * @param evt The ActionEvent object with relevant data */ private void btnRunScanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRunScanActionPerformed if (hosts.size() < 1) { JOptionPane.showMessageDialog(this, "Please enter at least one host."); } else { scanning.setVisible(true); ScanManager manager = new ScanManager(hosts); ScanLauncher launcher = new ScanLauncher(this, manager); launcher.execute(); } }//GEN-LAST:event_btnRunScanActionPerformed /** * Allows the user to save the current configuration from the file * @param evt The ActionEvent object with relevant data */ private void menuSaveConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuSaveConfigActionPerformed int returnCode = fc.showSaveDialog(this); if (returnCode == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String filename = file.getName(); //Make sure the filename ends in .xml if (!filename.matches("(.*)\\.xml$")) { filename = filename + ".xml"; file = new File(filename); } ConfigurationManager config = new ConfigurationManager(file); for (Host h : hosts) { config.addHost(h); } JOptionPane.showMessageDialog(this, "File Saved Successfully!", "Save Successful", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_menuSaveConfigActionPerformed /** * Shows the Output window (called after the scan is completed) * @param report The Full Report on all hosts */ public void displayReport(FullReport report) { OutputReview output = new OutputReview(report); output.setVisible(true); } /** * Starts the application * @param args the command line arguments */ @SuppressWarnings("TryWithIdenticalCatches") public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainGUI().setVisible(true); } }); } /** * Adds a host to be scanned into the JTable and to the ArrayList. Note that * the JTable is merely for presentation, the ArrayList holds the actual * data. * @param h The host to add to the table */ public void updateTable(Host h) { final int ROWS_BY_DEFAULT = 4; hosts.add(h); DefaultTableModel model = (DefaultTableModel) currentConfTable.getModel(); String hosts = h.toString(); //We have four rows by default if (currentRow >= ROWS_BY_DEFAULT) { Vector v = new Vector(); model.addRow(v); } int rowToFill = currentRow; currentConfTable.setValueAt(true, rowToFill, 0); currentConfTable.setValueAt(hosts, rowToFill, 1); currentConfTable.setValueAt("Full Scan", rowToFill, 2); currentRow++; } /** * Returns a "cleaned" version of the hostname * @return Just the IP address of a hostname */ private String getCleanHostname(Host h) { String hosts = h.getAddress().toString(); int c = hosts.indexOf("/"); hosts = hosts.substring((c + 1)); return hosts; } /** * Shows the "Please Wait" Dialog while the scan runs. */ @Override public void showPleaseWaitDialog() { scanning.setVisible(true); } /** * Removes the "Please Wait" Dialog once the scan is finished. */ @Override public void disposePleaseWaitDialog() { scanning.dispose(); } /** * Returns a list of hosts to be scanned (factoring in the checkboxes) * @return A list of hosts that are "checked" and should be scanned */ public ArrayList<Host> getHostsToScan() { ArrayList<Host> toScan = new ArrayList<>(); DefaultTableModel tableModel = (DefaultTableModel) currentConfTable.getModel(); int numRows = tableModel.getRowCount(); for (int i = 0; i < numRows; i++) { //If the host is unchecked if (!((boolean)tableModel.getValueAt(i, 0))) { continue; //Don't bother processing it } String guiHostname = (String) tableModel.getValueAt(i,1); for (Host h : hosts) { String hostname = h.toString(); if (hostname.compareTo(guiHostname) == 0) { toScan.add(h); } } } return toScan; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddDevice; private javax.swing.JToggleButton btnRunScan; private static javax.swing.JTable currentConfTable; private javax.swing.JMenu editMenu; private javax.swing.JMenu fileMenu; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblConfTable; private javax.swing.JMenuItem menuAddDevice; private javax.swing.JMenuBar menuBar; private javax.swing.JMenuItem menuClose; private javax.swing.JMenuItem menuOpenConfig; private javax.swing.JMenuItem menuRunScan; private javax.swing.JMenuItem menuSaveConfig; private javax.swing.JMenuItem menuSecurityChange; // End of variables declaration//GEN-END:variables }
CiscoRouterTool/src/ciscoroutertool/gui/MainGUI.java
package ciscoroutertool.gui; import ciscoroutertool.config.ConfigurationManager; import ciscoroutertool.scanner.FullReport; import ciscoroutertool.scanner.ScanManager; import ciscoroutertool.settings.SettingsManager; import ciscoroutertool.utils.Host; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import java.io.File; import java.util.ArrayList; import java.util.Vector; /** * Runs the Main GUI and acts as a portal to the rest of the application * @version 0.01ALPHA * @author Andrew H. Johnston */ public class MainGUI extends javax.swing.JFrame implements ScanLauncherParent { /** * Default Serial ID */ private static final long serialVersionUID = 1L; /** * Filter that will only show configuration (XML) files in the open dialog. */ private final FileNameExtensionFilter filter = new FileNameExtensionFilter("Configuration File", "xml"); /** * The file dialog used to open/save files */ private final JFileChooser fc = new JFileChooser(); /** * The object that allows the app to access and store settings */ public final static SettingsManager settingsManager = new SettingsManager(); /** * The "Please Wait" dialog that displays while scanning */ private final ScanningDialog scanning = new ScanningDialog(); /** * The list of hosts to be scanned */ private static final ArrayList<Host> hosts = new ArrayList<>(); /** * The current row of the table we are filling */ private int currentRow = 0; /** * Creates new form MainGUI */ public MainGUI() { initComponents(); fc.setFileFilter(filter); if (settingsManager.requiresAuth()) { AuthDialog auth = new AuthDialog(); auth.setVisible(true); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); currentConfTable = new javax.swing.JTable(); lblConfTable = new javax.swing.JLabel(); btnAddDevice = new javax.swing.JButton(); btnRunScan = new javax.swing.JToggleButton(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); menuOpenConfig = new javax.swing.JMenuItem(); menuSaveConfig = new javax.swing.JMenuItem(); menuRunScan = new javax.swing.JMenuItem(); menuClose = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); menuAddDevice = new javax.swing.JMenuItem(); menuSecurityChange = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Crest Security Cisco Router Testing Tool"); currentConfTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Scan", "IP Address", "Scan Type" } ) { Class[] types = new Class [] { java.lang.Boolean.class, java.lang.Object.class, java.lang.Object.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); currentConfTable.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(currentConfTable); if (currentConfTable.getColumnModel().getColumnCount() > 0) { currentConfTable.getColumnModel().getColumn(0).setMinWidth(80); currentConfTable.getColumnModel().getColumn(0).setPreferredWidth(80); currentConfTable.getColumnModel().getColumn(0).setMaxWidth(80); } lblConfTable.setText("Current Configuration: "); btnAddDevice.setText("Add New Device..."); btnAddDevice.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddDeviceActionPerformed(evt); } }); btnRunScan.setText("Run Scan..."); btnRunScan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRunScanActionPerformed(evt); } }); fileMenu.setText("File"); menuOpenConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); menuOpenConfig.setText("Open..."); menuOpenConfig.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuOpenConfigActionPerformed(evt); } }); fileMenu.add(menuOpenConfig); menuSaveConfig.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); menuSaveConfig.setText("Save..."); menuSaveConfig.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuSaveConfigActionPerformed(evt); } }); fileMenu.add(menuSaveConfig); menuRunScan.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK)); menuRunScan.setText("Run"); fileMenu.add(menuRunScan); menuClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK)); menuClose.setText("Close..."); menuClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuCloseActionPerformed(evt); } }); fileMenu.add(menuClose); menuBar.add(fileMenu); editMenu.setText("Edit"); menuAddDevice.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); menuAddDevice.setText("Add a Device.."); menuAddDevice.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuAddDeviceActionPerformed(evt); } }); editMenu.add(menuAddDevice); menuSecurityChange.setText("Enable/Disable Security"); menuSecurityChange.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { menuSecurityChangeActionPerformed(evt); } }); editMenu.add(menuSecurityChange); menuBar.add(editMenu); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 649, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblConfTable, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(btnAddDevice) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnRunScan))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(lblConfTable, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddDevice) .addComponent(btnRunScan)) .addContainerGap(143, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Handles the opening of previously saved scanning configurations * @param evt The ActionEvent object with relevant data */ private void menuOpenConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuOpenConfigActionPerformed int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); ConfigurationManager manager = new ConfigurationManager(f); ArrayList<Host> configHosts = manager.getAllHosts(); hosts.addAll(configHosts); for(Host h : hosts) { this.updateTable(h); } } }//GEN-LAST:event_menuOpenConfigActionPerformed /** * Show the box that allows for the setting of a password * @param evt The ActionEvent object with relevant data */ private void menuSecurityChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuSecurityChangeActionPerformed SecurityDialog secDialog = new SecurityDialog(); secDialog.setVisible(true); }//GEN-LAST:event_menuSecurityChangeActionPerformed /** * Allows the user to close the application * @param evt The ActionEvent object with relevant data */ private void menuCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCloseActionPerformed int confirm = JOptionPane.showConfirmDialog(this, "Are you sure you'd like to quit?", "Quit the Application", JOptionPane.YES_NO_OPTION); if (confirm == JOptionPane.YES_OPTION) { System.exit(0); } //Otherwise do nothing }//GEN-LAST:event_menuCloseActionPerformed /** * Opens the window to allow a new device to be added to the current scan * configuration. * @param evt The ActionEvent object with relevant data */ private void menuAddDeviceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuAddDeviceActionPerformed this.openNewDeviceDialog(); }//GEN-LAST:event_menuAddDeviceActionPerformed /** * Opens the window to allow a new device to be added to the current scan * configuration. * @param evt The ActionEvent object with relevant data */ private void btnAddDeviceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddDeviceActionPerformed this.openNewDeviceDialog(); }//GEN-LAST:event_btnAddDeviceActionPerformed /** * Opens the new device dialog with all relevant parameters */ private void openNewDeviceDialog() { NewDeviceDialog device = new NewDeviceDialog(this); device.setVisible(true); } /** * Runs a scan on the selected hosts. * @param evt The ActionEvent object with relevant data */ private void btnRunScanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRunScanActionPerformed if (hosts.size() < 1) { JOptionPane.showMessageDialog(this, "Please enter at least one host."); } else { scanning.setVisible(true); ScanManager manager = new ScanManager(hosts); ScanLauncher launcher = new ScanLauncher(this, manager); launcher.execute(); } }//GEN-LAST:event_btnRunScanActionPerformed /** * Allows the user to save the current configuration from the file * @param evt The ActionEvent object with relevant data */ private void menuSaveConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuSaveConfigActionPerformed int returnCode = fc.showSaveDialog(this); if (returnCode == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String filename = file.getName(); //Make sure the filename ends in .xml if (!filename.matches("(.*)\\.xml$")) { filename = filename + ".xml"; file = new File(filename); } ConfigurationManager config = new ConfigurationManager(file); for (Host h : hosts) { config.addHost(h); } JOptionPane.showMessageDialog(this, "File Saved Successfully!", "Save Successful", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_menuSaveConfigActionPerformed /** * Shows the Output window (called after the scan is completed) * @param report The Full Report on all hosts */ public void displayReport(FullReport report) { OutputReview output = new OutputReview(report); output.setVisible(true); } /** * Starts the application * @param args the command line arguments */ @SuppressWarnings("TryWithIdenticalCatches") public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainGUI().setVisible(true); } }); } /** * Adds a host to be scanned into the JTable and to the ArrayList. Note that * the JTable is merely for presentation, the ArrayList holds the actual * data. * @param h The host to add to the table */ public void updateTable(Host h) { final int ROWS_BY_DEFAULT = 4; hosts.add(h); DefaultTableModel model = (DefaultTableModel) currentConfTable.getModel(); String hosts = h.toString(); //We have four rows by default if (currentRow >= ROWS_BY_DEFAULT) { Vector v = new Vector(); model.addRow(v); } int rowToFill = currentRow; currentConfTable.setValueAt(true, rowToFill, 0); currentConfTable.setValueAt(hosts, rowToFill, 1); currentConfTable.setValueAt("Full Scan", rowToFill, 2); currentRow++; } /** * Returns a "cleaned" version of the hostname * @return Just the IP address of a hostname */ private String getCleanHostname(Host h) { String hosts = h.getAddress().toString(); int c = hosts.indexOf("/"); hosts = hosts.substring((c + 1)); return hosts; } /** * Shows the "Please Wait" Dialog while the scan runs. */ @Override public void showPleaseWaitDialog() { scanning.setVisible(true); } /** * Removes the "Please Wait" Dialog once the scan is finished. */ @Override public void disposePleaseWaitDialog() { scanning.dispose(); } /** * Returns a list of hosts to be scanned (factoring in the checkboxes) * @return A list of hosts that are "checked" and should be scanned */ public ArrayList<Host> getHostsToScan() { ArrayList<Host> toScan = new ArrayList<>(); DefaultTableModel tableModel = (DefaultTableModel) currentConfTable.getModel(); int numRows = tableModel.getRowCount(); for (int i = 0; i < numRows; i++) { //If the host is unchecked if (!((boolean)tableModel.getValueAt(i, 0))) { continue; //Don't bother processing it } String guiHostname = (String) tableModel.getValueAt(i,1); for (Host h : hosts) { String hostname = h.toString(); if (hostname.compareTo(guiHostname) == 0) { toScan.add(h); } } } return toScan; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddDevice; private javax.swing.JToggleButton btnRunScan; private static javax.swing.JTable currentConfTable; private javax.swing.JMenu editMenu; private javax.swing.JMenu fileMenu; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblConfTable; private javax.swing.JMenuItem menuAddDevice; private javax.swing.JMenuBar menuBar; private javax.swing.JMenuItem menuClose; private javax.swing.JMenuItem menuOpenConfig; private javax.swing.JMenuItem menuRunScan; private javax.swing.JMenuItem menuSaveConfig; private javax.swing.JMenuItem menuSecurityChange; // End of variables declaration//GEN-END:variables }
Added debugging line for user directory test.
CiscoRouterTool/src/ciscoroutertool/gui/MainGUI.java
Added debugging line for user directory test.
Java
mit
225cdc23f062519c6c171e0da298dc66e4addb36
0
yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods
/* * FilterAlignment */ package net.maizegenetics.pal.alignment; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.maizegenetics.pal.ids.IdGroup; import net.maizegenetics.pal.ids.Identifier; import net.maizegenetics.pal.ids.SimpleIdGroup; import net.maizegenetics.util.BitSet; /** * All taxa and site filtering should be controlled through this class. * It essentially creates views of the baseAlignment * @author terry */ public class FilterAlignment extends AbstractAlignment { private static final long serialVersionUID = -5197800047652332969L; private final boolean myIsTaxaFilter; private final boolean myIsSiteFilter; private final boolean myIsSiteFilterByRange; private final Alignment myBaseAlignment; private final int[] myTaxaRedirect; private final int[] mySiteRedirect; private final int myRangeStart; private final int myRangeEnd; private Locus[] myLoci; private int[] myLociOffsets; private FilterAlignment(Alignment a, IdGroup subIdGroup, int[] taxaRedirect, FilterAlignment original) { super(subIdGroup); if (subIdGroup.getIdCount() != taxaRedirect.length) { throw new IllegalArgumentException("FilterAlignment: init: subIdGroup should be same size as taxaRedirect."); } myIsTaxaFilter = true; myBaseAlignment = a; myTaxaRedirect = taxaRedirect; if (original == null) { myIsSiteFilter = false; myIsSiteFilterByRange = false; mySiteRedirect = null; myRangeStart = -1; myRangeEnd = -1; myLoci = myBaseAlignment.getLoci(); myLociOffsets = myBaseAlignment.getLociOffsets(); } else { myIsSiteFilter = original.isSiteFilter(); myIsSiteFilterByRange = original.isSiteFilterByRange(); mySiteRedirect = original.getSiteRedirect(); myRangeStart = original.getRangeStart(); myRangeEnd = original.getRangeEnd(); myLoci = original.getLoci(); myLociOffsets = original.getLociOffsets(); } } /** * This returns FilterAlignment with only specified subIdGroup. Defaults * to retain unknown taxa. * * @param a alignment * @param subIdGroup subset id group * * @return filter alignment */ public static Alignment getInstance(Alignment a, IdGroup subIdGroup) { return getInstance(a, subIdGroup, true); } /** * This returns FilterAlignment with only specified subIdGroup. If * retainUnknownTaxa is true then Alignment will return unknown values * for missing taxa. * * @param a alignment * @param subIdGroup subset id group * @param retainUnknownTaxa whether to retain unknown taxa * * @return filter alignment */ public static Alignment getInstance(Alignment a, IdGroup subIdGroup, boolean retainUnknownTaxa) { Alignment baseAlignment = a; FilterAlignment original = null; if (baseAlignment instanceof FilterAlignment) { original = (FilterAlignment) a; baseAlignment = ((FilterAlignment) a).getBaseAlignment(); } List<Integer> taxaRedirectList = new ArrayList<Integer>(); List<Identifier> idList = new ArrayList<Identifier>(); boolean noNeedToFilter = true; if (subIdGroup.getIdCount() != a.getSequenceCount()) { noNeedToFilter = false; } for (int i = 0, n = subIdGroup.getIdCount(); i < n; i++) { int ion = a.getIdGroup().whichIdNumber(subIdGroup.getIdentifier(i)); if (ion != i) { noNeedToFilter = false; } if ((retainUnknownTaxa) && (ion < 0)) { taxaRedirectList.add(-1); idList.add(subIdGroup.getIdentifier(i)); } else { int idn = baseAlignment.getIdGroup().whichIdNumber(subIdGroup.getIdentifier(i)); if (idn > -1) { taxaRedirectList.add(idn); idList.add(baseAlignment.getIdGroup().getIdentifier(idn)); } else if (retainUnknownTaxa) { taxaRedirectList.add(-1); idList.add(subIdGroup.getIdentifier(i)); } } } if (noNeedToFilter) { return a; } int[] taxaRedirect = new int[taxaRedirectList.size()]; for (int j = 0, n = taxaRedirectList.size(); j < n; j++) { taxaRedirect[j] = (int) taxaRedirectList.get(j); } Identifier[] ids = new Identifier[idList.size()]; idList.toArray(ids); IdGroup resultIdGroup = new SimpleIdGroup(ids); return new FilterAlignment(baseAlignment, resultIdGroup, taxaRedirect, original); } /** * Removes specified IDs. * * @param a alignment to filter * @param subIdGroup specified IDs * * @return Filtered Alignment */ public static Alignment getInstanceRemoveIDs(Alignment a, IdGroup subIdGroup) { List result = new ArrayList(); IdGroup current = a.getIdGroup(); for (int i = 0, n = current.getIdCount(); i < n; i++) { if (subIdGroup.whichIdNumber(current.getIdentifier(i)) == -1) { result.add(current.getIdentifier(i)); } } Identifier[] ids = new Identifier[result.size()]; result.toArray(ids); return FilterAlignment.getInstance(a, new SimpleIdGroup(ids)); } /** * Constructor * * @param a base alignment * @param startSite start site (included) * @param endSite end site (included) */ private FilterAlignment(Alignment a, int startSite, int endSite, FilterAlignment original) { super(original == null ? a.getIdGroup() : original.getIdGroup()); if (startSite > endSite) { throw new IllegalArgumentException("FilterAlignment: init: start site: " + startSite + " is larger than end site: " + endSite); } if ((startSite < 0) || (startSite > a.getSiteCount() - 1)) { throw new IllegalArgumentException("FilterAlignment: init: start site: " + startSite + " is out of range."); } if ((endSite < 0) || (endSite > a.getSiteCount() - 1)) { throw new IllegalArgumentException("FilterAlignment: init: end site: " + endSite + " is out of range."); } myBaseAlignment = a; myIsSiteFilterByRange = true; myIsSiteFilter = false; myRangeStart = startSite; myRangeEnd = endSite; mySiteRedirect = null; getLociFromBase(); if (original == null) { myIsTaxaFilter = false; myTaxaRedirect = null; } else { myIsTaxaFilter = original.isTaxaFilter(); myTaxaRedirect = original.getTaxaRedirect(); } } /** * Constructor * * @param a base alignment * @param subSites site to include */ private FilterAlignment(Alignment a, int[] subSites, FilterAlignment original) { super(original == null ? a.getIdGroup() : original.getIdGroup()); myBaseAlignment = a; myIsSiteFilter = true; myIsSiteFilterByRange = false; if ((subSites == null) || (subSites.length == 0)) { mySiteRedirect = new int[0]; } else { mySiteRedirect = new int[subSites.length]; Arrays.sort(subSites); System.arraycopy(subSites, 0, mySiteRedirect, 0, subSites.length); } myRangeStart = -1; myRangeEnd = -1; getLociFromBase(); if (original == null) { myIsTaxaFilter = false; myTaxaRedirect = null; } else { myIsTaxaFilter = original.isTaxaFilter(); myTaxaRedirect = original.getTaxaRedirect(); } } public static FilterAlignment getInstance(Alignment a, int[] subSites) { if (a instanceof FilterAlignment) { FilterAlignment original = (FilterAlignment) a; Alignment baseAlignment = ((FilterAlignment) a).getBaseAlignment(); if (original.isSiteFilter()) { int[] newSubSites = new int[subSites.length]; for (int i = 0; i < subSites.length; i++) { newSubSites[i] = original.translateSite(subSites[i]); } return new FilterAlignment(baseAlignment, newSubSites, original); } else if (original.isSiteFilterByRange()) { int[] newSubSites = new int[subSites.length]; for (int i = 0; i < subSites.length; i++) { newSubSites[i] = original.translateSite(subSites[i]); } return new FilterAlignment(baseAlignment, newSubSites, original); } else if (original.isTaxaFilter()) { return new FilterAlignment(baseAlignment, subSites, original); } else { throw new IllegalStateException("FilterAlignment: getInstance: original not in known state."); } } else { return new FilterAlignment(a, subSites, null); } } public static FilterAlignment getInstance(Alignment a, String[] siteNamesToKeep) { Arrays.sort(siteNamesToKeep); int[] temp = new int[siteNamesToKeep.length]; int count = 0; for (int i = 0, n = a.getSiteCount(); i < n; i++) { if (Arrays.binarySearch(siteNamesToKeep, a.getSNPID(i)) >= 0) { temp[count++] = i; if (count == siteNamesToKeep.length) { break; } } } int[] result = null; if (count == siteNamesToKeep.length) { result = temp; } else { result = new int[count]; System.arraycopy(temp, 0, result, 0, count); } return getInstance(a, result); } public static FilterAlignment getInstance(Alignment a, int startSite, int endSite) { if (a instanceof FilterAlignment) { FilterAlignment original = (FilterAlignment) a; Alignment baseAlignment = ((FilterAlignment) a).getBaseAlignment(); if (original.isSiteFilter()) { int[] subSites = new int[endSite - startSite + 1]; int[] originalSites = original.getSiteRedirect(); for (int i = startSite; i <= endSite; i++) { subSites[i - startSite] = originalSites[i]; } return new FilterAlignment(baseAlignment, subSites, original); } else if (original.isSiteFilterByRange()) { return new FilterAlignment(baseAlignment, original.translateSite(startSite), original.translateSite(endSite), original); } else if (original.isTaxaFilter()) { return new FilterAlignment(baseAlignment, startSite, endSite, original); } else { throw new IllegalStateException("FilterAlignment: getInstance: original not in known state."); } } else { return new FilterAlignment(a, startSite, endSite, null); } } public byte getBase(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return Alignment.UNKNOWN_ALLELE; } else { return myBaseAlignment.getBase(taxaIndex, translateSite(site)); } } @Override public byte[] getBaseRange(int taxon, int startSite, int endSite) { int siteCount = endSite - startSite; byte[] result = new byte[siteCount]; int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { for (int i = 0; i < siteCount; i++) { result[i] = Alignment.UNKNOWN_ALLELE; } return result; } else { if (myIsSiteFilterByRange) { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, startSite + myRangeStart + i); } return result; } else if (myIsSiteFilter) { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, mySiteRedirect[startSite + i]); } return result; } else { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, startSite + i); } return result; } } } @Override public byte getBase(int taxon, Locus locus, int physicalPosition) { int site = getSiteOfPhysicalPosition(physicalPosition, locus); int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return Alignment.UNKNOWN_ALLELE; } else { return myBaseAlignment.getBase(taxaIndex, site); } } public int translateSite(int site) { if (myIsSiteFilterByRange) { return site + myRangeStart; } else if (myIsSiteFilter) { return mySiteRedirect[site]; } else { return site; } } /** * Returns site of this FilterAlignment based on given site from * embedded Alignment. * * @param site site * @return site in this alignment */ public int reverseTranslateSite(int site) { if (myIsSiteFilterByRange) { return site - myRangeStart; } else if (myIsSiteFilter) { return Arrays.binarySearch(mySiteRedirect, site); } else { return site; } } /** * Returns sites from original alignment that are viewable (not filtered) * by this filter alignment. * * @return list of sites */ public int[] getBaseSitesShown() { int numSites = getSiteCount(); int[] result = new int[numSites]; for (int i = 0; i < numSites; i++) { result[i] = translateSite(i); } return result; } public int translateTaxon(int taxon) { if (myIsTaxaFilter) { return myTaxaRedirect[taxon]; } else { return taxon; } } private void getLociFromBase() { if ((!myIsSiteFilter) && (!myIsSiteFilterByRange)) { myLoci = myBaseAlignment.getLoci(); } int numSites = getSiteCount(); List loci = new ArrayList(); List offsets = new ArrayList(); for (int i = 0; i < numSites; i++) { Locus current = getLocus(i); if (!loci.contains(current)) { loci.add(current); offsets.add(i); } } myLoci = new Locus[loci.size()]; loci.toArray(myLoci); myLociOffsets = new int[offsets.size()]; for (int i = 0; i < offsets.size(); i++) { myLociOffsets[i] = (Integer) offsets.get(i); } } @Override public int getIndelSize(int site) { return myBaseAlignment.getIndelSize(translateSite(site)); } @Override public Locus[] getLoci() { return myLoci; } @Override public Locus getLocus(int site) { return myBaseAlignment.getLocus(translateSite(site)); } @Override public int getLocusSiteCount(Locus locus) { int numSites = getSiteCount(); int result = 0; for (int i = 0; i < numSites; i++) { if (getLocus(translateSite(i)) == locus) { result++; } } return result; } @Override public int getNumLoci() { return myLoci.length; } @Override public int getPositionInLocus(int site) { return myBaseAlignment.getPositionInLocus(translateSite(site)); } @Override public byte getPositionType(int site) { return myBaseAlignment.getPositionType(translateSite(site)); } @Override public byte[] getPositionTypes() { int numSites = getSiteCount(); byte[] result = new byte[numSites]; for (int i = 0; i < numSites; i++) { result[i] = myBaseAlignment.getPositionType(translateSite(i)); } return result; } @Override public float[][] getSiteScores() { if (!myBaseAlignment.hasSiteScores()) { return null; } int numSites = getSiteCount(); int numSeqs = getSequenceCount(); float[][] result = new float[numSeqs][numSites]; for (int i = 0; i < numSites; i++) { for (int j = 0; j < numSeqs; j++) { int taxaIndex = translateTaxon(j); if (taxaIndex == -1) { result[j][i] = -9; } else { result[j][i] = myBaseAlignment.getSiteScore(taxaIndex, translateSite(i)); } } } return result; } @Override public byte getReferenceAllele(int site) { return myBaseAlignment.getReferenceAllele(translateSite(site)); } @Override public int getSiteCount() { if (myIsSiteFilterByRange) { return myRangeEnd - myRangeStart + 1; } else if (myIsSiteFilter) { return mySiteRedirect.length; } else { return myBaseAlignment.getSiteCount(); } } @Override public String getSNPID(int site) { return myBaseAlignment.getSNPID(translateSite(site)); } @Override public String[] getSNPIDs() { int numSites = getSiteCount(); String[] result = new String[numSites]; for (int i = 0; i < numSites; i++) { result[i] = myBaseAlignment.getSNPID(translateSite(i)); } return result; } @Override public boolean hasReference() { return myBaseAlignment.hasReference(); } @Override public boolean isIndel(int site) { return myBaseAlignment.isIndel(translateSite(site)); } @Override public int getSiteOfPhysicalPosition(int physicalPosition, Locus locus) { int temp = myBaseAlignment.getSiteOfPhysicalPosition(physicalPosition, locus); if (temp < 0) { temp = -temp; } return reverseTranslateSite(temp); } public Alignment getBaseAlignment() { return myBaseAlignment; } public boolean isTaxaFilter() { return myIsTaxaFilter; } public boolean isSiteFilter() { return myIsSiteFilter; } public boolean isSiteFilterByRange() { return myIsSiteFilterByRange; } protected int[] getTaxaRedirect() { return myTaxaRedirect; } protected int[] getSiteRedirect() { return mySiteRedirect; } protected int getRangeStart() { return myRangeStart; } protected int getRangeEnd() { return myRangeEnd; } @Override public byte[] getBaseArray(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return new byte[]{Alignment.UNKNOWN_ALLELE, Alignment.UNKNOWN_ALLELE}; } else { return myBaseAlignment.getBaseArray(taxaIndex, translateSite(site)); } } @Override public byte[] getBaseRow(int taxon) { int siteCount = getSiteCount(); byte[] result = new byte[siteCount]; int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { for (int i = 0; i < siteCount; i++) { result[i] = Alignment.UNKNOWN_ALLELE; } return result; } else { if (myIsSiteFilterByRange) { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, myRangeStart + i); } return result; } else if (myIsSiteFilter) { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, mySiteRedirect[i]); } return result; } else { return myBaseAlignment.getBaseRow(taxaIndex); } } } @Override public BitSet getAllelePresenceForAllSites(int taxon, int alleleNumber) { throw new UnsupportedOperationException("Not supported yet."); } @Override public BitSet getAllelePresenceForAllTaxa(int site, int alleleNumber) { throw new UnsupportedOperationException("Not supported yet."); } @Override public long[] getAllelePresenceForSitesBlock(int taxon, int alleleNumber, int startBlock, int endBlock) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getBaseAsString(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return Alignment.UNKNOWN_ALLELE_STR; } else { return myBaseAlignment.getBaseAsString(taxaIndex, translateSite(site)); } } @Override public String[] getBaseAsStringArray(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return new String[]{Alignment.UNKNOWN_ALLELE_STR, Alignment.UNKNOWN_ALLELE_STR}; } else { return myBaseAlignment.getBaseAsStringArray(taxaIndex, translateSite(site)); } } @Override public byte[] getReference() { if ((myIsSiteFilterByRange) || (myIsSiteFilter)) { return myBaseAlignment.getReference(0, getSiteCount()); } else { return myBaseAlignment.getReference(); } } @Override public boolean isHeterozygous(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return false; } else { return myBaseAlignment.isHeterozygous(taxaIndex, translateSite(site)); } } @Override public int[] getPhysicalPositions() { if ((myIsSiteFilterByRange) || (myIsSiteFilter)) { int numSites = getSiteCount(); int[] result = new int[numSites]; for (int i = 0; i < numSites; i++) { result[i] = getPositionInLocus(i); } return result; } else { return myBaseAlignment.getPhysicalPositions(); } } @Override public String getLocusName(int site) { return myBaseAlignment.getLocusName(translateSite(site)); } @Override public int[] getLociOffsets() { return myLociOffsets; } @Override public float getSiteScore(int seq, int site) { int taxaIndex = translateTaxon(seq); if (taxaIndex == -1) { return Float.NaN; } else { return myBaseAlignment.getSiteScore(taxaIndex, translateSite(site)); } } @Override public boolean hasSiteScores() { return myBaseAlignment.hasSiteScores(); } @Override public SITE_SCORE_TYPE getSiteScoreType() { return myBaseAlignment.getSiteScoreType(); } @Override public String getGenomeAssembly() { return myBaseAlignment.getGenomeAssembly(); } @Override public boolean isPositiveStrand(int site) { return myBaseAlignment.isPositiveStrand(translateSite(site)); } @Override public boolean isPhased() { return myBaseAlignment.isPhased(); } @Override public GeneticMap getGeneticMap() { return myBaseAlignment.getGeneticMap(); } @Override public boolean retainsRareAlleles() { return myBaseAlignment.retainsRareAlleles(); } @Override public String[][] getAlleleEncodings() { String[][] encodings = myBaseAlignment.getAlleleEncodings(); if (encodings.length == 1) { return encodings; } else if ((myIsSiteFilterByRange) || (myIsSiteFilter)) { int numSites = getSiteCount(); String[][] result = new String[numSites][]; for (int i = 0; i < numSites; i++) { result[i] = getAlleleEncodings(i); } return result; } else { return encodings; } } @Override public String[] getAlleleEncodings(int site) { return myBaseAlignment.getAlleleEncodings(translateSite(site)); } @Override public String getBaseAsString(int site, byte value) { return myBaseAlignment.getBaseAsString(translateSite(site), value); } @Override public int getMaxNumAlleles() { return myBaseAlignment.getMaxNumAlleles(); } @Override public int[][] getAllelesSortedByFrequency(int site) { if (myIsTaxaFilter) { return super.getAllelesSortedByFrequency(site); } else { return myBaseAlignment.getAllelesSortedByFrequency(translateSite(site)); } } @Override public double getMajorAlleleFrequency(int site) { if (myIsTaxaFilter) { return super.getMajorAlleleFrequency(site); } else { return myBaseAlignment.getMajorAlleleFrequency(translateSite(site)); } } @Override public int getHeterozygousCount(int site) { if (myIsTaxaFilter) { return super.getHeterozygousCount(site); } else { return myBaseAlignment.getHeterozygousCount(translateSite(site)); } } @Override public boolean isPolymorphic(int site) { if (myIsTaxaFilter) { return super.isPolymorphic(site); } else { return myBaseAlignment.isPolymorphic(translateSite(site)); } } @Override public int getTotalGametesNotMissing(int site) { if (myIsTaxaFilter) { return super.getTotalGametesNotMissing(site); } else { return myBaseAlignment.getTotalGametesNotMissing(translateSite(site)); } } @Override public int getMinorAlleleCount(int site) { if (myIsTaxaFilter) { return super.getMinorAlleleCount(site); } else { return myBaseAlignment.getMinorAlleleCount(translateSite(site)); } } @Override public double getMinorAlleleFrequency(int site) { if (myIsTaxaFilter) { return super.getMinorAlleleFrequency(site); } else { return myBaseAlignment.getMinorAlleleFrequency(translateSite(site)); } } @Override public int getMajorAlleleCount(int site) { if (myIsTaxaFilter) { return super.getMajorAlleleCount(site); } else { return myBaseAlignment.getMajorAlleleCount(translateSite(site)); } } @Override public Object[][] getDiploidssSortedByFrequency(int site) { if (myIsTaxaFilter) { return super.getDiploidssSortedByFrequency(site); } else { return myBaseAlignment.getDiploidssSortedByFrequency(translateSite(site)); } } @Override public int getTotalGametesNotMissingForTaxon(int taxon) { if (myIsSiteFilter || myIsSiteFilterByRange) { return super.getTotalGametesNotMissingForTaxon(taxon); } else { return myBaseAlignment.getTotalGametesNotMissingForTaxon(translateTaxon(taxon)); } } @Override public int getHeterozygousCountForTaxon(int taxon) { if (myIsSiteFilter || myIsSiteFilterByRange) { return super.getHeterozygousCountForTaxon(taxon); } else { return myBaseAlignment.getHeterozygousCountForTaxon(translateTaxon(taxon)); } } @Override public boolean isSBitFriendly() { if (!myIsTaxaFilter && myBaseAlignment.isSBitFriendly()) { return true; } else { return false; } } @Override public boolean isTBitFriendly() { if (!myIsSiteFilter && !myIsSiteFilterByRange && myBaseAlignment.isTBitFriendly()) { return true; } else { return false; } } }
src/net/maizegenetics/pal/alignment/FilterAlignment.java
/* * FilterAlignment */ package net.maizegenetics.pal.alignment; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.maizegenetics.pal.ids.IdGroup; import net.maizegenetics.pal.ids.Identifier; import net.maizegenetics.pal.ids.SimpleIdGroup; import net.maizegenetics.util.BitSet; /** * All taxa and site filtering should be controlled through this class. * It essentially creates views of the baseAlignment * @author terry */ public class FilterAlignment extends AbstractAlignment { private static final long serialVersionUID = -5197800047652332969L; private final boolean myIsTaxaFilter; private final boolean myIsSiteFilter; private final boolean myIsSiteFilterByRange; private final Alignment myBaseAlignment; private final int[] myTaxaRedirect; private final int[] mySiteRedirect; private final int myRangeStart; private final int myRangeEnd; private Locus[] myLoci; private int[] myLociOffsets; private FilterAlignment(Alignment a, IdGroup subIdGroup, int[] taxaRedirect, FilterAlignment original) { super(subIdGroup); if (subIdGroup.getIdCount() != taxaRedirect.length) { throw new IllegalArgumentException("FilterAlignment: init: subIdGroup should be same size as taxaRedirect."); } myIsTaxaFilter = true; myBaseAlignment = a; myTaxaRedirect = taxaRedirect; if (original == null) { myIsSiteFilter = false; myIsSiteFilterByRange = false; mySiteRedirect = null; myRangeStart = -1; myRangeEnd = -1; myLoci = myBaseAlignment.getLoci(); myLociOffsets = myBaseAlignment.getLociOffsets(); } else { myIsSiteFilter = original.isSiteFilter(); myIsSiteFilterByRange = original.isSiteFilterByRange(); mySiteRedirect = original.getSiteRedirect(); myRangeStart = original.getRangeStart(); myRangeEnd = original.getRangeEnd(); myLoci = original.getLoci(); myLociOffsets = original.getLociOffsets(); } } /** * This returns FilterAlignment with only specified subIdGroup. Defaults * to retain unknown taxa. * * @param a alignment * @param subIdGroup subset id group * * @return filter alignment */ public static Alignment getInstance(Alignment a, IdGroup subIdGroup) { return getInstance(a, subIdGroup, true); } /** * This returns FilterAlignment with only specified subIdGroup. If * retainUnknownTaxa is true then Alignment will return unknown values * for missing taxa. * * @param a alignment * @param subIdGroup subset id group * @param retainUnknownTaxa whether to retain unknown taxa * * @return filter alignment */ public static Alignment getInstance(Alignment a, IdGroup subIdGroup, boolean retainUnknownTaxa) { Alignment baseAlignment = a; FilterAlignment original = null; if (baseAlignment instanceof FilterAlignment) { original = (FilterAlignment) a; baseAlignment = ((FilterAlignment) a).getBaseAlignment(); } List<Integer> taxaRedirectList = new ArrayList<Integer>(); List<Identifier> idList = new ArrayList<Identifier>(); boolean noNeedToFilter = true; if (subIdGroup.getIdCount() != a.getSequenceCount()) { noNeedToFilter = false; } for (int i = 0, n = subIdGroup.getIdCount(); i < n; i++) { int ion = a.getIdGroup().whichIdNumber(subIdGroup.getIdentifier(i)); if (ion != i) { noNeedToFilter = false; } if ((retainUnknownTaxa) && (ion < 0)) { taxaRedirectList.add(-1); idList.add(subIdGroup.getIdentifier(i)); } else { int idn = baseAlignment.getIdGroup().whichIdNumber(subIdGroup.getIdentifier(i)); if (idn > -1) { taxaRedirectList.add(idn); idList.add(baseAlignment.getIdGroup().getIdentifier(idn)); } else if (retainUnknownTaxa) { taxaRedirectList.add(-1); idList.add(subIdGroup.getIdentifier(i)); } } } if (noNeedToFilter) { return a; } int[] taxaRedirect = new int[taxaRedirectList.size()]; for (int j = 0, n = taxaRedirectList.size(); j < n; j++) { taxaRedirect[j] = (int) taxaRedirectList.get(j); } Identifier[] ids = new Identifier[idList.size()]; idList.toArray(ids); IdGroup resultIdGroup = new SimpleIdGroup(ids); return new FilterAlignment(baseAlignment, resultIdGroup, taxaRedirect, original); } /** * Removes specified IDs. * * @param a alignment to filter * @param subIdGroup specified IDs * * @return Filtered Alignment */ public static Alignment getInstanceRemoveIDs(Alignment a, IdGroup subIdGroup) { List result = new ArrayList(); IdGroup current = a.getIdGroup(); for (int i = 0, n = current.getIdCount(); i < n; i++) { if (subIdGroup.whichIdNumber(current.getIdentifier(i)) == -1) { result.add(current.getIdentifier(i)); } } Identifier[] ids = new Identifier[result.size()]; result.toArray(ids); return FilterAlignment.getInstance(a, new SimpleIdGroup(ids)); } /** * Constructor * * @param a base alignment * @param startSite start site (included) * @param endSite end site (included) */ private FilterAlignment(Alignment a, int startSite, int endSite, FilterAlignment original) { super(original == null ? a.getIdGroup() : original.getIdGroup()); if (startSite > endSite) { throw new IllegalArgumentException("FilterAlignment: init: start site: " + startSite + " is larger than end site: " + endSite); } if ((startSite < 0) || (startSite > a.getSiteCount() - 1)) { throw new IllegalArgumentException("FilterAlignment: init: start site: " + startSite + " is out of range."); } if ((endSite < 0) || (endSite > a.getSiteCount() - 1)) { throw new IllegalArgumentException("FilterAlignment: init: end site: " + endSite + " is out of range."); } myBaseAlignment = a; myIsSiteFilterByRange = true; myIsSiteFilter = false; myRangeStart = startSite; myRangeEnd = endSite; mySiteRedirect = null; getLociFromBase(); if (original == null) { myIsTaxaFilter = false; myTaxaRedirect = null; } else { myIsTaxaFilter = original.isTaxaFilter(); myTaxaRedirect = original.getTaxaRedirect(); } } /** * Constructor * * @param a base alignment * @param subSites site to include */ private FilterAlignment(Alignment a, int[] subSites, FilterAlignment original) { super(original == null ? a.getIdGroup() : original.getIdGroup()); myBaseAlignment = a; myIsSiteFilter = true; myIsSiteFilterByRange = false; if ((subSites == null) || (subSites.length == 0)) { mySiteRedirect = new int[0]; } else { mySiteRedirect = new int[subSites.length]; Arrays.sort(subSites); System.arraycopy(subSites, 0, mySiteRedirect, 0, subSites.length); } myRangeStart = -1; myRangeEnd = -1; getLociFromBase(); if (original == null) { myIsTaxaFilter = false; myTaxaRedirect = null; } else { myIsTaxaFilter = original.isTaxaFilter(); myTaxaRedirect = original.getTaxaRedirect(); } } public static FilterAlignment getInstance(Alignment a, int[] subSites) { if (a instanceof FilterAlignment) { FilterAlignment original = (FilterAlignment) a; Alignment baseAlignment = ((FilterAlignment) a).getBaseAlignment(); if (original.isSiteFilter()) { int[] newSubSites = new int[subSites.length]; for (int i = 0; i < subSites.length; i++) { newSubSites[i] = original.translateSite(subSites[i]); } return new FilterAlignment(baseAlignment, newSubSites, original); } else if (original.isSiteFilterByRange()) { int[] newSubSites = new int[subSites.length]; for (int i = 0; i < subSites.length; i++) { newSubSites[i] = original.translateSite(subSites[i]); } return new FilterAlignment(baseAlignment, newSubSites, original); } else if (original.isTaxaFilter()) { return new FilterAlignment(baseAlignment, subSites, original); } else { throw new IllegalStateException("FilterAlignment: getInstance: original not in known state."); } } else { return new FilterAlignment(a, subSites, null); } } public static FilterAlignment getInstance(Alignment a, String[] siteNamesToKeep) { Arrays.sort(siteNamesToKeep); int[] temp = new int[siteNamesToKeep.length]; int count = 0; for (int i = 0, n = a.getSiteCount(); i < n; i++) { if (Arrays.binarySearch(siteNamesToKeep, a.getSNPID(i)) >= 0) { temp[count++] = i; if (count == siteNamesToKeep.length) { break; } } } int[] result = null; if (count == siteNamesToKeep.length) { result = temp; } else { result = new int[count]; System.arraycopy(temp, 0, result, 0, count); } return getInstance(a, result); } public static FilterAlignment getInstance(Alignment a, int startSite, int endSite) { if (a instanceof FilterAlignment) { FilterAlignment original = (FilterAlignment) a; Alignment baseAlignment = ((FilterAlignment) a).getBaseAlignment(); if (original.isSiteFilter()) { int[] subSites = new int[endSite - startSite + 1]; int[] originalSites = original.getSiteRedirect(); for (int i = startSite; i <= endSite; i++) { subSites[i - startSite] = originalSites[i]; } return new FilterAlignment(baseAlignment, subSites, original); } else if (original.isSiteFilterByRange()) { return new FilterAlignment(baseAlignment, original.translateSite(startSite), original.translateSite(endSite), original); } else if (original.isTaxaFilter()) { return new FilterAlignment(baseAlignment, startSite, endSite, original); } else { throw new IllegalStateException("FilterAlignment: getInstance: original not in known state."); } } else { return new FilterAlignment(a, startSite, endSite, null); } } public byte getBase(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return Alignment.UNKNOWN_ALLELE; } else { return myBaseAlignment.getBase(taxaIndex, translateSite(site)); } } @Override public byte[] getBaseRange(int taxon, int startSite, int endSite) { int siteCount = endSite - startSite; byte[] result = new byte[siteCount]; int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { for (int i = 0; i < siteCount; i++) { result[i] = Alignment.UNKNOWN_ALLELE; } return result; } else { if (myIsSiteFilterByRange) { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, startSite + myRangeStart + i); } return result; } else if (myIsSiteFilter) { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, mySiteRedirect[startSite + i]); } return result; } else { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, startSite + i); } return result; } } } @Override public byte getBase(int taxon, Locus locus, int physicalPosition) { int site = getSiteOfPhysicalPosition(physicalPosition, locus); int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return Alignment.UNKNOWN_ALLELE; } else { return myBaseAlignment.getBase(taxaIndex, site); } } public int translateSite(int site) { if (myIsSiteFilterByRange) { return site + myRangeStart; } else if (myIsSiteFilter) { return mySiteRedirect[site]; } else { return site; } } /** * Returns site of this FilterAlignment based on given site from * embedded Alignment. * * @param site site * @return site in this alignment */ public int reverseTranslateSite(int site) { if (myIsSiteFilterByRange) { return site - myRangeStart; } else if (myIsSiteFilter) { return Arrays.binarySearch(mySiteRedirect, site); } else { return site; } } /** * Returns sites from original alignment that are viewable (not filtered) * by this filter alignment. * * @return list of sites */ public int[] getBaseSitesShown() { int numSites = getSiteCount(); int[] result = new int[numSites]; for (int i = 0; i < numSites; i++) { result[i] = translateSite(i); } return result; } public int translateTaxon(int taxon) { if (myIsTaxaFilter) { return myTaxaRedirect[taxon]; } else { return taxon; } } private void getLociFromBase() { if ((!myIsSiteFilter) && (!myIsSiteFilterByRange)) { myLoci = myBaseAlignment.getLoci(); } int numSites = getSiteCount(); List loci = new ArrayList(); List offsets = new ArrayList(); for (int i = 0; i < numSites; i++) { Locus current = getLocus(i); if (!loci.contains(current)) { loci.add(current); offsets.add(i); } } myLoci = new Locus[loci.size()]; loci.toArray(myLoci); myLociOffsets = new int[offsets.size()]; for (int i = 0; i < offsets.size(); i++) { myLociOffsets[i] = (Integer) offsets.get(i); } } @Override public int getIndelSize(int site) { return myBaseAlignment.getIndelSize(translateSite(site)); } @Override public Locus[] getLoci() { return myLoci; } @Override public Locus getLocus(int site) { return myBaseAlignment.getLocus(translateSite(site)); } @Override public int getLocusSiteCount(Locus locus) { int numSites = getSiteCount(); int result = 0; for (int i = 0; i < numSites; i++) { if (getLocus(translateSite(i)) == locus) { result++; } } return result; } @Override public int getNumLoci() { return myLoci.length; } @Override public int getPositionInLocus(int site) { return myBaseAlignment.getPositionInLocus(translateSite(site)); } @Override public byte getPositionType(int site) { return myBaseAlignment.getPositionType(translateSite(site)); } @Override public byte[] getPositionTypes() { int numSites = getSiteCount(); byte[] result = new byte[numSites]; for (int i = 0; i < numSites; i++) { result[i] = myBaseAlignment.getPositionType(translateSite(i)); } return result; } @Override public float[][] getSiteScores() { if (!myBaseAlignment.hasSiteScores()) { return null; } int numSites = getSiteCount(); int numSeqs = getSequenceCount(); float[][] result = new float[numSeqs][numSites]; for (int i = 0; i < numSites; i++) { for (int j = 0; j < numSeqs; j++) { int taxaIndex = translateTaxon(j); if (taxaIndex == -1) { result[j][i] = -9; } else { result[j][i] = myBaseAlignment.getSiteScore(taxaIndex, translateSite(i)); } } } return result; } @Override public byte getReferenceAllele(int site) { return myBaseAlignment.getReferenceAllele(translateSite(site)); } @Override public int getSiteCount() { if (myIsSiteFilterByRange) { return myRangeEnd - myRangeStart + 1; } else if (myIsSiteFilter) { return mySiteRedirect.length; } else { return myBaseAlignment.getSiteCount(); } } @Override public String getSNPID(int site) { return myBaseAlignment.getSNPID(translateSite(site)); } @Override public String[] getSNPIDs() { int numSites = getSiteCount(); String[] result = new String[numSites]; for (int i = 0; i < numSites; i++) { result[i] = myBaseAlignment.getSNPID(translateSite(i)); } return result; } @Override public boolean hasReference() { return myBaseAlignment.hasReference(); } @Override public boolean isIndel(int site) { return myBaseAlignment.isIndel(translateSite(site)); } @Override public int getSiteOfPhysicalPosition(int physicalPosition, Locus locus) { int temp = myBaseAlignment.getSiteOfPhysicalPosition(physicalPosition, locus); if (temp < 0) { temp = -temp; } return reverseTranslateSite(temp); } public Alignment getBaseAlignment() { return myBaseAlignment; } public boolean isTaxaFilter() { return myIsTaxaFilter; } public boolean isSiteFilter() { return myIsSiteFilter; } public boolean isSiteFilterByRange() { return myIsSiteFilterByRange; } protected int[] getTaxaRedirect() { return myTaxaRedirect; } protected int[] getSiteRedirect() { return mySiteRedirect; } protected int getRangeStart() { return myRangeStart; } protected int getRangeEnd() { return myRangeEnd; } @Override public byte[] getBaseArray(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return new byte[]{Alignment.UNKNOWN_ALLELE, Alignment.UNKNOWN_ALLELE}; } else { return myBaseAlignment.getBaseArray(taxaIndex, translateSite(site)); } } @Override public byte[] getBaseRow(int taxon) { int siteCount = getSiteCount(); byte[] result = new byte[siteCount]; int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { for (int i = 0; i < siteCount; i++) { result[i] = Alignment.UNKNOWN_ALLELE; } return result; } else { if (myIsSiteFilterByRange) { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, myRangeStart + i); } return result; } else if (myIsSiteFilter) { for (int i = 0; i < siteCount; i++) { result[i] = myBaseAlignment.getBase(taxaIndex, mySiteRedirect[i]); } return result; } else { return myBaseAlignment.getBaseRow(taxaIndex); } } } @Override public BitSet getAllelePresenceForAllSites(int taxon, int alleleNumber) { throw new UnsupportedOperationException("Not supported yet."); } @Override public BitSet getAllelePresenceForAllTaxa(int site, int alleleNumber) { throw new UnsupportedOperationException("Not supported yet."); } @Override public long[] getAllelePresenceForSitesBlock(int taxon, int alleleNumber, int startBlock, int endBlock) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getBaseAsString(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return Alignment.UNKNOWN_ALLELE_STR; } else { return myBaseAlignment.getBaseAsString(taxaIndex, translateSite(site)); } } @Override public String[] getBaseAsStringArray(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return new String[]{Alignment.UNKNOWN_ALLELE_STR, Alignment.UNKNOWN_ALLELE_STR}; } else { return myBaseAlignment.getBaseAsStringArray(taxaIndex, translateSite(site)); } } @Override public byte[] getReference() { if ((myIsSiteFilterByRange) || (myIsSiteFilter)) { return myBaseAlignment.getReference(0, getSiteCount()); } else { return myBaseAlignment.getReference(); } } @Override public boolean isHeterozygous(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return false; } else { return myBaseAlignment.isHeterozygous(taxaIndex, translateSite(site)); } } @Override public int[] getPhysicalPositions() { if ((myIsSiteFilterByRange) || (myIsSiteFilter)) { int numSites = getSiteCount(); int[] result = new int[numSites]; for (int i = 0; i < numSites; i++) { result[i] = getPositionInLocus(i); } return result; } else { return myBaseAlignment.getPhysicalPositions(); } } @Override public String getLocusName(int site) { return myBaseAlignment.getLocusName(translateSite(site)); } @Override public int[] getLociOffsets() { return myLociOffsets; } @Override public float getSiteScore(int seq, int site) { int taxaIndex = translateTaxon(seq); if (taxaIndex == -1) { return Float.NaN; } else { return myBaseAlignment.getSiteScore(taxaIndex, translateSite(site)); } } @Override public boolean hasSiteScores() { return myBaseAlignment.hasSiteScores(); } @Override public SITE_SCORE_TYPE getSiteScoreType() { return myBaseAlignment.getSiteScoreType(); } @Override public String getGenomeAssembly() { return myBaseAlignment.getGenomeAssembly(); } @Override public boolean isPositiveStrand(int site) { return myBaseAlignment.isPositiveStrand(translateSite(site)); } @Override public boolean isPhased() { return myBaseAlignment.isPhased(); } @Override public GeneticMap getGeneticMap() { return myBaseAlignment.getGeneticMap(); } @Override public boolean retainsRareAlleles() { return myBaseAlignment.retainsRareAlleles(); } @Override public String[][] getAlleleEncodings() { String[][] encodings = myBaseAlignment.getAlleleEncodings(); if (encodings.length == 1) { return encodings; } else if ((myIsSiteFilterByRange) || (myIsSiteFilter)) { int numSites = getSiteCount(); String[][] result = new String[numSites][]; for (int i = 0; i < numSites; i++) { result[i] = getAlleleEncodings(i); } return result; } else { return encodings; } } @Override public String[] getAlleleEncodings(int site) { return myBaseAlignment.getAlleleEncodings(translateSite(site)); } @Override public String getBaseAsString(int site, byte value) { return myBaseAlignment.getBaseAsString(translateSite(site), value); } @Override public int getMaxNumAlleles() { return myBaseAlignment.getMaxNumAlleles(); } @Override public int[][] getAllelesSortedByFrequency(int site) { if (myIsTaxaFilter) { return super.getAllelesSortedByFrequency(site); } else { return myBaseAlignment.getAllelesSortedByFrequency(translateSite(site)); } } @Override public double getMajorAlleleFrequency(int site) { if (myIsTaxaFilter) { return super.getMajorAlleleFrequency(site); } else { return myBaseAlignment.getMajorAlleleFrequency(translateSite(site)); } } @Override public int getHeterozygousCount(int site) { if (myIsTaxaFilter) { return super.getHeterozygousCount(site); } else { return myBaseAlignment.getHeterozygousCount(translateSite(site)); } } @Override public boolean isPolymorphic(int site) { if (myIsTaxaFilter) { return super.isPolymorphic(site); } else { return myBaseAlignment.isPolymorphic(translateSite(site)); } } @Override public int getTotalGametesNotMissing(int site) { if (myIsTaxaFilter) { return super.getTotalGametesNotMissing(site); } else { return myBaseAlignment.getTotalGametesNotMissing(translateSite(site)); } } @Override public int getMinorAlleleCount(int site) { if (myIsTaxaFilter) { return super.getMinorAlleleCount(site); } else { return myBaseAlignment.getMinorAlleleCount(translateSite(site)); } } @Override public double getMinorAlleleFrequency(int site) { if (myIsTaxaFilter) { return super.getMinorAlleleFrequency(site); } else { return myBaseAlignment.getMinorAlleleFrequency(translateSite(site)); } } @Override public int getMajorAlleleCount(int site) { if (myIsTaxaFilter) { return super.getMajorAlleleCount(site); } else { return myBaseAlignment.getMajorAlleleCount(translateSite(site)); } } @Override public Object[][] getDiploidssSortedByFrequency(int site) { if (myIsTaxaFilter) { return super.getDiploidssSortedByFrequency(site); } else { return myBaseAlignment.getDiploidssSortedByFrequency(translateSite(site)); } } @Override public int getTotalGametesNotMissingForTaxon(int taxon) { if (myIsSiteFilter || myIsSiteFilterByRange) { return super.getTotalGametesNotMissingForTaxon(taxon); } else { return myBaseAlignment.getTotalGametesNotMissingForTaxon(translateTaxon(taxon)); } } @Override public int getHeterozygousCountForTaxon(int taxon) { if (myIsSiteFilter || myIsSiteFilterByRange) { return super.getHeterozygousCountForTaxon(taxon); } else { return myBaseAlignment.getHeterozygousCountForTaxon(translateTaxon(taxon)); } } @Override public boolean isSBitFriendly() { if (!myIsTaxaFilter && (myBaseAlignment instanceof SBitAlignment)) { return true; } else { return false; } } @Override public boolean isTBitFriendly() { if (!myIsSiteFilter && !myIsSiteFilterByRange && (myBaseAlignment instanceof TBitAlignment)) { return true; } else { return false; } } }
Improvement to isSBitFriendly() and isTBitFriendly()
src/net/maizegenetics/pal/alignment/FilterAlignment.java
Improvement to isSBitFriendly() and isTBitFriendly()
Java
mit
2bbc248cfe8fdc4866b2ab0de120c9f0cd41c5a9
0
sormuras/bach,sormuras/bach
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // default package import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.UncheckedIOException; import java.lang.module.ModuleFinder; import java.net.URI; import java.net.URISyntaxException; import java.net.URLConnection; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.TreeSet; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.spi.ToolProvider; import java.util.stream.Collectors; /** Java Shell Builder. */ @SuppressWarnings("WeakerAccess") public class Bach { /** Version of Bach, {@link Runtime.Version#parse(String)}-compatible. */ public static final String VERSION = "2-ea"; /** Convenient short-cut to {@code "user.home"} as a path. */ static final Path USER_HOME = Path.of(System.getProperty("user.home")); /** * Main entry-point of Bach. * * @param arguments task name(s) and their argument(s) * @throws Error on a non-zero error code */ public static void main(String... arguments) { var bach = new Bach(); var args = List.of(arguments); var code = bach.main(args); if (code != 0) { throw new Error("Bach (" + args + ") failed with error code: " + code); } } private final PrintWriter out; private final PrintWriter err; private final boolean verbose; private final Path home; private final Path work; private final Runner runner; private final Project project; Bach() { this(new PrintWriter(System.out, true), new PrintWriter(System.err, true)); } Bach(PrintWriter out, PrintWriter err) { this( out, err, ProcessBuilder::inheritIO, Path.of(System.getProperty("bach.home", "")), Path.of(System.getProperty("bach.work", "")), Boolean.getBoolean("bach.verbose")); } Bach( PrintWriter out, PrintWriter err, UnaryOperator<ProcessBuilder> redirectIO, Path home, Path work, boolean verbose) { this.out = out; this.err = err; this.runner = new Runner(redirectIO); this.home = home; this.work = work; this.verbose = verbose; this.project = new Project(); log("Bach %s initialized.", VERSION); } void log(String format, Object... args) { if (verbose) { out.println(String.format(format, args)); } } /** Print runtime and project-related information. */ public void info() { log("Bach::info()"); out.println("Bach information"); out.println(" out = " + out); out.println(" err = " + err); out.println(" cwd = " + Path.of(System.getProperty("user.dir"))); out.println(" home = '" + home + "'"); out.println(" work = '" + work + "'"); out.println(" verbose = " + verbose); project.toStrings(out::println); log("Bach::info() end."); } /** Build the project. */ public void build() { log("Bach::build()"); if (verbose) { info(); } compile(); test(); summary(); log("Bach::build() end."); } /** Compile all modules. */ public void compile() { log("Bach::compile()"); compile(project.main); compile(project.test); log("Bach::compile() end."); } private void compile(Project.Realm realm) { log("Bach::compile(%s)", realm.name); if (realm.modules.isEmpty()) { log("Bach::compile(%s) end -- no modules to compile.", realm.name); return; } try { compile(realm, realm.modules); } catch (Exception e) { throw new Error("Compiling realm " + realm.name + " failed!", e); } } private void compile(Project.Realm realm, List<String> modules) throws Exception { var javac = new Command("javac") .add("-d", realm.binClasses) .add("-encoding", "UTF-8") .add("-parameters") .add("-Xlint") .addIff(realm.preview, "--enable-preview") .addIff(realm.release != null, "--release", realm.release) .add("--module-path", realm.modulePath) .add("--module-source-path", realm.moduleSourcePath) .add("--module-version", project.version) .add("--module", String.join(",", modules)); if (realm == project.test) { for (var module : modules) { if (!project.main.modules.contains(module)) { continue; } var patch = project.main.binClasses.resolve(module); // patch = project.main.moduleSourcePath.replace("*", module); javac.add("--patch-module", module + "=" + patch); } } if (runner.run(javac) != 0) { throw new IllegalStateException("javac failed"); } var realmModules = Files.createDirectories(realm.binModules); var realmSources = Files.createDirectories(realm.binSources); for (var module : modules) { var moduleNameDashVersion = module + '-' + project.version; var modularJar = realmModules.resolve(moduleNameDashVersion + ".jar"); var sourcesJar = realmSources.resolve(moduleNameDashVersion + "-sources.jar"); var resources = realm.srcResources; var jarModule = new Command("jar") .add("--create") .add("--file", modularJar) .addIff(verbose, "--verbose") .add("-C", realm.binClasses.resolve(module)) .add(".") .addIff(Files.isDirectory(resources), cmd -> cmd.add("-C", resources).add(".")); var jarSources = new Command("jar") .add("--create") .add("--file", sourcesJar) .addIff(verbose, "--verbose") .add("--no-manifest") .add("-C", project.src.resolve(module).resolve(realm.name).resolve("java")) .add(".") .addIff(Files.isDirectory(resources), cmd -> cmd.add("-C", resources).add(".")); if (runner.run(jarModule) != 0) { log("Creating " + realm.name + " modular jar failed: ", modularJar); return; } if (runner.run(jarSources) != 0) { log("Creating " + realm.name + " sources jar failed: ", sourcesJar); return; } } log("Bach::compile(realm=%s) end.", realm.name); } /** Launch JUnit Platform for all test modules. */ public void test() { log("Bach::test()"); if (Files.notExists(project.test.binClasses)) { out.println("Bach::test() end - no compiled test classes found."); return; } new Tester().test(project.test.modules); log("Bach::test() end."); } /** Print build summary. */ public void summary() { log("Bach::summary()"); var path = project.main.binModules; if (Files.notExists(path)) { out.println("No module destination directory created: " + path.toUri()); return; } var jars = Util.findFiles(List.of(path), Util::isJarFile); if (jars.isEmpty()) { out.printf("No module created for %s%n", project.name); return; } if (verbose) { for (var jar : jars) { runner.run(new Command("jar", "--describe-module", "--file", jar)); } runner.run( new Command( "jdeps", "--module-path", project.main.binModules, "--check", String.join(",", project.main.modules))); } out.printf("%d module(s) created for %s in %s:%n", jars.size(), project.name, path.toUri()); for (var jar : jars) { var module = ModuleFinder.of(jar).findAll().iterator().next().descriptor(); out.printf(" -> %9d %s <- %s%n", Util.size(jar), jar.getFileName(), module); } log("Bach::summary() end."); } /** Print the version string. */ public void version() { out.println(VERSION); } /** Main-entry point converting strings to commands and executing each. */ int main(List<String> arguments) { log("Bach::main(%s)", arguments); if (arguments.isEmpty()) { build(); return 0; } var commands = runner.commands(arguments); return runner.run(commands); } /** Execute the named tool and throw an error the expected and actual exit values aren't equal. */ void run(int expected, String name, Object... arguments) { log("Bach::run(%d, %s, %s)", expected, name, List.of(arguments)); var actual = run(name, arguments); if (expected != actual) { var command = name + (arguments.length == 0 ? "" : " " + List.of(arguments)); throw new Error("Expected " + expected + ", but got " + actual + " as result of: " + command); } } /** Execute the named tool and return its exit value. */ int run(String name, Object... arguments) { log("Bach::run(%s, %s)", name, List.of(arguments)); return runner.run(new Command(name, arguments)); } /** Runtime context. */ class Runner { private final UnaryOperator<ProcessBuilder> redirectIO; Runner(UnaryOperator<ProcessBuilder> redirectIO) { this.redirectIO = redirectIO; } /** Transmute strings to commands. */ List<Command> commands(List<String> strings) { var commands = new ArrayList<Command>(); var deque = new ArrayDeque<>(strings); while (!deque.isEmpty()) { var string = deque.removeFirst(); if ("tool".equals(string)) { var tool = deque.removeFirst(); commands.add(new Command(tool).addEach(deque)); break; } commands.add(new Command(string)); } return commands; } void printCommandDetails(String command, String... args) { if (args.length < 2) { out.printf("%s%s%n", command, (args.length == 1 ? " " + args[0] : "")); out.println(); return; } out.printf("%s with %d arguments%n", command, args.length); var simple = true; var indent = 8; var max = 100; // line length for (String arg : args) { indent = simple ? 8 : arg.startsWith("-") ? 8 : 10; simple = !arg.startsWith("-"); if (arg.length() > max) { if (arg.contains(File.pathSeparator)) { for (String path : arg.split(File.pathSeparator)) { out.printf("%-10s%s%n", "", path); } continue; } arg = arg.substring(0, max - 5) + "[...]"; } out.printf("%-" + indent + "s%s%n", "", arg); } out.println(); } /** Run given list of of commands sequentially and fail-fast on non-zero result. */ int run(List<Command> commands) { log("Running %s command(s): %s", commands.size(), commands); for (var command : commands) { var code = runner.run(command); if (code != 0) { return code; } } return 0; } /** Run given command. */ int run(Command command) { return run(command.name, command.toStringArray()); } /** * Run named tool, as loaded by {@link java.util.ServiceLoader} using the system class loader. */ int run(String name, String... args) { if (verbose) { printCommandDetails(name, args); } var providedTool = ToolProvider.findFirst(name); if (providedTool.isPresent()) { var tool = providedTool.get(); log("Running provided tool in-process: " + tool); return run(tool, args); } try { var method = Bach.class.getMethod(name); // no parameters log("Invoking instance method: " + method); var result = method.invoke(Bach.this); // no arguments return result instanceof Number ? ((Number) result).intValue() : 0; } catch (NoSuchMethodException e) { // fall-through } catch (ReflectiveOperationException e) { e.getCause().printStackTrace(err); return 1; } log("Starting new process for '%s'", name); var processBuilder = new ProcessBuilder(name); processBuilder.command().addAll(List.of(args)); processBuilder.environment().put("BACH_VERSION", Bach.VERSION); processBuilder.environment().put("BACH_HOME", home.toString()); processBuilder.environment().put("BACH_WORK", work.toString()); return run(redirectIO.apply(processBuilder)); } /** Run provided tool. */ int run(ToolProvider tool, String... args) { log("Bach::run(%s, %s)", tool.name(), String.join(", ", args)); var code = tool.run(out, err, args); if (code == 0) { log("Tool '%s' successfully run.", tool.name()); } return code; } /** Start new process and wait for its termination. */ int run(ProcessBuilder processBuilder) { log("Bach::run(%s)", processBuilder); try { var process = processBuilder.start(); var code = process.waitFor(); if (code == 0) { log("Process '%s' successfully terminated.", process); } return code; } catch (Exception e) { throw new Error("Starting process failed: " + e); } } } /** Command-line program argument list builder. */ static class Command { final String name; final List<String> list = new ArrayList<>(); /** Initialize Command instance with zero or more arguments. */ Command(String name, Object... args) { this.name = name; addEach(args); } /** Add single argument by invoking {@link Object#toString()} on the given argument. */ Command add(Object argument) { list.add(argument.toString()); return this; } /** Add two arguments by invoking {@link #add(Object)} for the key and value elements. */ Command add(Object key, Object value) { return add(key).add(value); } /** Add two (or zero) arguments, the key and the paths joined by system's path separator. */ Command add(Object key, Collection<Path> paths) { return add(key, paths, UnaryOperator.identity()); } /** Add two (or zero) arguments, the key and the paths joined by system's path separator. */ Command add(Object key, Collection<Path> paths, UnaryOperator<String> operator) { var stream = paths.stream().filter(Files::exists).map(Object::toString); var value = stream.collect(Collectors.joining(File.pathSeparator)); if (value.isEmpty()) { return this; } return add(key, operator.apply(value)); } /** Add all arguments by invoking {@link #add(Object)} for each element. */ Command addEach(Object... arguments) { return addEach(List.of(arguments)); } /** Add all arguments by invoking {@link #add(Object)} for each element. */ Command addEach(Iterable<?> arguments) { arguments.forEach(this::add); return this; } /** Add a single argument iff the conditions is {@code true}. */ Command addIff(boolean condition, Object argument) { return condition ? add(argument) : this; } /** Add two arguments iff the conditions is {@code true}. */ Command addIff(boolean condition, Object key, Object value) { return condition ? add(key, value) : this; } /** Let the consumer visit, usually modify, this instance iff the conditions is {@code true}. */ Command addIff(boolean condition, Consumer<Command> visitor) { if (condition) { visitor.accept(this); } return this; } @Override public String toString() { var args = list.isEmpty() ? "<empty>" : "'" + String.join("', '", list) + "'"; return "Command{name='" + name + "', list=[" + args + "]}"; } /** Returns an array of {@link String} containing all of the collected arguments. */ String[] toStringArray() { return list.toArray(String[]::new); } } /** Project information. */ class Project { final String name = home.toAbsolutePath().normalize().getFileName().toString(); final String version = System.getProperty("bach.project.version", "1.0.0-SNAPSHOT"); final Path bin = work.resolve(Path.of(System.getProperty("bach.bin", "bin"))); final Path src = home.resolve(Path.of(System.getProperty("bach.src", "src"))); final List<String> modules = Util.findDirectoryNames(src); final Realm main = new Realm("main"); final Realm test = new Realm("test", main.binModules); void toStrings(Consumer<String> consumer) { consumer.accept("Project properties"); consumer.accept(" name = " + name); consumer.accept(" version = " + version); consumer.accept(" modulesDirectory = " + src); consumer.accept(" modules = " + modules); main.toStrings(consumer); test.toStrings(consumer); } /** Project realm: main or test. */ class Realm { final String name; final String moduleSourcePath; final List<String> modules; final List<Path> modulePath; final boolean preview; final String release; final Path srcResources; final Path binClasses; final Path binModules; final Path binSources; Realm(String name, Path... initialModulePath) { this.name = name; this.modulePath = List.of(initialModulePath); this.preview = Boolean.getBoolean("bach." + name + ".preview"); this.release = System.getProperty("bach." + name + ".release", null); this.srcResources = src.resolve(name).resolve("resources"); this.binClasses = bin.resolve(name).resolve("compiled").resolve("classes"); this.binModules = bin.resolve(name).resolve("modules"); this.binSources = bin.resolve(name).resolve("sources"); if (Files.notExists(src)) { this.moduleSourcePath = src.toString(); this.modules = List.of(); return; } var modules = new ArrayList<String>(); var moduleSourcePaths = new TreeSet<String>(); var declarations = Util.findFiles(List.of(src), Util::isModuleInfo); for (var declaration : declarations) { var relative = src.relativize(declaration); // <module>/<realm>/.../module-info.java var module = relative.getName(0).toString(); var realm = relative.getName(1).toString(); if (!name.equals(realm)) { continue; } modules.add(module); var offset = relative.subpath(1, relative.getNameCount() - 1).toString(); moduleSourcePaths.add(String.join(File.separator, src.toString(), "*", offset)); } this.moduleSourcePath = String.join(File.pathSeparator, moduleSourcePaths); this.modules = List.copyOf(modules); } void toStrings(Consumer<String> consumer) { var prefix = " " + name + '.'; consumer.accept("Realm '" + name + "' properties"); consumer.accept(prefix + "modules = " + modules); consumer.accept(prefix + "moduleSourcePath = " + moduleSourcePath); } } } /** JUnit Platform Launcher. */ class Tester { final Path junit = Util.download( USER_HOME.resolve(".bach/tool/junit"), "org.junit.platform", "junit-platform-console-standalone", "1.5.0"); final Path mainRunner = Util.download( work.resolve("lib/test-runtime-only"), "de.sormuras.mainrunner", "de.sormuras.mainrunner.engine", "2.0.5"); void check(int code) { if (code == 2) { throw new Error("No tests found!"); } if (code != 0) { throw new Error("Test run failed!"); } } void test(List<String> modules) { modules.forEach(this::testModulePath); modules.forEach(this::testClassPath); } void testClassPath(String module) { var classPath = new ArrayList<Path>(); if (Files.isDirectory(project.test.binClasses)) { classPath.add(project.test.binClasses.resolve(module)); } if (Files.isDirectory(project.main.binModules)) { classPath.addAll(Util.findDirectoryEntries(project.main.binModules, "*.jar")); } classPath.add(junit); classPath.add(mainRunner); var java = new Command("java") .add("-ea") .add("--class-path", classPath) .add("org.junit.platform.console.ConsoleLauncher") .add("--fail-if-no-tests") .add("--scan-class-path"); check(runner.run(java)); } void testModulePath(String module) { var classPath = new ArrayList<Path>(); classPath.add(junit); classPath.add(mainRunner); var modulePath = new ArrayList<Path>(); modulePath.add(project.test.binModules); if (Files.isDirectory(project.main.binModules)) { modulePath.add(project.main.binModules); } var java = new Command("java") .add("-ea") .add("--module-path", modulePath) .add("--add-modules", module); if (project.main.modules.contains(module)) { var moduleNameDashVersion = module + '-' + project.version; var modularJar = project.main.binModules.resolve(moduleNameDashVersion + ".jar"); var patch = modularJar.toString(); java.add("--patch-module", module + "=" + patch); } java.add("--class-path", classPath) .add("org.junit.platform.console.ConsoleLauncher") .add("--fail-if-no-tests") .add("--select-module", module); check(runner.run(java)); } } /** Static helpers. */ static class Util { /** Download an artifact from a Maven 2 repository specified by its GAV coordinates. */ static Path download(Path destination, String group, String artifact, String version) { var host = "https://repo1.maven.org/maven2"; var path = group.replace('.', '/'); var file = artifact + '-' + version + ".jar"; var uri = URI.create(String.join("/", host, path, artifact, version, file)); try { return download(destination, uri, Boolean.getBoolean("bach.offline")); } catch (Exception e) { throw new Error("Download failed!", e); } } /** Download a file denoted by the specified uri. */ static Path download(Path destination, URI uri, boolean offline) throws Exception { // run.log(TRACE, "Downloader::download(%s)", uri); var fileName = extractFileName(uri); var target = Files.createDirectories(destination).resolve(fileName); var url = uri.toURL(); // fails for non-absolute uri if (offline) { // run.log(DEBUG, "Offline mode is active!"); if (Files.exists(target)) { // var file = target.getFileName().toString(); // run.log(DEBUG, "Target already exists: %s, %d bytes.", file, size(target)); return target; } var message = "Offline mode is active and target is missing: " + target; // run.log(ERROR, message); throw new IllegalStateException(message); } return download(destination, url.openConnection()); } /** Download a file using the given URL connection. */ static Path download(Path destination, URLConnection connection) throws Exception { var millis = connection.getLastModified(); // 0 means "unknown" var lastModified = FileTime.fromMillis(millis == 0 ? System.currentTimeMillis() : millis); // run.log(TRACE, "Remote was modified on %s", lastModified); var target = destination.resolve(extractFileName(connection)); // run.log(TRACE, "Local target file is %s", target.toUri()); // var file = target.getFileName().toString(); if (Files.exists(target)) { var fileModified = Files.getLastModifiedTime(target); // run.log(TRACE, "Local last modified on %s", fileModified); if (fileModified.equals(lastModified)) { // run.log(TRACE, "Timestamp match: %s, %d bytes.", file, size(target)); connection.getInputStream().close(); // release all opened resources return target; } // run.log(DEBUG, "Local target file differs from remote source -- replacing it..."); } try (var sourceStream = connection.getInputStream()) { try (var targetStream = Files.newOutputStream(target)) { // run.log(DEBUG, "Transferring %s...", file); sourceStream.transferTo(targetStream); } Files.setLastModifiedTime(target, lastModified); } // run.log(DEBUG, "Downloaded %s, %d bytes.", file, Files.size(target)); return target; } /** Extract last path element from the supplied uri. */ static String extractFileName(URI uri) { var path = uri.getPath(); // strip query and fragment elements return path.substring(path.lastIndexOf('/') + 1); } /** Extract target file name either from 'Content-Disposition' header or. */ static String extractFileName(URLConnection connection) { var contentDisposition = connection.getHeaderField("Content-Disposition"); if (contentDisposition != null && contentDisposition.indexOf('=') > 0) { return contentDisposition.split("=")[1].replaceAll("\"", ""); } try { return extractFileName(connection.getURL().toURI()); } catch (URISyntaxException e) { throw new Error("URL connection returned invalid URL?!", e); } } /** List names of all directories found in given directory. */ static List<String> findDirectoryNames(Path directory) { return findDirectoryEntries(directory, Files::isDirectory); } /** List paths of all entries found in given directory after applying the filter. */ static List<String> findDirectoryEntries(Path directory, DirectoryStream.Filter<Path> filter) { var names = new ArrayList<String>(); try (var stream = Files.newDirectoryStream(directory, filter)) { stream.forEach(entry -> names.add(entry.getFileName().toString())); } catch (Exception e) { throw new Error("Scanning directory entries failed: " + e); } return names; } /** List paths of all entries found in given directory after applying the glob pattern. */ static List<Path> findDirectoryEntries(Path directory, String glob) { var paths = new ArrayList<Path>(); try (var stream = Files.newDirectoryStream(directory, glob)) { stream.forEach(paths::add); } catch (Exception e) { throw new Error("Scanning directory entries failed: " + e, e); } return paths; } /** List all regular files matching the given filter. */ static List<Path> findFiles(Collection<Path> roots, Predicate<Path> filter) { var files = new ArrayList<Path>(); for (var root : roots) { try (var stream = Files.walk(root)) { stream.filter(Files::isRegularFile).filter(filter).forEach(files::add); } catch (Exception e) { throw new Error("Scanning directory '" + root + "' failed: " + e, e); } } return files; } /** List all regular Java files in given root directory. */ static List<Path> findJavaFiles(Path root) { return findFiles(List.of(root), Util::isJavaFile); } /** Test supplied path for pointing to a Java source compilation unit. */ static boolean isJavaFile(Path path) { if (Files.isRegularFile(path)) { var name = path.getFileName().toString(); if (name.endsWith(".java")) { return name.indexOf('.') == name.length() - 5; // single dot in filename } } return false; } /** Test supplied path for pointing to a Java source compilation unit. */ static boolean isJarFile(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().endsWith(".jar"); } /** Test supplied path for pointing to a Java module declaration source compilation unit. */ static boolean isModuleInfo(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().equals("module-info.java"); } /** Join supplied paths into a single string joined by current path separator. */ static String join(Collection<?> paths) { return paths.stream().map(Object::toString).collect(Collectors.joining(File.pathSeparator)); } /** Join supplied paths into a single string joined by current path separator. */ static String join(Path path, Path... more) { if (more.length == 0) { return path.toString(); } var strings = new String[1 + more.length]; strings[0] = path.toString(); for (var i = 0; i < more.length; i++) { strings[1 + i] = more[i].toString(); } return String.join(File.pathSeparator, strings); } /** Returns the size of a file in bytes. */ static long size(Path path) { try { return Files.size(path); } catch (IOException e) { throw new UncheckedIOException(e); } } /** Delete all files and directories from and including the root directory. */ static void treeDelete(Path root) throws Exception { treeDelete(root, __ -> true); } /** Delete selected files and directories from and including the root directory. */ static void treeDelete(Path root, Predicate<Path> filter) throws Exception { // trivial case: delete existing empty directory or single file if (filter.test(root)) { try { Files.deleteIfExists(root); return; } catch (DirectoryNotEmptyException ignored) { // fall-through } } // default case: walk the tree... try (var stream = Files.walk(root)) { var selected = stream.filter(filter).sorted((p, q) -> -p.compareTo(q)); for (var path : selected.collect(Collectors.toList())) { Files.deleteIfExists(path); } } } } }
src/bach/Bach.java
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // default package import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.UncheckedIOException; import java.lang.module.ModuleFinder; import java.net.URI; import java.net.URISyntaxException; import java.net.URLConnection; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.TreeSet; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.spi.ToolProvider; import java.util.stream.Collectors; /** Java Shell Builder. */ @SuppressWarnings("WeakerAccess") public class Bach { /** Version of Bach, {@link Runtime.Version#parse(String)}-compatible. */ public static final String VERSION = "2-ea"; /** Convenient short-cut to {@code "user.home"} as a path. */ static final Path USER_HOME = Path.of(System.getProperty("user.home")); /** * Main entry-point of Bach. * * @param arguments task name(s) and their argument(s) * @throws Error on a non-zero error code */ public static void main(String... arguments) { var bach = new Bach(); var args = List.of(arguments); var code = bach.main(args); if (code != 0) { throw new Error("Bach (" + args + ") failed with error code: " + code); } } private final PrintWriter out; private final PrintWriter err; private final boolean verbose; private final Path home; private final Path work; private final Runner runner; private final Project project; Bach() { this(new PrintWriter(System.out, true), new PrintWriter(System.err, true)); } Bach(PrintWriter out, PrintWriter err) { this( out, err, ProcessBuilder::inheritIO, Path.of(System.getProperty("bach.home", "")), Path.of(System.getProperty("bach.work", "")), Boolean.getBoolean("bach.verbose")); } Bach( PrintWriter out, PrintWriter err, UnaryOperator<ProcessBuilder> redirectIO, Path home, Path work, boolean verbose) { this.out = out; this.err = err; this.runner = new Runner(redirectIO); this.home = home; this.work = work; this.verbose = verbose; this.project = new Project(); log("Bach %s initialized.", VERSION); } void log(String format, Object... args) { if (verbose) { out.println(String.format(format, args)); } } /** Print runtime and project-related information. */ public void info() { log("Bach::info()"); out.println("Bach information"); out.println(" out = " + out); out.println(" err = " + err); out.println(" cwd = " + Path.of(System.getProperty("user.dir"))); out.println(" home = '" + home + "'"); out.println(" work = '" + work + "'"); out.println(" verbose = " + verbose); project.toStrings(out::println); log("Bach::info() end."); } /** Build the project. */ public void build() { log("Bach::build()"); if (verbose) { info(); } compile(); test(); summary(); log("Bach::build() end."); } /** Compile all modules. */ public void compile() { log("Bach::compile()"); compile(project.main); compile(project.test); log("Bach::compile() end."); } private void compile(Project.Realm realm) { log("Bach::compile(%s)", realm.name); if (realm.modules.isEmpty()) { log("Bach::compile(%s) end -- no modules to compile.", realm.name); return; } try { compile(realm, realm.modules); } catch (Exception e) { throw new Error("Compiling realm " + realm.name + " failed!", e); } } private void compile(Project.Realm realm, List<String> modules) throws Exception { var javac = new Command("javac") .add("-d", realm.binClasses) .add("-encoding", "UTF-8") .add("-parameters") .add("-Xlint") .addIff(realm.preview, "--enable-preview") .addIff(realm.release != null, "--release", realm.release) .add("--module-path", realm.modulePath) .add("--module-source-path", realm.moduleSourcePath) .add("--module-version", project.version) .add("--module", String.join(",", modules)); if (realm == project.test) { for (var module : modules) { if (!project.main.modules.contains(module)) { continue; } var patch = project.main.binClasses.resolve(module); // patch = project.main.moduleSourcePath.replace("*", module); javac.add("--patch-module", module + "=" + patch); } } if (runner.run(javac) != 0) { throw new IllegalStateException("javac failed"); } var realmModules = Files.createDirectories(realm.binModules); var realmSources = Files.createDirectories(realm.binSources); for (var module : modules) { var moduleNameDashVersion = module + '-' + project.version; var modularJar = realmModules.resolve(moduleNameDashVersion + ".jar"); var sourcesJar = realmSources.resolve(moduleNameDashVersion + "-sources.jar"); var resources = realm.srcResources; var jarModule = new Command("jar") .add("--create") .add("--file", modularJar) .addIff(verbose, "--verbose") .add("-C", realm.binClasses.resolve(module)) .add(".") .addIff(Files.isDirectory(resources), cmd -> cmd.add("-C", resources).add(".")); var jarSources = new Command("jar") .add("--create") .add("--file", sourcesJar) .addIff(verbose, "--verbose") .add("--no-manifest") .add("-C", project.src.resolve(module).resolve(realm.name).resolve("java")) .add(".") .addIff(Files.isDirectory(resources), cmd -> cmd.add("-C", resources).add(".")); if (runner.run(jarModule) != 0) { log("Creating " + realm.name + " modular jar failed: ", modularJar); return; } if (runner.run(jarSources) != 0) { log("Creating " + realm.name + " sources jar failed: ", sourcesJar); return; } } log("Bach::compile(realm=%s) end.", realm.name); } /** Launch JUnit Platform for all test modules. */ public void test() { log("Bach::test()"); if (Files.notExists(project.test.binClasses)) { out.println("Bach::test() end - no compiled test classes found."); return; } new Tester().test(project.test.modules); log("Bach::test() end."); } /** Print build summary. */ public void summary() { log("Bach::summary()"); var path = project.main.binModules; if (Files.notExists(path)) { out.println("No module destination directory created: " + path.toUri()); return; } var jars = Util.findFiles(List.of(path), Util::isJarFile); if (jars.isEmpty()) { out.printf("No module created for %s%n", project.name); return; } if (verbose) { for (var jar : jars) { runner.run(new Command("jar", "--describe-module", "--file", jar)); } runner.run( new Command( "jdeps", "--module-path", project.main.binModules, "--check", String.join(",", project.main.modules))); } out.printf("%d module(s) created for %s in %s:%n", jars.size(), project.name, path.toUri()); for (var jar : jars) { var module = ModuleFinder.of(jar).findAll().iterator().next().descriptor(); out.printf(" -> %9d %s <- %s%n", Util.size(jar), jar.getFileName(), module); } log("Bach::summary() end."); } /** Print the version string. */ public void version() { out.println(VERSION); } /** Main-entry point converting strings to commands and executing each. */ int main(List<String> arguments) { log("Bach::main(%s)", arguments); if (arguments.isEmpty()) { build(); return 0; } var commands = runner.commands(arguments); return runner.run(commands); } /** Execute the named tool and throw an error the expected and actual exit values aren't equal. */ void run(int expected, String name, Object... arguments) { log("Bach::run(%d, %s, %s)", expected, name, List.of(arguments)); var actual = run(name, arguments); if (expected != actual) { var command = name + (arguments.length == 0 ? "" : " " + List.of(arguments)); throw new Error("Expected " + expected + ", but got " + actual + " as result of: " + command); } } /** Execute the named tool and return its exit value. */ int run(String name, Object... arguments) { log("Bach::run(%s, %s)", name, List.of(arguments)); return runner.run(new Command(name, arguments)); } /** Runtime context. */ class Runner { private final UnaryOperator<ProcessBuilder> redirectIO; Runner(UnaryOperator<ProcessBuilder> redirectIO) { this.redirectIO = redirectIO; } /** Transmute strings to commands. */ List<Command> commands(List<String> strings) { var commands = new ArrayList<Command>(); var deque = new ArrayDeque<>(strings); while (!deque.isEmpty()) { var string = deque.removeFirst(); if ("tool".equals(string)) { var tool = deque.removeFirst(); commands.add(new Command(tool).addEach(deque)); break; } commands.add(new Command(string)); } return commands; } void printCommandDetails(String command, String... args) { if (args.length < 2) { out.printf("%s%s%n", command, (args.length == 1 ? " " + args[0] : "")); out.println(); return; } out.printf("%s with %d arguments%n", command, args.length); var simple = true; var indent = 8; var max = 100; // line length for (String arg : args) { indent = simple ? 8 : arg.startsWith("-") ? 8 : 10; simple = !arg.startsWith("-"); if (arg.length() > max) { if (arg.contains(File.pathSeparator)) { for (String path : arg.split(File.pathSeparator)) { out.printf("%-10s%s%n", "", path); } continue; } arg = arg.substring(0, max - 5) + "[...]"; } out.printf("%-" + indent + "s%s%n", "", arg); } out.println(); } /** Run given list of of commands sequentially and fail-fast on non-zero result. */ int run(List<Command> commands) { log("Running %s command(s): %s", commands.size(), commands); for (var command : commands) { var code = runner.run(command); if (code != 0) { return code; } } return 0; } /** Run given command. */ int run(Command command) { return run(command.name, command.toStringArray()); } /** * Run named tool, as loaded by {@link java.util.ServiceLoader} using the system class loader. */ int run(String name, String... args) { if (verbose) { printCommandDetails(name, args); } var providedTool = ToolProvider.findFirst(name); if (providedTool.isPresent()) { var tool = providedTool.get(); log("Running provided tool in-process: " + tool); return run(tool, args); } try { var method = Bach.class.getMethod(name); // no parameters log("Invoking instance method: " + method); var result = method.invoke(Bach.this); // no arguments return result instanceof Number ? ((Number) result).intValue() : 0; } catch (NoSuchMethodException e) { // fall-through } catch (ReflectiveOperationException e) { e.getCause().printStackTrace(err); return 1; } log("Starting new process for '%s'", name); var processBuilder = new ProcessBuilder(name); processBuilder.command().addAll(List.of(args)); processBuilder.environment().put("BACH_VERSION", Bach.VERSION); processBuilder.environment().put("BACH_HOME", home.toString()); processBuilder.environment().put("BACH_WORK", work.toString()); return run(redirectIO.apply(processBuilder)); } /** Run provided tool. */ int run(ToolProvider tool, String... args) { log("Bach::run(%s, %s)", tool.name(), String.join(", ", args)); var code = tool.run(out, err, args); if (code == 0) { log("Tool '%s' successfully run.", tool.name()); } return code; } /** Start new process and wait for its termination. */ int run(ProcessBuilder processBuilder) { log("Bach::run(%s)", processBuilder); try { var process = processBuilder.start(); var code = process.waitFor(); if (code == 0) { log("Process '%s' successfully terminated.", process); } return code; } catch (Exception e) { throw new Error("Starting process failed: " + e); } } } /** Command-line program argument list builder. */ static class Command { final String name; final List<String> list = new ArrayList<>(); /** Initialize Command instance with zero or more arguments. */ Command(String name, Object... args) { this.name = name; addEach(args); } /** Add single argument by invoking {@link Object#toString()} on the given argument. */ Command add(Object argument) { list.add(argument.toString()); return this; } /** Add two arguments by invoking {@link #add(Object)} for the key and value elements. */ Command add(Object key, Object value) { return add(key).add(value); } /** Add two (or zero) arguments, the key and the paths joined by system's path separator. */ Command add(Object key, Collection<Path> paths) { return add(key, paths, UnaryOperator.identity()); } /** Add two (or zero) arguments, the key and the paths joined by system's path separator. */ Command add(Object key, Collection<Path> paths, UnaryOperator<String> operator) { var stream = paths.stream().filter(Files::exists).map(Object::toString); var value = stream.collect(Collectors.joining(File.pathSeparator)); if (value.isEmpty()) { return this; } return add(key, operator.apply(value)); } /** Add all arguments by invoking {@link #add(Object)} for each element. */ Command addEach(Object... arguments) { return addEach(List.of(arguments)); } /** Add all arguments by invoking {@link #add(Object)} for each element. */ Command addEach(Iterable<?> arguments) { arguments.forEach(this::add); return this; } /** Add a single argument iff the conditions is {@code true}. */ Command addIff(boolean condition, Object argument) { return condition ? add(argument) : this; } /** Add two arguments iff the conditions is {@code true}. */ Command addIff(boolean condition, Object key, Object value) { return condition ? add(key, value) : this; } /** Let the consumer visit, usually modify, this instance iff the conditions is {@code true}. */ Command addIff(boolean condition, Consumer<Command> visitor) { if (condition) { visitor.accept(this); } return this; } @Override public String toString() { var args = list.isEmpty() ? "<empty>" : "'" + String.join("', '", list) + "'"; return "Command{name='" + name + "', list=[" + args + "]}"; } /** Returns an array of {@link String} containing all of the collected arguments. */ String[] toStringArray() { return list.toArray(String[]::new); } } /** Project information. */ class Project { final String name = home.toAbsolutePath().normalize().getFileName().toString(); final String version = System.getProperty("bach.project.version", "1.0.0-SNAPSHOT"); final Path bin = work.resolve(Path.of(System.getProperty("bach.bin", "bin"))); final Path src = home.resolve(Path.of(System.getProperty("bach.src", "src"))); final List<String> modules = Util.findDirectoryNames(src); final Realm main = new Realm("main"); final Realm test = new Realm("test", main.binModules); void toStrings(Consumer<String> consumer) { consumer.accept("Project properties"); consumer.accept(" name = " + name); consumer.accept(" version = " + version); consumer.accept(" modulesDirectory = " + src); consumer.accept(" modules = " + modules); main.toStrings(consumer); test.toStrings(consumer); } /** Project realm: main or test. */ class Realm { final String name; final String moduleSourcePath; final List<String> modules; final List<Path> modulePath; final boolean preview; final String release; final Path srcResources; final Path binClasses; final Path binModules; final Path binSources; Realm(String name, Path... initialModulePath) { this.name = name; this.modulePath = List.of(initialModulePath); this.preview = Boolean.getBoolean("bach." + name + ".preview"); this.release = System.getProperty("bach." + name + ".release", null); this.srcResources = src.resolve(name).resolve("resources"); this.binClasses = bin.resolve(name).resolve("compiled").resolve("classes"); this.binModules = bin.resolve(name).resolve("modules"); this.binSources = bin.resolve(name).resolve("sources"); if (Files.notExists(src)) { this.moduleSourcePath = src.toString(); this.modules = List.of(); return; } var modules = new ArrayList<String>(); var moduleSourcePaths = new TreeSet<String>(); var declarations = Util.findFiles(List.of(src), Util::isModuleInfo); for (var declaration : declarations) { var relative = src.relativize(declaration); // <module>/<realm>/.../module-info.java var module = relative.getName(0).toString(); var realm = relative.getName(1).toString(); if (!name.equals(realm)) { continue; } modules.add(module); var offset = relative.subpath(1, relative.getNameCount() - 1).toString(); moduleSourcePaths.add(String.join(File.separator, src.toString(), "*", offset)); } this.moduleSourcePath = String.join(File.pathSeparator, moduleSourcePaths); this.modules = List.copyOf(modules); } void toStrings(Consumer<String> consumer) { var prefix = " " + name + '.'; consumer.accept("Realm '" + name + "' properties"); consumer.accept(prefix + "modules = " + modules); consumer.accept(prefix + "moduleSourcePath = " + moduleSourcePath); } } } /** JUnit Platform Launcher. */ class Tester { final Path junit = Util.download( USER_HOME.resolve(".bach/tool/junit"), "org.junit.platform", "junit-platform-console-standalone", "1.5.0"); final Path mainRunner = Util.download( work.resolve("lib/test-runtime-only"), "de.sormuras.mainrunner", "de.sormuras.mainrunner.engine", "2.0.5"); void check(int code) { if (code == 2) { throw new Error("No tests found!"); } if (code != 0) { throw new Error("Test run failed!"); } } void test(List<String> modules) { modules.forEach(this::testClassPath); } void testClassPath(String module) { var classPath = new ArrayList<Path>(); if (Files.isDirectory(project.test.binClasses)) { classPath.add(project.test.binClasses.resolve(module)); } if (Files.isDirectory(project.main.binModules)) { classPath.addAll(Util.findDirectoryEntries(project.main.binModules, "*.jar")); } classPath.add(junit); classPath.add(mainRunner); var java = new Command("java") .add("-ea") .add("--class-path", classPath) .add("org.junit.platform.console.ConsoleLauncher") .add("--fail-if-no-tests") .add("--scan-class-path"); check(runner.run(java)); } } /** Static helpers. */ static class Util { /** Download an artifact from a Maven 2 repository specified by its GAV coordinates. */ static Path download(Path destination, String group, String artifact, String version) { var host = "https://repo1.maven.org/maven2"; var path = group.replace('.', '/'); var file = artifact + '-' + version + ".jar"; var uri = URI.create(String.join("/", host, path, artifact, version, file)); try { return download(destination, uri, Boolean.getBoolean("bach.offline")); } catch (Exception e) { throw new Error("Download failed!", e); } } /** Download a file denoted by the specified uri. */ static Path download(Path destination, URI uri, boolean offline) throws Exception { // run.log(TRACE, "Downloader::download(%s)", uri); var fileName = extractFileName(uri); var target = Files.createDirectories(destination).resolve(fileName); var url = uri.toURL(); // fails for non-absolute uri if (offline) { // run.log(DEBUG, "Offline mode is active!"); if (Files.exists(target)) { // var file = target.getFileName().toString(); // run.log(DEBUG, "Target already exists: %s, %d bytes.", file, size(target)); return target; } var message = "Offline mode is active and target is missing: " + target; // run.log(ERROR, message); throw new IllegalStateException(message); } return download(destination, url.openConnection()); } /** Download a file using the given URL connection. */ static Path download(Path destination, URLConnection connection) throws Exception { var millis = connection.getLastModified(); // 0 means "unknown" var lastModified = FileTime.fromMillis(millis == 0 ? System.currentTimeMillis() : millis); // run.log(TRACE, "Remote was modified on %s", lastModified); var target = destination.resolve(extractFileName(connection)); // run.log(TRACE, "Local target file is %s", target.toUri()); // var file = target.getFileName().toString(); if (Files.exists(target)) { var fileModified = Files.getLastModifiedTime(target); // run.log(TRACE, "Local last modified on %s", fileModified); if (fileModified.equals(lastModified)) { // run.log(TRACE, "Timestamp match: %s, %d bytes.", file, size(target)); connection.getInputStream().close(); // release all opened resources return target; } // run.log(DEBUG, "Local target file differs from remote source -- replacing it..."); } try (var sourceStream = connection.getInputStream()) { try (var targetStream = Files.newOutputStream(target)) { // run.log(DEBUG, "Transferring %s...", file); sourceStream.transferTo(targetStream); } Files.setLastModifiedTime(target, lastModified); } // run.log(DEBUG, "Downloaded %s, %d bytes.", file, Files.size(target)); return target; } /** Extract last path element from the supplied uri. */ static String extractFileName(URI uri) { var path = uri.getPath(); // strip query and fragment elements return path.substring(path.lastIndexOf('/') + 1); } /** Extract target file name either from 'Content-Disposition' header or. */ static String extractFileName(URLConnection connection) { var contentDisposition = connection.getHeaderField("Content-Disposition"); if (contentDisposition != null && contentDisposition.indexOf('=') > 0) { return contentDisposition.split("=")[1].replaceAll("\"", ""); } try { return extractFileName(connection.getURL().toURI()); } catch (URISyntaxException e) { throw new Error("URL connection returned invalid URL?!", e); } } /** List names of all directories found in given directory. */ static List<String> findDirectoryNames(Path directory) { return findDirectoryEntries(directory, Files::isDirectory); } /** List paths of all entries found in given directory after applying the filter. */ static List<String> findDirectoryEntries(Path directory, DirectoryStream.Filter<Path> filter) { var names = new ArrayList<String>(); try (var stream = Files.newDirectoryStream(directory, filter)) { stream.forEach(entry -> names.add(entry.getFileName().toString())); } catch (Exception e) { throw new Error("Scanning directory entries failed: " + e); } return names; } /** List paths of all entries found in given directory after applying the glob pattern. */ static List<Path> findDirectoryEntries(Path directory, String glob) { var paths = new ArrayList<Path>(); try (var stream = Files.newDirectoryStream(directory, glob)) { stream.forEach(paths::add); } catch (Exception e) { throw new Error("Scanning directory entries failed: " + e, e); } return paths; } /** List all regular files matching the given filter. */ static List<Path> findFiles(Collection<Path> roots, Predicate<Path> filter) { var files = new ArrayList<Path>(); for (var root : roots) { try (var stream = Files.walk(root)) { stream.filter(Files::isRegularFile).filter(filter).forEach(files::add); } catch (Exception e) { throw new Error("Scanning directory '" + root + "' failed: " + e, e); } } return files; } /** List all regular Java files in given root directory. */ static List<Path> findJavaFiles(Path root) { return findFiles(List.of(root), Util::isJavaFile); } /** Test supplied path for pointing to a Java source compilation unit. */ static boolean isJavaFile(Path path) { if (Files.isRegularFile(path)) { var name = path.getFileName().toString(); if (name.endsWith(".java")) { return name.indexOf('.') == name.length() - 5; // single dot in filename } } return false; } /** Test supplied path for pointing to a Java source compilation unit. */ static boolean isJarFile(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().endsWith(".jar"); } /** Test supplied path for pointing to a Java module declaration source compilation unit. */ static boolean isModuleInfo(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().equals("module-info.java"); } /** Join supplied paths into a single string joined by current path separator. */ static String join(Collection<?> paths) { return paths.stream().map(Object::toString).collect(Collectors.joining(File.pathSeparator)); } /** Join supplied paths into a single string joined by current path separator. */ static String join(Path path, Path... more) { if (more.length == 0) { return path.toString(); } var strings = new String[1 + more.length]; strings[0] = path.toString(); for (var i = 0; i < more.length; i++) { strings[1 + i] = more[i].toString(); } return String.join(File.pathSeparator, strings); } /** Returns the size of a file in bytes. */ static long size(Path path) { try { return Files.size(path); } catch (IOException e) { throw new UncheckedIOException(e); } } /** Delete all files and directories from and including the root directory. */ static void treeDelete(Path root) throws Exception { treeDelete(root, __ -> true); } /** Delete selected files and directories from and including the root directory. */ static void treeDelete(Path root, Predicate<Path> filter) throws Exception { // trivial case: delete existing empty directory or single file if (filter.test(root)) { try { Files.deleteIfExists(root); return; } catch (DirectoryNotEmptyException ignored) { // fall-through } } // default case: walk the tree... try (var stream = Files.walk(root)) { var selected = stream.filter(filter).sorted((p, q) -> -p.compareTo(q)); for (var path : selected.collect(Collectors.toList())) { Files.deleteIfExists(path); } } } } }
Add testModulePath() to Tester class
src/bach/Bach.java
Add testModulePath() to Tester class
Java
mit
df828467a500ba3767ed80985a4942f8cb0bcfc1
0
ITB15-S4-GroupD/Planchester,ITB15-S4-GroupD/Planchester
package Utils; import javax.xml.bind.ValidationException; import java.security.DomainCombiner; import java.sql.Timestamp; import java.util.Date; /** * Created by julia on 19.04.2017. */ public class Validator { public static void validateString(String s, int maxLength) throws ValidationException { if(s != null && s.length() > maxLength) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryString(String s) throws ValidationException { if(s == null || s.isEmpty()) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryString(String s, int maxLength) throws ValidationException { if(s == null || s.isEmpty() || s.length() > maxLength) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateInteger(Integer i, int minValue, int maxValue) throws ValidationException { if(i != null && (i < minValue || i > maxValue)) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryInteger(Integer i) throws ValidationException { if(i == null) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryInteger(Integer i, int minValue, int maxValue) throws ValidationException { if(i == null || i < minValue || i > maxValue) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateDouble(Double d, double minValue, double maxValue) throws ValidationException { if(d != null && (d < minValue || d > maxValue)) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryDouble(Double d) throws ValidationException { if(d == null) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryDouble(Double d, double minValue, double maxValue) throws ValidationException { if(d == null || d < minValue || d > maxValue) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryTimestamp(Timestamp timestamp) throws ValidationException { if(timestamp == null) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateTimestampAfterToday(Timestamp timestamp) throws ValidationException { if(timestamp != null && timestamp.before(new Date())) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateTimestamp1BeforeTimestamp2(Timestamp timestamp1, Timestamp timestamp2) throws ValidationException { if(timestamp1 != null && timestamp2 != null && timestamp1.after(timestamp2)) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } }
src/Utils/Validator.java
package Utils; import javax.xml.bind.ValidationException; import java.security.DomainCombiner; import java.sql.Timestamp; import java.util.Date; /** * Created by julia on 19.04.2017. */ public class Validator { public static void validateString(String s, int maxLength) throws ValidationException { if(s != null && s.length() > maxLength) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryString(String s) throws ValidationException { if(s == null || s.isEmpty()) { if(s != null && s.length() > maxLength) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryString(String s, int maxLength) throws ValidationException { if(s == null || s.isEmpty() || s.length() > maxLength) { if(s != null && s.length() > maxLength) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateInteger(Integer i, int minValue, int maxValue) throws ValidationException { if(i != null && (i < minValue || i > maxValue)) { if(s != null && s.length() > maxLength) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryInteger(Integer i) throws ValidationException { if(s != null && s.length() > maxLength) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryInteger(Integer i, int minValue, int maxValue) throws ValidationException { if(s != null && s.length() > maxLength) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateDouble(Double d, double minValue, double maxValue) throws ValidationException { if(d != null && (d < minValue || d > maxValue)) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryDouble(Double d) throws ValidationException { if(d == null) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryDouble(Double d, double minValue, double maxValue) throws ValidationException { if(d == null || d < minValue || d > maxValue) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateMandatoryTimestamp(Timestamp timestamp) throws ValidationException { if(timestamp == null) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateTimestampAfterToday(Timestamp timestamp) throws ValidationException { if(timestamp != null && timestamp.before(new Date())) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } public static void validateTimestamp1BeforeTimestamp2(Timestamp timestamp1, Timestamp timestamp2) throws ValidationException { if(timestamp1 != null && timestamp2 != null && timestamp1.after(timestamp2)) { throw new ValidationException(PlanchesterMessages.VALIDATION_FAILDED); } } }
Validator solved
src/Utils/Validator.java
Validator solved
Java
mpl-2.0
a7486e2882fd0dd66d1d8f7599f1b43a8eaa3ec6
0
sensiasoft/lib-swe-common
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.vast.swe; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.HashSet; import net.opengis.swe.v20.DataComponent; import net.opengis.swe.v20.DataEncoding; import net.opengis.swe.v20.ScalarComponent; /** * <p> * Delegating writer for writing only the selected components.<br/> * This is used to implement filtering by observed property in SOS. * </p> * * @author Alex Robin <[email protected]> * @since Oct 9, 2015 */ public class FilteredWriter extends AbstractDataWriter { AbstractDataWriter writer; HashSet<String> enabledDefUris; Record enabledRecord; public FilteredWriter(AbstractDataWriter writer, Collection<String> enabledDefUris) { this.writer = writer; this.enabledDefUris = new HashSet<String>(); this.enabledDefUris.addAll(enabledDefUris); } @Override protected void processAtom(ScalarComponent component) throws IOException { if (isComponentEnabled(component) || isParentEnabled(component)) writer.processAtom(component); } @Override protected boolean processBlock(DataComponent component) throws IOException { if (!isParentEnabled(component) && isComponentEnabled(component)) enabledRecord = currentRecord; return writer.processBlock(component); } private boolean isParentEnabled(DataComponent component) { if (enabledRecord != null && componentStack.contains(enabledRecord)) return true; return false; } private boolean isComponentEnabled(DataComponent component) { String defUri = component.getDefinition(); if (enabledDefUris != null && defUri != null) { if (!enabledDefUris.contains(defUri)) return false; } return true; } @Override protected void endDataBlock() throws Exception { writer.endDataBlock(); } @Override public void setDataComponents(DataComponent dataInfo) { writer.setDataComponents(dataInfo); super.dataComponents = writer.getDataComponents(); } @Override public void setDataEncoding(DataEncoding dataEncoding) { writer.setDataEncoding(dataEncoding); super.dataEncoding = writer.getDataEncoding(); } @Override public void setOutput(OutputStream os) throws IOException { writer.setOutput(os); } @Override public void close() throws IOException { writer.close(); } @Override public void flush() throws IOException { writer.flush(); } @Override public void reset() { super.reset(); writer.reset(); } }
swe-common-core/src/main/java/org/vast/swe/FilteredWriter.java
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.vast.swe; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.HashSet; import net.opengis.swe.v20.DataComponent; import net.opengis.swe.v20.DataEncoding; import net.opengis.swe.v20.ScalarComponent; /** * <p> * Delegating writer for writing only the selected components.<br/> * This is used to implement filtering by observed property in SOS. * </p> * * @author Alex Robin <[email protected]> * @since Oct 9, 2015 */ public class FilteredWriter extends AbstractDataWriter { AbstractDataWriter writer; HashSet<String> enabledDefUris; Record enabledRecord; public FilteredWriter(AbstractDataWriter writer, Collection<String> enabledDefUris) { this.writer = writer; this.enabledDefUris = new HashSet<String>(); this.enabledDefUris.addAll(enabledDefUris); } @Override protected void processAtom(ScalarComponent component) throws IOException { if (isComponentEnabled(component)) writer.processAtom(component); } @Override protected boolean processBlock(DataComponent component) throws IOException { if (isComponentEnabled(component)) enabledRecord = currentRecord; return writer.processBlock(component); } private boolean isComponentEnabled(DataComponent component) { if (enabledRecord != null && componentStack.contains(enabledRecord)) return true; String defUri = component.getDefinition(); if (enabledDefUris != null && defUri != null) { if (!enabledDefUris.contains(defUri)) return false; } return true; } @Override protected void endDataBlock() throws Exception { writer.endDataBlock(); } @Override public void setDataComponents(DataComponent dataInfo) { writer.setDataComponents(dataInfo); super.dataComponents = writer.getDataComponents(); } @Override public void setDataEncoding(DataEncoding dataEncoding) { writer.setDataEncoding(dataEncoding); super.dataEncoding = writer.getDataEncoding(); } @Override public void setOutput(OutputStream os) throws IOException { writer.setOutput(os); } @Override public void close() throws IOException { writer.close(); } @Override public void flush() throws IOException { writer.flush(); } @Override public void reset() { super.reset(); writer.reset(); } }
Fixed bug occuring with nested record structures in FilteredWriter
swe-common-core/src/main/java/org/vast/swe/FilteredWriter.java
Fixed bug occuring with nested record structures in FilteredWriter
Java
mpl-2.0
a36f6cdb34dd83f50dc396e1ca3962a31e04fb8c
0
Wurst-Imperium/Wurst-MC-1.11
/* * Copyright 2014 - 2017 | Wurst-Imperium | All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package net.wurstclient.features.mods; import net.minecraft.item.ItemFishingRod; import net.minecraft.item.ItemStack; import net.minecraft.network.play.server.SPacketSoundEffect; import net.wurstclient.compatibility.WMinecraft; import net.wurstclient.compatibility.WPlayerController; import net.wurstclient.compatibility.WSoundEvents; import net.wurstclient.events.PacketInputEvent; import net.wurstclient.events.listeners.PacketInputListener; import net.wurstclient.events.listeners.UpdateListener; import net.wurstclient.settings.CheckboxSetting; import net.wurstclient.utils.ChatUtils; import net.wurstclient.utils.InventoryUtils; @Mod.Info( description = "Automatically catches fish until either all of your fishing rods are completely used up or your\n" + "inventory is completely full. If fishing rods are placed outside of the hotbar, they will\n" + "automatically be moved into the hotbar once needed.", name = "AutoFish", tags = "FishBot, auto fish, fish bot, fishing", help = "Mods/AutoFish") @Mod.Bypasses public final class AutoFishMod extends Mod implements UpdateListener, PacketInputListener { private final CheckboxSetting overfillInventory = new CheckboxSetting("Overfill inventory", false); private int timer; @Override public void initSettings() { settings.add(overfillInventory); } @Override public void onEnable() { wurst.events.add(UpdateListener.class, this); wurst.events.add(PacketInputListener.class, this); } @Override public void onDisable() { wurst.events.remove(UpdateListener.class, this); wurst.events.remove(PacketInputListener.class, this); // reset timer timer = 0; } @Override public void onUpdate() { // check if inventory is full if(!overfillInventory.isChecked() && WMinecraft.getPlayer().inventory.getFirstEmptyStack() == -1) { ChatUtils.message("Inventory is full."); setEnabled(false); return; } // search fishing rod in hotbar int rodInHotbar = -1; for(int i = 0; i < 9; i++) { // skip non-rod items ItemStack stack = WMinecraft.getPlayer().inventory.getStackInSlot(i); if(InventoryUtils.isEmptySlot(stack) || !(stack.getItem() instanceof ItemFishingRod)) continue; rodInHotbar = i; break; } // check if any rod was found if(rodInHotbar != -1) { // select fishing rod if(WMinecraft.getPlayer().inventory.currentItem != rodInHotbar) { WMinecraft.getPlayer().inventory.currentItem = rodInHotbar; return; } // wait for timer if(timer > 0) { timer--; return; } // check bobber if(WMinecraft.getPlayer().fishEntity != null) return; // cast rod rightClick(); return; } // search fishing rod in inventory int rodInInventory = -1; for(int i = 9; i < 36; i++) { // skip non-rod items ItemStack stack = WMinecraft.getPlayer().inventory.getStackInSlot(i); if(InventoryUtils.isEmptySlot(stack) || !(stack.getItem() instanceof ItemFishingRod)) continue; rodInInventory = i; break; } // check if completely out of rods if(rodInInventory == -1) { ChatUtils.message("Out of fishing rods."); setEnabled(false); return; } // find empty hotbar slot int hotbarSlot = -1; for(int i = 0; i < 9; i++) { // skip non-empty slots if(!InventoryUtils.isSlotEmpty(i)) continue; hotbarSlot = i; break; } // check if hotbar is full boolean swap = false; if(hotbarSlot == -1) { hotbarSlot = WMinecraft.getPlayer().inventory.currentItem; swap = true; } // place rod in hotbar slot WPlayerController.windowClick_PICKUP(rodInInventory); WPlayerController.windowClick_PICKUP(36 + hotbarSlot); // swap old hotbar item with rod if(swap) WPlayerController.windowClick_PICKUP(rodInInventory); } @Override public void onReceivedPacket(PacketInputEvent event) { // check packet type if(!(event.getPacket() instanceof SPacketSoundEffect)) return; // check sound type if(!WSoundEvents.isBobberSplash((SPacketSoundEffect)event.getPacket())) return; // catch fish rightClick(); } private void rightClick() { // check held item ItemStack stack = WMinecraft.getPlayer().inventory.getCurrentItem(); if(InventoryUtils.isEmptySlot(stack) || !(stack.getItem() instanceof ItemFishingRod)) return; // right click mc.rightClickMouse(); // reset timer timer = 15; } }
shared-src/net/wurstclient/features/mods/AutoFishMod.java
/* * Copyright 2014 - 2017 | Wurst-Imperium | All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package net.wurstclient.features.mods; import net.minecraft.item.ItemFishingRod; import net.minecraft.item.ItemStack; import net.minecraft.network.play.server.SPacketSoundEffect; import net.wurstclient.compatibility.WMinecraft; import net.wurstclient.compatibility.WPlayerController; import net.wurstclient.compatibility.WSoundEvents; import net.wurstclient.events.PacketInputEvent; import net.wurstclient.events.listeners.PacketInputListener; import net.wurstclient.events.listeners.UpdateListener; import net.wurstclient.utils.ChatUtils; import net.wurstclient.utils.InventoryUtils; @Mod.Info( description = "Automatically catches fish until either all of your fishing rods are completely used up or your\n" + "inventory is completely full. If fishing rods are placed outside of the hotbar, they will\n" + "automatically be moved into the hotbar once needed.", name = "AutoFish", tags = "FishBot, auto fish, fish bot, fishing", help = "Mods/AutoFish") @Mod.Bypasses public final class AutoFishMod extends Mod implements UpdateListener, PacketInputListener { private int timer; @Override public void onEnable() { wurst.events.add(UpdateListener.class, this); wurst.events.add(PacketInputListener.class, this); } @Override public void onDisable() { wurst.events.remove(UpdateListener.class, this); wurst.events.remove(PacketInputListener.class, this); // reset timer timer = 0; } @Override public void onUpdate() { // check if inventory is full if(WMinecraft.getPlayer().inventory.getFirstEmptyStack() == -1) { ChatUtils.message("Inventory is full."); setEnabled(false); return; } // search fishing rod in hotbar int rodInHotbar = -1; for(int i = 0; i < 9; i++) { // skip non-rod items ItemStack stack = WMinecraft.getPlayer().inventory.getStackInSlot(i); if(InventoryUtils.isEmptySlot(stack) || !(stack.getItem() instanceof ItemFishingRod)) continue; rodInHotbar = i; break; } // check if any rod was found if(rodInHotbar != -1) { // select fishing rod if(WMinecraft.getPlayer().inventory.currentItem != rodInHotbar) { WMinecraft.getPlayer().inventory.currentItem = rodInHotbar; return; } // wait for timer if(timer > 0) { timer--; return; } // check bobber if(WMinecraft.getPlayer().fishEntity != null) return; // cast rod rightClick(); return; } // search fishing rod in inventory int rodInInventory = -1; for(int i = 9; i < 36; i++) { // skip non-rod items ItemStack stack = WMinecraft.getPlayer().inventory.getStackInSlot(i); if(InventoryUtils.isEmptySlot(stack) || !(stack.getItem() instanceof ItemFishingRod)) continue; rodInInventory = i; break; } // check if completely out of rods if(rodInInventory == -1) { ChatUtils.message("Out of fishing rods."); setEnabled(false); return; } // find empty hotbar slot int hotbarSlot = -1; for(int i = 0; i < 9; i++) { // skip non-empty slots if(!InventoryUtils.isSlotEmpty(i)) continue; hotbarSlot = i; break; } // check if hotbar is full boolean swap = false; if(hotbarSlot == -1) { hotbarSlot = WMinecraft.getPlayer().inventory.currentItem; swap = true; } // place rod in hotbar slot WPlayerController.windowClick_PICKUP(rodInInventory); WPlayerController.windowClick_PICKUP(36 + hotbarSlot); // swap old hotbar item with rod if(swap) WPlayerController.windowClick_PICKUP(rodInInventory); } @Override public void onReceivedPacket(PacketInputEvent event) { // check packet type if(!(event.getPacket() instanceof SPacketSoundEffect)) return; // check sound type if(!WSoundEvents.isBobberSplash((SPacketSoundEffect)event.getPacket())) return; // catch fish rightClick(); } private void rightClick() { // check held item ItemStack stack = WMinecraft.getPlayer().inventory.getCurrentItem(); if(InventoryUtils.isEmptySlot(stack) || !(stack.getItem() instanceof ItemFishingRod)) return; // right click mc.rightClickMouse(); // reset timer timer = 15; } }
Improve AutoFishMod
shared-src/net/wurstclient/features/mods/AutoFishMod.java
Improve AutoFishMod
Java
agpl-3.0
60bf7e1e649b39c5104cfd5243b9c18ccb82c185
0
donsunsoft/axelor-development-kit,marioestradarosa/axelor-development-kit,marioestradarosa/axelor-development-kit,marioestradarosa/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,donsunsoft/axelor-development-kit,marioestradarosa/axelor-development-kit,donsunsoft/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,donsunsoft/axelor-development-kit
package com.axelor.data.csv; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import au.com.bytecode.opencsv.CSVReader; import com.axelor.data.ImportException; import com.axelor.data.ImportTask; import com.axelor.data.Importer; import com.axelor.data.Listener; import com.axelor.data.adapter.DataAdapter; import com.axelor.db.JPA; import com.axelor.db.Model; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Injector; public class CSVImporter implements Importer { private Logger LOG = LoggerFactory.getLogger(getClass()); private File dataDir; private Injector injector; private CSVConfig config; private List<Listener> listeners = Lists.newArrayList(); private Map<String, Object> context; public void addListener(Listener listener) { this.listeners.add(listener); } public void clearListener() { this.listeners.clear(); } public void setContext(Map<String, Object> context) { this.context = context; } public CSVImporter(Injector injector, String configFile) { this(injector, configFile, null); } @Inject public CSVImporter(Injector injector, @Named("axelor.data.config") String config, @Named("axelor.data.dir") String dataDir) { File _file = new File(config); Preconditions.checkNotNull(_file); Preconditions.checkArgument(_file.isFile()); if (dataDir != null) { File _data = new File(dataDir); Preconditions.checkNotNull(_data); Preconditions.checkArgument(_data.isDirectory()); this.dataDir = _data; } this.config = CSVConfig.parse(_file); this.injector = injector; } private List<File> getFiles(String... names) { List<File> all = Lists.newArrayList(); for (String name : names) all.add(new File(dataDir, name)); return all; } /** * Run the task from the configured readers * @param task */ public void runTask(ImportTask task) { try { if (task.readers.isEmpty()) { task.configure(); } for (CSVInput input : config.getInputs()) { for(Reader reader : task.readers.get(input.getFileName())) { try { this.process(input, reader); } catch (IOException e) { if (LOG.isErrorEnabled()){ LOG.error("I/O error while accessing {}.", input.getFileName()); } if (!task.handle(e)) { break; } } catch (ClassNotFoundException e) { if (LOG.isErrorEnabled()) { LOG.error("Error while importing {}.", input.getFileName()); LOG.error("No such class found {}.", input.getTypeName()); } if (!task.handle(e)) { break; } } catch(Exception e){ if (!task.handle(new ImportException(e))) { break; } } } } } catch(IOException e) { throw new IllegalArgumentException(e); } finally { task.readers.clear(); } } @Override public void run(Map<String, String[]> mappings) throws IOException { if (mappings == null) { mappings = new HashMap<String, String[]>(); } for (CSVInput input : config.getInputs()) { String fileName = input.getFileName(); Pattern pattern = Pattern.compile("\\[([\\w.]+)\\]"); Matcher matcher = pattern.matcher(fileName); List<File> files = matcher.matches() ? this.getFiles(mappings.get(matcher.group(1))) : this.getFiles(fileName); for(File file : files) { try { this.process(input, file); } catch (IOException e) { if (LOG.isErrorEnabled()) LOG.error("Error while accessing {}.", file); } catch (ClassNotFoundException e) { if (LOG.isErrorEnabled()) { LOG.error("Error while importing {}.", file); LOG.error("No such class found {}.", input.getTypeName()); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error while importing {}.", file); LOG.error("Unable to import data."); LOG.error("With following exception:", e); } } } } } /** * Check if the String array is empty. * @param line * @return <code>true</code> if line is null or empty, <code>false</code> otherwise */ private boolean isEmpty(String[] line) { if (line == null || line.length == 0) return true; if (line.length == 1 && (line[0] == null || "".equals(line[0].trim()))) return true; return false; } /** * Lauch the import for the input and file. * @param input * @param file * @throws IOException * @throws ClassNotFoundException */ private void process(CSVInput input, File file) throws IOException, ClassNotFoundException { this.process(input, new FileReader(file)); } /** * Lauch the import for the input and reader. * @param csvInput * @param reader * @throws IOException * @throws ClassNotFoundException */ private void process(CSVInput csvInput, Reader reader) throws IOException, ClassNotFoundException { String beanName = csvInput.getTypeName(); if (LOG.isInfoEnabled()) { LOG.info("Importing {} from {}", beanName, csvInput.getFileName()); } BufferedReader streamReader = new BufferedReader(reader); CSVReader csvReader = new CSVReader(streamReader, csvInput.getSeparator()); String[] fields = csvReader.readNext(); Class<?> beanClass = Class.forName(beanName); if (LOG.isDebugEnabled()) LOG.debug("Header {}", Arrays.asList(fields)); CSVBinder binder = new CSVBinder(beanClass, fields, csvInput); String[] values = null; int count = 0; JPA.em().getTransaction().begin(); try { Map<String, Object> context = Maps.newHashMap(); //Put global context if (this.context != null) { context.putAll(this.context); } csvInput.callPrepareContext(context, injector); // register type adapters for(DataAdapter adapter : defaultAdapters) { binder.registerAdapter(adapter); } for(DataAdapter adapter : this.config.getAdapters()) { binder.registerAdapter(adapter); } for(DataAdapter adapter : csvInput.getAdapters()) { binder.registerAdapter(adapter); } //Process for each lines while((values = csvReader.readNext()) != null) { if (isEmpty(values)) continue; if (LOG.isDebugEnabled()) { LOG.debug("Record {}", Arrays.asList(values)); } try { Map<String, Object> ctx = Maps.newHashMap(context); Object bean = binder.bind(values, ctx); if (LOG.isTraceEnabled()) LOG.trace("bean created: {}", bean); bean = csvInput.call(bean, ctx, injector); if (bean != null) { JPA.manage((Model) bean); count++; for(Listener listener : listeners) { listener.imported((Model) bean); } } LOG.debug("bean saved: {}", bean); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error while importing {}.", csvInput.getFileName()); LOG.error("Unable to import record: {}", Arrays.asList(values)); LOG.error("With following exception:", e); } // Recover the transaction if (JPA.em().getTransaction().getRollbackOnly()) { JPA.em().getTransaction().rollback(); } if (!JPA.em().getTransaction().isActive()) { JPA.em().getTransaction().begin(); } } if (count % 20 == 0) { JPA.flush(); JPA.em().clear(); } } if (JPA.em().getTransaction().isActive()){ JPA.em().getTransaction().commit(); JPA.em().clear(); } } catch (Exception e) { if (JPA.em().getTransaction().isActive()) JPA.em().getTransaction().rollback(); if (LOG.isErrorEnabled()) LOG.error("Error while importing {}.", csvInput.getFileName()); LOG.error("Unable to import data."); LOG.error("With following exception:", e); } finally { for(Listener listener : listeners) { listener.imported(count); } csvReader.close(); } } }
axelor-data/src/main/java/com/axelor/data/csv/CSVImporter.java
package com.axelor.data.csv; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import au.com.bytecode.opencsv.CSVReader; import com.axelor.data.ImportException; import com.axelor.data.ImportTask; import com.axelor.data.Importer; import com.axelor.data.Listener; import com.axelor.data.adapter.DataAdapter; import com.axelor.db.JPA; import com.axelor.db.Model; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Injector; public class CSVImporter implements Importer { private Logger LOG = LoggerFactory.getLogger(getClass()); private File dataDir; private Injector injector; private CSVConfig config; private List<Listener> listeners = Lists.newArrayList(); private Map<String, Object> context; public void addListener(Listener listener) { this.listeners.add(listener); } public void setContext(Map<String, Object> context) { this.context = context; } public CSVImporter(Injector injector, String configFile) { this(injector, configFile, null); } @Inject public CSVImporter(Injector injector, @Named("axelor.data.config") String config, @Named("axelor.data.dir") String dataDir) { File _file = new File(config); Preconditions.checkNotNull(_file); Preconditions.checkArgument(_file.isFile()); if (dataDir != null) { File _data = new File(dataDir); Preconditions.checkNotNull(_data); Preconditions.checkArgument(_data.isDirectory()); this.dataDir = _data; } this.config = CSVConfig.parse(_file); this.injector = injector; } private List<File> getFiles(String... names) { List<File> all = Lists.newArrayList(); for (String name : names) all.add(new File(dataDir, name)); return all; } /** * Run the task from the configured readers * @param task */ public void runTask(ImportTask task) { try { if (task.readers.isEmpty()) { task.configure(); } for (CSVInput input : config.getInputs()) { for(Reader reader : task.readers.get(input.getFileName())) { try { this.process(input, reader); } catch (IOException e) { if (LOG.isErrorEnabled()){ LOG.error("I/O error while accessing {}.", input.getFileName()); } if (!task.handle(e)) { break; } } catch (ClassNotFoundException e) { if (LOG.isErrorEnabled()) { LOG.error("Error while importing {}.", input.getFileName()); LOG.error("No such class found {}.", input.getTypeName()); } if (!task.handle(e)) { break; } } catch(Exception e){ if (!task.handle(new ImportException(e))) { break; } } } } } catch(IOException e) { throw new IllegalArgumentException(e); } finally { task.readers.clear(); } } @Override public void run(Map<String, String[]> mappings) throws IOException { if (mappings == null) { mappings = new HashMap<String, String[]>(); } for (CSVInput input : config.getInputs()) { String fileName = input.getFileName(); Pattern pattern = Pattern.compile("\\[([\\w.]+)\\]"); Matcher matcher = pattern.matcher(fileName); List<File> files = matcher.matches() ? this.getFiles(mappings.get(matcher.group(1))) : this.getFiles(fileName); for(File file : files) { try { this.process(input, file); } catch (IOException e) { if (LOG.isErrorEnabled()) LOG.error("Error while accessing {}.", file); } catch (ClassNotFoundException e) { if (LOG.isErrorEnabled()) { LOG.error("Error while importing {}.", file); LOG.error("No such class found {}.", input.getTypeName()); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error while importing {}.", file); LOG.error("Unable to import data."); LOG.error("With following exception:", e); } } } } } /** * Check if the String array is empty. * @param line * @return <code>true</code> if line is null or empty, <code>false</code> otherwise */ private boolean isEmpty(String[] line) { if (line == null || line.length == 0) return true; if (line.length == 1 && (line[0] == null || "".equals(line[0].trim()))) return true; return false; } /** * Lauch the import for the input and file. * @param input * @param file * @throws IOException * @throws ClassNotFoundException */ private void process(CSVInput input, File file) throws IOException, ClassNotFoundException { this.process(input, new FileReader(file)); } /** * Lauch the import for the input and reader. * @param csvInput * @param reader * @throws IOException * @throws ClassNotFoundException */ private void process(CSVInput csvInput, Reader reader) throws IOException, ClassNotFoundException { String beanName = csvInput.getTypeName(); if (LOG.isInfoEnabled()) { LOG.info("Importing {} from {}", beanName, csvInput.getFileName()); } BufferedReader streamReader = new BufferedReader(reader); CSVReader csvReader = new CSVReader(streamReader, csvInput.getSeparator()); String[] fields = csvReader.readNext(); Class<?> beanClass = Class.forName(beanName); if (LOG.isDebugEnabled()) LOG.debug("Header {}", Arrays.asList(fields)); CSVBinder binder = new CSVBinder(beanClass, fields, csvInput); String[] values = null; int count = 0; JPA.em().getTransaction().begin(); try { Map<String, Object> context = Maps.newHashMap(); //Put global context if (this.context != null) { context.putAll(this.context); } csvInput.callPrepareContext(context, injector); // register type adapters for(DataAdapter adapter : defaultAdapters) { binder.registerAdapter(adapter); } for(DataAdapter adapter : this.config.getAdapters()) { binder.registerAdapter(adapter); } for(DataAdapter adapter : csvInput.getAdapters()) { binder.registerAdapter(adapter); } //Process for each lines while((values = csvReader.readNext()) != null) { if (isEmpty(values)) continue; if (LOG.isDebugEnabled()) { LOG.debug("Record {}", Arrays.asList(values)); } try { Map<String, Object> ctx = Maps.newHashMap(context); Object bean = binder.bind(values, ctx); if (LOG.isTraceEnabled()) LOG.trace("bean created: {}", bean); bean = csvInput.call(bean, ctx, injector); if (bean != null) { JPA.manage((Model) bean); for(Listener listener : listeners) { listener.imported((Model) bean); } } LOG.debug("bean saved: {}", bean); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error while importing {}.", csvInput.getFileName()); LOG.error("Unable to import record: {}", Arrays.asList(values)); LOG.error("With following exception:", e); } continue; } if (++count % 20 == 0) { JPA.flush(); JPA.em().clear(); } } if (JPA.em().getTransaction().isActive()) JPA.em().getTransaction().commit(); } catch (Exception e) { if (JPA.em().getTransaction().isActive()) JPA.em().getTransaction().rollback(); if (LOG.isErrorEnabled()) LOG.error("Error while importing {}.", csvInput.getFileName()); LOG.error("Unable to import data."); LOG.error("With following exception:", e); } finally { for(Listener listener : listeners) { listener.imported(count); } csvReader.close(); } } }
Added optimization for CSVImporter
axelor-data/src/main/java/com/axelor/data/csv/CSVImporter.java
Added optimization for CSVImporter
Java
agpl-3.0
0965a61f293a787836a3e5e4cef2776febfdb987
0
rkataine/BasePlayer
/* Author: Riku Katainen @ University of Helsinki * * Tumor Genomics Group (http://research.med.helsinki.fi/gsb/aaltonen/) * Contact: [email protected] / [email protected] * * LICENSE: * * GNU AFFERO GENERAL PUBLIC LICENSE * Version 3, 19 November 2007 * */ package base.BasePlayer; import htsjdk.samtools.CRAMFileReader; import htsjdk.samtools.CigarElement; import htsjdk.samtools.CigarOperator; import htsjdk.samtools.QueryInterval; //import htsjdk.samtools.SAMFileReader; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import htsjdk.tribble.Feature; import htsjdk.tribble.readers.TabixReader; import htsjdk.tribble.index.Block; import htsjdk.tribble.index.Index; import htsjdk.tribble.index.IndexFactory; import htsjdk.tribble.index.tabix.TabixIndex; import htsjdk.tribble.index.tabix.TabixIndexCreator; import htsjdk.samtools.cram.ref.ReferenceSource; import htsjdk.samtools.util.BlockCompressedOutputStream; import java.awt.Dimension; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.SwingWorker; import org.apache.commons.io.FilenameUtils; @SuppressWarnings("deprecation") public class FileRead extends SwingWorker< String, Object > { static boolean caller = false; Boolean readVCF = false, changeChrom = false, readBAM = false,searchInsSites = false, varcalc = false, getreads = false; File[] files; String chrom = "0"; static boolean asked = false; int pos; static boolean searchingBams = false; int calls1, calls2; static boolean nobeds = false; private boolean found, noref = false, multi = false; private int xpos; private ReadNode mundane = null; VariantCaller varc = null; VariantCaller.VarCaller varcal = null; static int searchwindow = 1000; private boolean left; boolean stop = false; private ReadNode lastAdded; private ReadNode addNode; static VarNode lastVar = null, lastWriteVar = null, returnnode = null; static Gene currentGene = new Gene(); static int currentGeneEnd = 0; static StringBuffer sampleString = new StringBuffer(""); SamReader samFileReader; CRAMFileReader CRAMReader = null; Iterator<SAMRecord> bamIterator = null; SAMRecord samRecord, samRecordBuffer; private String[] info; private String[] coverages; private Sample sample; private Float quality, gq; static boolean novars = false; String basecontext = ""; int start, end, viewLength; double pixel; public Reads readClass; static final int headnode = 0, tailnode = 1; public static VarNode head; VarNode current; static int firstReadPos; static int lastReadPos; private int startY; private boolean right; public SplitClass splitIndex; private Sample currentSample; public boolean statcalc; private boolean genotype; private int mutcount, linecounter = 0; private short firstallele; private short secondallele; private String altbase; private short refallele; private int refcalls; private short altallele; private int altcalls; private String altbase2; static String[] headersplit; private boolean first; private int samplecount; private int middle; private ReadBuffer currentread; private int searchPos; private boolean isDiscordant; private double[][] coverageArray; private int pointer; private int oldstart; private int addlength; private int readstart; private int readpos; private int mispos; private CigarElement element; boolean firstCov; //public boolean firstSample = false; static int affected = 0; private int gtindex; private int timecounter = 0; static boolean bigcalc=false; static boolean changing = false; static boolean readFiles; public static boolean search; public static int searchStart; public static int searchEnd; public static boolean cancelvarcount= false; public static boolean cancelfileread = false; public static boolean cancelreadread= false; public static BufferedWriter output = null; public static BlockCompressedOutputStream outputgz =null; public static File outFile = null; public static TabixIndexCreator indexCreator; public static int lastpos = 0; public static String outputName = ""; public static long filepointer = 0; HashMap<String, Integer[]> contexts; //HashMap<String, Float[]> contextQuals; //static int[][] array; public static BufferedWriter sigOutput; public FileRead(File[] files) { this.files = files; } public FileRead() { } protected String doInBackground() throws Exception { if(readVCF) { if(Main.drawCanvas.drawVariables.projectName.equals("Untitled")) { Main.frame.setTitle("BasePlayer - Untitled Project"); } readVCF(files); readVCF = false; Draw.updatevars = true; Main.drawCanvas.repaint(); } else if(readBAM) { if(Main.drawCanvas.drawVariables.projectName.equals("Untitled")) { Main.frame.setTitle("BasePlayer - Untitled Project"); } Main.drawCanvas.loading("Loading samples"); readBAM(files); readBAM = false; Main.drawCanvas.ready("Loading samples"); } else if(changeChrom) { changeChrom(chrom); changeChrom = false; Draw.updatevars = true; Draw.updateReads = true; Main.drawCanvas.repaint(); } else if(varcalc) { Main.drawCanvas.loading("Processing variants..."); try { //if(FileRead.head.getNext() == null) { if(VariantHandler.windowcalc.isSelected()) { varCalcBig(); } else { varCalc(); } /*if(caller || VariantHandler.allChroms.isSelected() && !VariantHandler.allChromsfrom.isSelected() && Main.selectedChrom != 0) { varCalc(); } else { varCalcBig(); } /*} else { varCalc(); }*/ varcalc = false; } catch(Exception e) { e.printStackTrace(); Main.drawCanvas.ready("Processing variants..."); } Main.drawCanvas.ready("Processing variants..."); } else if(getreads) { Main.drawCanvas.loading("Loading reads"); if(splitIndex.viewLength <= Settings.readDrawDistance) { for(int i = Main.drawCanvas.drawVariables.visiblestart; i<Main.drawCanvas.drawVariables.visiblestart+Main.drawCanvas.drawVariables.visiblesamples; i++) { if(i>Main.drawCanvas.sampleList.size()-1) { break; } if(Main.drawCanvas.sampleList.get(i).samFile == null) { continue; } //this.readClass.loading = true; this.readClass = Main.drawCanvas.sampleList.get(i).getreadHash().get(splitIndex); getReads(chrom, start, end, this.readClass,splitIndex); splitIndex.updateReads = true; //this.readClass.loading = false; } } else { //this.readClass.loading = true; getReads(chrom, start, end, this.readClass,splitIndex); splitIndex.updateReads = true; //this.readClass.loading = false; } //readClass.nullifyRef(); getreads = false; Main.drawCanvas.ready("Loading reads"); Main.drawCanvas.repaint(); } return null; } /* File ref = new File("C:/HY-Data/RKATAINE/Rikurator/NewRator/genomes/hs37d5/hs37d5.fa"); CRAMFileReader reader = new CRAMFileReader(new File("X:/cg8/Riku/HG00096.alt_bwamem_GRCh38DH.20150718.GBR.low_coverage.cram"), new File("X:/cg8/Riku/HG00096.alt_bwamem_GRCh38DH.20150718.GBR.low_coverage.cram.crai"),new ReferenceSource(ref)); QueryInterval[] interval = { new QueryInterval(reader.getFileHeader().getSequence("chr2").getSequenceIndex(), 1000000, 2000000) }; CloseableIterator<SAMRecord> iterator = reader.query(interval, true); while(iterator.hasNext()) { System.out.println(iterator.next().getSAMString()); }*/ // fetchAnnotation(); // fetchEnsembl(); /* try { String tabixfile = "C:/HY-Data/RKATAINE/BasePlayer/BasePlayer/demo/Somatic-CRC/c32_5332_T_LP6005135-DNA_B01_somatic_GRCh37_20150513.vcf.gz"; TabixIndex index = new TabixIndex(new File(tabixfile+".tbi")); java.util.List<Block> blocks = index.getBlocks("1", 1000000, 4000000); System.out.println(blocks.get(0).getStartPosition()); BlockCompressedInputStream input = new BlockCompressedInputStream(new File(tabixfile)); input.seek(blocks.get(0).getStartPosition()); // gzip.skip(blocks.get(0).getStartPosition()); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); // reader.skip(blocks.get(0).getStartPosition()); String line = reader.readLine(); System.out.println(line); reader.close(); } catch(Exception e) { e.printStackTrace(); }*/ // } /* TabixReader.Iterator getTabixIterator(String chrom, int start, int end, Sample sample) { try { tabixreader = new TabixReader(sample.getTabixFile()); TabixReader.Iterator iterator = tabixreader.query(sample.vcfchr +chrom +":" +start+"-"+end); return iterator; } catch(Exception e) { // JOptionPane.showMessageDialog(Main.chromDraw, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); try { if(search) { if(chrom.equals("X")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("23:" +searchStart+"-"+searchEnd); } else if(chrom.equals("Y")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("24:" +searchStart+"-"+searchEnd); } else if(chrom.contains("M")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("25:" +searchStart+"-"+searchEnd); } } else { if(chrom.equals("X")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("23"); } else if(chrom.equals("Y")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("24"); } else if(chrom.contains("M")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("25"); } } } catch(ArrayIndexOutOfBoundsException ex) { ErrorLog.addError(ex.getStackTrace()); return null; // System.out.println("Chromosome " +chrom +" not found in " +Main.drawCanvas.sampleList.get(i).getName()); } catch(Exception ex) { FileRead.search = false; ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); return null; } } return iterator; }*/ static String setVCFFileStart(String chrom, int start, int end, Sample sample) { try { Index index = null; if(sample.getVCFReader() != null) { try { index = IndexFactory.loadIndex(sample.getTabixFile()+".idx"); } catch(Exception e) { index = IndexFactory.loadIndex(sample.getTabixFile()+".tbi"); } } else { index = new TabixIndex(new File(sample.getTabixFile()+".tbi")); } java.util.List<Block> blocks = null; if(index.containsChromosome(sample.vcfchr +chrom)) { chrom = sample.vcfchr +chrom; try { blocks = index.getBlocks(chrom, start, end); } catch(Exception e) { sample.vcfEndPos = 0; return ""; } if(blocks.size() > 0) { if(sample.getVCFReader() != null) { sample.setInputStream(); sample.getVCFReader().skip(blocks.get(0).getStartPosition()); } else { try { sample.getVCFInput().seek(0); sample.getVCFInput().seek(blocks.get(0).getStartPosition()); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); return ""; } } sample.vcfEndPos = blocks.get(blocks.size()-1).getEndPosition(); } else { if(sample.getVCFReader() != null) { sample.setInputStream(); } else { sample.getVCFInput().seek(0); } } } else { if(index.containsChromosome(sample.vcfchr +(Main.chromosomeDropdown.getSelectedIndex()+1))) { try { blocks = index.getBlocks(sample.vcfchr+(Main.chromosomeDropdown.getSelectedIndex()+1), start, end); } catch(Exception e) { sample.vcfEndPos = 0; return ""; } if(blocks.size() > 0) { if(sample.getVCFReader() != null) { sample.setInputStream(); sample.getVCFReader().skip(blocks.get(0).getStartPosition()); } else { sample.getVCFInput().seek(0); sample.getVCFInput().seek(blocks.get(0).getStartPosition()); } } else { if(sample.getVCFReader() != null) { sample.setInputStream(); } else { sample.getVCFInput().seek(0); } } chrom = sample.vcfchr+(Main.chromosomeDropdown.getSelectedIndex()+1); } else { sample.vcfEndPos = 0; } } } catch(Exception e) { e.printStackTrace(); } return chrom; } void cancelFileRead() { changing = false; FileRead.search = false; bigcalc = false; //Main.opensamples.setText("Add samples"); head.putNext(null); current = null; Main.drawCanvas.current = FileRead.head; Main.drawCanvas.variantsStart = 0; Main.drawCanvas.variantsEnd = 1; Draw.updatevars = true; Main.drawCanvas.repaint(); try { if(output != null) { output.close(); } } catch(Exception e) { e.printStackTrace(); } } void getVariantWindow(String chrom, int start, int end) { try { FileRead.lastpos = 0; removeNonListVariants(); removeBedLinks(); for (int i = 0; i<Control.controlData.fileArray.size(); i++) { Control.controlData.fileArray.get(i).controlled = false; } readFiles = true; head.putNext(null); current = head; cancelvarcount = false; cancelfileread = false; Main.drawCanvas.loadingtext = "Loading variants..."; for(int i = 0; i<Main.samples; i++) { if(cancelvarcount || cancelfileread) { cancelFileRead(); break; } if( Main.drawCanvas.sampleList.get(i).getTabixFile() == null || Main.drawCanvas.sampleList.get(i).multipart) { continue; } current = head; getVariants(chrom,start,end, Main.drawCanvas.sampleList.get(i)); } readFiles =false; annotate(); if(Control.controlData.controlsOn) { Control.applyControl(); } Main.bedCanvas.intersected = false; if(bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head,1); } if(Main.bedCanvas.bedOn) { //VarNode current = FileRead.head.getNext(); /*while(current != null) { current.bedhit = true; current = current.getNext(); }*/ ArrayList<BedTrack> bigs = new ArrayList<BedTrack>(); int smalls = 0; for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { if(!Main.bedCanvas.bedTrack.get(i).small || Main.bedCanvas.bedTrack.get(i).getZoomlevel() != null) { if(Main.bedCanvas.bedTrack.get(i).intersect) { bigs.add(Main.bedCanvas.bedTrack.get(i)); Main.bedCanvas.bedTrack.get(i).intersect = false; } } else { if(Main.bedCanvas.bedTrack.get(i).intersect) { smalls++; } } } if(smalls == 0) { VarNode current = FileRead.head.getNext(); while(current != null) { current.bedhit = true; current = current.getNext(); } } for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { Main.bedCanvas.bedTrack.get(i).used = false; if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getZoomlevel() == null) { if( Main.bedCanvas.bedTrack.get(i).intersect && !Main.bedCanvas.bedTrack.get(i).loading) { Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(), FileRead.head.getNext()); } else if(Main.bedCanvas.bedTrack.get(i).intersect && Main.bedCanvas.bedTrack.get(i).loading) { Main.bedCanvas.bedTrack.get(i).waiting = true; } } //else if(Main.bedCanvas.bedTrack.get(i).intersect) { /*BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); */ // } } if(bigs.size() > 0) { for(int i = 0 ;i<bigs.size(); i++) { bigs.get(i).intersect = true; BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(bigs.get(i)); annotator.annotateVars(); } bigs.clear(); } Main.bedCanvas.intersected = true; if(FileRead.bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head,1); } } } catch(Exception e) { e.printStackTrace(); } } static String getVCFLine(String chrom, int start, int end, Sample sample) { if(Draw.variantcalculator) { return ""; } if(sample.calledvariants) { StringBuffer altbases = new StringBuffer(""); int alts=0, refs=0; for(int i = 0 ; i<Main.drawCanvas.varOverLap.vars.size()-1; i++) { altbases.append(Main.drawCanvas.varOverLap.vars.get(i).getKey()); } alts = Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCalls(); refs = (Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCoverage()-Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCalls()); String genotype = ""; if(alts/(double)refs > 0.95) { genotype = "1/1"; } else { genotype = "0/1"; } altbases.append(Main.drawCanvas.varOverLap.vars.get(Main.drawCanvas.varOverLap.vars.size()-1).getKey()); return Main.drawCanvas.splits.get(0).chrom +"\t" +(Main.drawCanvas.varOverLap.getPosition()+1) +"\t.\t" +Main.getBase.get(Main.drawCanvas.varOverLap.getRefBase()) +"\t" +altbases +"\t99\tPASS\tINFO\tGT:AD:DP\t" +genotype +":" +refs +"," +alts +":" +(refs+alts); } String line = ""; cancelfileread = false; cancelvarcount = false; try { if(!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) { if(sample.multipart) { for(int i = sample.getIndex(); i>= 0; i--) { if(!Main.drawCanvas.sampleList.get(i).multipart) { sample = Main.drawCanvas.sampleList.get(i); break; } } } if(sample.getTabixFile() != null) { setVCFFileStart(chrom, start, end+3, sample); boolean vcf = sample.getVCFReader() != null; while(line != null) { if(vcf) { try { sample.getVCFReader().ready(); } catch(IOException ex) { } } try { if(vcf) { line = sample.getVCFReader().readLine(); } else { line = sample.getVCFInput().readLine(); } if(line == null ||line.split("\t").length < 3 || line.startsWith("#")) { continue; } if(line != null && Integer.parseInt(line.split("\t")[1]) == start+1 ) { if(sample.getVCFReader() != null) { sample.getVCFReader().close(); } return line; } } catch(Exception ex) { Main.showError(ex.getMessage(), "Error"); ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); Main.cancel(); changing = false; } } if(sample.getVCFReader() != null) { sample.getVCFReader().close(); } return line; } } } catch(Exception exc) { Main.showError(exc.getMessage(), "Error"); System.out.println(sample.getName()); exc.printStackTrace(); ErrorLog.addError(exc.getStackTrace()); changing = false; } return ""; } void getVariants(String chrom, int start, int end, Sample sample) { if(sample.calledvariants) { Main.drawCanvas.variantsStart = start; Main.drawCanvas.variantsEnd = end; return; } String line; String[] split; cancelfileread = false; cancelvarcount = false; try { if(!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) { readFiles = true; Main.drawCanvas.splits.get(0).transStart = 0; Main.drawCanvas.variantsStart = start; Main.drawCanvas.variantsEnd = end; Main.drawCanvas.loadbarAll = (int)((sample.getIndex()/(double)(Main.samples))*100); linecounter = 0; if(cancelfileread) { cancelFileRead(); return; } if(sample.multipart){ return; } if(sample.getTabixFile() != null) { String searchChrom = setVCFFileStart(chrom, start, end, sample); boolean vcf = sample.getVCFReader() != null; if(vcf) { try { sample.getVCFReader().ready(); } catch(IOException ex) { return; } } sample.setMaxCoverage(0F); current = head; line = ""; first = true; stop = false; while(true) { if(stop) { break; } if(cancelfileread || cancelvarcount || !Main.drawCanvas.loading) { cancelFileRead(); break; } try { if(vcf) { line = sample.getVCFReader().readLine(); if(line != null && line.startsWith("#")) { continue; } } else { try { line = sample.getVCFInput().readLine(); } catch(htsjdk.samtools.FileTruncatedException e) { e.printStackTrace(); } } if(line == null) { break; } } catch(Exception ex) { Main.showError(ex.getMessage(), "Error"); ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); Main.cancel(); changing = false; break; } if(sample.oddchar != null) { line = line.replaceAll(sample.oddchar, ""); } split = line.split("\\t+"); try { if(split[0].startsWith("#")) { continue; } if(vcf && split.length >2 && (Integer.parseInt(split[1]) > end || !split[0].equals(searchChrom))) { break; } } catch(Exception e) { String string = ""; for(int i = 0 ; i< split.length; i++) { string += split[i]+"\t"; } ErrorLog.addError(string); } if(sample.getVCFInput() != null) { if(sample.getVCFInput().getFilePointer() > sample.vcfEndPos ) { break; } } if(sample.multiVCF) { readLineMulti(split, sample); } else { readLine(split, sample); } if(first) { first = false; } } if(sample.getVCFReader() != null) { sample.getVCFReader().close(); } Draw.updatevars = true; if(sample.getIndex()*Main.drawCanvas.drawVariables.sampleHeight < Main.drawScroll.getViewport().getHeight()+Main.drawCanvas.drawVariables.sampleHeight) { if(Main.drawCanvas.splits.get(0).viewLength < 2000000) { Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } } } } } catch(Exception exc) { Main.showError(exc.getMessage(), "Error"); System.out.println(sample.getName()); exc.printStackTrace(); ErrorLog.addError(exc.getStackTrace()); changing = false; } } public void changeChrom(String chrom) { try { nobeds = false; cancelfileread = false; if(!search) { FileRead.novars = false; } try { Main.drawCanvas.loading("Loading annotation..."); Main.drawCanvas.splits.get(0).setGenes(getExons(chrom)); Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } Main.drawCanvas.ready("Loading annotation..."); ArrayList<BedTrack> bigs = new ArrayList<BedTrack>(); if(Main.bedCanvas.bedTrack.size() > 0) { Main.drawCanvas.loading("Loading BED-files..."); Main.bedCanvas.bedOn = true; boolean ison = false; for(int i = 0 ; i<Main.bedCanvas.bedTrack.size();i++) { if(Main.bedCanvas.bedTrack.get(i).intersect) { ison = true; break; } } if(!ison) { Main.bedCanvas.bedOn = false; } //if(search) { for(int i = 0; i< Main.bedCanvas.bedTrack.size(); i++) { Main.bedCanvas.bedTrack.get(i).used = false; if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd); } else { if(search && searchEnd- searchStart < Settings.windowSize) { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), searchStart, searchEnd); } else { if(Main.bedCanvas.bedTrack.get(i).small) { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd); } } } if(Main.bedCanvas.bedTrack.get(i).intersect && (!Main.bedCanvas.bedTrack.get(i).small || Main.bedCanvas.bedTrack.get(i).getBBfileReader() != null)) { Main.bedCanvas.bedTrack.get(i).intersect = false; bigs.add(Main.bedCanvas.bedTrack.get(i)); } if(nobeds) { Main.drawCanvas.ready("Loading BED-files..."); return; } } } /* } else { for(int i = 0; i< Main.bedCanvas.bedTrack.size(); i++) { Main.bedCanvas.bedTrack.get(i).used = false; if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd); } else { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd); } if(Main.bedCanvas.bedTrack.get(i).intersect && (!Main.bedCanvas.bedTrack.get(i).small || Main.bedCanvas.bedTrack.get(i).getBBfileReader() != null)) { Main.bedCanvas.bedTrack.get(i).intersect = false; bigs.add(Main.bedCanvas.bedTrack.get(i)); } if(nobeds) { Main.drawCanvas.ready("Loading BED-files..."); return; } } } */ //} Main.drawCanvas.ready("Loading BED-files..."); if(novars) { Main.drawCanvas.variantsStart= 0; Main.drawCanvas.variantsEnd = 0; } else { changing = true; } if(Main.varsamples > 0 && !novars && !bigcalc) { removeNonListVariants(); removeBedLinks(); Main.drawCanvas.loading("Loading variants..."); head.putNext(null); current = FileRead.head; if(FileRead.head.getPosition() > 0) { FileRead.head = new VarNode(0, (byte)0,"N", 0, 0, false,(float)0,(float)0,null,null, null, null, null); } Main.drawCanvas.current = head; Main.chromDraw.varnode = null; Main.chromDraw.vardraw = null; for(int i = 0; i<Main.samples; i++) { if(nobeds) { return; } if(cancelfileread || !Main.drawCanvas.loading) { cancelFileRead(); break; } if( Main.drawCanvas.sampleList.get(i).getTabixFile() == null || Main.drawCanvas.sampleList.get(i).multipart) { continue; } if(search) { getVariants(chrom, FileRead.searchStart, FileRead.searchEnd, Main.drawCanvas.sampleList.get(i)); } else { getVariants(chrom, 0, Main.drawCanvas.splits.get(0).chromEnd, Main.drawCanvas.sampleList.get(i)); } } annotate(); if(Main.drawCanvas.annotationOn) { SampleDialog.checkAnnotation(); } Main.drawCanvas.loading("Applying controls..."); if(Control.controlData.controlsOn) { Control.applyControl(); } Main.drawCanvas.ready("Applying controls..."); readFiles = false; Main.bedCanvas.intersected = false; if(bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head); } if(Main.bedCanvas.bedOn) { Main.drawCanvas.loadingtext = "Annotating variants"; int smalls = 0; for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) { if( Main.bedCanvas.bedTrack.get(i).intersect && !Main.bedCanvas.bedTrack.get(i).loading) { smalls++; Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(), FileRead.head.getNext()); Main.bedCanvas.intersected = true; } else if(Main.bedCanvas.bedTrack.get(i).intersect && Main.bedCanvas.bedTrack.get(i).loading) { Main.bedCanvas.bedTrack.get(i).waiting = true; } } //else if(Main.bedCanvas.bedTrack.get(i).intersect) { //bigs.add(Main.bedCanvas.bedTrack.get(i)); /*BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); Main.bedCanvas.intersected = true; */ //} } if(smalls == 0) { VarNode current = FileRead.head.getNext(); while(current != null) { current.bedhit = true; current = current.getNext(); } } for(int i =0;i<bigs.size(); i++) { bigs.get(i).intersect = true; BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(bigs.get(i)); annotator.annotateVars(); Main.bedCanvas.intersected = true; } bigs.clear(); } if(FileRead.bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head); } } Draw.updatevars = true; Main.drawCanvas.ready("Loading variants..."); if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } if(novars) { Main.drawCanvas.variantsStart= 0; Main.drawCanvas.variantsEnd = Main.drawCanvas.splits.get(0).chromEnd; } search = false; changing = false; current = null; Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } catch(Exception e) { e.printStackTrace(); ErrorLog.addError(e.getStackTrace()); changing = false; } Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; Main.drawCanvas.repaint(); } public ArrayList<Gene> getExons(String chrom) { ArrayList<Gene> transcriptsTemp = new ArrayList<Gene>(); try { if(Main.genomehash.size() == 0 || Main.genomehash.get(Main.defaultGenome).size() == 0) { return new ArrayList<Gene>(); } if(ChromDraw.exonReader != null) { ChromDraw.exonReader.close(); } ChromDraw.exonReader = new TabixReader(Main.genomehash.get(Main.defaultGenome).get(Main.annotation).getCanonicalPath()); if(chrom == null) { return null; } TabixReader.Iterator exonIterator = null; try { if(!ChromDraw.exonReader.getChromosomes().contains(chrom)) { String[] gene = { Main.chromosomeDropdown.getSelectedItem().toString(), "1", ""+Main.drawCanvas.splits.get(0).chromEnd, Main.chromosomeDropdown.getSelectedItem().toString(), "1", "+", "-", "-", "-", "-","-","1","1","1",""+Main.drawCanvas.splits.get(0).chromEnd,"-1,","-"}; Gene addGene = new Gene(gene); Transcript addtrans = null; try { addtrans = new Transcript(gene); } catch(Exception e) { e.printStackTrace(); } addGene.addTranscript(addtrans); addGene.setLongest(addtrans); addtrans.setGene(addGene); transcriptsTemp.add(addGene); return transcriptsTemp; //return new ArrayList<Gene>(); } else { exonIterator = ChromDraw.exonReader.query(chrom); } } catch(Exception e) { try { if(chrom.matches("\\w+")) { exonIterator = ChromDraw.exonReader.query("M"); } } catch(Exception ex) { System.out.println(chrom); e.printStackTrace(); } } String s; String[] exonSplit; Transcript addtrans = null; Hashtable<String, Gene> genes = new Hashtable<String, Gene>(); Gene setGene; while(exonIterator != null && (s = exonIterator.next()) != null) { exonSplit = s.split("\t"); if(exonSplit[0].equals("23")) { exonSplit[0] = "X"; } else if(exonSplit[0].equals("24")) { exonSplit[0] = "Y"; } else if (exonSplit[0].equals("25")) { exonSplit[0] = "MT"; } addtrans = new Transcript(exonSplit); if(!genes.containsKey(exonSplit[6])) { Gene addgene = new Gene(exonSplit); genes.put(exonSplit[6],addgene); addgene.addTranscript(addtrans); addgene.setLongest(addtrans); addtrans.setGene(addgene); transcriptsTemp.add(addgene); } else { setGene = genes.get(exonSplit[6]); setGene.addTranscript(addtrans); addtrans.setGene(setGene); if(addtrans.getLength() > setGene.getLongest().getLength()) { setGene.setLongest(addtrans); } } } genes.clear(); ChromDraw.exonReader.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } return transcriptsTemp; } static File[] readLinkFile(File linkfile) { File[] bamfiles = null; try { FileReader freader = new FileReader(linkfile); BufferedReader reader = new BufferedReader(freader); ArrayList<File> filetemp = new ArrayList<File>(); String line; while((line = reader.readLine()) != null) { File addfile = new File(line.trim()); if(addfile.exists()) { filetemp.add(addfile); } } if(freader != null) { freader.close(); } reader.close(); bamfiles = new File[filetemp.size()]; for(int i = 0; i<filetemp.size(); i++) { bamfiles[i] = filetemp.get(i); } } catch(Exception e) { e.printStackTrace(); } return bamfiles; } private void readBAM(File[] files) { try { File addFile =null; File[] addDir; Sample currentSample = null; Boolean added = false; if(files.length == 1 && files[0].getName().endsWith(".link")) { files = readLinkFile(files[0]); } for(int i = 0; i<files.length; i++) { if(files[i].isDirectory()) { addDir = files[i].listFiles(); for(int f = 0; f<addDir.length; f++) { if(addDir[f].getName().endsWith(".bam") ||addDir[f].getName().endsWith(".cram") ) { addFile = addDir[f]; break; } } } else { if(files[i].getName().endsWith(".bam") || files[i].getName().endsWith(".cram")) { addFile = files[i]; } else { continue; } } if(addFile != null) { Main.drawCanvas.bam = true; currentSample = new Sample(addFile.getName(), (short)Main.samples, null); Main.drawCanvas.sampleList.add(currentSample); currentSample.samFile = addFile; currentSample.resetreadHash(); if(addFile.getName().endsWith(".cram")) { currentSample.CRAM = true; } if(currentSample.samFile.getName().endsWith(".cram")) { currentSample.readString = "CRAM"; } else { currentSample.readString = "BAM"; } try { } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } added = true; Main.readsamples++; Main.samples++; } } if(!added) { return; } checkSamples(); Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.samples); // Main.drawCanvas.checkSampleZoom(); if(Main.drawScroll.getViewport().getHeight()/(Main.drawCanvas.sampleList.size()) > Draw.defaultSampleHeight) { Main.drawCanvas.drawVariables.sampleHeight = Main.drawScroll.getViewport().getHeight()/Main.drawCanvas.sampleList.size(); } else { Main.drawCanvas.drawVariables.sampleHeight = Draw.defaultSampleHeight; } if(Main.drawCanvas.getHeight() < (Main.drawCanvas.sampleList.size())*Main.drawCanvas.drawVariables.sampleHeight) { Main.drawCanvas.resizeCanvas(Main.drawCanvas.getWidth(), (int)((Main.drawCanvas.sampleList.size())*Main.drawCanvas.drawVariables.sampleHeight)); Main.drawCanvas.revalidate(); } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } Draw.updateReads = true; Draw.updatevars = true; Main.drawCanvas.repaint(); } static boolean checkIndex(File file) { try { if(file.getName().endsWith(".vcf")) { return new File(file.getCanonicalPath() +".idx").exists() || new File(file.getCanonicalPath() +".tbi").exists(); } else if(file.getName().toLowerCase().endsWith(".vcf.gz")) { return new File(file.getCanonicalPath() +".tbi").exists(); } else if(file.getName().toLowerCase().endsWith(".bam")) { if(!new File(file.getCanonicalPath() +".bai").exists()) { return new File(file.getCanonicalPath().replace(".bam", "") +".bai").exists(); } else { return true; } } else if(file.getName().toLowerCase().endsWith(".bed.gz") || file.getName().toLowerCase().endsWith(".gff.gz") || file.getName().toLowerCase().endsWith(".bed") || file.getName().toLowerCase().endsWith(".gff")) { return new File(file.getCanonicalPath() +".tbi").exists(); } else if(file.getName().toLowerCase().endsWith(".tsv.gz") || file.getName().toLowerCase().endsWith(".tsv.bgz") ) { return new File(file.getCanonicalPath() +".tbi").exists(); } else { return true; } } catch(Exception e) { e.printStackTrace(); } return false; } static void checkMulti(Sample sample) { try { Sample addSample; BufferedReader reader = null; GZIPInputStream gzip = null; FileReader freader = null; String line; Boolean somatic = Main.drawCanvas.drawVariables.somatic; String[] split; if(somatic != null && somatic) { asked = true; } if(sample.getTabixFile().endsWith(".gz")) { try { gzip = new GZIPInputStream(new FileInputStream(sample.getTabixFile())); reader = new BufferedReader(new InputStreamReader(gzip)); } catch(Exception e) { Main.showError("Could not read the file: " +sample.getTabixFile() +"\nCheck that you have permission to read the file or try to bgzip and recreate the index file.", "Error"); Main.drawCanvas.sampleList.remove(sample); Main.varsamples--; Main.samples--; } } else { freader = new FileReader(sample.getTabixFile()); reader = new BufferedReader(freader); } line = reader.readLine(); if(!sample.multipart && line != null) { while(line != null ) { try { if(line.startsWith("##INFO")) { if(line.contains("Type=Float") || line.contains("Type=Integer")) { VariantHandler.addMenuComponents(line); } } if(line.startsWith("##FILTER")) { if(line.contains("ID=") || line.contains("Description=")) { VariantHandler.addMenuComponents(line); } } if(line.toLowerCase().contains("#chrom")) { headersplit = line.split("\t+"); if(headersplit.length > 10) { if(headersplit.length == 11 && !asked) { if (JOptionPane.showConfirmDialog(Main.drawScroll, "Is this somatic project?", "Somatic?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ somatic = true; Main.drawCanvas.drawVariables.somatic = true; } asked = true; } if(!somatic) { sample.multiVCF = true; Main.varsamples--; for(int h = 9; h<headersplit.length; h++) { addSample = new Sample(headersplit[h], (short)(Main.samples), null); addSample.multipart = true; Main.drawCanvas.sampleList.add(addSample); Main.samples++; Main.varsamples++; if(sampleString == null) { sampleString = new StringBuffer(""); } sampleString.append(addSample.getName() +";"); } VariantHandler.commonSlider.setMaximum(Main.varsamples); VariantHandler.commonSlider.setUpperValue(Main.varsamples); VariantHandler.geneSlider.setMaximum(Main.varsamples); Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.drawCanvas.sampleList.size()); Main.drawCanvas.checkSampleZoom(); Main.drawCanvas.resizeCanvas(Main.drawScroll.getViewport().getWidth(),Main.drawScroll.getViewport().getHeight()); } } line = reader.readLine(); break; } split = line.split("\t"); if(split.length > 2 && split[1].matches("\\d+")) { break; } } catch(Exception ex) { ex.printStackTrace(); } line = reader.readLine(); } if (line == null) { return; } while(line != null && line.startsWith("#")) { line = reader.readLine(); } split = line.split("\t"); if(line.contains("\"")) { sample.oddchar = "\""; } if(split != null && split.length == 8) { sample.annoTrack = true; } if(line != null) { if(line.startsWith("chr")) { sample.vcfchr = "chr"; } } if(somatic != null && somatic) { line = reader.readLine(); if(line != null) { headersplit = line.split("\t"); if(headersplit.length == 11) { if(headersplit[10].startsWith("0:") || (headersplit[10].charAt(0) == '0' && headersplit[10].charAt(2) == '0')) { sample.somaticColumn = 9; } else { sample.somaticColumn = 10; } } } } checkSamples(); line = null; if(freader != null) { freader.close(); } reader.close(); if(gzip != null) { gzip.close(); } } else { reader.close(); if(gzip != null) { gzip.close(); } } } catch(Exception e) { e.printStackTrace(); } } public static class SearchBamFiles extends SwingWorker<String, Object> { boolean cram = false; //SamReader samFileReader; int sampletemp; CRAMFileReader CRAMReader = null; File[] files; ArrayList<File> bamdirs; public SearchBamFiles(File[] files, ArrayList<File> bamdirs, int sampletemp) { this.files = files; this.bamdirs = bamdirs; /*this.fileindex = fileindex;*/ this.sampletemp = sampletemp; } protected String doInBackground() { try { File[] bamfilestemp = null; ArrayList<File> bamfiles = new ArrayList<File>(); searchingBams = true; for(int i = 0 ; i<bamdirs.size(); i++) { bamfilestemp = bamdirs.get(i).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".bam") || name.toLowerCase().endsWith(".cram"); } }); if(bamfilestemp != null && bamfilestemp.length > 0) { for(int j = 0; j<bamfilestemp.length; j++) { bamfiles.add(bamfilestemp[j]); } } else { bamfilestemp = bamdirs.get(i).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".link"); } }); if(bamfilestemp != null && bamfilestemp.length > 0) { for(int j = 0; j<bamfilestemp.length; j++) { File[] fileTemp = readLinkFile(bamfilestemp[j]); for(int f = 0; f<fileTemp.length; f++) { bamfiles.add(fileTemp[f]); } } } } } /* if(fileindex > files.length) { bamfiles = files[0].listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".bam") || name.toLowerCase().endsWith(".cram"); } }); } else { bamfiles = files[fileindex].getParentFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".bam") || name.toLowerCase().endsWith(".cram"); } }); } /* File[] cramfiles = files[fileindex].getParentFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".cram"); } }); */ if(bamfiles.size() > 0) { int index = -1, sampleindex; for(int i = 0; i<bamfiles.size(); i++) { cram = false; sampleindex = 0; index = sampleString.indexOf(bamfiles.get(i).getName().substring(0,bamfiles.get(i).getName().indexOf("."))); if (index < 0) continue; if(!checkIndex(bamfiles.get(i))) { Main.putMessage("Check Tools->View log"); ErrorLog.addError("No index file found for " +bamfiles.get(i).getName()); continue; } for(char letter : sampleString.substring(0, index).toString().toCharArray()) { if(letter == ';') sampleindex++; } Main.drawCanvas.bam = true; Main.readsamples++; Main.drawCanvas.sampleList.get(sampleindex+sampletemp).samFile = new File(bamfiles.get(i).getCanonicalPath()); Main.drawCanvas.sampleList.get(sampleindex+sampletemp).resetreadHash(); if(Main.readsamples==1) { checkSamples(); } if(bamfiles.get(i).getName().endsWith(".cram")){ cram = true; } else { cram = false; } Main.drawCanvas.sampleList.get(sampleindex+sampletemp).CRAM = cram; if(cram) { Main.drawCanvas.sampleList.get(sampleindex+sampletemp).readString = "CRAM"; } else { Main.drawCanvas.sampleList.get(sampleindex+sampletemp).readString = "BAM"; } /* if(samFileReader != null) { samFileReader.close(); }*/ } } sampleString = null; files = null; } catch(Exception e) { searchingBams = false; e.printStackTrace(); } searchingBams = false; Main.drawCanvas.repaint(); return ""; } } private void readVCF(File[] files) { try { if(files.length == 1 && files[0].getName().endsWith(".tbi")) { Main.showError("Please select vcf.gz file, not the index (.tbi)", "Error"); return; } Main.drawCanvas.loading("Loading samples..."); File[] addDir; int sampletemp = Main.samples; Boolean added = false; Sample addSample = null; sampleString = new StringBuffer(""); int fileindex = -1; readFiles = true; cancelfileread = false; ArrayList<File> bamdirs = new ArrayList<File>(); if(Control.controlData.controlsOn) { Control.dismissControls(head); } int addnumber = 0; for(int fi = 0; fi<files.length; fi++) { if(Main.cancel || !Main.drawCanvas.loading) { current = null; FileRead.head.putNext(null); return; } if(!files[fi].exists()) { continue; } addDir = null; if(files[fi].isDirectory()) { addDir = files[fi].listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".vcf.gz") || name.toLowerCase().endsWith(".vcf"); } }); bamdirs.add(files[fi]); for(int f= 0; f<addDir.length; f++) { if(cancelfileread || !Main.drawCanvas.loading) { current = null; FileRead.head.putNext(null); return; } if(!checkIndex(addDir[f])) { Main.putMessage("Check Tools->View log"); ErrorLog.addError("No index file found for " +addDir[f].getName()); } addSample = new Sample(addDir[f].getName(), (short)Main.samples, addDir[f].getCanonicalPath()); Main.drawCanvas.sampleList.add(addSample); Main.varsamples++; Main.samples++; Main.drawCanvas.drawVariables.visiblesamples++; checkMulti(addSample); addnumber++; Main.drawCanvas.loadingtext = "Loading samples... " +addnumber; added = true; VariantHandler.commonSlider.setMaximum(Main.varsamples); VariantHandler.commonSlider.setUpperValue(Main.varsamples); VariantHandler.geneSlider.setMaximum(Main.varsamples); sampleString.append(addSample.getName() +";"); fileindex = f; } } else { if(!files[fi].getName().endsWith(".vcf") && !files[fi].getName().endsWith(".vcf.gz")) { continue; } if(!bamdirs.contains(files[fi].getParentFile())) { bamdirs.add(files[fi].getParentFile()); } File testfile = null; boolean testing = false; if(!checkIndex(files[fi])) { Main.putMessage("Check Tools->View log"); ErrorLog.addError("No index file found for " +files[fi].getName()); if (JOptionPane.showConfirmDialog(Main.drawScroll, "No index file found. Do you want to create one?", "Indexing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ Main.drawCanvas.loadingtext = "Creating index for " +files[fi].getName(); if(files[fi].getName().endsWith(".vcf.gz")) { testing = true; testfile = MethodLibrary.createVCFIndex(files[fi]); } else { MethodLibrary.createVCFIndex2(files[fi]); } } else { continue; } } if(testing && testfile != null) { files[fi] = testfile; } if(fileindex > -1) { if(!files[fi].getParent().equals(files[fileindex].getParent())) { // diffPaths = true; } } fileindex =fi; addSample = new Sample(files[fi].getName(), (short)Main.samples, files[fi].getCanonicalPath()); Main.drawCanvas.sampleList.add(addSample); Main.varsamples++; Main.samples++; Main.drawCanvas.drawVariables.visiblesamples = (short)Main.samples; sampleString.append(addSample.getName() +";"); checkMulti(addSample); addnumber++; Main.drawCanvas.loadingtext = "Loading samples... " +addnumber; added = true; VariantHandler.commonSlider.setMaximum(Main.varsamples); VariantHandler.commonSlider.setUpperValue(Main.varsamples); VariantHandler.geneSlider.setMaximum(Main.varsamples); } } if(!added) { Main.drawCanvas.ready("Loading samples..."); return; } if(bamdirs.size() > 0) { SearchBamFiles search = new SearchBamFiles(files, bamdirs, sampletemp); search.execute(); } Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.drawCanvas.sampleList.size()); Main.drawCanvas.checkSampleZoom(); Main.drawCanvas.resizeCanvas(Main.drawScroll.getViewport().getWidth(),Main.drawScroll.getViewport().getHeight()); int loading = 0; if(!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) { Main.drawCanvas.loadingtext = "Loading variants..."; for(int i = sampletemp; i < Main.drawCanvas.sampleList.size(); i++) { linecounter = 0; if(cancelfileread || !Main.drawCanvas.loading) { cancelFileRead(); break; } if(( Main.drawCanvas.sampleList.get(i).getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight < Main.drawScroll.getViewport().getHeight()+Main.drawCanvas.drawVariables.sampleHeight) { // Main.drawCanvas.drawVariables.visibleend = (short)(Main.drawCanvas.sampleList.get(i).getIndex()); // Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.drawCanvas.sampleList.get(i).getIndex()+1); Main.drawCanvas.checkSampleZoom(); } Main.drawCanvas.loadbarAll = (int)((loading/(double)(Main.drawCanvas.sampleList.size()-sampletemp))*100); // if(!Main.drawCanvas.sampleList.get(i).multipart) { try { // vcfreader = new VCFFileReader(new File(Main.drawCanvas.sampleList.get(i).getTabixFile())); /* try { tabixreader = new TabixReader(Main.drawCanvas.sampleList.get(i).getTabixFile()); } catch(Exception ex) { JOptionPane.showMessageDialog(Main.chromDraw, "Index file (tbi) not found for " +Main.drawCanvas.sampleList.get(i).getName(), "Error", JOptionPane.ERROR_MESSAGE); ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); }*/ // iterator=null; if(Main.drawCanvas.sampleList.get(i).getTabixFile() == null) { continue; } if(start > 10000 && end < Main.drawCanvas.splits.get(0).chromEnd-10000) { if(Main.drawCanvas.variantsEnd > 0) { // iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString()+":" +Main.drawCanvas.variantsStart +"-" +Main.drawCanvas.variantsEnd); getVariants(Main.chromosomeDropdown.getSelectedItem().toString(), Main.drawCanvas.variantsStart,Main.drawCanvas.variantsEnd, Main.drawCanvas.sampleList.get(i)); } else { Main.drawCanvas.variantsStart = start; Main.drawCanvas.variantsEnd = end; // iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString()+":" +Main.drawCanvas.variantsStart +"-" +Main.drawCanvas.variantsEnd); getVariants(Main.chromosomeDropdown.getSelectedItem().toString(), Main.drawCanvas.variantsStart,Main.drawCanvas.variantsEnd, Main.drawCanvas.sampleList.get(i)); } } else { // iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString()); Main.drawCanvas.variantsStart = 0; Main.drawCanvas.variantsEnd = Main.drawCanvas.splits.get(0).chromEnd; getVariants(Main.chromosomeDropdown.getSelectedItem().toString(), Main.drawCanvas.variantsStart,Main.drawCanvas.variantsEnd, Main.drawCanvas.sampleList.get(i)); } } catch(Exception e) { Main.showError( e.getMessage(), "Error"); ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } /* if(iterator == null) { tabixreader = null; continue; }*/ // } /* else { continue; } line = null; current = head; first = true; while(true) { try { if(cancelfileread) { cancelFileRead(); } try { line = iterator.next(); // vcfline = vcfIterator.next(); if(line == null) { break; } // line = vcfline.getSource(); } catch(Exception ex) { JOptionPane.showMessageDialog(Main.chromDraw, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); Main.cancel(); // tabixreader.mFp.close(); ex.printStackTrace(); break; } split = line.split("\\t+"); if(Main.drawCanvas.sampleList.get(i).multiVCF) { readLineMulti(split, Main.drawCanvas.sampleList.get(i)); } else { readLine(split, Main.drawCanvas.sampleList.get(i)); // readLine(vcfline, Main.drawCanvas.sampleList.get(i)); } if(first) { first = false; } } catch(Exception e) { e.printStackTrace(); // tabixreader.mFp.close(); } } // tabixreader.mFp.close(); Main.drawCanvas.current = FileRead.head.getNext(); if(Main.drawCanvas.splits.get(0).viewLength < 2000000) { Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } Draw.updatevars = true; Draw.updateReads = true; Main.drawCanvas.repaint(); loading++;*/ } } //Main.opensamples.setText("Add samples"); checkSamples(); annotate(); readFiles = false; // Main.drawCanvas.clusterCalc = true; if(Control.controlData.controlsOn) { Control.applyControl(); } Main.bedCanvas.intersected = false; if(bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head,1); } if(Main.bedCanvas.bedOn) { Main.drawCanvas.loadingtext = "Annotating variants"; for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).intersect && !Main.bedCanvas.bedTrack.get(i).loading) { if(Main.bedCanvas.bedTrack.get(i).small) { Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(), FileRead.head.getNext()); } else { BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); } } else if(Main.bedCanvas.bedTrack.get(i).intersect && Main.bedCanvas.bedTrack.get(i).loading) { Main.bedCanvas.bedTrack.get(i).waiting = true; } } Main.bedCanvas.intersected = true; } if(bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head,1); } if(Main.drawCanvas.splits.get(0).viewLength < 2000000) { Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } // Main.drawCanvas.drawVariables.visibleend = Main.samples; //Main.drawCanvas.drawVariables.visiblesamples = Main.samples; Main.drawCanvas.checkSampleZoom(); Main.drawCanvas.current = head; // Draw.updatevars = true; // Main.drawCanvas.repaint(); current = null; Main.drawCanvas.ready("Loading samples..."); Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; } catch(Exception e) { e.printStackTrace(); ErrorLog.addError(e.getStackTrace()); } } static void checkSamples() { /*if(Main.varsamples == 0) { Main.drawCanvas.varbuffer = MethodLibrary.toCompatibleImage(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.g2v = (Graphics2D)Main.drawCanvas.varbuffer.getGraphics(); } else {*/ // Main.drawCanvas.varbuffer = MethodLibrary.toCompatibleImage(new BufferedImage(Main.screenSize.width, Main.screenSize.height, BufferedImage.TYPE_INT_ARGB)); // Main.drawCanvas.g2v = (Graphics2D)Main.drawCanvas.varbuffer.getGraphics(); // } if(Main.varsamples < 2) { VariantHandler.commonSlider.setMaximum(1); VariantHandler.commonSlider.setValue(1); VariantHandler.commonSlider.setUpperValue(1); VariantHandler.geneSlider.setMaximum(1); VariantHandler.geneSlider.setValue(1); //VariantHandler.filterPanes.setEnabledAt(VariantHandler.filterPanes.getTabCount()-1, false); VariantHandler.filterPanes.setToolTipTextAt(VariantHandler.filterPanes.getTabCount()-1, "Open more samples to compare variants."); } else { VariantHandler.commonSlider.setMaximum(Main.varsamples); VariantHandler.commonSlider.setValue(1); VariantHandler.commonSlider.setUpperValue(Main.varsamples); VariantHandler.geneSlider.setMaximum(Main.varsamples); VariantHandler.geneSlider.setValue(1); VariantHandler.filterPanes.setEnabledAt(VariantHandler.filterPanes.getTabCount()-1, true); VariantHandler.filterPanes.setToolTipTextAt(VariantHandler.filterPanes.getTabCount()-1, "Compare variants."); } if(Main.readsamples > 0) { /* Main.drawCanvas.readbuffer = MethodLibrary.toCompatibleImage(new BufferedImage(Main.screenSize.width, Main.screenSize.height, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.rbuf = (Graphics2D)Main.drawCanvas.readbuffer.getGraphics(); Main.drawCanvas.backupr = Main.drawCanvas.rbuf.getComposite(); Main.drawCanvas.rbuf.setRenderingHints(Draw.rh); Main.drawCanvas.coveragebuffer = MethodLibrary.toCompatibleImage(new BufferedImage(Main.screenSize.width, Main.screenSize.height, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.cbuf = (Graphics2D)Main.drawCanvas.coveragebuffer.getGraphics(); Main.drawCanvas.backupc = Main.drawCanvas.cbuf.getComposite(); */ Main.average.setEnabled(true); Main.variantCaller.setEnabled(true); Main.peakCaller.setEnabled(true); if(caller) { if(Main.readsamples > 1) { VariantHandler.filterPanes.setEnabledAt(VariantHandler.filterPanes.getTabCount()-1, true); VariantHandler.commonSlider.setMaximum(Main.readsamples); VariantHandler.commonSlider.setUpperValue(Main.readsamples); VariantHandler.geneSlider.setMaximum(Main.readsamples); VariantHandler.geneSlider.setValue(1); } Main.manage.setEnabled(true); } } else { /* Main.drawCanvas.readbuffer = MethodLibrary.toCompatibleImage(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.rbuf = (Graphics2D)Main.drawCanvas.readbuffer.getGraphics(); Main.drawCanvas.backupr = Main.drawCanvas.rbuf.getComposite(); Main.drawCanvas.rbuf.setRenderingHints(Draw.rh); Main.drawCanvas.coveragebuffer = MethodLibrary.toCompatibleImage(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.cbuf = (Graphics2D)Main.drawCanvas.coveragebuffer.getGraphics(); Main.drawCanvas.backupc = Main.drawCanvas.cbuf.getComposite(); */ Main.average.setEnabled(false); Main.average.setToolTipText("No bam/cram files opened"); Main.variantCaller.setEnabled(false); Main.variantCaller.setToolTipText("No bam/cram files opened"); } } static void annotate() { if(Main.drawCanvas.splits.get(0).getGenes().size() == 0) { return; } Transcript transcript; Gene gene, prevGene = Main.drawCanvas.splits.get(0).getGenes().get(0); VarNode current = FileRead.head.getNext(); Transcript.Exon exon; int position = 0, baselength; boolean intronic = true; try { if(current != null) { for(int g=0; g<Main.drawCanvas.splits.get(0).getGenes().size(); g++ ) { gene = Main.drawCanvas.splits.get(0).getGenes().get(g); /* while(current != null && current.getPosition() < gene.getStart()) { if(!current.isInGene()) { if(current.getTranscripts() == null) { current.setTranscripts(); } current.getTranscripts().add(prevGene.getTranscripts().get(0)); current.getTranscripts().add(gene.getTranscripts().get(0)); } current = current.getNext(); }*/ if(current == null) { break; } for(int t = 0; t<gene.getTranscripts().size(); t++) { transcript = gene.getTranscripts().get(t); if(current != null && current.getPrev() != null) { while(current.getPrev().getPosition() >= transcript.getStart()) { if(current.getPrev() != null) { current = current.getPrev(); } } } position = current.getPosition(); if(current.indel) { position++; baselength = MethodLibrary.getBaseLength(current.vars, 1); } while(position < transcript.getEnd()) { try { if(position >= transcript.getStart() && position <= transcript.getEnd()) { current.setInGene(); baselength = 0; intronic = true; for(int e=0;e<transcript.getExons().length; e++) { exon = transcript.getExons()[e]; if(position+baselength >= exon.getStart()-2 && position < exon.getEnd()+2) { if(current.getExons() == null) { current.setExons(); } intronic = false; if(!current.getExons().contains(exon)) { current.getExons().add(exon); if(exon.getStartPhase() > -1 && position+baselength >= exon.getTranscript().getCodingStart() && position < exon.getTranscript().getCodingEnd() ) { current.coding = true; } break; } } } if(intronic) { if(current.getTranscripts() == null) { current.setTranscripts(); } current.getTranscripts().add(transcript); } } if(!current.isInGene()) { if(current.getTranscripts() == null) { current.setTranscripts(); current.getTranscripts().add(prevGene.getTranscripts().get(0)); current.getTranscripts().add(gene.getTranscripts().get(0)); } } if(current.getNext() != null) { current = current.getNext(); position = current.getPosition(); } else { break; } } catch(Exception e) { System.out.println(position); e.printStackTrace(); break; } } } if(gene.getEnd() > prevGene.getEnd()) { prevGene = gene; } } while(current != null) { if(!current.isInGene()) { if(current.getTranscripts() == null) { current.setTranscripts(); current.getTranscripts().add(prevGene.getTranscripts().get(0)); current.getTranscripts().add(prevGene.getTranscripts().get(0)); } } current = current.getNext(); } } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } current = null; transcript = null; exon = null; } public void readLineMulti(String[] split, Sample sample) { samplecount = 0; try { pos = Integer.parseInt(split[1])-1; } catch(Exception e) { return; } if(pos < Main.drawCanvas.variantsStart) { return; } else if(pos >=Main.drawCanvas.variantsEnd) { stop = true; return; } /*else if(sample.getVCFInput().getFilePointer() > sample.vcfEndPos) { return; }*/ if(linecounter == 0 || pos -linecounter > (Main.drawCanvas.variantsEnd-Main.drawCanvas.variantsStart)/100) { Main.drawCanvas.loadBarSample = (int)(((pos-Main.drawCanvas.variantsStart)/(double)(Main.drawCanvas.variantsEnd-Main.drawCanvas.variantsStart))*100); Draw.updatevars = true; linecounter = pos; } first = true; while(current != null && current.getNext() != null && current.getPosition() < pos ){ current = current.getNext(); } if(current.getPosition() == pos) { first = false; } for(int s = 9; s < split.length;s++) { try { currentSample = Main.drawCanvas.sampleList.get(sample.getIndex()+1+s-9 ); if(currentSample.removed) { continue; } info = split[s].split(":"); noref = false; HashMap<String, Integer> infofield = new HashMap<String, Integer>(); String[] infos = split[8].split(":"); for(int i = 0; i<infos.length; i++) { infofield.put(infos[i], i); } if(infofield.containsKey("GT")) { gtindex = infofield.get("GT"); if(info[gtindex].contains(".") || info[gtindex].length() < 3) { continue; } if(info[gtindex].contains("|")) { firstallele = Short.parseShort(""+info[gtindex].split("|")[0]); secondallele = Short.parseShort(""+info[gtindex].split("|")[2]); } else { firstallele = Short.parseShort(""+info[gtindex].split("/")[0]); secondallele = Short.parseShort(""+info[gtindex].split("/")[1]); } genotype = firstallele == secondallele; if(genotype && firstallele == 0) { continue; } if(infofield.containsKey("AD")) { if(infofield.containsKey("RD")) { refcalls = Integer.parseInt(info[infofield.get("RD")]); altcalls = Integer.parseInt(info[infofield.get("AD")]); } else { try { coverages = info[infofield.get("AD")].split(","); calls1 = Integer.parseInt(coverages[firstallele]); calls2 = Integer.parseInt(coverages[secondallele]); } catch(Exception e) { return; } } } else { calls1 = 20; calls2 = 20; } if(!genotype) { if(firstallele == 0) { refallele = firstallele; refcalls = calls1; altallele = secondallele; altcalls = calls2; } else if(secondallele == 0){ refallele = secondallele; refcalls = calls2; altallele = firstallele; altcalls = calls1; } else { noref = true; refallele = firstallele; refcalls = calls1; altallele = secondallele; altcalls = calls2; } } else { refcalls = calls1; //(short)(Short.parseShort(coverages[0])); altallele = secondallele; altcalls = calls2; } } if(!split[4].contains(",")) { altbase = getVariant(split[3], split[4]); } else if(!noref){ altbase = getVariant(split[3], split[4].split(",")[altallele-1]); } else { altbase = getVariant(split[3], split[4].split(",")[altallele-1]); altbase2 = getVariant(split[3], split[4].split(",")[refallele-1]); } if(altbase.contains("*") || (altbase2!=null && altbase2.contains("*"))) { continue; } quality = null; if(split[8].contains("Q")) { if(infofield.containsKey("GQ") && !info[infofield.get("GQ")].equals(".")) { gq = (float)Double.parseDouble(info[split[8].indexOf("GQ")/3]); } else if(infofield.containsKey("BQ") && !info[infofield.get("BQ")].equals(".")) { quality = (float)Double.parseDouble(info[infofield.get("BQ")]); } else if(split[7].contains("SSC")) { quality = Float.parseFloat(split[7].substring(split[7].indexOf("SSC") +4).split(";")[0]); } } if(quality == null) { if(split[5].matches("\\d+.?.*")) { quality = (float)Double.parseDouble(split[5]); } } HashMap<String, Float> advancedQualities = null; if(VariantHandler.freeze.isSelected()) { if(refcalls+altcalls < VariantHandler.coverageSlider.getValue()) { continue; } if(quality != null && quality < VariantHandler.qualitySlider.getValue()) { continue; } if(gq != null && gq < VariantHandler.gqSlider.getValue()) { continue; } if(altcalls/(double)(refcalls+altcalls) < VariantHandler.callSlider.getValue()/100.0) { continue; } if(VariantHandler.hideSNVs.isSelected() && altbase.length() == 1 ) { continue; } if(VariantHandler.hideIndels.isSelected() && altbase.length() > 1) { continue; } if(VariantHandler.rscode.isSelected() && !split[2].equals(".")) { continue; } } if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { return; } } if(refcalls+altcalls > VariantHandler.maxCoverageSlider.getMaximum()) { VariantHandler.maxCoverageSlider.setMaximum(refcalls+altcalls); VariantHandler.maxCoverageSlider.setValue(refcalls+altcalls); } /* if(currentSample.getMaxCoverage() < calls1+calls2) { currentSample.setMaxCoverage((float)(calls1+calls2)); } */ if(first && current.getNext() == null) { if(!split[2].equals(".")) { current.putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, split[2], currentSample, current, null)); } else { current.putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase,refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, null, currentSample, current, null)); } if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.getNext().addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, currentSample); } current = current.getNext(); first = false; } else if(pos == current.getPosition()){ current.addSample(altbase, refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, currentSample); if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, currentSample); } if(current.isRscode() == null && !split[2].equals(".")) { current.setRscode(split[2]); } } else if(current.getPosition() > pos) { if(!split[2].equals(".")) { current.getPrev().putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, split[2], currentSample, current.getPrev(), current)); } else { current.getPrev().putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, null, currentSample, current.getPrev(), current)); } if(noref ) { if(split.length > 7) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.getPrev().addSample(altbase2,refcalls+altcalls, refcalls, genotype, quality, gq,advancedQualities, currentSample); } current.putPrev(current.getPrev().getNext()); current = current.getPrev(); } } catch(Exception ex) { ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); for(int i=0; i<split.length; i++) { System.out.print(split[i] +" "); } System.out.println(); break; } if(first) { first = false; } } } boolean checkAdvQuals(String split, boolean indel) { if(!VariantHandler.indelFilters.isSelected()) { if(Main.drawCanvas.drawVariables.advQDraw != null && Main.drawCanvas.drawVariables.advQDraw.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDraw.size(); i++) { if(split.contains(Main.drawCanvas.drawVariables.advQDraw.get(i).key)) { if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals("<")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) < Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals("<=")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) <= Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals(">")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) > Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) >= Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } } } } } else { if(indel) { if(Main.drawCanvas.drawVariables.advQDrawIndel != null && Main.drawCanvas.drawVariables.advQDrawIndel.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDrawIndel.size(); i++) { if(split.contains(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key)) { if(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).format.equals("<")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key.length()+1).split(";")[0].trim()) < Main.drawCanvas.drawVariables.advQDrawIndel.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).format.equals("<=")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key.length()+1).split(";")[0].trim()) <= Main.drawCanvas.drawVariables.advQDrawIndel.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).format.equals(">")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key.length()+1).split(";")[0].trim()) > Main.drawCanvas.drawVariables.advQDrawIndel.get(i).value) { return true; } } else { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key.length()+1).split(";")[0].trim()) >= Main.drawCanvas.drawVariables.advQDrawIndel.get(i).value) { return true; } } } } } } else { if(Main.drawCanvas.drawVariables.advQDraw != null && Main.drawCanvas.drawVariables.advQDraw.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDraw.size(); i++) { if(split.contains(Main.drawCanvas.drawVariables.advQDraw.get(i).key)) { if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals("<")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) < Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals("<=")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) <= Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals(">")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) > Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) >= Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } } } } } } return false; } boolean checkAdvFilters(String split, boolean indel) { if(!VariantHandler.indelFilters.isSelected()) { if(Main.drawCanvas.drawVariables.advQDraw != null && Main.drawCanvas.drawVariables.advQDraw.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDraw.size(); i++) { if(split.equals(Main.drawCanvas.drawVariables.advQDraw.get(i).key)) { return true; } } } } else { if(indel) { if(Main.drawCanvas.drawVariables.advQDrawIndel != null && Main.drawCanvas.drawVariables.advQDrawIndel.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDrawIndel.size(); i++) { if(split.equals(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key)) { return true; } } } } else { if(Main.drawCanvas.drawVariables.advQDraw != null && Main.drawCanvas.drawVariables.advQDraw.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDraw.size(); i++) { if(split.equals(Main.drawCanvas.drawVariables.advQDraw.get(i).key)) { return true; } } } } } return false; } public void readLine(String[] split, Sample sample) { try { if(split.length < 3) { return; } if(split[0].startsWith("#") || split[4].equals("*")) { return; } pos = Integer.parseInt(split[1])-1; if(pos < Main.drawCanvas.variantsStart) { return; } else if(pos >= Main.drawCanvas.variantsEnd) { stop = true; return; } if(linecounter == 0 || pos -linecounter > (Main.drawCanvas.variantsEnd-Main.drawCanvas.variantsStart)/100) { Main.drawCanvas.loadBarSample = (int)(((pos-Main.drawCanvas.variantsStart)/(double)(Main.drawCanvas.variantsEnd-Main.drawCanvas.variantsStart))*100); // Draw.updatevars = true; linecounter = pos; if(search) { if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } } } /* if(first) { info = split[split.length-1].split(":"); if(info[0].length() == 1 || info[0].charAt(0) == '0' && info[0].charAt(2) =='0') { info = split[split.length-2].split(":"); sample.infolocation = (short)(split.length-2); } else { sample.infolocation = (short)(split.length-1); } } else { */ //} if(sample.somaticColumn != null) { if(sample.somaticColumn > split.length-1) { sample.somaticColumn = null; info = split[split.length-1].split(":"); } else { info = split[sample.somaticColumn].split(":"); } } else { info = split[split.length-1].split(":"); } noref = false; multi = false; HashMap<String, Integer> infofield = new HashMap<String, Integer>(); if(split.length > 8) { String[] infos = split[8].split(":"); for(int i = 0; i<infos.length; i++) { infofield.put(infos[i], i); } } if(infofield.containsKey("GT")) { gtindex = infofield.get("GT"); if(info[gtindex].contains(".")) { return; } if(info[gtindex].contains("|")) { firstallele = Short.parseShort(""+info[gtindex].split("|")[0]); secondallele = Short.parseShort(""+info[gtindex].split("|")[2]); } else { firstallele = Short.parseShort(""+info[gtindex].split("/")[0]); secondallele = Short.parseShort(""+info[gtindex].split("/")[1]); } genotype = firstallele == secondallele; if(genotype && firstallele == 0) { return; } if(infofield.containsKey("AD")) { if(infofield.containsKey("RD")) { calls1 = Integer.parseInt(info[infofield.get("RD")]); try { if(info[infofield.get("AD")].contains(",")) { calls2 = Integer.parseInt(info[infofield.get("AD")].split(",")[1]); } else { calls2 = Integer.parseInt(info[infofield.get("AD")]); } } catch(Exception e) { System.out.println(info[infofield.get("AD")]); e.printStackTrace(); } } else { coverages = info[infofield.get("AD")].split(","); if(genotype) { calls1 = Integer.parseInt(coverages[0]); } else { try { calls1 = Integer.parseInt(coverages[firstallele]); } catch(Exception ex) { calls1 = Integer.parseInt(coverages[coverages.length-1]); //System.out.println(split[3] +" " +split[4] +" " +split[8] +" " +split[9] +" " +split[10]); } } try { calls2 = Integer.parseInt(coverages[secondallele]); } catch(Exception ex) { calls2 = Integer.parseInt(coverages[coverages.length-1]); //System.out.println(split[3] +" " +split[4] +" " +split[8] +" " +split[9] +" " +split[10]); } } if(!genotype) { if(firstallele == 0) { refallele = firstallele; refcalls = calls1; altallele = secondallele; altcalls = calls2; } else if(secondallele == 0){ refallele = secondallele; refcalls = calls2; altallele = firstallele; altcalls = calls1; } else { noref = true; refallele = firstallele; refcalls = calls1; altallele = secondallele; altcalls = calls2; } } else { try { refcalls =calls1; // Short.parseShort(info[split[8].indexOf("AD")/3].split(",")[0]); altallele = secondallele; altcalls = calls2; } catch(Exception e) { for(int i = 0 ; i<split.length; i++) { System.out.print(split[i] +"\t"); } System.out.println(); e.printStackTrace(); } } } else if (split[7].contains("DP4")) { coverages = split[7].substring(split[7].indexOf("DP4")+4).split(";")[0].split(","); refallele = firstallele; altallele = secondallele; refcalls = Integer.parseInt(coverages[0])+Integer.parseInt(coverages[1]); altcalls = Integer.parseInt(coverages[2])+Integer.parseInt(coverages[3]); } else { if(firstallele == 0) { refallele = firstallele; altallele = secondallele; } else if(secondallele == 0){ refallele = secondallele; altallele = firstallele; } else { refallele = firstallele; altallele = secondallele; } refcalls = 20; altcalls = 20; } } else { refcalls = 20; altcalls = 20; } if(!split[4].contains(",")) { altbase = getVariant(split[3], split[4]); } else if(!noref){ if (altallele > 0) { altbase = getVariant(split[3], split[4].split(",")[altallele-1]); } else { altbase = getVariant(split[3], split[4].split(",")[0]); multi = true; } } else { altbase = getVariant(split[3], split[4].split(",")[altallele-1]); altbase2 = getVariant(split[3], split[4].split(",")[refallele-1]); } quality = null; if(split.length > 8 && split[8].contains("Q")) { if(infofield.containsKey("GQ") && !info[infofield.get("GQ")].equals(".")) { gq = (float)Double.parseDouble(info[infofield.get("GQ")]); } else if(infofield.containsKey("BQ") && !info[infofield.get("BQ")].equals(".")) { quality = (float)Double.parseDouble(info[infofield.get("BQ")]); } else if(split[7].contains("SSC")) { quality = Float.parseFloat(split[7].substring(split[7].indexOf("SSC") +4).split(";")[0]); } } if(quality == null) { if(split.length > 5 && split[5].matches("\\d+.?.*")) { quality = (float)Double.parseDouble(split[5]); } } HashMap<String, Float> advancedQualities = null; if(VariantHandler.freeze.isSelected()) { if(!sample.annoTrack) { if(refcalls+altcalls < VariantHandler.coverageSlider.getValue()) { return; } if(quality != null && quality < VariantHandler.qualitySlider.getValue()) { return; } if(gq != null && gq < VariantHandler.gqSlider.getValue()) { return; } if(altcalls/(double)(refcalls+altcalls) < VariantHandler.callSlider.getValue()/100.0) { return; } } if(!sample.annotation) { if(VariantHandler.hideSNVs.isSelected() && altbase.length() == 1) { return; } if(VariantHandler.hideIndels.isSelected() && altbase.length() > 1) { return; } if(VariantHandler.rscode.isSelected() && !split[2].equals(".")) { return; } } } if(!sample.annoTrack) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { return; } } if(refcalls+altcalls > VariantHandler.maxCoverageSlider.getMaximum()) { VariantHandler.maxCoverageSlider.setMaximum(refcalls+altcalls); VariantHandler.maxCoverageSlider.setValue(refcalls+altcalls); } } while(current != null && current.getNext() != null && current.getPosition() < pos ){ current = current.getNext(); } if(current.getNext() == null && current.getPosition() < pos) { try { if(!split[2].equals(".")) { current.putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase,refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, split[2], sample, current, null)); } else { current.putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase,refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, null, sample, current, null)); } if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.getNext().addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } if(multi) { String[] altsplit = split[4].split(","); for(int i = 1; i<altsplit.length; i++) { altbase = getVariant(split[3],altsplit[i]); if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { continue; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { continue; } } current.getNext().addSample(altbase, refcalls+altcalls, refcalls, genotype, quality, gq,advancedQualities, sample); } } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); //Main.drawCanvas.ready("all"); } } else if(current.getPosition() == pos) { current.addSample(altbase, refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, sample); if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } if(current.isRscode() == null && !split[2].equals(".")) { current.setRscode(split[2]); } if(multi) { String[] altsplit = split[4].split(","); for(int i = 1; i<altsplit.length; i++) { altbase = getVariant(split[3],altsplit[i]); if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { continue; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { continue; } } try { current.getNext().addSample(altbase, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } catch(Exception e) { System.out.println(current.getChrom() +":" +current.getPosition()); } } } } else if(current.getPosition() > pos) { if(!split[2].equals(".")) { current.getPrev().putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, split[2], sample, current.getPrev(), current)); } else { if(current.getPrev() == null) { System.out.println(current.getPosition()); Main.cancel(); } current.getPrev().putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, null, sample, current.getPrev(), current)); } current.putPrev(current.getPrev().getNext()); current = current.getPrev(); if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } if(multi) { String[] altsplit = split[4].split(","); for(int i = 1; i<altsplit.length; i++) { altbase = getVariant(split[3],altsplit[i]); if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { continue; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { continue; } } current.addSample(altbase, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } } } } catch(Exception ex) { //System.out.println(split[8] +" " +split[10] +" " +split[3] +" " +split[4]); ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); } } /* File getListFile(File listfile, String chrom) { try { if(!listfile.exists()) { return new File(listfile.getCanonicalPath().replace(".list", ".cram")); } BufferedReader reader = new BufferedReader(new FileReader(listfile)); String mnt = "/mnt"; if(!listfile.getAbsolutePath().startsWith("/mnt")) { if(listfile.getAbsolutePath().indexOf("\\cg") < 0) { if(listfile.getAbsolutePath().indexOf("/cg") > -1) { mnt = listfile.getAbsolutePath().substring(0,listfile.getAbsolutePath().indexOf("/cg")); } else { mnt = "X:"; } } else { mnt = listfile.getAbsolutePath().substring(0,listfile.getAbsolutePath().indexOf("\\cg")); } } String listline; while((listline = reader.readLine()) != null) { if(Main.selectedChrom > 24) { if(listline.contains("_" +"GL" +".")) { reader.close(); return new File(listline.replace("/mnt", mnt)); } } else if(listline.contains("_" +chrom +".")) { reader.close(); return new File(listline.replace("/mnt", mnt)); } } reader.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } return null; }*/ static String getVariant(String ref, String alt) { if(ref.length() == 1 && alt.length() == 1) { return alt; } else if (ref.length() == 1 || alt.length() == 1) { if(ref.length() == 2) { return "del" +ref.substring(1); } else if(alt.length() >= 2) { return "ins" +alt.substring(1); } else { return "del" +(ref.length()-1); } } else if(alt.length() == ref.length()) { if(ref.contains("-")) { return getVariant(ref, ""+alt.charAt(0)); } else if(alt.contains("-")) { return getVariant(ref, ""+alt.replaceAll("-", "")); } else { return "" +alt.charAt(0); } } else { if(ref.length() < alt.length()) { return "ins" +alt.substring(1, alt.length()-(ref.length()-1)); } else { if(ref.length() -alt.length() == 1) { return "del" +ref.substring(1, ref.length()-(alt.length()-1)); } else { return "del" +(ref.length() -alt.length()); } } } } void addToSequence(SplitClass split, StringBuffer buffer, int length) { /* if(length < 0) { buffer.insert(0, Main.chromDraw.getSeq(split.chrom, (int)(split.readSeqStart-length)-1, split.readSeqStart, Main.referenceFile)); split.readSeqStart = (int)(split.readSeqStart-length)-1; if(split.readSeqStart < 0) { split.readSeqStart = 0; } readSeqStart = split.readSeqStart; } else { split.readSequence.append(Main.chromDraw.getSeq(split.chrom, split.readSeqStart+split.readSequence.length(), (int)(split.readSeqStart+split.readSequence.length()+length+200), Main.referenceFile)); } */ } Iterator<SAMRecord> getBamIterator(Reads readClass, String chrom, int startpos, int endpos) { try { if(samFileReader != null) { samFileReader.close(); } if(CRAMReader != null) { CRAMReader.close(); } if(readClass.sample.CRAM) { CRAMReader = new CRAMFileReader(readClass.sample.samFile, new File(readClass.sample.samFile.getCanonicalFile() +".crai"),new ReferenceSource(Main.ref),/*Main.referenceFile, */ValidationStringency.SILENT); if(CRAMReader != null && !CRAMReader.hasIndex()) { Main.showError("Index file is missing (.crai) for " +readClass.sample.samFile.getName(), "Note"); return null; } } else { try { samFileReader = SamReaderFactory.make().open(readClass.sample.samFile); //samFileReader = new SAMFileReader(readClass.sample.samFile); if(samFileReader != null && !samFileReader.hasIndex()) { Main.showError("Index file is missing (.bai) for " +readClass.sample.samFile.getName(), "Note"); return null; } } catch(Exception e) { Main.showError(e.getMessage(), "Note"); e.printStackTrace(); } } } catch(Exception e) { if(readClass.sample.CRAM) { if(CRAMReader != null && !CRAMReader.hasIndex()) { Main.showError("Index file is missing (.crai) for " +readClass.sample.samFile.getName(), "Note"); return null; } } else { if(samFileReader != null && !samFileReader.hasIndex()) { Main.showError("Index file is missing (.bai) for " +readClass.sample.samFile.getName(), "Note"); return null; } } e.printStackTrace(); } try { if(readClass.sample.CRAM) { if(!readClass.sample.chrSet) { if(CRAMReader.getFileHeader().getSequence(0).getSAMString().contains("chr")) { readClass.sample.chr = "chr"; } readClass.sample.chrSet = true; } QueryInterval[] interval = { new QueryInterval(CRAMReader.getFileHeader().getSequence(readClass.sample.chr+chrom).getSequenceIndex(), startpos, endpos) }; Iterator<SAMRecord> value = CRAMReader.query(interval, false); return value; } else { Iterator<SAMRecord> value = null; // SAMReadGroupRecord record = new SAMReadGroupRecord("fixed_My6090N_sorted"); // samFileReader.getFileHeader().addReadGroup(record); try { //SAMFileReader.setDefaultValidationStringency(ValidationStringency.SILENT); if(!readClass.sample.chrSet) { if(samFileReader.getFileHeader().getSequence(0).getSAMString().contains("chr")) { readClass.sample.chr = "chr"; } readClass.sample.chrSet = true; } value = samFileReader.queryOverlapping(readClass.sample.chr+chrom, startpos, endpos); } catch(htsjdk.samtools.SAMFormatException e) { e.printStackTrace(); } return value; } } catch(Exception e) { try { if(readClass.sample.CRAM) { e.printStackTrace(); /*if(CRAMReader.getFileHeader().getSequence(readClass.sample.chr + "M") != null) { QueryInterval[] interval = { new QueryInterval(CRAMReader.getFileHeader().getSequence(readClass.sample.chr + "M").getSequenceIndex(), startpos, endpos) }; } Iterator<SAMRecord> value = CRAMReader.query(interval, false); if(!readClass.sample.chrSet) { if(!value.hasNext()) { QueryInterval[] interval2 = { new QueryInterval(CRAMReader.getFileHeader().getSequence("chrM").getSequenceIndex(), startpos, endpos) }; value = CRAMReader.query(interval2, false); if(value.hasNext()) { readClass.sample.chr = "chr"; readClass.sample.chrSet = true; } } else { readClass.sample.chrSet = true; } }*/ return null; //return value; } else { Iterator<SAMRecord> value = samFileReader.queryOverlapping(readClass.sample.chr+"M", startpos, endpos); if(!readClass.sample.chrSet) { if(!value.hasNext()) { value = samFileReader.queryOverlapping("chrM", startpos, endpos); if(value.hasNext()) { readClass.sample.chr = "chr"; readClass.sample.chrSet = true; } } else { readClass.sample.chrSet = true; } } return value; } } catch(Exception ex) { ex.printStackTrace(); ErrorLog.addError(e.getStackTrace()); return null; } } } public SAMRecord getRead(String chrom, int startpos, int endpos, String name, Reads readClass) { Iterator<SAMRecord> bamIterator = getBamIterator(readClass,chrom,startpos-1, endpos); SAMRecord samRecord = null; while(bamIterator != null && bamIterator.hasNext()) { try { samRecord = bamIterator.next(); if(samRecord.getUnclippedStart() < startpos) { continue; } if(samRecord.getUnclippedStart() == startpos && samRecord.getReadName().equals(name)) { return samRecord; } } catch(Exception e) { e.printStackTrace(); } } return null; } public ArrayList<ReadNode> getReads(String chrom, int startpos, int endpos, Reads readClass, SplitClass split) { // ReadAdder readrunner = null; try { //Sample sample = readClass.sample; if(Main.drawCanvas.drawVariables.sampleHeight > 100) { if(viewLength > Settings.readDrawDistance) { if(firstCov || readClass.getCoverageStart() == 0 || (readClass.getCoverageStart() < startpos && readClass.getCoverageEnd() > endpos) || (readClass.getCoverageStart() > startpos && readClass.getCoverageEnd() < endpos) ) { double[][] coverages = new double[(int)Main.frame.getWidth()][8]; readClass.setCoverages(coverages); readClass.setMaxcoverage(1); readClass.setCoverageStart(startpos); oldstart = endpos; readClass.setCoverageEnd(endpos); bamIterator = getBamIterator(readClass,chrom,startpos, endpos); firstCov = false; } else if(readClass.getCoverageStart() > startpos) { /* int[][] coverages = new int[(int)(readClass.getCoverages().length +((readClass.getCoverageStart()-startpos)*pixel))][8]; pointer = coverages.length-1; for(int i = readClass.getCoverages().length-1; i>=0; i--) { coverages[pointer][0] = readClass.getCoverages()[i][0]; pointer--; } left = true; oldstart = readClass.getCoverageStart(); bamIterator = getBamIterator(readClass,readClass.sample.chr + chrom,startpos, readClass.getCoverageStart()); readClass.setCoverageStart(startpos); readClass.setCoverages(coverages); */ double[][] coverages = new double[(int)Main.frame.getWidth()][8]; readClass.setCoverages(coverages); readClass.setMaxcoverage(1); bamIterator = getBamIterator(readClass,chrom,startpos, endpos); // readClass.setReadEnd(endpos); readClass.setCoverageStart(startpos); readClass.setCoverageEnd(endpos); oldstart = endpos; } else if(readClass.getCoverageEnd() < endpos) { double[][] coverages = new double[(int)Main.frame.getWidth()][8]; readClass.setCoverages(coverages); readClass.setMaxcoverage(1); bamIterator = getBamIterator(readClass,chrom,startpos, endpos); // readClass.setReadEnd(endpos); readClass.setCoverageStart(startpos); readClass.setCoverageEnd(endpos); oldstart = endpos; } else { return null; } } else { firstCov = true; if(readClass.getReads().isEmpty()) { right = false; left = false; if(!chrom.contains("M")) { searchwindow = viewLength +readClass.sample.longestRead; } else { searchwindow = 0; } /*if(firstSample) { splitIndex.setReference(new ReferenceSeq(splitIndex.chrom,startpos-searchwindow-1, endpos+searchwindow +200, Main.referenceFile)); }*/ try { bamIterator = getBamIterator(readClass,chrom,startpos-searchwindow, endpos+searchwindow ); } catch(Exception e) { e.printStackTrace(); /* try { } catch(java.lang.IllegalArgumentException ex) { readClass.loading = false; System.out.println("Chromosome " +chrom +" not found in " +readClass.sample.samFile.getName()); ErrorLog.addError(ex.getStackTrace()); return null; } */ } startpos = startpos - searchwindow; endpos = endpos + searchwindow; if(startpos < 1) { startpos = 1; } readClass.setCoverageStart(startpos); readClass.startpos = startpos; readClass.endpos = endpos; readClass.setReadStart(startpos); readClass.setReadEnd(endpos); if(splitIndex.getMinReadStart() > startpos) { splitIndex.setMinReadStart(startpos); } if(splitIndex.getMaxReadEnd() < endpos) { splitIndex.setMaxReadEnd(endpos); } double[][] coverages = new double[endpos-startpos+searchwindow*2][8]; readClass.setCoverageEnd(startpos + coverages.length); readClass.setCoverages(coverages); readClass.setMaxcoverage(1); } else if(!readClass.getReads().isEmpty() && readClass.getReadStart() /*(readClass.getFirstRead().getPosition()*/ < startpos && readClass.getReadEnd() /*readClass.getLastRead().getPosition()*/ > endpos){ left = false; right = false; if(!chrom.contains("M")) { searchwindow = viewLength +readClass.sample.longestRead; } else { searchwindow = 0; } return readClass.getReads(); } else if(readClass.getLastRead() != null && readClass.getReadEnd() < endpos) { if(!chrom.contains("M")) { searchwindow = viewLength; } else { searchwindow = 0; } right = true; left = false; startpos = readClass.getReadEnd(); endpos = endpos+searchwindow; addlength = 1000; // readClass.reference.append( endpos+200); /*if(firstSample) { System.out.println("jhou"); //if(splitIndex.getReadReference() == null) { splitIndex.setReference(new ReferenceSeq(splitIndex.chrom,startpos-searchwindow-1, endpos+searchwindow +200, Main.referenceFile)); // } //else { // splitIndex.getReadReference().append( endpos+200); // } }*/ bamIterator = getBamIterator(readClass,chrom,startpos, endpos ); if(readClass.getCoverageEnd() < endpos) { if(searchwindow < 1000) { addlength = 2000; } else if(searchwindow < 10000) { addlength = 20000; } else { addlength = 200000; } } double[][] coverages = new double[(int)(readClass.getCoverages().length +(addlength))][8]; for(int i =0; i<readClass.getCoverages().length; i++) { coverages[i][0] = readClass.getCoverages()[i][0]; coverages[i][1] = readClass.getCoverages()[i][1]; coverages[i][2] = readClass.getCoverages()[i][2]; coverages[i][3] = readClass.getCoverages()[i][3]; coverages[i][4] = readClass.getCoverages()[i][4]; coverages[i][5] = readClass.getCoverages()[i][5]; coverages[i][6] = readClass.getCoverages()[i][6]; coverages[i][7] = readClass.getCoverages()[i][7]; } readClass.endpos = endpos; if(splitIndex.getMaxReadEnd() < endpos) { splitIndex.setMaxReadEnd(endpos); } readClass.setReadEnd(endpos); readClass.setCoverageEnd(readClass.getCoverageStart()+coverages.length); readClass.setCoverages(coverages); } else if(readClass.getFirstRead() != null && readClass.getFirstRead().getPosition() > startpos) { left = true; right = false; if(!chrom.contains("M")) { searchwindow = viewLength+readClass.sample.longestRead; } else { searchwindow = 0; } endpos = readClass.getReadStart(); startpos = startpos-searchwindow; /* if(firstSample) { splitIndex.getReadReference().appendToStart( startpos-1); }*/ bamIterator = getBamIterator(readClass,chrom,startpos, endpos+100 ); addlength = 0; if(searchwindow < 1000) { addlength = 2000; } else if(searchwindow < 10000) { addlength = 20000; } else { addlength = 200000; } double[][] coverages = new double[(int)(readClass.getCoverages().length +addlength)][8]; readClass.setCoverageStart(readClass.getCoverageStart()-addlength); pointer = coverages.length-1; for(int i = readClass.getCoverages().length-1; i>=0; i--) { coverages[pointer][0] = readClass.getCoverages()[i][0]; coverages[pointer][1] = readClass.getCoverages()[i][1]; coverages[pointer][2] = readClass.getCoverages()[i][2]; coverages[pointer][3] = readClass.getCoverages()[i][3]; coverages[pointer][4] = readClass.getCoverages()[i][4]; coverages[pointer][5] = readClass.getCoverages()[i][5]; coverages[pointer][6] = readClass.getCoverages()[i][6]; coverages[pointer][7] = readClass.getCoverages()[i][7]; pointer--; } left = true; readClass.startpos = startpos; readClass.setReadStart(startpos); if(splitIndex.getMinReadStart() > startpos) { splitIndex.setMinReadStart(startpos); } readClass.setCoverages(coverages); } } coverageArray = readClass.getCoverages(); if(readClass.getReadStart() == null) { readClass.setReadStart(startpos); } while(bamIterator != null && bamIterator.hasNext()) { try { if(cancelreadread || !Main.drawCanvas.loading ||readClass.sample.getIndex() < Main.drawCanvas.drawVariables.visiblestart || readClass.sample.getIndex() > Main.drawCanvas.drawVariables.visiblestart + Main.drawCanvas.drawVariables.visiblesamples) { return null; } try { samRecord = bamIterator.next(); } catch(htsjdk.samtools.SAMFormatException ex) { ex.printStackTrace(); } if(samRecord.getReadUnmappedFlag()) { continue; } if(Draw.variantcalculator) { if(readClass.getHeadAndTail().size() > Settings.readDepthLimit) { break; } } //TODO jos on pienempi ku vika unclipped start if(samRecord.getUnclippedEnd() < startpos) { //this.readSeqStart+1) { continue; } if(samRecord.getUnclippedStart() >= endpos){ Main.drawCanvas.loadBarSample = 0; Main.drawCanvas.loadbarAll =0; break; } if(readClass.sample.longestRead <samRecord.getCigar().getReferenceLength()) { readClass.sample.longestRead = samRecord.getCigar().getReferenceLength(); } if(readClass.sample.getComplete() == null) { if(samRecord.getReadName().startsWith("GS")) { readClass.sample.setcomplete(true); } else { readClass.sample.setcomplete(false); } } if(viewLength < Settings.readDrawDistance) { /* if(splitIndex.reference == null) { splitIndex.reference = new ReferenceSeq(chrom, samRecord.getUnclippedStart()-2000, end+1000, Main.referenceFile); } else if(samRecord.getUnclippedStart()-1 < splitIndex.reference.getStartPos()) { splitIndex.reference.appendToStart(samRecord.getUnclippedStart()-1); } else if(samRecord.getUnclippedEnd() > splitIndex.reference.getEndPos()) { splitIndex.reference.append(samRecord.getUnclippedEnd()); } */ if(samRecord.getUnclippedEnd() > readClass.getCoverageEnd()-1) { double[][] coverages = new double[(int)(readClass.getCoverages().length +(samRecord.getUnclippedEnd()-samRecord.getUnclippedStart() + (int)splitIndex.viewLength))][8]; //pointer = coverages.length-1; for(int i =0; i<readClass.getCoverages().length; i++) { coverages[i][0] = readClass.getCoverages()[i][0]; coverages[i][1] = readClass.getCoverages()[i][1]; coverages[i][2] = readClass.getCoverages()[i][2]; coverages[i][3] = readClass.getCoverages()[i][3]; coverages[i][4] = readClass.getCoverages()[i][4]; coverages[i][5] = readClass.getCoverages()[i][5]; coverages[i][6] = readClass.getCoverages()[i][6]; coverages[i][7] = readClass.getCoverages()[i][7]; // pointer--; } readClass.setCoverageEnd(readClass.getCoverageStart()+coverages.length); readClass.setCoverages(coverages); coverageArray = readClass.getCoverages(); } else if(samRecord.getUnclippedStart() > 0 && samRecord.getUnclippedStart() < readClass.getCoverageStart() ) { /* double[][] coverages = null; if(readClass.getCoverageStart()-(readClass.getCoverageStart()-samRecord.getUnclippedStart())-1000 < 1) { coverages = new double[(int)(readClass.getCoverages().length + readClass.getCoverageStart())][8]; readClass.setCoverageStart(1); } else { coverages = new double[(int)(readClass.getCoverages().length + (readClass.getCoverageStart()-samRecord.getUnclippedStart())+1000)][8]; readClass.setCoverageStart(readClass.getCoverageStart()-(readClass.getCoverageStart()-samRecord.getUnclippedStart())-1000); } pointer = coverages.length-1; for(int i = readClass.getCoverages().length-1; i>=0; i--) { coverages[pointer][0] = readClass.getCoverages()[i][0]; coverages[pointer][1] = readClass.getCoverages()[i][1]; coverages[pointer][2] = readClass.getCoverages()[i][2]; coverages[pointer][3] = readClass.getCoverages()[i][3]; coverages[pointer][4] = readClass.getCoverages()[i][4]; coverages[pointer][5] = readClass.getCoverages()[i][5]; coverages[pointer][6] = readClass.getCoverages()[i][6]; coverages[pointer][7] = readClass.getCoverages()[i][7]; pointer--; } readClass.setCoverages(coverages); */ } } if(((viewLength < Settings.readDrawDistance && samRecord.getUnclippedStart() >= startpos) || (viewLength >= Settings.readDrawDistance && samRecord.getUnclippedEnd() >= startpos)) && samRecord.getUnclippedStart() <= endpos) { java.util.ArrayList<java.util.Map.Entry<Integer,Byte>> mismatches = null; if(samRecord.getMappingQuality() >= Settings.mappingQ) { if(viewLength > Settings.readDrawDistance) { if( Main.drawCanvas.loadBarSample != (int)(((samRecord.getUnclippedStart()-startpos)/(double)(oldstart-startpos))*100) ) { Main.drawCanvas.loadBarSample = (int)(((samRecord.getUnclippedStart()-startpos)/(double)(oldstart-startpos))*100); Main.drawCanvas.loadbarAll = (int)(((samRecord.getUnclippedStart()-startpos)/(double)(oldstart-startpos))*100); } for(int i = 0; i<(int)(samRecord.getReadLength()*splitIndex.pixel +1); i++) { if((samRecord.getUnclippedStart()-start)*splitIndex.pixel +i < 0) { continue; } if((samRecord.getUnclippedStart()-start)*splitIndex.pixel + i > coverageArray.length-1) { break; } if(samRecord.getReadLength()*splitIndex.pixel >= 1) { coverageArray[(int)((samRecord.getUnclippedStart()-start)*splitIndex.pixel+i)][0]+=(1/splitIndex.pixel); } else { coverageArray[(int)((samRecord.getUnclippedStart()-start)*splitIndex.pixel+i)][0]+=samRecord.getReadLength(); } if(coverageArray[(int)((samRecord.getUnclippedStart()-start)*splitIndex.pixel+i)][0]/*pixel*/ > readClass.getMaxcoverage()) { readClass.setMaxcoverage((coverageArray[(int)((samRecord.getUnclippedStart()-start)*splitIndex.pixel+i)][0]/*pixel*/)); } } } else { if( Main.drawCanvas.loadBarSample != (int)(((samRecord.getUnclippedStart()-startpos)/(double)(endpos-startpos))*100) ) { Main.drawCanvas.loadBarSample = (int)(((samRecord.getUnclippedStart()-startpos)/(double)(endpos-startpos))*100); Main.drawCanvas.loadbarAll = (int)(((samRecord.getUnclippedStart()-startpos)/(double)(endpos-startpos))*100); } } } if(viewLength <= Settings.readDrawDistance) { if(right && readClass.getLastRead() != null && (samRecord.getUnclippedStart() <= startpos)) { continue; } if(right && samRecord.getUnclippedStart() > endpos) { right = false; } try { mismatches = getMismatches(samRecord, readClass, coverageArray, split); } catch(Exception e) { e.printStackTrace(); } if(left) { if(readClass.getFirstRead().getPosition() > samRecord.getUnclippedStart()) { ReadNode addNode = new ReadNode(samRecord, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); readClass.setFirstRead(addNode); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-(readClass.readHeight+2))); addNode.setPrev(null); addNode.setNext(readClass.getHeadAndTail().get(0)[headnode]); readClass.getHeadAndTail().get(0)[headnode].setPrev(addNode); lastAdded = addNode; } else { ReadNode addNode = new ReadNode(samRecord, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-(readClass.readHeight+2))); addNode.setPrev(lastAdded); addNode.setNext(lastAdded.getNext()); lastAdded.setNext(addNode); lastAdded = addNode; readClass.getHeadAndTail().get(0)[headnode].setPrev(addNode); addNode.setNext(readClass.getHeadAndTail().get(0)[headnode]); } } else { try { if(samRecord.getAlignmentEnd() >= readClass.getCoverageEnd()) { coverageArray = coverageArrayAdd(readClass.sample.longestRead*2, coverageArray); } readSam(chrom, readClass, samRecord, mismatches); } catch(Exception e) { System.out.println(samRecord +" " +currentread); e.printStackTrace(); break; } } } } else { continue; } } catch(Exception e) { if(readClass.getReadStart() > startpos) { readClass.setReadStart(startpos); } if(readClass.getReadEnd() < endpos) { readClass.setReadEnd(endpos); } ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); break; } } if(left) { Main.drawCanvas.loadBarSample = 0; Main.drawCanvas.loadbarAll =0; setLevels(lastAdded, readClass.sample, readClass); lastAdded = null; } } } catch(Exception ex) { if(readClass == null) { sample.resetreadHash(); } if(readClass.getReadStart() == null) { readClass.setReadStart(startpos); } else if(readClass.getReadStart() > startpos) { readClass.setReadStart(startpos); } if(readClass.getReadEnd() < endpos) { readClass.setReadEnd(endpos); } ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); return null; // readrunner.end = true; } return null; } double[][] coverageArrayAdd(int addlength, double[][] coverageArray) { double[][] coverages = new double[(int)(coverageArray.length +(addlength)+1000)][8]; //pointer = coverages.length-1; for(int i =0; i<coverageArray.length; i++) { coverages[i][0] = coverageArray[i][0]; coverages[i][1] = coverageArray[i][1]; coverages[i][2] = coverageArray[i][2]; coverages[i][3] = coverageArray[i][3]; coverages[i][4] = coverageArray[i][4]; coverages[i][5] = coverageArray[i][5]; coverages[i][6] = coverageArray[i][6]; coverages[i][7] = coverageArray[i][7]; } Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; readClass.setCoverageEnd(readClass.getCoverageStart()+coverages.length); readClass.setCoverages(coverages); return coverages; } VariantCall[][] coverageArrayAdd(int addlength, VariantCall[][] coverageArray, Reads readClass) { VariantCall[][] coverages = new VariantCall[(int)(coverageArray.length +(addlength)+1000)][8]; //pointer = coverages.length-1; for(int i =0; i<coverageArray.length; i++) { coverages[i][0] = coverageArray[i][0]; coverages[i][1] = coverageArray[i][1]; coverages[i][2] = coverageArray[i][2]; coverages[i][3] = coverageArray[i][3]; coverages[i][4] = coverageArray[i][4]; coverages[i][5] = coverageArray[i][5]; coverages[i][6] = coverageArray[i][6]; coverages[i][7] = coverageArray[i][7]; } //Main.drawCanvas.loadbarAll = 0; // Main.drawCanvas.loadBarSample= 0; readClass.setCoverageEnd(readClass.getCoverageStart()+coverages.length); //readClass.setCoverages(coverages); return coverages; } java.util.ArrayList<java.util.Map.Entry<Integer,Byte>> getMismatches(SAMRecord samRecord, Reads readClass, double[][] coverageArray, SplitClass split) { if(readClass == null) { sample.resetreadHash(); } java.util.ArrayList<java.util.Map.Entry<Integer,Byte>> mismatches = null; String MD = samRecord.getStringAttribute("MD"); String SA = samRecord.getStringAttribute("SA"); if(samRecord.getReadBases().length == 0) { return null; } try { if(MD == null) { if(readClass.sample.MD) { readClass.sample.MD = false; } } if((readClass.sample.MD || MD!=null) && (samRecord.getCigarString().contains("S") && Settings.softClips == 0)/* && ((!samRecord.getCigarString().contains("S") && SA == null) || SA !=null)*/) { /*if(samRecord.getReadName().contains("1104:8947:11927")) { System.out.println(readClass.sample.MD +" " +MD +" " +samRecord.getCigarString().contains("S") +" " +Settings.softClips); }*/ if(!readClass.sample.MD) { readClass.sample.MD = true; } java.util.ArrayList<java.util.Map.Entry<Integer,Integer>> insertions = null; int softstart = 0; if(samRecord.getCigarLength() > 1) { readstart = samRecord.getUnclippedStart(); if(readClass.getCoverageStart()>readstart) { return null; } readpos= 0; for(int i = 0; i<samRecord.getCigarLength(); i++) { element = samRecord.getCigar().getCigarElement(i); if(element.getOperator().compareTo(CigarOperator.MATCH_OR_MISMATCH)== 0) { for(int r = readpos; r<readpos+element.getLength(); r++) { try { coverageArray[((readstart+r)-readClass.getCoverageStart())][0]++; } catch(Exception e) { //TODO } try { if(coverageArray[((readstart+r)-readClass.getCoverageStart())][0] > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverageArray[((readstart+r)-readClass.getCoverageStart())][0]); } } catch(Exception e) { //TODO } mispos++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.DELETION)== 0) { for(int d = 0; d<element.getLength(); d++) { readClass.getCoverages()[(readstart+readpos+d)- readClass.getCoverageStart()][Main.baseMap.get((byte)'D')]++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.INSERTION)== 0) { if(insertions == null) { insertions = new java.util.ArrayList<java.util.Map.Entry<Integer,Integer>>(); } java.util.Map.Entry<Integer, Integer> ins = new java.util.AbstractMap.SimpleEntry<>(readpos, element.getLength()); insertions.add(ins); readClass.getCoverages()[(readstart+readpos)- readClass.getCoverageStart()][Main.baseMap.get((byte)'I')]++; mispos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.SOFT_CLIP)== 0 ) { if(i==0 && SA == null) { softstart = element.getLength(); } if(Settings.softClips == 1) { for(int r = readpos; r<readpos+element.getLength(); r++) { if(SA == null) { coverageArray[((readstart+r)-readClass.getCoverageStart())][0]++; } mispos++; } readpos+=element.getLength(); } else { if(i == 0) { readstart = samRecord.getAlignmentStart(); mispos+=element.getLength(); } } } else if (element.getOperator().compareTo(CigarOperator.HARD_CLIP)== 0) { if(i == 0) { readstart = samRecord.getAlignmentStart(); } } else if(element.getOperator().compareTo(CigarOperator.SKIPPED_REGION)== 0) { readpos+=element.getLength(); } } } else { readstart = samRecord.getUnclippedStart(); for(int i = 0; i<samRecord.getReadLength(); i++) { try { if(readClass.getCoverageStart()>readstart) { break; } coverageArray[(readstart+i)-readClass.getCoverageStart()][0]++; if(coverageArray[(samRecord.getUnclippedStart()-readClass.getCoverageStart())+i][0] > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverageArray[(samRecord.getUnclippedStart()-readClass.getCoverageStart())+i][0]); } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); FileRead.cancelreadread = true; break; } } } if(MD != null) { try { Integer.parseInt(MD); return null; } catch(Exception ex) { readstart = samRecord.getAlignmentStart()-softstart; char[] chars = MD.toCharArray(); String bases = samRecord.getReadString(); String qualities = samRecord.getBaseQualityString(); if(SA == null) { softstart = 0; } int readpos = softstart; int mispos = softstart; int add =0; int digitpointer = 0, insertionpointer = 0; boolean first = true; for(int i = 0; i<chars.length; i++) { try { if(insertions != null) { if(insertionpointer < insertions.size() && insertions.get(insertionpointer).getKey() <= readpos) { while(insertionpointer < insertions.size() && insertions.get(insertionpointer).getKey() <= readpos) { mispos+=insertions.get(insertionpointer).getValue(); insertionpointer++; } } } if(Character.isDigit(chars[i])) { digitpointer = i+1; while(digitpointer < chars.length && Character.isDigit(chars[digitpointer])) { digitpointer++; } if(digitpointer== chars.length) { //System.out.println(MD.substring(i)); if((mispos +Integer.parseInt(MD.substring(i,digitpointer))) > samRecord.getReadLength()) { if(!first) { break; } first = false; readpos = 0; mispos = 0; i = -1; digitpointer = 0; insertionpointer = 0; mismatches.clear(); continue; } break; } else { add = Integer.parseInt(MD.substring(i,digitpointer)); readpos += add; mispos += add; } i = digitpointer-1; } else if(chars[i] != '^') { if(mismatches == null) { mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer,Byte>>(); } readClass.getCoverages()[(readstart+readpos)- readClass.getCoverageStart()][Main.baseMap.get((byte)bases.charAt(mispos))]++; if(samRecord.getBaseQualityString().length() != 1 && (int)qualities.charAt(mispos)-readClass.sample.phred < Settings.baseQ) { java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(readpos, (byte)Character.toLowerCase(bases.charAt(mispos))); mismatches.add(mismatch); } else { java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(readpos, (byte)bases.charAt(mispos)); mismatches.add(mismatch); } mispos++; readpos++; } else { digitpointer = i+1; while(!Character.isDigit(chars[digitpointer])) { digitpointer++; readpos++; } i=digitpointer-1; } } catch(Exception exc) { if(!first) { break; } first = false; readpos = 0; mispos = 0; i = -1; digitpointer = 0; insertionpointer = 0; mismatches.clear(); } } } } } else { /*if(split.getReference() == null) { readClass.setReference(new ReferenceSeq(splitIndex.chrom,start-500, end+500, Main.referenceFile)); //System.out.println(readClass.sample.getName() +" " +split.getReference().getStartPos() +" " +split.getReference().getSeq()[0]); }*/ //timecounter = 0; /*while(splitIndex.getReadReference() == null) { Thread.sleep(100); timecounter++; if(timecounter > 20) { break; } } Thread.sleep(0); */ // if(splitIndex.getReadReference() == null) { //splitIndex.setReference(new ReferenceSeq(splitIndex.chrom,startpos-searchwindow-1, endpos+searchwindow +200, Main.referenceFile)); // return null; //} if(samRecord.getCigarLength() > 1) { readstart = samRecord.getUnclippedStart(); readpos= 0; mispos= 0; /*if(readClass.getCoverageStart()>readstart) { return null; }*/ if(mismatches == null) { mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer,Byte>>(); } //testbranch for(int i = 0; i<samRecord.getCigarLength(); i++) { element = samRecord.getCigar().getCigarElement(i); if(element.getOperator().compareTo(CigarOperator.MATCH_OR_MISMATCH)== 0) { for(int r = readpos; r<readpos+element.getLength(); r++) { if(((readstart+r)-split.getReadReference().getStartPos()-1) > split.getReadReference().getSeq().length-1) { split.getReadReference().append(samRecord.getUnclippedEnd()+1000); } if(((readstart+r)-split.getReadReference().getStartPos()-1) < 0) { split.getReadReference().appendToStart(samRecord.getUnclippedStart()-1000); } try { if(samRecord.getReadBases()[mispos] != split.getReadReference().getSeq()[((readstart+r)-split.getReadReference().getStartPos()-1)]) { readClass.getCoverages()[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])]++; if(samRecord.getBaseQualityString().length() != 1 && (int)samRecord.getBaseQualityString().charAt(mispos)-readClass.sample.phred < Settings.baseQ ) { java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(r, (byte)Character.toLowerCase((char)samRecord.getReadBases()[mispos])); mismatches.add(mismatch); } else { java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(r, samRecord.getReadBases()[mispos]); mismatches.add(mismatch); } } } catch(Exception e) { System.out.println(samRecord.getReadBases().length); e.printStackTrace(); } try { coverageArray[((readstart+r)-readClass.getCoverageStart())][0]++; if(coverageArray[((readstart+r)-readClass.getCoverageStart())][0] > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverageArray[((readstart+r)-readClass.getCoverageStart())][0]); } } catch(Exception e) { //TODO } mispos++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.DELETION)== 0) { // readWidth+=element.getLength(); for(int d = 0; d<element.getLength(); d++) { readClass.getCoverages()[(readstart+readpos+d)- readClass.getCoverageStart()][Main.baseMap.get((byte)'D')]++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.INSERTION)== 0) { readClass.getCoverages()[(readstart+readpos)- readClass.getCoverageStart()][Main.baseMap.get((byte)'I')]++; mispos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.SOFT_CLIP)== 0 ) { if(Settings.softClips == 1) { for(int r = readpos; r<readpos+element.getLength(); r++) { if(((readstart+r)-split.getReadReference().getStartPos()-1) > split.getReadReference().getSeq().length-1) { split.getReadReference().append(samRecord.getUnclippedEnd()+1000); } if(((readstart+r)-splitIndex.getReadReference().getStartPos()-1) < 0) { split.getReadReference().appendToStart(samRecord.getUnclippedStart()-1000); } /* if(((readstart+r)-readClass.reference.getStartPos()-1) < 0) { continue; }*/ if(samRecord.getReadBases()[mispos] != split.getReadReference().getSeq()[((readstart+r)-split.getReadReference().getStartPos()-1)]) { if(SA == null) { readClass.getCoverages()[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get(samRecord.getReadBases()[mispos])]++; } if(mismatches == null) { mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer,Byte>>(); } java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(r, samRecord.getReadBases()[mispos]); mismatches.add(mismatch); } if(SA == null) { coverageArray[((readstart+r)-readClass.getCoverageStart())][0]++; } mispos++; } readpos+=element.getLength(); } else { if(i == 0) { readpos+=element.getLength(); mispos+=element.getLength(); } } } else if (element.getOperator().compareTo(CigarOperator.HARD_CLIP)== 0) { if(i == 0) { readstart = samRecord.getAlignmentStart(); } } else if(element.getOperator().compareTo(CigarOperator.SKIPPED_REGION)== 0) { readpos+=element.getLength(); // this.readWidth+=element.getLength(); } } } else { readstart = samRecord.getUnclippedStart(); /*if(readClass.getCoverageStart()>readstart) { return null; }*/ if((samRecord.getUnclippedEnd()-split.getReadReference().getStartPos()-1) > split.getReadReference().getSeq().length-1) { split.getReadReference().append(samRecord.getUnclippedEnd()+100); } if((samRecord.getUnclippedStart()-split.getReadReference().getStartPos()-1) < 0) { split.getReadReference().appendToStart(samRecord.getUnclippedStart()-100); } for(int r = 0; r<samRecord.getReadLength(); r++) { try { if(samRecord.getReadBases()[r] != split.getReadReference().getSeq()[((readstart+r)-split.getReadReference().getStartPos()-1)]) { if((readstart+r)-readClass.getCoverageStart() < readClass.getCoverages().length-1) { readClass.getCoverages()[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get(samRecord.getReadBases()[r])]++; if(mismatches == null) { mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer,Byte>>(); } java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(r, samRecord.getReadBases()[r]); mismatches.add(mismatch); } } try { coverageArray[(readstart+r)-readClass.getCoverageStart()][0]++; } catch(Exception e) { // System.out.println(readClass.getCoverageStart()); //TODO //e.printStackTrace(); continue; } if(coverageArray[(samRecord.getUnclippedStart()-readClass.getCoverageStart())+r][0] > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverageArray[(samRecord.getUnclippedStart()-readClass.getCoverageStart())+r][0]); } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); break; } } } } } catch(Exception e) { e.printStackTrace(); return null; } return mismatches; } /* public class ReadAdder extends SwingWorker<String, Object> { boolean end = false; String chrom; Reads readClass; ReadBuffer buffer; public ReadAdder(String chrom, Reads readClass, ReadBuffer buffer) { this.chrom = chrom; this.readClass = readClass; this.buffer = buffer; } protected String doInBackground() { while(true) { try { if(buffer.prev != null ) { readSam(chrom, readClass,buffer.record); // buffer.prev.next = null; buffer.prev = null; } if(buffer.next != null) { buffer = buffer.next; } if(end && buffer.next == null) { buffer.prev = null; break; } } catch(Exception e) { e.printStackTrace(); end = true; break; } } Draw.updateReads = true; buffer.prev = null; buffer = null; return ""; } } */ public static boolean isTrackFile(String file) { if(file.toLowerCase().endsWith(".bed") || file.toLowerCase().endsWith(".bed.gz")) { return true; } else if(file.toLowerCase().endsWith(".bedgraph.gz")) { return true; } else if(file.toLowerCase().endsWith("gff.gz")) { return true; } else if(file.toLowerCase().endsWith(".bigwig")) { return true; } else if(file.toLowerCase().endsWith(".bw")) { return true; } else if(file.toLowerCase().endsWith(".bigbed")) { return true; } else if(file.toLowerCase().endsWith(".bb")) { return true; } else if(file.toLowerCase().endsWith(".tsv.gz")) { return true; } else if(file.toLowerCase().endsWith(".tsv.bgz")) { return true; } return false; } public static boolean isTrackFile(File file) { if(file.getName().toLowerCase().endsWith(".bed") || file.getName().toLowerCase().endsWith(".bed.gz")) { return true; } else if(file.getName().toLowerCase().endsWith(".bedgraph.gz")) { return true; } else if(file.getName().toLowerCase().endsWith("gff.gz")) { return true; } else if(file.getName().toLowerCase().endsWith(".bigwig")) { return true; } else if(file.getName().toLowerCase().endsWith(".bw")) { return true; } else if(file.getName().toLowerCase().endsWith(".bigbed")) { return true; } else if(file.getName().toLowerCase().endsWith(".bb")) { return true; } else if(file.getName().toLowerCase().endsWith(".tsv.gz")) { return true; } else if(file.getName().toLowerCase().endsWith(".tsv.bgz")) { return true; } else if(file.getName().toLowerCase().endsWith(".txt")) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); String line, gene; int counter = 0, founds = 0; while((line = reader.readLine()) != null) { counter++; if(counter > 500) { break; } gene = line.replace(" ", ""); if(Main.searchTable.containsKey(gene.toUpperCase()) || Main.geneIDMap.containsKey(gene.toUpperCase())) { founds++; } } reader.close(); if(counter > 500) { Main.showError("Please give less than 500 genes in a txt-file.", "Error."); return false; } else if(founds == 0) { Main.showError("No genes could be identified from the " +file.getName(), "Error."); return false; } else { return true; } } catch(Exception e) { e.printStackTrace(); } } return false; } void readBED(File[] files) { try { File bedfile; Main.drawCanvas.loading("Loading tracks"); int addedfiles = 0; for(int i = 0; i<files.length; i++) { bedfile = files[i]; if(!isTrackFile(bedfile)) { continue; } if(!checkIndex(files[i])) { if(files[i].getName().endsWith(".tsv.gz") ||files[i].getName().endsWith(".tsv.bgz")) { Main.showError("No index file for the TSV file. Use Tools -> BED converter.", "Error"); continue; } if (JOptionPane.showConfirmDialog(Main.drawScroll, "No index file found. Do you want to create one?", "Indexing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ Main.drawCanvas.loadingtext = "Indexing " +files[i].getName(); if(files[i].getName().endsWith(".gz")) { MethodLibrary.createBEDIndex(files[i]); } else { MethodLibrary.createBEDIndex2(files[i]); } } } if(!checkIndex(files[i])) { Main.showError("Could not open file. Is the file sorted?", "Note"); continue; } BedTrack addTrack = new BedTrack(bedfile,Main.bedCanvas.bedTrack.size()); if(bedfile.getName().endsWith("tsv.gz") || bedfile.getName().endsWith("tsv.bgz")) { addTrack.getZerobased().setSelected(false); addTrack.iszerobased = 1; addTrack.getSelector().frame.setVisible(true); } Main.bedCanvas.bedTrack.add(addTrack); Main.bedCanvas.trackDivider.add(0.0); addTrack.minvalue = 0; if(bedfile.length() / 1048576 < Settings.settings.get("bigFile")) { addTrack.small = true; Main.bedCanvas.getBEDfeatures(addTrack, 1, Main.drawCanvas.splits.get(0).chromEnd); } if(bedfile.getName().toLowerCase().endsWith(".bedgraph") || bedfile.getName().toLowerCase().endsWith(".bedgraph.gz")) { Main.bedCanvas.pressGraph(addTrack); addTrack.getSelectorButton().setVisible(true); } else if(bedfile.getName().toLowerCase().endsWith("bigwig") || bedfile.getName().toLowerCase().endsWith("bw")) { addTrack.bigWig = true; addTrack.small = true; Main.bedCanvas.pressGraph(addTrack); addTrack.getSelectorButton().setVisible(false); Main.bedCanvas.getBEDfeatures(addTrack, (int)Main.drawCanvas.splits.get(0).start, (int)Main.drawCanvas.splits.get(0).end); } else { setBedTrack(addTrack); } addedfiles++; setTable(addTrack); } Main.drawCanvas.ready("Loading tracks"); if(Main.bedCanvas.bedTrack.size() == 0) { return; } if(!Main.trackPane.isVisible()) { Main.trackPane.setVisible(true); Main.varpane.setDividerSize(3); if(addedfiles < 5) { Main.varpane.setResizeWeight(addedfiles *0.1); Main.trackPane.setDividerLocation(addedfiles *0.1); Main.varpane.setDividerLocation(addedfiles *0.1); } else { Main.varpane.setResizeWeight(0.8); Main.trackPane.setDividerLocation(0.8); /*Main.bedCanvas.setPreferredSize(new Dimension(Main.drawWidth, Main.bedCanvas.bedTrack.size()*30 )); Main.bedCanvas.bufImage = MethodLibrary.toCompatibleImage(new BufferedImage((int)Main.screenSize.getWidth(), (int)Main.bedCanvas.bedTrack.size()*30, BufferedImage.TYPE_INT_ARGB)); Main.bedCanvas.buf = (Graphics2D)Main.bedCanvas.bufImage.getGraphics(); Main.bedCanvas.nodeImage = MethodLibrary.toCompatibleImage(new BufferedImage((int)Main.screenSize.getWidth(), (int)Main.bedCanvas.bedTrack.size()*30, BufferedImage.TYPE_INT_ARGB)); Main.bedCanvas.nodebuf = (Graphics2D)Main.bedCanvas.nodeImage.getGraphics(); */ Main.varpane.setDividerLocation(0.8); } Main.trackPane.revalidate(); Main.varpane.revalidate(); } else { Main.trackPane.setDividerLocation(Main.trackPane.getDividerLocation()+70); Main.varpane.setDividerLocation(Main.varpane.getDividerLocation()+70); Main.varpane.revalidate(); Main.trackPane.revalidate(); if(Main.controlScroll.isVisible()) { Main.trackPane.setDividerSize(3); } } Main.bedScroll.setVisible(true); Main.bedCanvas.setVisible(true); for(int i = 0 ; i<Main.bedCanvas.trackDivider.size(); i++) { Main.bedCanvas.trackDivider.set(i, ((i+1)*(Main.varpane.getDividerLocation()/(double)Main.bedCanvas.trackDivider.size()))); // System.out.println(((i+1)*(Main.varpane.getDividerLocation()/(double)Main.bedCanvas.trackDivider.size()))); } Main.trackPane.setDividerLocation((int)((Main.bedCanvas.trackDivider.size())*(Main.varpane.getDividerLocation()/(double)Main.bedCanvas.trackDivider.size()))); } catch(Exception e) { e.printStackTrace(); ErrorLog.addError(e.getStackTrace()); } } static void setBedTrack(BedTrack addTrack) { try { /* if(!addTrack.file.getName().endsWith(".gz")) { return; }*/ if(addTrack.getBBfileReader() != null) { return; } String name = ""; if(addTrack.file != null) { name = addTrack.file.getName().toLowerCase(); } else { name = addTrack.url.toString().toLowerCase(); } if(name.endsWith(".bw") ||name.endsWith(".bigwig") || name.endsWith(".bb") || name.endsWith(".bigbed")) { return; } InputStream in = null; String[] split; BufferedReader reader = null; GZIPInputStream gzip = null; FileReader freader = null; if(addTrack.file != null) { if(addTrack.file.getName().endsWith(".gz") || addTrack.file.getName().endsWith(".bgz")) { gzip = new GZIPInputStream(new FileInputStream(addTrack.file)); reader = new BufferedReader(new InputStreamReader(gzip)); } else { freader = new FileReader(addTrack.file); reader = new BufferedReader(freader); } } else { in = addTrack.url.openStream(); gzip = new GZIPInputStream(in); reader = new BufferedReader(new InputStreamReader(gzip)); } int count = 0; if(name.endsWith(".gff.gz")) { addTrack.iszerobased = 1; addTrack.getZerobased().setSelected(false); while(count < 10) { if(reader.readLine().startsWith("#")) { continue; } split = reader.readLine().split("\\t"); if(split.length > 5) { if(!Double.isNaN(Double.parseDouble(split[5]))) { addTrack.hasvalues = true; } } if(Main.SELEXhash.containsKey(split[2].replace(".pfm", ""))) { addTrack.selex = true; addTrack.getAffinityBox().setVisible(true); } count++; } } else if(name.endsWith(".bed.gz") || name.endsWith(".bed")) { while(count < 10) { if(reader.readLine().startsWith("#") || reader.readLine().startsWith("track")) { continue; } split = reader.readLine().split("\\t"); if(split.length > 4) { try { if(!Double.isNaN(Double.parseDouble(split[4]))) { addTrack.hasvalues = true; } } catch(Exception e) { } } if(split.length > 3 && Main.SELEXhash.containsKey(split[3])) { addTrack.selex = true; addTrack.getAffinityBox().setVisible(true); } count++; } } else if(name.endsWith(".tsv.gz") ||name.endsWith(".tsv.bgz")) { if(addTrack.valuecolumn != null) { while(count < 10) { if(reader.readLine().startsWith("#")) { continue; } split = reader.readLine().split("\\t"); if(!Double.isNaN(Double.parseDouble(split[addTrack.valuecolumn]))) { addTrack.hasvalues = true; break; } count++; } } } if(addTrack.getBBfileReader() == null && !addTrack.hasvalues) { addTrack.getLimitField().setVisible(false); } else { addTrack.getLimitField().setVisible(true); } if(gzip != null) { gzip.close(); } if(freader != null) { freader.close(); } if(in != null) { in.close(); } reader.close(); } catch(Exception e) { e.printStackTrace(); } } static String getInfoValue(HashMap<String, String> map, String key ) { if(map.containsKey(key)) { return map.get(key); } else { return "-"; } } static HashMap<String, String> makeHash(String[] line) { if(line == null || line.length < 9) { return null; } HashMap<String, String> hash = new HashMap<String, String>(); String[] infosplit = line[8].split(";"); hash.put("seqid", line[0].replace("chr", "")); hash.put("source", line[1]); hash.put("type", line[2]); hash.put("start", ""+(Integer.parseInt(line[3])-1)); hash.put("end", line[4]); hash.put("score", line[5]); hash.put("strand", line[6]); if(line[7].equals("2")) { line[7] = "1"; } else if(line[7].equals("1")) { line[7] = "2"; } hash.put("phase", line[7]); String[] split; for(int i = 0 ; i<infosplit.length; i++) { if(infosplit[i].contains("=")) { split = infosplit[i].split("="); hash.put(split[0].toLowerCase(),split[1]); } else { split = infosplit[i].trim().split(" "); hash.put(split[0].toLowerCase().replaceAll("\"", "").replace("name", "symbol"), split[1].replaceAll("\"", "")); } } return hash; } static void readGTF(File infile, String outfile, SAMSequenceDictionary dict) { BufferedReader reader = null; GZIPInputStream gzip = null; FileReader freader = null; String line= "", chrom = "-1"; HashMap<String, String> lineHash; HashMap<String,Gene> genes = new HashMap<String, Gene>(); HashMap<String,Transcript> transcripts = new HashMap<String, Transcript>(); Gene addgene; //Boolean found = false; Transcript addtranscript; try { if(infile.getName().endsWith(".gz")) { gzip = new GZIPInputStream(new FileInputStream(infile)); reader = new BufferedReader(new InputStreamReader(gzip)); } else { freader = new FileReader(infile); reader = new BufferedReader(freader); } // line = reader.readLine(); while((line = reader.readLine()) != null) { if(line.startsWith("#")) { continue; } /* if(!line.contains("Rp1h")) { if(found) { break; } continue; } found = true; */ lineHash = makeHash(line.split("\t")); chrom = lineHash.get("seqid"); if(!genes.containsKey(lineHash.get("gene_id"))) { /*if(genes.size() > 1) { break; }*/ Gene gene = new Gene(chrom, lineHash, true); genes.put(lineHash.get("gene_id"),gene); if(lineHash.get("transcript_id") == null) { continue; } //continue; } if(!transcripts.containsKey(lineHash.get("transcript_id"))) { addgene = genes.get(lineHash.get("gene_id")); transcripts.put(getInfoValue(lineHash, "transcript_id"), new Transcript(lineHash,addgene)); if(lineHash.get("type").equals("exon")) { addtranscript = transcripts.get(getInfoValue(lineHash, "transcript_id")); addtranscript.addExon(lineHash, addtranscript); } if(addgene.getDescription().equals("-")) { if(lineHash.containsKey("gene_symbol")) { addgene.setDescription(lineHash.get("gene_symbol")); } } continue; } if(transcripts.containsKey(lineHash.get("transcript_id"))) { if(lineHash.get("type").contains("UTR")) { continue; } addtranscript = transcripts.get(lineHash.get("transcript_id")); addtranscript.addExon(lineHash, addtranscript); continue; } } } catch(Exception e) { System.out.println(line); e.printStackTrace(); System.exit(0); } try { Transcript transcript; Gene gene; StringBuffer exStarts, exEnds, exPhases; Iterator<Map.Entry<String,Gene>> it = genes.entrySet().iterator(); ArrayList<String[]> geneArray = new ArrayList<String[]>(); while (it.hasNext()) { Map.Entry<String,Gene> pair = (Map.Entry<String,Gene>)it.next(); gene = pair.getValue(); for(int i = 0 ; i<gene.getTranscripts().size(); i++) { transcript = gene.getTranscripts().get(i); exStarts = new StringBuffer(""); exEnds = new StringBuffer(""); exPhases = new StringBuffer(""); for(int e =0;e<transcript.exonArray.size(); e++) { exStarts.append(transcript.exonArray.get(e).getStart() +","); exEnds.append(transcript.exonArray.get(e).getEnd() +","); exPhases.append(transcript.exonArray.get(e).getStartPhase()+","); } String[] row = {gene.getChrom(), ""+transcript.getStart(), ""+transcript.getEnd(), gene.getName(), ""+transcript.exonArray.size(), MethodLibrary.getStrand(gene.getStrand()), gene.getID(), transcript.getENST(), transcript.getUniprot(), "-", transcript.getBiotype(), ""+transcript.getCodingStart(), ""+transcript.getCodingEnd(), exStarts.toString(), exEnds.toString(), exPhases.toString(), transcript.getDescription() }; if(transcript.getCodingEnd() == -1) { row[11] = "" +gene.getEnd(); row[12] = "" +gene.getStart(); } /*for(int g = 0 ;g<row.length; g++) { System.out.print(row[g] +"\t"); } System.out.println(); */ geneArray.add(row); } it.remove(); } gffSorter gffsorter = new gffSorter(); Collections.sort(geneArray, gffsorter); if(outfile != null) { MethodLibrary.blockCompressAndIndex(geneArray, outfile, false, dict); } geneArray.clear(); if(freader != null) { freader.close(); } reader.close(); if(gzip != null) { gzip.close(); } } catch(Exception e) { e.printStackTrace(); } } static void readGFF(File infile, String outfile, SAMSequenceDictionary dict) { BufferedReader reader = null; GZIPInputStream gzip = null; FileReader freader = null; String line= "", chrom = "-1"; HashMap<String, String> lineHash; HashMap<String,Gene> genes = new HashMap<String, Gene>(); HashMap<String,Transcript> transcripts = new HashMap<String, Transcript>(); Gene addgene; Transcript addtranscript; try { if(infile.getName().endsWith(".gz")) { gzip = new GZIPInputStream(new FileInputStream(infile)); reader = new BufferedReader(new InputStreamReader(gzip)); } else { freader = new FileReader(infile); reader = new BufferedReader(freader); } // line = reader.readLine(); while((line = reader.readLine()) != null) { if(line.startsWith("#")) { continue; } lineHash = makeHash(line.split("\t")); if(lineHash.get("type").startsWith("region")) { if(line.contains("unlocalized")) { chrom = "unlocalized"; } else if(lineHash.get("chromosome") != null) { chrom = lineHash.get("chromosome").replace("chr", ""); } else if(lineHash.get("name") != null) { chrom = lineHash.get("name").replace("chr", ""); } continue; } if(!lineHash.containsKey("parent")) { /*if(!lineHash.get("type").contains("gene")) { continue; }*/ Gene gene = new Gene(chrom, lineHash); genes.put(getInfoValue(lineHash, "id"),gene); /*try { System.out.println(genes.get(genes.size()-1).getName()); } catch(Exception e) { System.out.println(line); }*/ continue; } if(genes.containsKey(lineHash.get("parent"))) { addgene = genes.get(lineHash.get("parent")); transcripts.put(getInfoValue(lineHash, "id"), new Transcript(lineHash,addgene)); if(lineHash.get("type").equals("exon")) { addtranscript = transcripts.get(getInfoValue(lineHash, "id")); addtranscript.addExon(lineHash, addtranscript); } if(addgene.getDescription().equals("-")) { if(lineHash.containsKey("product")) { addgene.setDescription(lineHash.get("product")); } } continue; } if(transcripts.containsKey(lineHash.get("parent"))) { addtranscript = transcripts.get(lineHash.get("parent")); addtranscript.addExon(lineHash, addtranscript); continue; } } } catch(Exception e) { System.out.println(line); e.printStackTrace(); System.exit(0); } try { Transcript transcript; Gene gene; StringBuffer exStarts, exEnds, exPhases; Iterator<Map.Entry<String,Gene>> it = genes.entrySet().iterator(); ArrayList<String[]> geneArray = new ArrayList<String[]>(); while (it.hasNext()) { Map.Entry<String,Gene> pair = (Map.Entry<String,Gene>)it.next(); gene = pair.getValue(); for(int i = 0 ; i<gene.getTranscripts().size(); i++) { transcript = gene.getTranscripts().get(i); exStarts = new StringBuffer(""); exEnds = new StringBuffer(""); exPhases = new StringBuffer(""); for(int e =0;e<transcript.exonArray.size(); e++) { exStarts.append(transcript.exonArray.get(e).getStart() +","); exEnds.append(transcript.exonArray.get(e).getEnd() +","); exPhases.append(transcript.exonArray.get(e).getStartPhase()+","); } String[] row = {gene.getChrom(), ""+transcript.getStart(), ""+transcript.getEnd(), gene.getName(), ""+transcript.exonArray.size(), MethodLibrary.getStrand(gene.getStrand()), gene.getID(), transcript.getENST(), transcript.getUniprot(), "-", transcript.getBiotype(), ""+transcript.getCodingStart(), ""+transcript.getCodingEnd(), exStarts.toString(), exEnds.toString(), exPhases.toString(), transcript.getDescription() }; geneArray.add(row); } it.remove(); } gffSorter gffsorter = new gffSorter(); Collections.sort(geneArray, gffsorter); if(outfile != null) { MethodLibrary.blockCompressAndIndex(geneArray, outfile, false, dict); } geneArray.clear(); if(freader != null) { freader.close(); } reader.close(); if(gzip != null) { gzip.close(); } } catch(Exception e) { e.printStackTrace(); } } public static class gffSorter implements Comparator<String[]> { public int compare(String[] o1, String[] o2) { if(o1[0].compareTo(o2[0]) == 0) { if(Integer.parseInt(o1[1]) < Integer.parseInt(o2[1])) { return -1; } else if(Integer.parseInt(o1[1]) > Integer.parseInt(o2[1])) { return 1; } else { return 0; } } else { return o1[0].compareTo(o2[0]); } } } public static class geneSorter implements Comparator<Gene> { public int compare(Gene o1, Gene o2) { if(o1.getChrom().compareTo(o2.getChrom()) == 0) { if(o1.getStart() < o2.getStart()) { return -1; } else if(o1.getStart() > o2.getStart()) { return 1; } else { return 0; } } else { return -o1.getChrom().compareTo(o2.getChrom()); } } } void readBED(String url, String index, boolean small) { try { if(!Main.trackPane.isVisible()) { Main.trackPane.setVisible(true); Main.varpane.setDividerSize(3); Main.varpane.setResizeWeight(0.1); Main.varpane.setDividerLocation(0.1); } else { Main.varpane.setDividerLocation(Main.varpane.getDividerLocation()+100); Main.varpane.revalidate(); Main.trackPane.setDividerLocation(Main.varpane.getDividerLocation()/2); if(Main.controlScroll.isVisible()) { Main.trackPane.setDividerSize(3); } } Main.bedScroll.setVisible(true); Main.bedCanvas.setVisible(true); BedTrack addTrack = null; if(index.equals("nan")) { addTrack = new BedTrack(new URL(url), null,Main.bedCanvas.bedTrack.size()); } else { addTrack = new BedTrack(new URL(url), new URL(index),Main.bedCanvas.bedTrack.size()); } //Main.bedCanvas.getBEDfeatures(addTrack, 1, Main.drawCanvas.splits.get(0).chromEnd); if(addTrack != null) { if(url.toLowerCase().endsWith("tsv.gz") || url.toLowerCase().endsWith("tsv.bgz")) { addTrack.getZerobased().setSelected(false); addTrack.iszerobased = 1; addTrack.getSelector().frame.setVisible(true); } addTrack.small = small; Main.bedCanvas.trackDivider.add(0.0); Main.bedCanvas.bedTrack.add(addTrack); setTable(addTrack); if(url.toLowerCase().endsWith(".bedgraph")) { Main.bedCanvas.pressGraph(addTrack); } if(url.toLowerCase().endsWith("bigwig") || url.toLowerCase().endsWith("bw")) { addTrack.small = true; addTrack.bigWig = true; addTrack.graph = true; //Main.bedCanvas.getBEDfeatures(addTrack, (int)Main.drawCanvas.splits.get(0).start, (int)Main.drawCanvas.splits.get(0).end); } setBedTrack(addTrack); if(addTrack.small) { // Main.drawCanvas.loading("loading"); Main.bedCanvas.getBEDfeatures(addTrack, 1, Main.drawCanvas.splits.get(0).chromEnd); //Main.drawCanvas.ready("loading"); } } } catch(Exception e) { e.printStackTrace(); ErrorLog.addError(e.getStackTrace()); } } static void setTable(BedTrack track) { JScrollPane addpane = new JScrollPane(); addpane.setPreferredSize(new Dimension(500,400)); BedTable add = new BedTable((int)Main.screenSize.width, (int)Main.screenSize.height, addpane, track); addpane.getViewport().add(add); addpane.getVerticalScrollBar().addAdjustmentListener( new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent event) { if(VariantHandler.tabs.getSelectedIndex() > 2) { VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).repaint(); } } } ); VariantHandler.tables.add(add); VariantHandler.tablescrolls.add(addpane); track.setTable(add); add.resizeTable(VariantHandler.tableScroll.getViewport().getWidth()); if(track.file != null) { /*if(track.file.getName().length() > 10) { VariantHandler.tabs.add(track.file.getName().substring(0, 10) +"...", addpane); add.setName(track.file.getName().substring(0, 10) +"..."); } else {*/ VariantHandler.tabs.add(track.file.getName().replace(".pfm", ""), addpane); add.setName(track.file.getName()); // } } else { /*if(FilenameUtils.getName(track.url.getFile()).length() > 10) { VariantHandler.tabs.add(FilenameUtils.getName(track.url.getFile()).substring(0, 10) +"...", addpane); add.setName(FilenameUtils.getName(track.url.getFile()).substring(0, 10) +"..."); } else {*/ VariantHandler.tabs.add(FilenameUtils.getName(track.url.getFile()), addpane); add.setName(FilenameUtils.getName(track.url.getFile())); // } } //VariantHandler.clusterTable.addHeaderColumn(track); MethodLibrary.addHeaderColumns(track); VariantHandler.tabs.revalidate(); } static void removeTable(BedTrack track) { try { if(VariantHandler.tables.indexOf(track.getTable()) > -1) { VariantHandler.tabs.remove(track.getTable().tablescroll); VariantHandler.tablescrolls.remove(track.getTable().tablescroll); VariantHandler.tables.remove(track.getTable()); VariantHandler.tabs.revalidate(); VariantHandler.tabs.repaint(); } } catch(Exception e) { e.printStackTrace(); } } /*int binarySearch(ArrayList<int[]> list, int value, int middle) { if(middle == 0) { return 0; } if(middle == list.size()-1) { return list.size()-1; } if(list.get(middle-1)[1] <= value) { middle = middle/2; return binarySearch(list, value, middle); } if(list.get(middle-1)[1] <= value && list.get(middle)[1] >= value) { return middle-1; } if(list.get(middle-1)[1] > value ) { return binarySearch(list, value, middle); } return -1; }*/ int searchIndex(ArrayList<int[]> list, int value, int low, int high) { middle = (high+low)/2; if(middle == list.size()-1) { return list.size(); } if(list.get(middle)[1] <= value && list.get(middle+1)[1] >= value) { return middle+1; } if(list.get(middle)[1] > value) { return searchIndex(list, value, low, middle); } if(list.get(middle)[1] < value) { return searchIndex(list, value, middle, high); } return -1; } void readSam(String chrom, Reads readClass, SAMRecord samRecordBuffer, java.util.ArrayList<java.util.Map.Entry<Integer,Byte>> mismatches) { try { if(readClass.getReads().isEmpty()) { addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); readClass.setFirstRead(addNode); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-(readClass.readHeight+2))); addNode.setRectBounds((int)((addNode.getPosition()-start)*pixel), startY, (int)(samRecordBuffer.getReadLength()*pixel), readClass.readHeight); readClass.getReads().add(addNode); ReadNode[] addList = new ReadNode[2]; addList[headnode] = addNode; addList[tailnode] = addNode; readClass.getHeadAndTail().add(addList); readClass.setLastRead(addNode); } else { mundane = null; found = false; isDiscordant = MethodLibrary.isDiscordant(samRecordBuffer, readClass.sample.getComplete()); if(samRecordBuffer.getCigarLength() > 1) { if(samRecordBuffer.getCigar().getCigarElement(0).getOperator().compareTo(CigarOperator.HARD_CLIP) == 0) { searchPos = samRecordBuffer.getAlignmentStart(); } else { searchPos = samRecordBuffer.getUnclippedStart(); } } else { searchPos = samRecordBuffer.getUnclippedStart(); } for(int i = 0; i<readClass.getHeadAndTail().size(); i++) { if(i>Settings.readDepthLimit) { found = true; mundane = null; addNode = null; break; } if(!isDiscordant) { if(readClass.getHeadAndTail().get(i)[tailnode].getPosition() +readClass.getHeadAndTail().get(i)[tailnode].getWidth() +2 < searchPos) { //.getPosition()) { try { if(mundane == null) { xpos = (int)((searchPos-start)*pixel); addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); readClass.setLastRead(addNode); } startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); addNode.setRectBounds(xpos, startY, (int)(addNode.getWidth()*pixel), readClass.readHeight); if(i > readClass.getHeadAndTail().size()-1) { return; } addNode.setPrev(readClass.getHeadAndTail().get(i)[tailnode]); readClass.getHeadAndTail().get(i)[tailnode].setNext(addNode); readClass.getHeadAndTail().get(i)[tailnode] = addNode; found = true; break; } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } } continue; } else { if(readClass.getHeadAndTail().get(i)[tailnode].getPosition()+readClass.getHeadAndTail().get(i)[tailnode].getWidth() +2 < searchPos) { /*if(readClass.readNames.containsKey(addNode.getName())) { readClass.readNames.get(addNode.getName())[1] = addNode; } else { ReadNode[] nameAdd = new ReadNode[2]; nameAdd[0] = addNode; nameAdd[1] = null; readClass.readNames.put(addNode.getName(), nameAdd); }*/ xpos = (int)((searchPos-start)*pixel); addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); addNode.setRectBounds(xpos, startY, (int)(addNode.getWidth()*pixel), readClass.readHeight); addNode.setPrev(readClass.getHeadAndTail().get(i)[tailnode]); readClass.getHeadAndTail().get(i)[tailnode].setNext(addNode); readClass.getHeadAndTail().get(i)[tailnode] = addNode; readClass.setLastRead(addNode); found = true; break; } else if(!readClass.getHeadAndTail().get(i)[tailnode].isDiscordant()) { xpos = (int)((searchPos-start)*pixel); addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); mundane = readClass.getHeadAndTail().get(i)[tailnode]; /* if(readClass.readNames.containsKey(addNode.getName())) { readClass.readNames.get(addNode.getName())[1] = addNode; } else { ReadNode[] nameAdd = new ReadNode[2]; nameAdd[0] = addNode; nameAdd[1] = null; readClass.readNames.put(addNode.getName(), nameAdd); }*/ startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); addNode.setRectBounds(xpos, startY, (int)(addNode.getWidth()*pixel), readClass.readHeight); if(mundane.getPrev() != null) { addNode.setPrev(mundane.getPrev()); mundane.getPrev().setNext(addNode); } if(readClass.getHeadAndTail().get(i)[headnode].equals(mundane)) { readClass.getHeadAndTail().get(i)[headnode] = addNode; } readClass.getHeadAndTail().get(i)[tailnode] = addNode; found = false; readClass.setLastRead(addNode); try { readClass.getReads().set(i,addNode); } catch(Exception e) { System.out.println(readClass.getHeadAndTail().size() +" " +readClass.getReads().size()); } addNode = mundane; searchPos = addNode.getPosition(); isDiscordant = false; addNode.setNext(null); addNode.setPrev(null); continue; } // continue; } } if(!found) { /* if(addNode.isDiscordant()) { if(readClass.readNames.containsKey(addNode.getName())) { readClass.readNames.get(addNode.getName())[1] = addNode; } else { ReadNode[] nameAdd = new ReadNode[2]; nameAdd[0] = addNode; nameAdd[1] = null; readClass.readNames.put(addNode.getName(), nameAdd); } }*/ if(mundane == null) { xpos = (int)((searchPos-start)*pixel); addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); } ReadNode[] addList = new ReadNode[2]; addList[headnode] = addNode; addList[tailnode] = addNode; addNode.setPrev(null); addNode.setNext(null); readClass.getHeadAndTail().add(addList); readClass.getReads().add(addNode); readClass.setLastRead(addNode); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((readClass.getReads().size())*(readClass.readHeight+2)))); addNode.setRectBounds(xpos, startY, (int)(addNode.getWidth()*pixel), readClass.readHeight); } } //preRecord = readClass.samRecordBuffer; } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } } void setLevels(ReadNode node, Sample sample, Reads readClass) { try { while(node != null) { mundane = null; addNode = node.getPrev(); found = false; xpos = (int)((node.getPosition()-start)*pixel); for(int i = 0; i<readClass.getReads().size(); i++) { if(i > Settings.readDepthLimit) { if(node.getNext() != null) { node.getNext().setPrev(node.getPrev());; } if(node.getPrev() != null) { node.getPrev().setNext(node.getNext()); } mundane = null; node = null; // addNode = null; found = true; break; } if(!node.isDiscordant()) { if(node.getPosition()+node.getWidth()+2 < readClass.getHeadAndTail().get(i)[headnode].getPosition()) { if(i > 0) { startY = (int)(((sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); node.setRectBounds(xpos, startY, (int)(node.getWidth()*pixel), readClass.readHeight); if(mundane == null) { if(node.getPrev()!=null) { node.getPrev().setNext(node.getNext()); } node.getNext().setPrev(node.getPrev()); } node.setNext(readClass.getHeadAndTail().get(i)[headnode]); readClass.getHeadAndTail().get(i)[headnode].setPrev(node); //node.setPrev(sample.headAndTail.get(i)[headnode].getPrev()); readClass.getHeadAndTail().get(i)[headnode] = node; readClass.getHeadAndTail().get(i)[headnode].setPrev(null); } else { readClass.getHeadAndTail().get(i)[headnode] = node; } found = true; break; } continue; } else { if(node.getPosition()+node.getWidth()+2 < readClass.getHeadAndTail().get(i)[headnode].getPosition()) { if(i > 0) { startY = (int)(((sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); node.setRectBounds(xpos, startY, (int)(node.getWidth()*pixel), readClass.readHeight); /* if(node.getPrev()!=null) { node.getPrev().setNext(node.getNext()); } node.getNext().setPrev(node.getPrev()); */ node.setNext(readClass.getHeadAndTail().get(i)[headnode]); readClass.getHeadAndTail().get(i)[headnode].setPrev(node); node.setPrev(null); readClass.getHeadAndTail().get(i)[headnode] = node; } else { readClass.getHeadAndTail().get(i)[headnode] = node; } found = true; break; } else if(readClass.getHeadAndTail().get(i)[headnode].isDiscordant()) { if(i==0) { if(node.getPrev() != null) { readClass.getHeadAndTail().get(i)[headnode].setPrev(node.getPrev()); node.getPrev().setNext(readClass.getHeadAndTail().get(i)[headnode]); } } continue; } else { mundane = readClass.getHeadAndTail().get(i)[headnode]; startY = (int)(((sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); node.setRectBounds(xpos, startY, (int)(node.getWidth()*pixel), readClass.readHeight); node.setNext(mundane.getNext()); if(mundane.getNext() != null) { mundane.getNext().setPrev(node); } mundane.setNext(null); mundane.setPrev(null); node.setPrev(null); readClass.getHeadAndTail().get(i)[headnode] = node; readClass.getReads().set(i, node); node = mundane; found = false; continue; } } } if(!found) { ReadNode[] addList = new ReadNode[2]; addList[headnode] = node; addList[tailnode] = node; readClass.getHeadAndTail().add(addList); if(node.getPrev() != null) { node.getPrev().setNext(node.getNext()); } if(node.getNext() != null) { node.getNext().setPrev(node.getPrev()); } node.setNext(null); node.setPrev(null); readClass.getReads().add(node); startY = (int)(((sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((readClass.getReads().size())*(readClass.readHeight+2)))); node.setRectBounds(xpos, startY, (int)(node.getWidth()*pixel), readClass.readHeight); } node = addNode; } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } mundane = null; } void removeNonListBeds(BedNode node, int topos) { BedNode tempNode = null; if(node.equals(node.getTrack().getHead())) { node = node.getNext(); } while(node != null ) { if(node.getPosition() >= topos) { node = null; break; } if(!node.inVarlist) { if(node.getPosition()+node.getLength()+1 < topos) { tempNode = node.getNext(); node.removeNode(); node = tempNode; } else { node = node.getNext(); } continue; } else { node = node.getNext(); } } tempNode = null; } static void removeNonListVariants() { VarNode node = FileRead.head.getNext(); VarNode tempNode; Map.Entry<String, ArrayList<SampleNode>> entry; int mutcount = 0; while(node != null ) { if(!node.inVarList || Main.drawCanvas.hideNode(node)) { tempNode = node.getNext(); node.removeNode(); node = tempNode; } else { for(int v = 0; v<node.vars.size(); v++) { entry = node.vars.get(v); mutcount = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(!Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { if(VariantHandler.onlyselected.isSelected()) { if(!entry.getValue().get(m).getSample().equals(Main.drawCanvas.selectedSample)) { entry.getValue().remove(m); m--; continue; } } mutcount++; } else { entry.getValue().remove(m); m--; } } } if(mutcount == 0) { tempNode = node.getNext(); node.removeNode(); node = tempNode; } else { node = node.getNext(); } } } node = null; tempNode = null; entry = null; Main.drawCanvas.current = FileRead.head; Draw.updatevars = true; Main.drawCanvas.repaint(); } static void removeBedLinks() { for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).used) { BedNode node = Main.bedCanvas.bedTrack.get(i).getHead(); BedNode tempnode; try { while(node !=null) { if(node.varnodes != null) { for(int n = 0 ; n < node.varnodes.size(); n++) { if(Main.drawCanvas.hideNode(node.varnodes.get(n))) { node.varnodes.remove(n); n--; if(n == -1) { break; } } } } tempnode = node.getNext(); if(!bigcalc) { node.putPrev(null); node.putNext(null); } node = tempnode; } } catch(Exception e) { e.printStackTrace(); } } } } void varCalc() { try { /*array = new int[Main.drawCanvas.sampleList.size()][101]; for(int i = 0; i<array.length; i++) { for(int j = 0; j<array[i].length; j++) { array[i][j] = 0; } } */ FileRead.novars = false; boolean isfreeze = VariantHandler.freeze.isSelected(); if(!VariantHandler.none.isSelected()) { SampleDialog.checkFiles(); if(affected == 0) { Main.showError("Set at least one individual as affected. (click sample name or right click sample sidebar)", "Note"); return; } } else { VariantHandler.freeze.setSelected(true); } contexts = null; //contextQuals = null; Draw.calculateVars = false; Draw.variantcalculator = true; if(VariantHandler.writetofile.isSelected()) { lastWriteVar = FileRead.head; } clearVariantsFromGenes(); SplitClass split = Main.drawCanvas.splits.get(0); int chromcounter = 0; VariantHandler.outputStrings.clear(); if(Main.drawCanvas.clusterNodes == null) { Main.drawCanvas.clusterNodes = new ArrayList<ClusterNode>(); } else { Main.drawCanvas.clusterNodes.clear(); } Main.drawCanvas.clusterId = 1; VariantHandler.table.variants = 0; VariantHandler.stattable.variants = 0; VariantHandler.clusterTable.variants = 0; for(int i = 0 ; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).variants = 0; } cancelvarcount = false; VariantHandler.table.genearray.clear(); VariantHandler.table.aminoarray.clear(); VariantHandler.table.controlarray = null; VariantHandler.stattable.sampleArray.clear(); for(int i = 0; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).bedarray =null; VariantHandler.tables.get(i).aminoarray=null; VariantHandler.tables.get(i).vararray=null; VariantHandler.tables.get(i).controlarray = null; VariantHandler.tables.get(i).variants = 0; } VarNode vardraw = Main.drawCanvas.current; Object[] addobject; for(int i=0; i<Main.drawCanvas.sampleList.size(); i++) { if(Main.drawCanvas.sampleList.get(i).multiVCF || (Main.drawCanvas.sampleList.get(i).getTabixFile() == null && !Main.drawCanvas.sampleList.get(i).multipart) && (FileRead.caller && Main.drawCanvas.sampleList.get(i).samFile == null) && !Main.drawCanvas.sampleList.get(i).calledvariants) { continue; } addobject = new Object[VariantHandler.stattable.headerlengths.length]; addobject[0] = Main.drawCanvas.sampleList.get(i); for(int j = 1; j<addobject.length; j++) { addobject[j] = 0; } Main.drawCanvas.sampleList.get(i).mutationTypes = new double[6]; for(int j = 0; j<6; j++) { Main.drawCanvas.sampleList.get(i).mutationTypes[j] = 0.0; } VariantHandler.stattable.sampleArray.add(addobject); Main.drawCanvas.sampleList.get(i).heterozygotes = 0; Main.drawCanvas.sampleList.get(i).homozygotes = 0; Main.drawCanvas.sampleList.get(i).varcount = 0; Main.drawCanvas.sampleList.get(i).indels = 0; Main.drawCanvas.sampleList.get(i).snvs = 0; Main.drawCanvas.sampleList.get(i).sitioRate = 0; Main.drawCanvas.sampleList.get(i).versioRate = 0; Main.drawCanvas.sampleList.get(i).ins = 0; Main.drawCanvas.sampleList.get(i).callrates = 0.0; Main.drawCanvas.sampleList.get(i).coding = 0; Main.drawCanvas.sampleList.get(i).syn = 0; Main.drawCanvas.sampleList.get(i).nonsyn = 0; Main.drawCanvas.sampleList.get(i).missense = 0; Main.drawCanvas.sampleList.get(i).splice = 0; Main.drawCanvas.sampleList.get(i).nonsense = 0; Main.drawCanvas.sampleList.get(i).fshift = 0; Main.drawCanvas.sampleList.get(i).inframe = 0; } VariantHandler.stattable.setPreferredSize(new Dimension(VariantHandler.statsScroll.getViewport().getWidth(), (VariantHandler.stattable.sampleArray.size()+1)*VariantHandler.stattable.rowHeight)); VariantHandler.stattable.revalidate(); VariantHandler.stattable.repaint(); for(int g = 0 ; g<split.getGenes().size(); g++) { split.getGenes().get(g).mutations = 0; split.getGenes().get(g).missense = 0; split.getGenes().get(g).nonsense = 0; split.getGenes().get(g).synonymous = 0; split.getGenes().get(g).intronic = 0; split.getGenes().get(g).utr = 0; split.getGenes().get(g).samples.clear(); split.getGenes().get(g).varnodes.clear(); split.getGenes().get(g).intergenic = false; split.getGenes().get(g).transcriptString = new StringBuffer(); } if(VariantHandler.allChroms.isSelected() && !VariantHandler.xLinked.isSelected()) { for(int i = 0 ; i < Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).getVarcalc().isSelected()) { Main.bedCanvas.bedTrack.get(i).intersect = true; } } if(VariantHandler.allChromsfrom.isSelected()) { chromcounter = Main.chromosomeDropdown.getSelectedIndex(); Main.nothread = true; Main.chromosomeDropdown.setSelectedIndex(Main.chromosomeDropdown.getSelectedIndex()); Main.nothread = false; vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } else if(Main.drawCanvas.splits.get(0).start != 1 || Main.chromosomeDropdown.getSelectedIndex() != 0) { Main.nothread = true; Main.chromosomeDropdown.setSelectedIndex(0); Main.nothread = false; vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } else { vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } } else { if(VariantHandler.xLinked.isSelected()) { if(Main.chromModel.getIndexOf("X") != -1) { if(Main.drawCanvas.splits.get(0).start != 1 || Main.chromosomeDropdown.getSelectedIndex() != 0) { Main.nothread = true; Main.chromosomeDropdown.setSelectedItem("X"); Main.nothread = false; vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } } else { JOptionPane.showMessageDialog(Main.drawScroll, "No chromosome X available.", "Note", JOptionPane.INFORMATION_MESSAGE); return; } } for(int i = 0 ; i < Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).getVarcalc().isSelected()) { Main.bedCanvas.bedTrack.get(i).intersect = true; if(Main.bedCanvas.bedTrack.get(i).small && !Main.bedCanvas.bedTrack.get(i).bigWig) { Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(), FileRead.head.getNext()); Main.bedCanvas.intersected = true; } else { BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); Main.bedCanvas.intersected = true; } } } } if(caller && varc == null) { varc = new VariantCaller(true); varcal = varc.new VarCaller(); } Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; if(caller && FileRead.head.getNext() == null) { varcal.callVariants(); vardraw = FileRead.head.getNext(); } while(true) { if(cancelvarcount || !Main.drawCanvas.loading) { cancelFileRead(); vardraw = null; break; } if(vardraw == null) { if(VariantHandler.writetofile.isSelected()) { for(int i = 0;i<VariantHandler.table.genearray.size(); i++) { VariantHandler.writeTranscriptToFile(VariantHandler.table.genearray.get(i), output); } FileRead.lastpos = 0; Main.drawCanvas.clusterNodes.clear(); } VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(),(VariantHandler.table.getTableSize()+1)*(VariantHandler.table.rowHeight))); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); try { if(VariantHandler.commonSlider.getValue() > 1 && VariantHandler.clusterSize > 0) { VariantHandler.clusterTable.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (Main.drawCanvas.clusterNodes.size()+1)*VariantHandler.clusterTable.rowHeight)); VariantHandler.clusterTable.revalidate(); VariantHandler.clusterTable.repaint(); } for(int i = 0; i<VariantHandler.stattable.sampleArray.size(); i++) { sample = (Sample)VariantHandler.stattable.sampleArray.get(i)[0]; VariantHandler.stattable.sampleArray.get(i)[1] = sample.varcount; VariantHandler.stattable.sampleArray.get(i)[2] = sample.snvs; VariantHandler.stattable.sampleArray.get(i)[3] = sample.indels; VariantHandler.stattable.sampleArray.get(i)[4] = sample.ins; VariantHandler.stattable.sampleArray.get(i)[5] = sample.coding; VariantHandler.stattable.sampleArray.get(i)[6] = MethodLibrary.round(sample.heterozygotes/(double)sample.homozygotes,2); VariantHandler.stattable.sampleArray.get(i)[7] = MethodLibrary.round((int)sample.sitioRate/(double)sample.versioRate,2); for(int j = 0; j<6; j++) { VariantHandler.stattable.sampleArray.get(i)[8+j] = MethodLibrary.round(sample.mutationTypes[j]/(double)sample.snvs, 2); } VariantHandler.stattable.sampleArray.get(i)[14] = MethodLibrary.round(sample.callrates / (double)sample.varcount,2); VariantHandler.stattable.repaint(); } } catch(Exception e) { e.printStackTrace(); } if(VariantHandler.allChroms.isSelected() && !VariantHandler.xLinked.isSelected()) { for(int i = 0; i<Main.bedCanvas.bedTrack.size(); i++) { removeNonListBeds( Main.bedCanvas.bedTrack.get(i).getHead(), Main.drawCanvas.splits.get(0).chromEnd); } if(VariantHandler.writetofile.isSelected()) { FileRead.head.putNext(null); nullifyVarNodes(); clearVariantsFromGenes(); } if(cancelvarcount || !Main.drawCanvas.loading) { cancelFileRead(); break; } FileRead.lastpos = 0; if(chromcounter < Main.chromosomeDropdown.getItemCount()) { chromcounter++; if(chromcounter == Main.chromosomeDropdown.getItemCount()) {// || Main.chromosomeDropdown.getItemAt(chromcounter).toString().contains("X")) { break; } if(VariantHandler.onlyAutosomes.isSelected()) { if(Main.chromosomeDropdown.getItemAt(chromcounter).toString().equals("X") || Main.chromosomeDropdown.getItemAt(chromcounter).toString().equals("Y")) { break; } } Main.nothread = true; Main.chromosomeDropdown.setSelectedIndex(chromcounter); Main.nothread = false; if(nobeds) { continue; } for(int g = 0 ; g<split.getGenes().size(); g++) { split.getGenes().get(g).mutations = 0; split.getGenes().get(g).missense = 0; split.getGenes().get(g).nonsense = 0; split.getGenes().get(g).synonymous = 0; split.getGenes().get(g).intronic = 0; split.getGenes().get(g).utr = 0; split.getGenes().get(g).samples.clear(); split.getGenes().get(g).varnodes.clear(); split.getGenes().get(g).intergenic = false; split.getGenes().get(g).transcriptString = new StringBuffer(); } if(caller) { varcal.callVariants(); } Main.drawCanvas.calcClusters(FileRead.head.getNext()); vardraw = FileRead.head.getNext(); FileRead.head.putNext(null); if(vardraw == null) { continue; } if(lastVar == null) { lastVar = FileRead.head; } if(lastWriteVar == null) { lastWriteVar = FileRead.head; } vardraw.putPrev(lastVar); lastVar.putNext(vardraw); } else { Main.drawCanvas.ready("all"); break; } } else { break; } } try { if(!VariantHandler.allChroms.isSelected()) { if(vardraw != null && vardraw.getPosition() < Main.drawCanvas.splits.get(0).start) { vardraw = vardraw.getNext(); continue; } if(vardraw == null || vardraw.getPosition() > Main.drawCanvas.splits.get(0).end) { vardraw= null; continue; } } //STATS vardraw = annotateVariant(vardraw); } catch(Exception ex) { ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); } } nullifyVarNodes(); vardraw =null; Draw.calculateVars = true; Draw.updatevars = true; VariantHandler.table.revalidate(); VariantHandler.table.repaint(); for(int i = 0; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.tables.get(i).getTableSize()+1)*(VariantHandler.tables.get(i).rowHeight))); VariantHandler.tables.get(i).revalidate(); VariantHandler.tables.get(i).repaint(); } VariantHandler.clusterTable.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.clusterTable.getTableSize()+1)*(VariantHandler.clusterTable.rowHeight))); VariantHandler.clusterTable.revalidate(); VariantHandler.clusterTable.repaint(); VariantHandler.clusterTable.repaint(); VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.table.getTableSize()+1)*(VariantHandler.table.rowHeight))); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } try { if(output != null) { if(VariantHandler.onlyStats.isSelected() && VariantHandler.outputContexts.isSelected()) { for(int i = 0 ; i<VariantHandler.stattable.sampleArray.size(); i++) { sample = (Sample)VariantHandler.stattable.sampleArray.get(i)[0]; output.write(sample.getName()); for(int j = 1; j<VariantHandler.stattable.headerlengths.length; j++) { output.write("\t" +VariantHandler.stattable.sampleArray.get(i)[j]); } output.write("\t" +sample.syn +"\t" +sample.nonsyn +"\t" +sample.missense +"\t" +sample.splice +"\t" +sample.nonsense +"\t" +sample.fshift +"\t" +sample.inframe); output.write(Main.lineseparator); } if(contexts != null) { /*Iterator<Entry<String, Float[]>> iterQuals = contextQuals.entrySet().iterator(); while(iterQuals.hasNext()) { Entry<String, Float[]> entry = iterQuals.next(); Float[] values = entry.getValue(); System.out.println(entry.getKey().substring(1)+">" +entry.getKey().charAt(1) +entry.getKey().charAt(0) +entry.getKey().charAt(3) +"\t" +(values[1]/values[0]) +"\t" +values[0]); } */ Iterator<Entry<String, Integer[]>> iter = contexts.entrySet().iterator(); sigOutput.write("#mutType"); for(int i = 0 ; i<Main.drawCanvas.sampleList.size(); i++) { if(!Main.drawCanvas.sampleList.get(i).multiVCF && !Main.drawCanvas.sampleList.get(i).removed) { sigOutput.write("\t" +Main.drawCanvas.sampleList.get(i).getName()); } } sigOutput.write("\n"); //Main.lineseparator);Main.lineseparator); while(iter.hasNext()) { Entry<String, Integer[]> entry = iter.next(); Integer[] samples = entry.getValue(); sigOutput.write(entry.getKey().substring(1)+">" +entry.getKey().charAt(1) +entry.getKey().charAt(0) +entry.getKey().charAt(3)); for(int i = 0; i<Main.drawCanvas.sampleList.size(); i++) { if(!Main.drawCanvas.sampleList.get(i).multiVCF && !Main.drawCanvas.sampleList.get(i).removed) { if(samples[i] == null) { sigOutput.write("\t0"); } else { sigOutput.write("\t" +samples[i]); } } } sigOutput.write("\n"); //Main.lineseparator); } sigOutput.close(); } } output.close(); } if(outputgz != null) { for(int i = 0 ; i<VariantHandler.outputStrings.size(); i++) { outputgz.write(VariantHandler.outputStrings.get(i).getBytes()); Feature vcf = VariantHandler.vcfCodec.decode(VariantHandler.outputStrings.get(i)); FileRead.indexCreator.addFeature(vcf, FileRead.filepointer); FileRead.filepointer = outputgz.getFilePointer(); } VariantHandler.outputStrings.clear(); outputgz.flush(); Index index = indexCreator.finalizeIndex(outputgz.getFilePointer()); index.writeBasedOnFeatureFile(outFile); outputgz.close(); } } catch(Exception e) { e.printStackTrace(); } split = null; if(!isfreeze) { VariantHandler.freeze.setSelected(false); } Main.drawCanvas.ready("all"); if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } Draw.variantcalculator = false; Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; if(VariantHandler.allChroms.isSelected()) { Main.showError("Variant annotation ready!", "Note"); } } catch(Exception e) { e.printStackTrace(); } /*if(contexts != null) { Iterator<Entry<String, Integer[]>> iter = contexts.entrySet().iterator(); System.out.print("#mutType"); for(int i = 0 ; i<Main.samples; i++) { if(!Main.drawCanvas.sampleList.get(i).multiVCF) { System.out.print("\t" +Main.drawCanvas.sampleList.get(i).getName()); } } System.out.println(); while(iter.hasNext()) { Entry<String, Integer[]> entry = iter.next(); Integer[] samples = entry.getValue(); System.out.print(entry.getKey().substring(1)+">" +entry.getKey().charAt(1) +entry.getKey().charAt(0) +entry.getKey().charAt(3)); for(int i = 0; i<samples.length; i++) { if(!Main.drawCanvas.sampleList.get(i).multiVCF) { if(samples[i] == null) { System.out.print("\t0"); } else { System.out.print("\t" +samples[i]); } } } System.out.println(); } }*/ //boolean found = false; /* StringBuffer copy = new StringBuffer(""); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); String type = ""; for(int i = 0 ; i<VariantHandler.table.genearray.size(); i++) { if(VariantHandler.table.genearray.get(i).getName().equals(Main.searchField.getText().trim().toUpperCase())) { for(int j = 0; j<Main.drawCanvas.sampleList.size(); j++) { if(Main.drawCanvas.sampleList.get(j).multiVCF) { continue; } found = false; for(int s = 0; s < VariantHandler.table.genearray.get(i).samples.size(); s++) { if(VariantHandler.table.genearray.get(i).samples.get(s).getName().equals(Main.drawCanvas.sampleList.get(j).getName())) { found = true; break; } } if(found) { if(Main.drawCanvas.sampleList.get(j).fshift > 0) { type = "frameshift"; } else if(Main.drawCanvas.sampleList.get(j).nonsense > 0) { type = "nonsense"; } else if(Main.drawCanvas.sampleList.get(j).inframe > 0) { type = "inframe"; } else if(Main.drawCanvas.sampleList.get(j).splice > 0) { type = "splice"; } else if(Main.drawCanvas.sampleList.get(j).missense > 0) { type = "missense"; } else if(Main.drawCanvas.sampleList.get(j).syn > 0) { type = "synonymous"; } else { System.out.println(Main.drawCanvas.sampleList.get(j).getName() +" " +VariantHandler.table.genearray.get(i).getName()); } copy.append(Main.drawCanvas.sampleList.get(j).getName() +"\t" +type +"\n" ); } else { copy.append(Main.drawCanvas.sampleList.get(j).getName() +"\t0\n" ); } } break; } } StringSelection stringSelection= new StringSelection(copy.toString()); clpbrd.setContents(stringSelection, null);*/ } static void clearVariantsFromBeds() { for(int b = 0; b< Main.bedCanvas.bedTrack.size(); b++) { BedNode node = Main.bedCanvas.bedTrack.get(b).getHead(); while(node != null) { if(node.varnodes != null) { node.varnodes = null; } node = node.getNext(); } } } static void nullifyVarNodes() { lastVar = null; lastWriteVar = null; returnnode = null; } void clearVariantsFromGenes() { SplitClass split = Main.drawCanvas.splits.get(0); for(int g = 0 ; g<split.getGenes().size(); g++) { split.getGenes().get(g).mutations = 0; split.getGenes().get(g).missense = 0; split.getGenes().get(g).nonsense = 0; split.getGenes().get(g).synonymous = 0; split.getGenes().get(g).intronic = 0; split.getGenes().get(g).utr = 0; split.getGenes().get(g).samples.clear(); split.getGenes().get(g).varnodes.clear(); split.getGenes().get(g).intergenic = false; split.getGenes().get(g).transcriptString = new StringBuffer(); } split = null; } void varCalcBig() { boolean isfreeze = VariantHandler.freeze.isSelected(); FileRead.novars = false; if(!VariantHandler.none.isSelected()) { SampleDialog.checkFiles(); if(affected == 0) { Main.showError("Set at least one individual as affected. (right click sample sidebar)", "Note"); return; } } else { VariantHandler.freeze.setSelected(true); } bigcalc = true; Draw.calculateVars = false; Draw.variantcalculator = true; int adder = Settings.windowSize, presearchpos = 1; clearVariantsFromGenes(); int chromcounter = 0; clearVariantsFromBeds(); if(Main.drawCanvas.clusterNodes == null) { Main.drawCanvas.clusterNodes = new ArrayList<ClusterNode>(); } else { Main.drawCanvas.clusterNodes.clear(); } for(int i = 0 ; i < Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).getVarcalc().isSelected()) { Main.bedCanvas.bedTrack.get(i).intersect = true; } } Main.drawCanvas.clusterId = 1; VariantHandler.table.variants = 0; VariantHandler.stattable.variants = 0; VariantHandler.clusterTable.variants = 0; for(int i = 0 ; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).variants = 0; } cancelvarcount = false; VariantHandler.table.genearray.clear(); VariantHandler.table.aminoarray.clear(); VariantHandler.table.controlarray = null; VariantHandler.stattable.sampleArray.clear(); for(int i = 0; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).bedarray= null; VariantHandler.tables.get(i).aminoarray= null; VariantHandler.tables.get(i).vararray= null; VariantHandler.tables.get(i).controlarray= null; VariantHandler.tables.get(i).variants = 0; } head.putNext(null); VarNode vardraw; Object[] addobject; for(int i=0; i<Main.drawCanvas.sampleList.size(); i++) { if(Main.drawCanvas.sampleList.get(i).multiVCF || (Main.drawCanvas.sampleList.get(i).getTabixFile() == null && !Main.drawCanvas.sampleList.get(i).multipart)) { continue; } addobject = new Object[VariantHandler.stattable.headerlengths.length]; addobject[0] = Main.drawCanvas.sampleList.get(i); for(int j = 1; j<addobject.length; j++) { addobject[j] = 0; } Main.drawCanvas.sampleList.get(i).mutationTypes = new double[6]; for(int j = 0; j<6; j++) { Main.drawCanvas.sampleList.get(i).mutationTypes[j] = 0.0; } VariantHandler.stattable.sampleArray.add(addobject); Main.drawCanvas.sampleList.get(i).heterozygotes = 0; Main.drawCanvas.sampleList.get(i).homozygotes = 0; Main.drawCanvas.sampleList.get(i).varcount = 0; Main.drawCanvas.sampleList.get(i).indels = 0; Main.drawCanvas.sampleList.get(i).snvs = 0; Main.drawCanvas.sampleList.get(i).sitioRate = 0; Main.drawCanvas.sampleList.get(i).versioRate = 0; Main.drawCanvas.sampleList.get(i).ins = 0; Main.drawCanvas.sampleList.get(i).callrates = 0.0; Main.drawCanvas.sampleList.get(i).coding = 0; Main.drawCanvas.sampleList.get(i).syn = 0; Main.drawCanvas.sampleList.get(i).nonsyn = 0; Main.drawCanvas.sampleList.get(i).missense = 0; Main.drawCanvas.sampleList.get(i).splice = 0; Main.drawCanvas.sampleList.get(i).nonsense = 0; Main.drawCanvas.sampleList.get(i).fshift = 0; Main.drawCanvas.sampleList.get(i).inframe = 0; } VariantHandler.stattable.setPreferredSize(new Dimension(VariantHandler.statsScroll.getViewport().getWidth(), (VariantHandler.stattable.sampleArray.size()+1)*(Main.defaultFontSize+5)+2)); VariantHandler.stattable.revalidate(); VariantHandler.stattable.repaint(); clearVariantsFromGenes(); if(VariantHandler.allChroms.isSelected()) { if(VariantHandler.allChromsfrom.isSelected()) { chromcounter = Main.chromosomeDropdown.getSelectedIndex(); Main.nothread = true; search = true; searchStart = (int)Main.drawCanvas.splits.get(0).start; searchEnd = (int)Main.drawCanvas.splits.get(0).start+Settings.windowSize; Main.chromosomeDropdown.setSelectedIndex(Main.chromosomeDropdown.getSelectedIndex()); Main.nothread = false; Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); vardraw = FileRead.head.getNext(); } else if(Main.drawCanvas.splits.get(0).start > 10 || Main.chromosomeDropdown.getSelectedIndex() != 0) { Main.nothread = true; search = true; Main.chromosomeDropdown.setSelectedIndex(0); Main.nothread = false; vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } else { searchStart = 0; searchEnd = searchStart+Settings.windowSize; getVariantWindow(Main.drawCanvas.splits.get(0).chrom,searchStart,searchEnd); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); vardraw = FileRead.head.getNext(); } } else { searchStart = (int)Main.drawCanvas.splits.get(0).start; searchEnd = getNextIntergenic(searchStart+adder); if(searchEnd > (int)Main.drawCanvas.splits.get(0).end) { searchEnd = (int)Main.drawCanvas.splits.get(0).end; } getVariantWindow(Main.drawCanvas.splits.get(0).chrom,searchStart,searchEnd); vardraw = FileRead.head.getNext(); /* for(int i = 0 ; i < Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).getVarcalc().isSelected()) { Main.bedCanvas.bedTrack.get(i).intersect = true; if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) { Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead()); Main.bedCanvas.intersected = true; } else { BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); Main.bedCanvas.intersected = true; } } } */ } presearchpos = searchEnd; lastVar = FileRead.head; if(VariantHandler.writetofile.isSelected()) { lastWriteVar = FileRead.head; } Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; while(true) { if(cancelvarcount || cancelfileread || !Main.drawCanvas.loading) { cancelFileRead(); nullifyVarNodes(); vardraw = null; break; } if(vardraw == null) { if(VariantHandler.writetofile.isSelected()) { if(VariantHandler.geneSlider.getValue() > 1) { flushVars(vardraw); } else { clearVariantsFromGenes(); } lastVar.putPrev(null); lastWriteVar.putPrev(null); } try { if(VariantHandler.commonSlider.getValue() > 1 && VariantHandler.clusterSize > 0 && Main.drawCanvas.clusterNodes.size() > 0) { Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).width = Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.get(Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.size()-1).getPosition() -Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.get(0).getPosition() +1; VariantHandler.clusterTable.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (Main.drawCanvas.clusterNodes.size()+1)*VariantHandler.clusterTable.rowHeight)); VariantHandler.clusterTable.revalidate(); VariantHandler.clusterTable.repaint(); } for(int i = 0; i<VariantHandler.stattable.sampleArray.size(); i++) { sample = (Sample)VariantHandler.stattable.sampleArray.get(i)[0]; VariantHandler.stattable.sampleArray.get(i)[1] = sample.varcount; VariantHandler.stattable.sampleArray.get(i)[2] = sample.snvs; VariantHandler.stattable.sampleArray.get(i)[3] = sample.indels; VariantHandler.stattable.sampleArray.get(i)[4] = sample.ins; VariantHandler.stattable.sampleArray.get(i)[5] = sample.coding; VariantHandler.stattable.sampleArray.get(i)[6] = MethodLibrary.round(sample.heterozygotes/(double)sample.homozygotes,2); VariantHandler.stattable.sampleArray.get(i)[7] = MethodLibrary.round((int)sample.sitioRate/(double)sample.versioRate,2); for(int j = 0; j<6; j++) { VariantHandler.stattable.sampleArray.get(i)[8+j] = MethodLibrary.round(sample.mutationTypes[j]/(double)sample.snvs, 2); } VariantHandler.stattable.sampleArray.get(i)[14] = MethodLibrary.round(sample.callrates / (double)sample.varcount,2); VariantHandler.stattable.repaint(); } } catch(Exception e) { e.printStackTrace(); } if(VariantHandler.allChroms.isSelected() && searchEnd > Main.drawCanvas.splits.get(0).chromEnd) { for(int i = 0; i<Main.bedCanvas.bedTrack.size(); i++) { removeNonListBeds( Main.bedCanvas.bedTrack.get(i).getHead(), Main.drawCanvas.splits.get(0).chromEnd); } if(cancelvarcount) { break; } if(Main.selectedChrom < Main.chromosomeDropdown.getItemCount()) { chromcounter++; if(chromcounter == Main.chromosomeDropdown.getItemCount()) { break; } if(VariantHandler.onlyAutosomes.isSelected()) { if(Main.chromosomeDropdown.getItemAt(chromcounter).toString().equals("X") || Main.chromosomeDropdown.getItemAt(chromcounter).toString().equals("Y")) { continue; } } //clearVariantsFromGenes(); Main.nothread = true; //search = true; Main.chromosomeDropdown.setSelectedIndex(chromcounter); searchStart = 1; searchEnd = adder; //search = false; Main.nothread = false; presearchpos = searchEnd; getVariantWindow(Main.drawCanvas.splits.get(0).chrom,searchStart,searchEnd); Main.drawCanvas.calcClusters(FileRead.head.getNext()); vardraw = head.getNext(); FileRead.head.putNext(null); if(vardraw == null) { continue; } vardraw.putPrev(lastVar); lastVar.putNext(vardraw); VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), VariantHandler.table.getTableSize()*VariantHandler.table.rowHeight)); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); } } else { VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), VariantHandler.table.getTableSize()*VariantHandler.table.rowHeight)); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); Main.chromDraw.varnode = null; Main.chromDraw.vardraw = null; if(searchEnd >= (int)Main.drawCanvas.splits.get(0).end) { break; } searchStart = presearchpos; searchEnd = searchStart + adder; //getNextIntergenic(presearchpos+adder); presearchpos = searchEnd; for(int i = 0; i<Main.bedCanvas.bedTrack.size(); i++) { removeNonListBeds( Main.bedCanvas.bedTrack.get(i).getHead(), searchStart); } getVariantWindow(Main.drawCanvas.splits.get(0).chrom,searchStart,searchEnd); vardraw = head.getNext(); head.putNext(null); if(vardraw == null) { continue; } vardraw.putPrev(lastVar); lastVar.putNext(vardraw); } } try { if(!VariantHandler.allChroms.isSelected()) { if(vardraw != null && vardraw.getPosition() < Main.drawCanvas.splits.get(0).start) { vardraw = vardraw.getNext(); } if(vardraw == null || vardraw.getPosition() > Main.drawCanvas.splits.get(0).end) { vardraw= null; continue; } } //STATS /* if(vardraw == null) { continue; } */ // Main.drawCanvas.loadbarAll = (int)((vardraw.getPosition()/(double)(Main.drawCanvas.splits.get(0).chromEnd))*100); /* coding = false; if(vardraw.getExons() != null) { for(int e = 0; e < vardraw.getExons().size(); e++) { if(vardraw.getPosition()+1 > vardraw.getExons().get(e).getTranscript().getCodingStart() && vardraw.getPosition()+1 < vardraw.getExons().get(e).getTranscript().getCodingEnd()) { if(vardraw.getPosition()+1 >= vardraw.getExons().get(e).getStart()-2 && vardraw.getPosition()+1 < vardraw.getExons().get(e).getEnd()+2) { coding = true; break; } } } } */ //if(!VariantHandler.vcf.isSelected()) { vardraw = annotateVariant(vardraw); /*} else { if(VariantHandler.writetofile.isSelected()) { VariantHandler.writeNodeToFile(vardraw,Main.chromosomeDropdown.getSelectedItem().toString(), output, outputgz); } else { annotateVariant(vardraw); } } */ //vardraw = vardraw.getNext(); } catch(Exception ex) { ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); } } Draw.calculateVars = true; Draw.updatevars = true; Main.drawCanvas.repaint(); vardraw = null; for(int i = 0; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.tables.get(i).getTableSize()+1)*VariantHandler.tables.get(i).rowHeight)); VariantHandler.tables.get(i).revalidate(); VariantHandler.tables.get(i).repaint(); } VariantHandler.stattable.repaint(); VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.table.getTableSize()+1)*VariantHandler.table.rowHeight)); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } try { if(output != null) { output.close(); } if(outputgz != null) { for(int i = 0 ; i<VariantHandler.outputStrings.size(); i++) { outputgz.write(VariantHandler.outputStrings.get(i).getBytes()); Feature vcf = VariantHandler.vcfCodec.decode(VariantHandler.outputStrings.get(i)); FileRead.indexCreator.addFeature(vcf, FileRead.filepointer); FileRead.filepointer = outputgz.getFilePointer(); } VariantHandler.outputStrings.clear(); outputgz.flush(); Index index = indexCreator.finalizeIndex(outputgz.getFilePointer()); index.writeBasedOnFeatureFile(outFile); outputgz.close(); } } catch(Exception e) { e.printStackTrace(); } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); if(!isfreeze) { VariantHandler.freeze.setSelected(false); } Main.drawCanvas.current = FileRead.head; if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } Main.drawCanvas.ready("all"); nullifyVarNodes(); bigcalc = false; Draw.variantcalculator = false; Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; if(VariantHandler.allChroms.isSelected()) { Main.showError("Variant annotation ready!", "Note"); } } int getNextIntergenic(int pos) { int returnpos = pos; int pointer = 0, gene = -1; while(true) { gene = MethodLibrary.getRegion(returnpos, Main.drawCanvas.splits.get(0), pointer); if(gene == -1) { break; } else { if(returnpos < Main.drawCanvas.splits.get(0).getGenes().get(gene).getEnd()+1) { returnpos = Main.drawCanvas.splits.get(0).getGenes().get(gene).getEnd()+1; } pointer = gene; } } return returnpos; } void writeToFile(VarNode vardraw, BufferedWriter output, BlockCompressedOutputStream outputgz) { if(VariantHandler.table.genearray.size() > 0) { if(VariantHandler.tsv.isSelected() || VariantHandler.compactTsv.isSelected()) { for(int i = 0 ; i<VariantHandler.table.genearray.size(); i++) { if(vardraw == null || vardraw.getPosition() > VariantHandler.table.genearray.get(i).getEnd()) { VariantHandler.writeTranscriptToFile(VariantHandler.table.genearray.get(i), output); if(VariantHandler.allChroms.isSelected() || bigcalc) { for(int s = 0; s<VariantHandler.table.genearray.get(i).varnodes.size(); s++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getExons() != null) { for(int e = 0 ; e<VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().size(); e++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().get(e).getTranscript().equals(VariantHandler.table.genearray.get(i))) { VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().remove(e); e--; } } } if(VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts() != null) { for(int e = 0 ; e<VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().size(); e++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().equals(VariantHandler.table.genearray.get(i))) { VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().remove(e); e--; } } } } } VariantHandler.table.genearray.get(i).samples.clear(); VariantHandler.table.genearray.get(i).varnodes.clear(); VariantHandler.table.genearray.remove(i); i--; } } } else if(VariantHandler.vcf.isSelected() || VariantHandler.oncodrive.isSelected()){ /* ArrayList<VarNode> nodes = new ArrayList<VarNode>(); String lastChrom; for(int v=0; v<VariantHandler.table.genearray.get(0).varnodes.size(); v++) { if(!nodes.contains(VariantHandler.table.genearray.get(0).varnodes.get(v))) { nodes.add(VariantHandler.table.genearray.get(0).varnodes.get(v)); } } if(lastpos < vardraw.getPosition()) { lastpos = vardraw.getPosition(); } else { return; } lastChrom = Main.chromosomeDropdown.getSelectedItem().toString(); */ /* if(bigcalc) { Main.drawCanvas.loadbarAll = (int)((lastpos/(double)(Main.drawCanvas.splits.get(0).chromEnd))*100); } else { Main.drawCanvas.loadbarAll = (int)((lastpos/(double)(Main.drawCanvas.variantsEnd))*100); } Main.drawCanvas.loadBarSample = Main.drawCanvas.loadbarAll; */ if(VariantHandler.geneSlider.getValue() > 1) { } else { VariantHandler.writeNodeToFile(vardraw,vardraw.getChrom(), output, outputgz); lastWriteVar = vardraw; } for(int i = 0 ; i< VariantHandler.table.genearray.size() ; i++) { if(vardraw == null || VariantHandler.table.genearray.get(i).getEnd() < vardraw.getPosition()) { if(VariantHandler.allChroms.isSelected() || bigcalc) { for(int s = 0; s<VariantHandler.table.genearray.get(i).varnodes.size(); s++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getExons() != null) { for(int e = 0 ; e<VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().size(); e++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().get(e).getTranscript().equals(VariantHandler.table.genearray.get(i))) { VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().remove(e); e--; } } } if(VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts() != null) { for(int e = 0 ; e<VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().size(); e++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().equals(VariantHandler.table.genearray.get(i))) { VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().remove(e); e--; } } } } } if(VariantHandler.geneSlider.getValue() == 1) { VariantHandler.table.genearray.get(i).samples.clear(); } VariantHandler.table.genearray.get(i).varnodes.clear(); VariantHandler.table.genearray.remove(i); i--; } } if(VariantHandler.geneSlider.getValue() > 1) { if(VariantHandler.table.genearray.size() == 0) { flushVars(vardraw); } } } } } void flushVars(VarNode vardraw) { if(VariantHandler.vcf.isSelected() || VariantHandler.oncodrive.isSelected()) { if(lastWriteVar != null) { if(lastWriteVar.getNext()== null) { found = false; if(lastWriteVar.isInGene()) { if(lastWriteVar.getExons() != null) { for(int i = 0 ; i<lastWriteVar.getExons().size(); i++) { if(lastWriteVar.getExons().get(i).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getExons().remove(i); i--; } } } else { for(int i = 0 ; i<lastWriteVar.getTranscripts().size(); i++) { if(lastWriteVar.getTranscripts().get(i).getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getTranscripts().remove(i); i--; } } } } if(found) { VariantHandler.writeNodeToFile(lastWriteVar,lastWriteVar.getChrom(), output, outputgz); } } else { lastWriteVar = lastWriteVar.getNext(); } } if(vardraw == null) { if(VariantHandler.table.genearray.size() > 0) { while(lastWriteVar != null) { found = false; if(lastWriteVar.isInGene()) { if(lastWriteVar.getExons() != null) { for(int i = 0 ; i<lastWriteVar.getExons().size(); i++) { if(lastWriteVar.getExons().get(i).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getExons().remove(i); i--; } } } else { for(int i = 0 ; i<lastWriteVar.getTranscripts().size(); i++) { if(lastWriteVar.getTranscripts().get(i).getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getTranscripts().remove(i); i--; } } } } if(found) { VariantHandler.writeNodeToFile(lastWriteVar,lastWriteVar.getChrom(), output, outputgz); } /*if(lastWriteVar.getNext() == null) { break; }*/ lastWriteVar = lastWriteVar.getNext(); } } } else { while(!lastWriteVar.equals(vardraw)) { found = false; if(lastWriteVar.isInGene()) { if(lastWriteVar.getExons() != null) { for(int i = 0 ; i<lastWriteVar.getExons().size(); i++) { if(lastWriteVar.getExons().get(i).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getExons().remove(i); i--; } } } else { for(int i = 0 ; i<lastWriteVar.getTranscripts().size(); i++) { if(lastWriteVar.getTranscripts().get(i).getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getTranscripts().remove(i); i--; } } } } if(found) { VariantHandler.writeNodeToFile(lastWriteVar,lastWriteVar.getChrom(), output, outputgz); } lastWriteVar = lastWriteVar.getNext(); } } } else { if(vardraw == null && VariantHandler.table.genearray.size() > 0) { for(int i =0;i< VariantHandler.table.genearray.size(); i++) { VariantHandler.writeTranscriptToFile(VariantHandler.table.genearray.get(i), output); } VariantHandler.table.genearray.clear(); } } } static boolean checkRecessiveHomo(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { boolean passed = true; int samples = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).getSample().affected) { //parentcount = entry.getValue().get(m).getSample().parents; if(!entry.getValue().get(m).isHomozygous()) { passed = false; break; } samples++; } else { if(entry.getValue().get(m).isHomozygous()) { passed = false; break; } } /*if(entry.getValue().get(m).getSample().children != null && entry.getValue().get(m).getSample().children.size() > 0) { if(entry.getValue().get(m).isHomozygous()) { passed = false; break; } parents++; }*/ entry.getValue().get(m).inheritance = true; } if(samples != FileRead.affected) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } /*if(parents != parentcount) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; }*/ if(!passed) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkDominant(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { boolean passed = true; int samples = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).isHomozygous()) { passed = false; break; } if(!entry.getValue().get(m).getSample().affected) { passed = false; break; } entry.getValue().get(m).inheritance = true; samples++; } if(samples != FileRead.affected) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } if(!passed) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkDeNovo(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { int samples = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).getSample().children != null) { samples = 0; break; } if(entry.getValue().get(m).getSample().parents != 2) { continue; } samples++; entry.getValue().get(m).inheritance = true; } if(samples != 1) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkXlinked(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { int samples = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).getSample().children != null && entry.getValue().get(m).getSample().children.size() > 0 && !entry.getValue().get(m).getSample().female) { samples = 0; break; } if(!entry.getValue().get(m).getSample().affected) { if(entry.getValue().get(m).isHomozygous()) { samples = 0; break; } } samples++; entry.getValue().get(m).inheritance = true; } if(samples != 2) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkCompound(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { boolean passed = true; int samples = 0, parentcount = 0, parents = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).isHomozygous()) { passed = false; break; } if(entry.getValue().get(m).getSample().children != null && entry.getValue().get(m).getSample().children.size() > 0) { parentcount++; } entry.getValue().get(m).inheritance = true; if(entry.getValue().get(m).getSample().affected) { if(parents < entry.getValue().get(m).getSample().parents) { parents =entry.getValue().get(m).getSample().parents; } samples++; } } if(!passed) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } if(parentcount == 2) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } if(parents != 0) { if(parentcount == 0) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } if(samples != FileRead.affected) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkCompoundGene(Gene gene, VarNode vardraw) { if(gene.varnodes.size() < 1) { gene.compounds.clear(); return false; } Entry<String, ArrayList<SampleNode>> entry, entry2; Boolean found2 = null; for(int i = 0 ; i< gene.varnodes.size(); i++) { for(int v = 0 ; v<gene.varnodes.get(i).vars.size(); v++) { entry = gene.varnodes.get(i).vars.get(v); ArrayList<Sample> healthArray = new ArrayList<Sample>(); for(int s = 0; s<entry.getValue().size(); s++) { if(entry.getValue().get(s).getSample() == null) { continue; } if(entry.getValue().get(s).getSample().annotation) { entry.getValue().get(s).inheritance = true; continue; } /*if(!entry.getValue().get(s).inheritance) { continue; }*/ if(!entry.getValue().get(s).getSample().affected) { healthArray.add(entry.getValue().get(s).getSample()); } else { if(entry.getValue().get(s).isHomozygous()) { healthArray.clear(); break; } } } if(healthArray.size() > 0) { for(int var = 0 ; var<vardraw.vars.size(); var++) { entry2 = vardraw.vars.get(var); found2=null; for(int s = 0; s<entry2.getValue().size(); s++) { if(entry2.getValue().get(s).getSample() == null) { continue; } if(entry2.getValue().get(s).getSample().annotation) { entry2.getValue().get(s).inheritance = true; continue; } /*if(!entry2.getValue().get(s).inheritance) { continue; }*/ if(!entry2.getValue().get(s).getSample().affected) { if(healthArray.contains(entry2.getValue().get(s).getSample())) { found2 = true; break; } else { found2 = false; } } } if(found2 != null && !found2) { if(!gene.compounds.contains(vardraw)) { gene.compounds.add(vardraw); } if(!gene.compounds.contains(gene.varnodes.get(i))) { gene.compounds.add(gene.varnodes.get(i)); } //System.out.println(gene.compounds.size()); } } } } } /*if(gene.samples.size() < FileRead.affected) { return false; }*/ if(gene.compounds.size()== 0) { return false; } return true; } static void setUninherited(Entry<String, ArrayList<SampleNode>> entry) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } } VarNode annotateVariant(VarNode vardraw) { if(Main.drawCanvas.hideNode(vardraw)) { returnnode = vardraw.getNext(); if(VariantHandler.allChroms.isSelected()) { vardraw.removeNode(); } return returnnode; } Map.Entry<String, ArrayList<SampleNode>> entry = null; String base = null, amino = null; int pretrack = -1, preI = -1; Main.drawCanvas.loadbarAll = (int)((vardraw.getPosition()/(double)(Main.drawCanvas.splits.get(0).chromEnd))*100); Main.drawCanvas.loadBarSample = Main.drawCanvas.loadbarAll; boolean recessivefound = false; for(int v = 0; v<vardraw.vars.size(); v++) { entry = vardraw.vars.get(v); if(Main.drawCanvas.hideNodeVar(vardraw, entry)) { if(VariantHandler.allChroms.isSelected()) { vardraw.vars.remove(v); v--; } continue; } if(Main.drawCanvas.annotationOn) { if(vardraw.vars.size() == 1 && vardraw.vars.get(0).getValue().size() == 1 && vardraw.vars.get(0).getValue().get(0).getSample().annotation) { if(VariantHandler.allChroms.isSelected()) { vardraw.vars.remove(v); v--; } continue; } } recessivefound = false; base = entry.getKey(); mutcount = 0; if(!VariantHandler.none.isSelected()) { if(VariantHandler.recessiveHomo.isSelected()) { if(!checkRecessiveHomo(vardraw, entry)) continue; } else if(VariantHandler.denovo.isSelected()) { if(!checkDeNovo(vardraw, entry)) continue; } else if(VariantHandler.dominant.isSelected()) { if(!checkDominant(vardraw, entry)) continue; } else if(VariantHandler.xLinked.isSelected()) { if(!checkXlinked(vardraw, entry)) continue; } else if(VariantHandler.compound.isSelected()) { if(!checkCompound(vardraw, entry)) continue; } else if(VariantHandler.recessive.isSelected()) { recessivefound = checkRecessiveHomo(vardraw, entry); if(!recessivefound) { if(Main.chromosomeDropdown.getSelectedItem().equals("X")) { recessivefound = checkXlinked(vardraw, entry); } } if(!recessivefound) { if(!checkCompound(vardraw, entry)) { continue; } } } } for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { if(VariantHandler.allChroms.isSelected()) { entry.getValue().remove(m); m--; } continue; } if(entry.getValue().get(m).getSample().annotation) { continue; } sample = entry.getValue().get(m).getSample(); if(VariantHandler.onlyselected.isSelected()) { if(!sample.equals(Main.drawCanvas.selectedSample)) { continue; } } sample.varcount++; mutcount++; VariantHandler.stattable.variants++; if(vardraw.coding) { sample.coding++; } sample.callrates += entry.getValue().get(m).getAlleleFraction(); if(entry.getValue().get(m).isHomozygous()) { sample.homozygotes++; } else { sample.heterozygotes++; } if(entry.getKey().length() > 1) { if(entry.getKey().contains("del")) { sample.indels++; } else { sample.ins++; } } else { //TODO //System.out.println((int)(MethodLibrary.round(entry.getValue().get(m).getAlleleFraction(),4)*10000)); //array[entry.getValue().get(m).getSample().getIndex()][(int)(MethodLibrary.round(entry.getValue().get(m).getAlleleFraction(),5)*10000)]++; /*if(sample.getName().contains("161")) { if(Main.getBase.get(vardraw.getRefBase()).equals("C")) { if(base.equals("A")) { System.out.println(vardraw.getChrom() +":" +vardraw.getPosition()); } } }*/ if(VariantHandler.onlyStats.isSelected()) { if(VariantHandler.outputContexts.isSelected()) { String context = Main.chromDraw.getSeq(Main.drawCanvas.splits.get(0).chrom,vardraw.getPosition()-1, vardraw.getPosition()+2, Main.referenceFile).toString(); //boolean set = false; if(contexts == null) { contexts = new HashMap<String, Integer[]>(); //contextQuals = new HashMap<String, Float[]>(); } /* if(base.equals("T")) { if(context.endsWith("CG")) { set = true; } } if(base.equals("A")) { if(context.startsWith("CG")) { set = true; } }*/ // if(set) { basecontext = base+context; if(contexts.containsKey(base+context)) { if(contexts.get(base+context)[sample.getIndex()] == null) { contexts.get(base+context)[sample.getIndex()] = 1; //contextQuals.get(base+context)[0]++; // contextQuals.get(base+context)[1] += entry.getValue().get(m).getQuality(); } else { contexts.get(base+context)[sample.getIndex()]++; //contextQuals.get(base+context)[0]++; //contextQuals.get(base+context)[1] += entry.getValue().get(m).getQuality(); } } else { if(contexts.containsKey(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))) { if(contexts.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[sample.getIndex()] == null) { contexts.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[sample.getIndex()] = 1; //contextQuals.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[0] = 1F; //contextQuals.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[1] = entry.getValue().get(m).getQuality(); } else { contexts.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[sample.getIndex()]++; //contextQuals.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[0]++; //contextQuals.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[1] += entry.getValue().get(m).getQuality(); } } else { contexts.put(base+context, new Integer[Main.drawCanvas.sampleList.size()]); contexts.get(base+context)[sample.getIndex()] = 1; //contextQuals.put(base+context, new Float[2]); //contextQuals.get(base+context)[0] = 1F; //contextQuals.get(base+context)[1] = entry.getValue().get(m).getQuality(); } } } // } } sample.snvs++; try { if(!Main.getBase.get(vardraw.getRefBase()).equals("N") && !entry.getKey().equals("N") && !entry.getKey().equals(".")) { sample.mutationTypes[Main.mutTypes.get(Main.getBase.get(vardraw.getRefBase()) +entry.getKey())]++; } } catch(Exception e) { System.out.println(sample.getName() +" " +vardraw.getPosition() +" " +(char)vardraw.getRefBase() +" " +Main.getBase.get(vardraw.getRefBase()) +" " +entry.getKey()); e.printStackTrace(); } if(((char)vardraw.getRefBase() == 'A' && entry.getKey().equals("G")) || ((char)vardraw.getRefBase() == 'G' && entry.getKey().equals("A")) || ((char)vardraw.getRefBase() == 'C' && entry.getKey().equals("T")) || ((char)vardraw.getRefBase() == 'T' && entry.getKey().equals("C"))) { sample.sitioRate++; } else { sample.versioRate++; } } } if(mutcount == 0) { continue; } // INTRONIC if(VariantHandler.intronic.isSelected() && vardraw.isInGene() && vardraw.getTranscripts() != null && vardraw.getExons() == null) { for(int t = 0; t<vardraw.getTranscripts().size(); t++) { for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { if(VariantHandler.allChroms.isSelected()) { entry.getValue().remove(i); i--; } continue; } if(VariantHandler.onlyselected.isSelected()) { if(!entry.getValue().get(i).getSample().equals(Main.drawCanvas.selectedSample)) { continue; } } if(!vardraw.getTranscripts().get(t).getGene().samples.contains(entry.getValue().get(i).getSample())) { vardraw.getTranscripts().get(t).getGene().samples.add(entry.getValue().get(i).getSample()); } } if(!VariantHandler.onlyStats.isSelected()) { boolean add = true; if(VariantHandler.recessive.isSelected()) { if(!recessivefound) { add = checkCompoundGene(vardraw.getTranscripts().get(t).getGene(),vardraw); } } else if(VariantHandler.compound.isSelected()) { add = checkCompoundGene(vardraw.getTranscripts().get(t).getGene(),vardraw); } if(add && vardraw.getTranscripts().get(t).getGene().mutations == 0 && vardraw.getTranscripts().get(t).getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { VariantHandler.table.addEntry(vardraw.getTranscripts().get(t).getGene()); VariantHandler.table.revalidate(); VariantHandler.table.repaint(); } } vardraw.getTranscripts().get(t).getGene().intronic+=mutcount; vardraw.inVarList = true; if(vardraw.inVarList) { if(!vardraw.getTranscripts().get(t).getGene().varnodes.contains(vardraw)) { if(!VariantHandler.onlyStats.isSelected()) { vardraw.getTranscripts().get(t).getGene().varnodes.add(vardraw); } preI = -1; } if(v != preI) { VariantHandler.table.variants += mutcount; vardraw.getTranscripts().get(t).getGene().mutations+=mutcount; preI = v; } } } } /*if(vardraw.getPosition() == 70117871) { System.out.println(vardraw.getExons()); }*/ if(vardraw != null && vardraw.getExons() != null) { ArrayList<Gene> calcgene = new ArrayList<Gene>(); for(int exon = 0; exon<vardraw.getExons().size(); exon++) { amino = Main.chromDraw.getAminoChange(vardraw,base,vardraw.getExons().get(exon)); if(amino.contains("UTR")) { if(VariantHandler.utr.isSelected()) { if(!VariantHandler.table.genearray.contains(vardraw.getExons().get(exon).getTranscript().getGene()) && vardraw.getExons().get(exon).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { if(!VariantHandler.onlyStats.isSelected()) { boolean add = true; if(VariantHandler.recessive.isSelected()) { if(!recessivefound) { add = checkCompoundGene(vardraw.getExons().get(exon).getTranscript().getGene(),vardraw); } } else if(VariantHandler.compound.isSelected()) { add = checkCompoundGene(vardraw.getExons().get(exon).getTranscript().getGene(),vardraw); } if(add) { VariantHandler.table.addEntry(vardraw.getExons().get(exon).getTranscript().getGene()); } } } vardraw.inVarList = true; vardraw.getExons().get(exon).getTranscript().getGene().utr +=mutcount; } else { continue; } } if(VariantHandler.nonsense.isSelected()) { if(!MethodLibrary.aminoEffect(amino).contains("nonsense")) { continue; } } if(VariantHandler.synonymous.isSelected()) { if(MethodLibrary.aminoEffect(amino).contains("synonymous") ) { continue; } } for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { continue; } if(VariantHandler.onlyselected.isSelected()) { if(!entry.getValue().get(i).getSample().equals(Main.drawCanvas.selectedSample)) { continue; } } if(!vardraw.getExons().get(exon).getTranscript().getGene().samples.contains(entry.getValue().get(i).getSample())) { if(!VariantHandler.onlyStats.isSelected()) { vardraw.getExons().get(exon).getTranscript().getGene().samples.add(entry.getValue().get(i).getSample()); } } } boolean add = true; if(!VariantHandler.onlyStats.isSelected()) { if(VariantHandler.recessive.isSelected()) { if(!recessivefound) { add = checkCompoundGene(vardraw.getExons().get(exon).getTranscript().getGene(),vardraw); } } else if(VariantHandler.compound.isSelected()) { add = checkCompoundGene(vardraw.getExons().get(exon).getTranscript().getGene(),vardraw); } if(add && !VariantHandler.table.genearray.contains(vardraw.getExons().get(exon).getTranscript().getGene()) && vardraw.getExons().get(exon).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue() ) { VariantHandler.table.addEntry(vardraw.getExons().get(exon).getTranscript().getGene()); } } if(MethodLibrary.aminoEffect(amino).contains("nonsense")) { if(!calcgene.contains(vardraw.getExons().get(exon).getTranscript().getGene())) { for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { continue; } entry.getValue().get(i).getSample().nonsense++; if(entry.getKey().length() > 1) { entry.getValue().get(i).getSample().fshift++; } if(amino.contains("spl")) { entry.getValue().get(i).getSample().splice++; } else { entry.getValue().get(i).getSample().nonsyn++; } } } vardraw.getExons().get(exon).getTranscript().getGene().nonsense +=mutcount; } else if(MethodLibrary.aminoEffect(amino).contains("missense")) { if(!calcgene.contains(vardraw.getExons().get(exon).getTranscript().getGene())) { for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { continue; } if(entry.getKey().length() > 1) { entry.getValue().get(i).getSample().inframe++; } entry.getValue().get(i).getSample().missense++; entry.getValue().get(i).getSample().nonsyn++; } } vardraw.getExons().get(exon).getTranscript().getGene().missense +=mutcount; } else if(MethodLibrary.aminoEffect(amino).contains("synonymous")) { if(!calcgene.contains(vardraw.getExons().get(exon).getTranscript().getGene())) { for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { continue; } entry.getValue().get(i).getSample().syn++; } } vardraw.getExons().get(exon).getTranscript().getGene().synonymous +=mutcount; } vardraw.inVarList = true; if(!vardraw.getExons().get(exon).getTranscript().getGene().varnodes.contains(vardraw)) { if(!VariantHandler.onlyStats.isSelected()) { vardraw.getExons().get(exon).getTranscript().getGene().varnodes.add(vardraw); } preI = -1; } if(v != preI) { vardraw.getExons().get(exon).getTranscript().getGene().mutations+=mutcount; VariantHandler.table.variants +=mutcount; preI = v; } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); if(!calcgene.contains(vardraw.getExons().get(exon).getTranscript().getGene())) { calcgene.add(vardraw.getExons().get(exon).getTranscript().getGene()); } } } preI = v; if(!vardraw.isInGene() && VariantHandler.intergenic.isSelected()) { /* for(int v = 0; v<vardraw.vars.size(); v++) { entry = vardraw.vars.get(v); if(Main.drawCanvas.hideNodeVar(vardraw, entry)) { continue; } base = entry.getKey(); mutcount = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(Main.drawCanvas.hideVar(entry.getValue().get(m))) { continue; } mutcount++; } */ if(mutcount > 0) { if(VariantHandler.table.genearray.size() == 0 || !VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).intergenic || !VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).getName().equals(vardraw.getTranscripts().get(0).getGene().getName())) { Gene addgene =null; try { addgene = new Gene(vardraw.getTranscripts().get(0).getGene()); } catch(Exception e) { e.printStackTrace(); //Main.drawCanvas.ready("all"); break; } addgene.intergenic = true; addgene.mutations = mutcount; VariantHandler.table.variants += mutcount; if(!VariantHandler.onlyStats.isSelected()) { addgene.varnodes.add(vardraw); boolean add = true; if(VariantHandler.recessive.isSelected()) { if(!recessivefound) { add = checkCompoundGene(addgene,vardraw); } } else if(VariantHandler.compound.isSelected()) { add = checkCompoundGene(addgene,vardraw); } if(add) { VariantHandler.table.addEntry(addgene); } } for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(entry.getValue().get(m).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { continue; } if(!addgene.samples.contains(entry.getValue().get(m).getSample())) { if(!VariantHandler.onlyStats.isSelected()) { addgene.samples.add(entry.getValue().get(m).getSample()); } } } } else { if(!VariantHandler.onlyStats.isSelected()) { VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).mutations +=mutcount; if(!VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).varnodes.contains(vardraw)) { VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).varnodes.add(vardraw); } } VariantHandler.table.variants += mutcount; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(entry.getValue().get(m).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { continue; } if(!VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).samples.contains(entry.getValue().get(m).getSample())) { if(!VariantHandler.onlyStats.isSelected()) { VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).samples.add(entry.getValue().get(m).getSample()); } } } // } } vardraw.inVarList = true; } } //TODO TAHAN // System.out.println(vardraw.getTranscripts().get(0).getGenename() +"..." +vardraw.getTranscripts().get(1).getGenename() ); } if(!vardraw.inVarList) { returnnode = vardraw.getNext(); if(VariantHandler.allChroms.isSelected()) { vardraw.removeNode(); } return returnnode; } else { mutcount = 0; for(int v = 0; v<vardraw.vars.size(); v++) { entry = vardraw.vars.get(v); if(Main.drawCanvas.hideNodeVar(vardraw, entry)) { if(VariantHandler.allChroms.isSelected()) { vardraw.vars.remove(v); v--; } continue; } base = entry.getKey(); for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(entry.getValue().get(m).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { if(VariantHandler.allChroms.isSelected()) { entry.getValue().remove(m); m--; } continue; } mutcount++; } } if(VariantHandler.commonSlider.getValue() > 1 && VariantHandler.clusterSize > 0) { if(Main.drawCanvas.clusterNodes.size() == 0) { ClusterNode cluster = new ClusterNode(); cluster.nodecount=mutcount; cluster.ID = vardraw.clusterId; vardraw.clusterNode = cluster; cluster.varnodes.add(vardraw); cluster.width = 1; Main.drawCanvas.clusterNodes.add(cluster); } else if(Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).ID != vardraw.clusterId) { Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).width = Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.get(Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.size()-1).getPosition() -Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.get(0).getPosition() +1; ClusterNode cluster = new ClusterNode(); cluster.nodecount+= mutcount; cluster.ID = vardraw.clusterId; vardraw.clusterNode = cluster; cluster.varnodes.add(vardraw); cluster.width = 1; Main.drawCanvas.clusterNodes.add(cluster); } else { vardraw.clusterNode = Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1); Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).nodecount+=mutcount; Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.add(vardraw); } VariantHandler.clusterTable.variants+=mutcount; } if(!VariantHandler.writetofile.isSelected()) { if(vardraw != null && vardraw.inVarList && vardraw.bedhit && vardraw.getBedHits() != null) { pretrack = -1; for(int i = 0; i<vardraw.getBedHits().size(); i++) { vardraw.getBedHits().get(i).inVarlist = true; if(pretrack != vardraw.getBedHits().get(i).getTrack().trackIndex) { vardraw.getBedHits().get(i).getTrack().getTable().variants += mutcount; pretrack = vardraw.getBedHits().get(i).getTrack().trackIndex; } if(vardraw.getBedHits().get(i).getTrack().getTable().bedarray == null) { vardraw.getBedHits().get(i).getTrack().getTable().bedarray = new ArrayList<BedNode>(); } if(!vardraw.getBedHits().get(i).getTrack().getTable().bedarray.contains(vardraw.getBedHits().get(i))) { vardraw.getBedHits().get(i).mutations+=mutcount; vardraw.getBedHits().get(i).getTrack().getTable().bedarray.add(vardraw.getBedHits().get(i)); vardraw.getBedHits().get(i).getTrack().getTable().setPreferredSize(new Dimension(vardraw.getBedHits().get(i).getTrack().getTable().tablescroll.getViewport().getWidth(), (vardraw.getBedHits().get(i).getTrack().getTable().getTableSize()+2+samplecount)*vardraw.getBedHits().get(i).getTrack().getTable().rowHeight)); vardraw.getBedHits().get(i).getTrack().getTable().revalidate(); // vardraw.inVarList = true; } else { vardraw.getBedHits().get(i).mutations+=mutcount; // vardraw.inVarList = true; } } } } } if(VariantHandler.writetofile.isSelected()) { writeToFile(vardraw, output, outputgz); } lastVar = vardraw; return vardraw.getNext(); // } } /* static void fetchEnsembl2() { try { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser("genome"); dataSource.setPassword(""); dataSource.setServerName("genome-mysql.cse.ucsc.edu"); dataSource.setDatabaseName("hg19"); Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("select S.*,X.*,G.* from ensemblSource as S,ensGene as G,knownToEnsembl as KE, kgXref as X where S.name = G.name and G.name=KE.value and KE.name=X.kgID"); ResultSet rs = stmt.executeQuery("select E.chrom, E.txStart, E.txEnd, N.value, E.exonCount, E.strand, E.name2, E.name, X.spID, C.transcript, S.source, E.cdsStart, E.cdsEnd, E.exonStarts, E.exonEnds, E.exonFrames, X.description from " + "knownToEnsembl as K left outer join knownCanonical as C on K.name = C.transcript " + "left outer join ensGene as E on K.value = E.name " + "left outer join kgXref as X on K.name = X.kgID " + "left outer join ensemblSource as S on S.name = E.name " + "left outer join ensemblToGeneName as N on E.name = N.name"); BufferedWriter writer = new BufferedWriter(new FileWriter("exons.txt")); String header = "#Chrom\tGeneStart\tGeneEnd\tName\tExonCount\tStrand\tENSG\tENST\tUniProt\tCanonical\tBiotype\tCodingStart\tCodingEnd\tExonStarts\tExonEnds\tStartPhases\tDescription"; writer.write(header +"\n"); while(rs.next()) { writer.write(rs.getString(1).substring(3) +"\t"); for(int i = 2; i <= rs.getMetaData().getColumnCount(); i++) { if(rs.getString(i) == null || rs.getString(i).equals("")) { writer.write("-\t"); } else if(i == 10) { if(rs.getString(i).equals("null")) { writer.write("0\t"); } else { writer.write("1\t"); } } else { writer.write(rs.getString(i) +"\t"); } } writer.write("\n"); } writer.close(); rs.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } } static void fetchEnsembl() { try { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser("anonymous"); dataSource.setPassword(""); dataSource.setServerName("ensembldb.ensembl.org"); dataSource.setPort(3337); dataSource.setDatabaseName("homo_sapiens_core_84_37"); Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("select S.*,X.*,G.* from ensemblSource as S,ensGene as G,knownToEnsembl as KE, kgXref as X where S.name = G.name and G.name=KE.value and KE.name=X.kgID"); ResultSet rs = stmt.executeQuery("SELECT transcript.stable_id, seq_region.name, transcript.seq_region_strand, transcript.biotype, start_exon.stable_id AS start_exon_id, translation.seq_start, end_exon.stable_id AS end_exon_id ,translation.seq_end " + "FROM translation JOIN transcript ON translation.transcript_id=transcript.transcript_id " + "JOIN exon AS start_exon ON translation.start_exon_id = start_exon.exon_id "+ "JOIN exon AS end_exon ON translation.end_exon_id = end_exon.exon_id " + "JOIN gene ON transcript.gene_id = gene.gene_id " + "JOIN seq_region ON gene.seq_region_id = seq_region.seq_region_id " + "WHERE seq_region.coord_system_id = 2"); BufferedWriter writer = new BufferedWriter(new FileWriter("exons.txt")); String header = "#Chrom\tGeneStart\tGeneEnd\tName\tExonCount\tStrand\tENSG\tENST\tUniProt\tCanonical\tBiotype\tCodingStart\tCodingEnd\tExonStarts\tExonEnds\tStartPhases\tDescription"; writer.write(header +"\n"); while(rs.next()) { writer.write(rs.getString(1).substring(3) +"\t"); System.out.print(rs.getString(1).substring(3) +"\t"); for(int i = 2; i <= rs.getMetaData().getColumnCount(); i++) { if(rs.getString(i) == null || rs.getString(i).equals("")) { writer.write("-\t"); System.out.print("-\t"); } else if(i == 10) { if(rs.getString(i).equals("null")) { writer.write("0\t"); System.out.print("0\t"); } else { writer.write("1\t"); System.out.print("1\t"); } } else { writer.write(rs.getString(i) +"\t"); System.out.print(rs.getString(i) +"\t"); } } System.out.println(); writer.write("\n"); } writer.close(); rs.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } } static void fetchAnnotation() { try { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser("genome"); dataSource.setPassword(""); dataSource.setServerName("genome-mysql.cse.ucsc.edu"); // dataSource.setDatabaseName("hg19"); dataSource.setDatabaseName("mm10"); Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); // ResultSet rs = conn.getMetaData().getCatalogs(); // ResultSet rs = stmt.executeQuery("select S.*,X.*,G.* from ensemblSource as S,ensGene as G,knownToEnsembl as KE, kgXref as X where S.name = G.name and G.name=KE.value and KE.name=X.kgID"); System.out.println("Fetching..."); ResultSet rs = stmt.executeQuery("select E.chrom, E.txStart, E.txEnd, N.value, E.exonCount, E.strand, E.name2, E.name, E.name, E.name, S.source, E.cdsStart, E.cdsEnd, E.exonStarts, E.exonEnds, E.exonFrames, E.name from " //+ "knownToEnsembl as K left outer join knownCanonical as C on K.name = C.transcript " + "ensGene as E left outer join ensemblToGeneName as N on E.name = N.name " + "left outer join ensemblSource as S on S.name = E.name"); System.out.println("Fecthed"); BufferedWriter writer = new BufferedWriter(new FileWriter("exons.txt")); String header = "#Chrom\tGeneStart\tGeneEnd\tName\tExonCount\tStrand\tENSG\tENST\tUniProt\tCanonical\tBiotype\tCodingStart\tCodingEnd\tExonStarts\tExonEnds\tStartPhases\tDescription"; writer.write(header +"\n"); while(rs.next()) { //ResultSetMetaData joo = rs.getMetaData(); writer.write(rs.getString(1).substring(3) +"\t"); // System.out.print(rs.getString(1).substring(3) +"\t"); for(int i = 2; i <= rs.getMetaData().getColumnCount(); i++) { if(rs.getString(i) == null || rs.getString(i).equals("")) { // System.out.print("-\t"); writer.write("-\t"); } else if(i == 10) { if(rs.getString(i).equals("null")) { // System.out.print("0\t"); writer.write("0\t"); } else { // System.out.print("1\t"); writer.write("1\t"); } } else { // System.out.print(rs.getString(i) +"\t"); writer.write(rs.getString(i) +"\t"); } } // System.out.println(); writer.write("\n"); } writer.close(); rs.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } }*/ public VariantCall[][] variantCaller(String chrom, int startpos, int endpos, Reads readClass, int minBaseQuality, int minReadQuality, ReferenceSeq reference) { VariantCall[][] coverages = new VariantCall[endpos-startpos +300][8]; Iterator<SAMRecord> bamIterator = getBamIterator(readClass,chrom,startpos, endpos); String run; int scanner = 0, scannerEnd = 0, scanWindow = 10; Boolean strand, scanFail = false; HashMap<String, String> runs = new HashMap<String,String>(); try { readClass.setCoverageStart(startpos); readClass.startpos = startpos; readClass.endpos = endpos; readClass.setReadStart(startpos); readClass.setReadEnd(endpos); readClass.setCoverageEnd(startpos + coverages.length); while(bamIterator != null && bamIterator.hasNext()) { if(!Main.drawCanvas.loading) { Main.drawCanvas.ready("all"); break; } try { try { samRecord = bamIterator.next(); } catch(htsjdk.samtools.SAMFormatException ex) { ex.printStackTrace(); } if(samRecord.getMappingQuality() < minReadQuality) { continue; } if(samRecord.getReadUnmappedFlag()) { continue; } if(samRecord.getReadLength() == 0) { continue; } //TODO jos on pienempi ku vika unclipped start if(samRecord.getUnclippedEnd() < startpos) { //this.readSeqStart+1) { continue; } if(samRecord.getUnclippedStart() >= endpos) { break; } if(readClass.sample.longestRead <samRecord.getCigar().getReferenceLength()) { readClass.sample.longestRead = samRecord.getCigar().getReferenceLength(); } /*if(readClass.sample.getComplete() == null) { if(samRecord.getReadName().startsWith("GS")) { readClass.sample.setcomplete(true); } else { readClass.sample.setcomplete(false); } }*/ if(MethodLibrary.isDiscordant(samRecord, false)) { continue; } if(samRecord.getReadName().contains(":")) { run = samRecord.getReadName().split(":")[1]; } else { run = samRecord.getReadName(); } if(!runs.containsKey(run)) { runs.put(run, ""); } if(samRecord.getAlignmentEnd() >= readClass.getCoverageEnd()) { coverages = coverageArrayAdd(readClass.sample.longestRead*2, coverages, readClass); reference.append(reference.getEndPos()+readClass.sample.longestRead*2); } strand = samRecord.getReadNegativeStrandFlag(); if(samRecord.getCigarLength() > 1) { /*if(samRecord.getCigarString().contains("S")) { continue; }*/ readstart = samRecord.getUnclippedStart(); readpos= 0; mispos= 0; for(int i = 0; i<samRecord.getCigarLength(); i++) { scanFail = false; element = samRecord.getCigar().getCigarElement(i); if(element.getOperator().compareTo(CigarOperator.MATCH_OR_MISMATCH)== 0) { for(int r = readpos; r<readpos+element.getLength(); r++) { if(((readstart+r)-readClass.getCoverageStart()) < 0) { continue; } try { if(samRecord.getReadBases()[mispos] != reference.getSeq()[((readstart+r)-reference.getStartPos()-1)]) { if((readstart+r)-readClass.getCoverageStart() < coverages.length-1 && (readstart+r)- readClass.getCoverageStart() > -1) { readClass.sample.basequalsum+=(int)samRecord.getBaseQualityString().charAt(mispos)-readClass.sample.phred; readClass.sample.basequals++; if((int)samRecord.getBaseQualityString().charAt(mispos)-readClass.sample.phred >= minBaseQuality) { if(mispos > 5 && mispos < samRecord.getReadLength()-5) { /* if(r < scanWindow) { scanner = 0; } else { scanner = r-scanWindow; } if(r > samRecord.getReadLength()-scanWindow) { scannerEnd = samRecord.getReadLength(); } else { scannerEnd = r+scanWindow; } for(int s = scanner ; s<scannerEnd;s++) { if(s == r) { continue; } if(samRecord.getReadBases()[s] != reference.getSeq()[((readstart+s)-reference.getStartPos()-1)]) { scanFail = true; break; } } */ if(!scanFail) { if(coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])] == null) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])] = new VariantCall(); } coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].calls++; coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].qualities += (int)samRecord.getBaseQualityString().charAt(mispos)-readClass.sample.phred; //if(readstart+mispos == 73789324) { // System.out.println(coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].calls); //} if(!coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].runs.contains(run)) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].runs.add(run); } if(!coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].strands.contains(strand)) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].strands.add(strand); } } } else { scanFail = true; } } else { scanFail = true; } } else { scanFail = true; } } } catch(Exception e) { System.out.println(samRecord.getSAMString()); System.out.println(samRecord.getReadLength() +" " +samRecord.getReadString().length()); e.printStackTrace(); return null; } if(!scanFail) { if(coverages[((readstart+r)-readClass.getCoverageStart())][0] == null) { coverages[((readstart+r)-readClass.getCoverageStart())][0] = new VariantCall(); } coverages[((readstart+r)-readClass.getCoverageStart())][0].calls++;; if(coverages[((readstart+r)-readClass.getCoverageStart())][0].calls > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverages[((readstart+r)-readClass.getCoverageStart())][0].calls); } } mispos++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.DELETION)== 0) { scanFail = true; readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.INSERTION)== 0) { // coverages[(readstart+readpos)- readClass.getCoverageStart()][Main.baseMap.get((byte)'I')]++; mispos+=element.getLength(); scanFail = true; } else if(element.getOperator().compareTo(CigarOperator.SOFT_CLIP)== 0 ) { scanFail = true; if(i == 0) { /*if(element.getLength() > 1000) { System.out.println(samRecord.getReadLength() +" " +samRecord.getReadString().length() +"\n" +samRecord.getSAMString()); }*/ readstart = samRecord.getAlignmentStart(); mispos+=element.getLength(); } //} } else if (element.getOperator().compareTo(CigarOperator.HARD_CLIP)== 0) { scanFail = true; if(i == 0) { readstart = samRecord.getAlignmentStart(); } } else if(element.getOperator().compareTo(CigarOperator.SKIPPED_REGION)== 0) { scanFail = true; readpos+=element.getLength(); } } } else { readstart = samRecord.getUnclippedStart(); for(int r = 0; r<samRecord.getReadLength(); r++) { try { scanFail = false; if(samRecord.getReadBases()[r] != reference.getSeq()[((readstart+r)-reference.getStartPos()-1)]) { if((readstart+r)-readClass.getCoverageStart() < coverages.length-1 && (readstart+r)- readClass.getCoverageStart() > -1) { readClass.sample.basequalsum+=(int)samRecord.getBaseQualityString().charAt(r)-readClass.sample.phred; readClass.sample.basequals++; if((int)samRecord.getBaseQualityString().charAt(r)-readClass.sample.phred >= minBaseQuality) { if(r > 5 && r < samRecord.getReadLength()-5) { /*if(samRecord.getReadString().charAt(r) == 'C' && samRecord.getReadString().charAt(r-1) == 'C' && samRecord.getReadString().charAt(r+1) == 'C') { if(samRecord.getReadString().charAt(r-2) != 'C' && samRecord.getReadString().charAt(r+2) != 'C') { VariantCaller.qualities += (int)samRecord.getBaseQualityString().charAt(r)-readClass.sample.phred; VariantCaller.amount++; } }*/ /* if(r < scanWindow) { scanner = 0; } else { scanner = r-scanWindow; } if(r > samRecord.getReadLength()-scanWindow) { scannerEnd = samRecord.getReadLength(); } else { scannerEnd = r+scanWindow; } for(int i = scanner ; i<scannerEnd;i++) { if(i == r) { continue; } if(samRecord.getReadBases()[i] != reference.getSeq()[((readstart+i)-reference.getStartPos()-1)]) { scanFail = true; break; } }*/ if(!scanFail) { if(coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])] == null) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])] = new VariantCall(); } coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].calls++; coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].qualities += (int)samRecord.getBaseQualityString().charAt(r)-readClass.sample.phred; if(!coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].runs.contains(run)) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].runs.add(run); } if(!coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].strands.contains(strand)) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].strands.add(strand); } } } else { scanFail = true; } } else { scanFail = true; } } else { scanFail = true; } } if(!scanFail) { if((readstart+r)-readClass.getCoverageStart() < 0) { continue; } if(coverages[((readstart+r)-readClass.getCoverageStart())][0] == null) { coverages[((readstart+r)-readClass.getCoverageStart())][0] = new VariantCall(); } coverages[(readstart+r)-readClass.getCoverageStart()][0].calls++; } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); break; } } } } catch(Exception e) { e.printStackTrace(); break; } } } catch(Exception ex) { ex.printStackTrace(); return null; } // readClass.setRuns(runs.size()); return coverages; } public static void main(String args[]) { /*String cram = "X:/cg7/Heikki/CRAMtest/cram3/Y_crc47_1_13-0818_cram3_test.cram"; String crai = cram + ".crai"; File ref = new File("C:/HY-Data/RKATAINE/BasePlayer/BasePlayer/genomes/Homo_sapiens_GRCh37/Homo_sapiens.GRCh37.dna.primary_assembly.fa"); */ try { File infile = new File("X:/cg8/Riku/temp/Homo_sapiens.GRCh37.87.chr.gff3.gz"); String outfile = "X:/cg8/Riku/temp/joo.bed.gz"; readGFF(infile, outfile, null); //AddGenome.updateEnsemblList(); //File file = new File("X:\\cg8\\Riku\\gtf\\Mus_musculus.NCBIM37.54.gtf.gz"); //File file = new File("X:\\cg8\\Riku\\gtf\\dmel-all-r6.19.gtf"); //FileRead.readGTF(file, file.getParent() +"/test.bed.gz", null); /* BufferedReader reader = new BufferedReader(new FileReader(file.replace(".idx", ""))); // VCFFileReader reader = new VCFFileReader(new File(file)); Index indexfile = IndexFactory.loadIndex(file); List<Block> list = indexfile.getBlocks("1", 100000000,100000000); System.out.println(list.get(0).getStartPosition()); reader.skip(list.get(0).getStartPosition()); int count = 0; while(count < 20) { System.out.println(reader.readLine()); count++; } reader.close(); /* while(iter.hasNext()) { System.out.println(iter.next().getStart()); } read.close(); */ /* RandomAccessFile random = new RandomAccessFile(ref, "r"); CRAMFileReader reader = new CRAMFileReader(new File(cram), new File(crai),new ReferenceSource(ref), random, ValidationStringency.SILENT); QueryInterval[] interval = { new QueryInterval(0, 1000000, 1010000) }; Iterator<SAMRecord> iter = reader.query(interval, true); System.out.println(iter.hasNext()); // while(iter.hasNext()) { // SAMRecord rec = iter.next(); // System.out.println(rec.getAlignmentStart() +" " +rec.getStringAttribute("MD")); // } /*SAMRecord record = iter.next(); do { System.out.println(record.getAlignmentStart()); record= iter.next(); } while(record != null); */ } catch(Exception e) { e.printStackTrace(); } } }
src/base/BasePlayer/FileRead.java
/* Author: Riku Katainen @ University of Helsinki * * Tumor Genomics Group (http://research.med.helsinki.fi/gsb/aaltonen/) * Contact: [email protected] / [email protected] * * LICENSE: * * GNU AFFERO GENERAL PUBLIC LICENSE * Version 3, 19 November 2007 * */ package base.BasePlayer; import htsjdk.samtools.CRAMFileReader; import htsjdk.samtools.CigarElement; import htsjdk.samtools.CigarOperator; import htsjdk.samtools.QueryInterval; //import htsjdk.samtools.SAMFileReader; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import htsjdk.tribble.Feature; import htsjdk.tribble.readers.TabixReader; import htsjdk.tribble.index.Block; import htsjdk.tribble.index.Index; import htsjdk.tribble.index.IndexFactory; import htsjdk.tribble.index.tabix.TabixIndex; import htsjdk.tribble.index.tabix.TabixIndexCreator; import htsjdk.samtools.cram.ref.ReferenceSource; import htsjdk.samtools.util.BlockCompressedOutputStream; import java.awt.Dimension; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.SwingWorker; import org.apache.commons.io.FilenameUtils; @SuppressWarnings("deprecation") public class FileRead extends SwingWorker< String, Object > { static boolean caller = false; Boolean readVCF = false, changeChrom = false, readBAM = false,searchInsSites = false, varcalc = false, getreads = false; File[] files; String chrom = "0"; static boolean asked = false; int pos; static boolean searchingBams = false; int calls1, calls2; static boolean nobeds = false; private boolean found, noref = false, multi = false; private int xpos; private ReadNode mundane = null; VariantCaller varc = null; VariantCaller.VarCaller varcal = null; static int searchwindow = 1000; private boolean left; boolean stop = false; private ReadNode lastAdded; private ReadNode addNode; static VarNode lastVar = null, lastWriteVar = null, returnnode = null; static Gene currentGene = new Gene(); static int currentGeneEnd = 0; static StringBuffer sampleString = new StringBuffer(""); SamReader samFileReader; CRAMFileReader CRAMReader = null; Iterator<SAMRecord> bamIterator = null; SAMRecord samRecord, samRecordBuffer; private String[] info; private String[] coverages; private Sample sample; private Float quality, gq; static boolean novars = false; String basecontext = ""; int start, end, viewLength; double pixel; public Reads readClass; static final int headnode = 0, tailnode = 1; public static VarNode head; VarNode current; static int firstReadPos; static int lastReadPos; private int startY; private boolean right; public SplitClass splitIndex; private Sample currentSample; public boolean statcalc; private boolean genotype; private int mutcount, linecounter = 0; private short firstallele; private short secondallele; private String altbase; private short refallele; private int refcalls; private short altallele; private int altcalls; private String altbase2; static String[] headersplit; private boolean first; private int samplecount; private int middle; private ReadBuffer currentread; private int searchPos; private boolean isDiscordant; private double[][] coverageArray; private int pointer; private int oldstart; private int addlength; private int readstart; private int readpos; private int mispos; private CigarElement element; boolean firstCov; //public boolean firstSample = false; static int affected = 0; private int gtindex; private int timecounter = 0; static boolean bigcalc=false; static boolean changing = false; static boolean readFiles; public static boolean search; public static int searchStart; public static int searchEnd; public static boolean cancelvarcount= false; public static boolean cancelfileread = false; public static boolean cancelreadread= false; public static BufferedWriter output = null; public static BlockCompressedOutputStream outputgz =null; public static File outFile = null; public static TabixIndexCreator indexCreator; public static int lastpos = 0; public static String outputName = ""; public static long filepointer = 0; HashMap<String, Integer[]> contexts; //HashMap<String, Float[]> contextQuals; //static int[][] array; public static BufferedWriter sigOutput; public FileRead(File[] files) { this.files = files; } public FileRead() { } protected String doInBackground() throws Exception { if(readVCF) { if(Main.drawCanvas.drawVariables.projectName.equals("Untitled")) { Main.frame.setTitle("BasePlayer - Untitled Project"); } readVCF(files); readVCF = false; Draw.updatevars = true; Main.drawCanvas.repaint(); } else if(readBAM) { if(Main.drawCanvas.drawVariables.projectName.equals("Untitled")) { Main.frame.setTitle("BasePlayer - Untitled Project"); } Main.drawCanvas.loading("Loading samples"); readBAM(files); readBAM = false; Main.drawCanvas.ready("Loading samples"); } else if(changeChrom) { changeChrom(chrom); changeChrom = false; Draw.updatevars = true; Draw.updateReads = true; Main.drawCanvas.repaint(); } else if(varcalc) { Main.drawCanvas.loading("Processing variants..."); try { //if(FileRead.head.getNext() == null) { if(VariantHandler.windowcalc.isSelected()) { varCalcBig(); } else { varCalc(); } /*if(caller || VariantHandler.allChroms.isSelected() && !VariantHandler.allChromsfrom.isSelected() && Main.selectedChrom != 0) { varCalc(); } else { varCalcBig(); } /*} else { varCalc(); }*/ varcalc = false; } catch(Exception e) { e.printStackTrace(); Main.drawCanvas.ready("Processing variants..."); } Main.drawCanvas.ready("Processing variants..."); } else if(getreads) { Main.drawCanvas.loading("Loading reads"); if(splitIndex.viewLength <= Settings.readDrawDistance) { for(int i = Main.drawCanvas.drawVariables.visiblestart; i<Main.drawCanvas.drawVariables.visiblestart+Main.drawCanvas.drawVariables.visiblesamples; i++) { if(i>Main.drawCanvas.sampleList.size()-1) { break; } if(Main.drawCanvas.sampleList.get(i).samFile == null) { continue; } //this.readClass.loading = true; this.readClass = Main.drawCanvas.sampleList.get(i).getreadHash().get(splitIndex); getReads(chrom, start, end, this.readClass,splitIndex); splitIndex.updateReads = true; //this.readClass.loading = false; } } else { //this.readClass.loading = true; getReads(chrom, start, end, this.readClass,splitIndex); splitIndex.updateReads = true; //this.readClass.loading = false; } //readClass.nullifyRef(); getreads = false; Main.drawCanvas.ready("Loading reads"); Main.drawCanvas.repaint(); } return null; } /* File ref = new File("C:/HY-Data/RKATAINE/Rikurator/NewRator/genomes/hs37d5/hs37d5.fa"); CRAMFileReader reader = new CRAMFileReader(new File("X:/cg8/Riku/HG00096.alt_bwamem_GRCh38DH.20150718.GBR.low_coverage.cram"), new File("X:/cg8/Riku/HG00096.alt_bwamem_GRCh38DH.20150718.GBR.low_coverage.cram.crai"),new ReferenceSource(ref)); QueryInterval[] interval = { new QueryInterval(reader.getFileHeader().getSequence("chr2").getSequenceIndex(), 1000000, 2000000) }; CloseableIterator<SAMRecord> iterator = reader.query(interval, true); while(iterator.hasNext()) { System.out.println(iterator.next().getSAMString()); }*/ // fetchAnnotation(); // fetchEnsembl(); /* try { String tabixfile = "C:/HY-Data/RKATAINE/BasePlayer/BasePlayer/demo/Somatic-CRC/c32_5332_T_LP6005135-DNA_B01_somatic_GRCh37_20150513.vcf.gz"; TabixIndex index = new TabixIndex(new File(tabixfile+".tbi")); java.util.List<Block> blocks = index.getBlocks("1", 1000000, 4000000); System.out.println(blocks.get(0).getStartPosition()); BlockCompressedInputStream input = new BlockCompressedInputStream(new File(tabixfile)); input.seek(blocks.get(0).getStartPosition()); // gzip.skip(blocks.get(0).getStartPosition()); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); // reader.skip(blocks.get(0).getStartPosition()); String line = reader.readLine(); System.out.println(line); reader.close(); } catch(Exception e) { e.printStackTrace(); }*/ // } /* TabixReader.Iterator getTabixIterator(String chrom, int start, int end, Sample sample) { try { tabixreader = new TabixReader(sample.getTabixFile()); TabixReader.Iterator iterator = tabixreader.query(sample.vcfchr +chrom +":" +start+"-"+end); return iterator; } catch(Exception e) { // JOptionPane.showMessageDialog(Main.chromDraw, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); try { if(search) { if(chrom.equals("X")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("23:" +searchStart+"-"+searchEnd); } else if(chrom.equals("Y")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("24:" +searchStart+"-"+searchEnd); } else if(chrom.contains("M")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("25:" +searchStart+"-"+searchEnd); } } else { if(chrom.equals("X")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("23"); } else if(chrom.equals("Y")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("24"); } else if(chrom.contains("M")) { tabixreader = new TabixReader(sample.getTabixFile()); iterator = tabixreader.query("25"); } } } catch(ArrayIndexOutOfBoundsException ex) { ErrorLog.addError(ex.getStackTrace()); return null; // System.out.println("Chromosome " +chrom +" not found in " +Main.drawCanvas.sampleList.get(i).getName()); } catch(Exception ex) { FileRead.search = false; ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); return null; } } return iterator; }*/ static String setVCFFileStart(String chrom, int start, int end, Sample sample) { try { Index index = null; if(sample.getVCFReader() != null) { try { index = IndexFactory.loadIndex(sample.getTabixFile()+".idx"); } catch(Exception e) { index = IndexFactory.loadIndex(sample.getTabixFile()+".tbi"); } } else { index = new TabixIndex(new File(sample.getTabixFile()+".tbi")); } java.util.List<Block> blocks = null; if(index.containsChromosome(sample.vcfchr +chrom)) { chrom = sample.vcfchr +chrom; try { blocks = index.getBlocks(chrom, start, end); } catch(Exception e) { sample.vcfEndPos = 0; return ""; } if(blocks.size() > 0) { if(sample.getVCFReader() != null) { sample.setInputStream(); sample.getVCFReader().skip(blocks.get(0).getStartPosition()); } else { try { sample.getVCFInput().seek(0); sample.getVCFInput().seek(blocks.get(0).getStartPosition()); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); return ""; } } sample.vcfEndPos = blocks.get(blocks.size()-1).getEndPosition(); } else { if(sample.getVCFReader() != null) { sample.setInputStream(); } else { sample.getVCFInput().seek(0); } } } else { if(index.containsChromosome(sample.vcfchr +(Main.chromosomeDropdown.getSelectedIndex()+1))) { try { blocks = index.getBlocks(sample.vcfchr+(Main.chromosomeDropdown.getSelectedIndex()+1), start, end); } catch(Exception e) { sample.vcfEndPos = 0; return ""; } if(blocks.size() > 0) { if(sample.getVCFReader() != null) { sample.setInputStream(); sample.getVCFReader().skip(blocks.get(0).getStartPosition()); } else { sample.getVCFInput().seek(0); sample.getVCFInput().seek(blocks.get(0).getStartPosition()); } } else { if(sample.getVCFReader() != null) { sample.setInputStream(); } else { sample.getVCFInput().seek(0); } } chrom = sample.vcfchr+(Main.chromosomeDropdown.getSelectedIndex()+1); } else { sample.vcfEndPos = 0; } } } catch(Exception e) { e.printStackTrace(); } return chrom; } void cancelFileRead() { changing = false; FileRead.search = false; bigcalc = false; //Main.opensamples.setText("Add samples"); head.putNext(null); current = null; Main.drawCanvas.current = FileRead.head; Main.drawCanvas.variantsStart = 0; Main.drawCanvas.variantsEnd = 1; Draw.updatevars = true; Main.drawCanvas.repaint(); try { if(output != null) { output.close(); } } catch(Exception e) { e.printStackTrace(); } } void getVariantWindow(String chrom, int start, int end) { try { FileRead.lastpos = 0; removeNonListVariants(); removeBedLinks(); for (int i = 0; i<Control.controlData.fileArray.size(); i++) { Control.controlData.fileArray.get(i).controlled = false; } readFiles = true; head.putNext(null); current = head; cancelvarcount = false; cancelfileread = false; Main.drawCanvas.loadingtext = "Loading variants..."; for(int i = 0; i<Main.samples; i++) { if(cancelvarcount || cancelfileread) { cancelFileRead(); break; } if( Main.drawCanvas.sampleList.get(i).getTabixFile() == null || Main.drawCanvas.sampleList.get(i).multipart) { continue; } current = head; getVariants(chrom,start,end, Main.drawCanvas.sampleList.get(i)); } readFiles =false; annotate(); if(Control.controlData.controlsOn) { Control.applyControl(); } Main.bedCanvas.intersected = false; if(bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head,1); } if(Main.bedCanvas.bedOn) { //VarNode current = FileRead.head.getNext(); /*while(current != null) { current.bedhit = true; current = current.getNext(); }*/ ArrayList<BedTrack> bigs = new ArrayList<BedTrack>(); int smalls = 0; for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { if(!Main.bedCanvas.bedTrack.get(i).small || Main.bedCanvas.bedTrack.get(i).getZoomlevel() != null) { if(Main.bedCanvas.bedTrack.get(i).intersect) { bigs.add(Main.bedCanvas.bedTrack.get(i)); Main.bedCanvas.bedTrack.get(i).intersect = false; } } else { if(Main.bedCanvas.bedTrack.get(i).intersect) { smalls++; } } } if(smalls == 0) { VarNode current = FileRead.head.getNext(); while(current != null) { current.bedhit = true; current = current.getNext(); } } for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { Main.bedCanvas.bedTrack.get(i).used = false; if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getZoomlevel() == null) { if( Main.bedCanvas.bedTrack.get(i).intersect && !Main.bedCanvas.bedTrack.get(i).loading) { Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(), FileRead.head.getNext()); } else if(Main.bedCanvas.bedTrack.get(i).intersect && Main.bedCanvas.bedTrack.get(i).loading) { Main.bedCanvas.bedTrack.get(i).waiting = true; } } //else if(Main.bedCanvas.bedTrack.get(i).intersect) { /*BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); */ // } } if(bigs.size() > 0) { for(int i = 0 ;i<bigs.size(); i++) { bigs.get(i).intersect = true; BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(bigs.get(i)); annotator.annotateVars(); } bigs.clear(); } Main.bedCanvas.intersected = true; if(FileRead.bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head,1); } } } catch(Exception e) { e.printStackTrace(); } } static String getVCFLine(String chrom, int start, int end, Sample sample) { if(Draw.variantcalculator) { return ""; } if(sample.calledvariants) { StringBuffer altbases = new StringBuffer(""); int alts=0, refs=0; for(int i = 0 ; i<Main.drawCanvas.varOverLap.vars.size()-1; i++) { altbases.append(Main.drawCanvas.varOverLap.vars.get(i).getKey()); } alts = Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCalls(); refs = (Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCoverage()-Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCalls()); String genotype = ""; if(alts/(double)refs > 0.95) { genotype = "1/1"; } else { genotype = "0/1"; } altbases.append(Main.drawCanvas.varOverLap.vars.get(Main.drawCanvas.varOverLap.vars.size()-1).getKey()); return Main.drawCanvas.splits.get(0).chrom +"\t" +(Main.drawCanvas.varOverLap.getPosition()+1) +"\t.\t" +Main.getBase.get(Main.drawCanvas.varOverLap.getRefBase()) +"\t" +altbases +"\t99\tPASS\tINFO\tGT:AD:DP\t" +genotype +":" +refs +"," +alts +":" +(refs+alts); } String line = ""; cancelfileread = false; cancelvarcount = false; try { if(!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) { if(sample.multipart) { for(int i = sample.getIndex(); i>= 0; i--) { if(!Main.drawCanvas.sampleList.get(i).multipart) { sample = Main.drawCanvas.sampleList.get(i); break; } } } if(sample.getTabixFile() != null) { setVCFFileStart(chrom, start, end+3, sample); boolean vcf = sample.getVCFReader() != null; while(line != null) { if(vcf) { try { sample.getVCFReader().ready(); } catch(IOException ex) { } } try { if(vcf) { line = sample.getVCFReader().readLine(); } else { line = sample.getVCFInput().readLine(); } if(line == null ||line.split("\t").length < 3 || line.startsWith("#")) { continue; } if(line != null && Integer.parseInt(line.split("\t")[1]) == start+1 ) { if(sample.getVCFReader() != null) { sample.getVCFReader().close(); } return line; } } catch(Exception ex) { Main.showError(ex.getMessage(), "Error"); ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); Main.cancel(); changing = false; } } if(sample.getVCFReader() != null) { sample.getVCFReader().close(); } return line; } } } catch(Exception exc) { Main.showError(exc.getMessage(), "Error"); System.out.println(sample.getName()); exc.printStackTrace(); ErrorLog.addError(exc.getStackTrace()); changing = false; } return ""; } void getVariants(String chrom, int start, int end, Sample sample) { if(sample.calledvariants) { Main.drawCanvas.variantsStart = start; Main.drawCanvas.variantsEnd = end; return; } String line; String[] split; cancelfileread = false; cancelvarcount = false; try { if(!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) { readFiles = true; Main.drawCanvas.splits.get(0).transStart = 0; Main.drawCanvas.variantsStart = start; Main.drawCanvas.variantsEnd = end; Main.drawCanvas.loadbarAll = (int)((sample.getIndex()/(double)(Main.samples))*100); linecounter = 0; if(cancelfileread) { cancelFileRead(); return; } if(sample.multipart){ return; } if(sample.getTabixFile() != null) { String searchChrom = setVCFFileStart(chrom, start, end, sample); boolean vcf = sample.getVCFReader() != null; if(vcf) { try { sample.getVCFReader().ready(); } catch(IOException ex) { return; } } sample.setMaxCoverage(0F); current = head; line = ""; first = true; stop = false; while(true) { if(stop) { break; } if(cancelfileread || cancelvarcount || !Main.drawCanvas.loading) { cancelFileRead(); break; } try { if(vcf) { line = sample.getVCFReader().readLine(); if(line != null && line.startsWith("#")) { continue; } } else { try { line = sample.getVCFInput().readLine(); } catch(htsjdk.samtools.FileTruncatedException e) { e.printStackTrace(); } } if(line == null) { break; } } catch(Exception ex) { Main.showError(ex.getMessage(), "Error"); ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); Main.cancel(); changing = false; break; } if(sample.oddchar != null) { line = line.replaceAll(sample.oddchar, ""); } split = line.split("\\t+"); try { if(split[0].startsWith("#")) { continue; } if(vcf && split.length >2 && (Integer.parseInt(split[1]) > end || !split[0].equals(searchChrom))) { break; } } catch(Exception e) { String string = ""; for(int i = 0 ; i< split.length; i++) { string += split[i]+"\t"; } ErrorLog.addError(string); } if(sample.getVCFInput() != null) { if(sample.getVCFInput().getFilePointer() > sample.vcfEndPos ) { break; } } if(sample.multiVCF) { readLineMulti(split, sample); } else { readLine(split, sample); } if(first) { first = false; } } if(sample.getVCFReader() != null) { sample.getVCFReader().close(); } Draw.updatevars = true; if(sample.getIndex()*Main.drawCanvas.drawVariables.sampleHeight < Main.drawScroll.getViewport().getHeight()+Main.drawCanvas.drawVariables.sampleHeight) { if(Main.drawCanvas.splits.get(0).viewLength < 2000000) { Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } } } } } catch(Exception exc) { Main.showError(exc.getMessage(), "Error"); System.out.println(sample.getName()); exc.printStackTrace(); ErrorLog.addError(exc.getStackTrace()); changing = false; } } public void changeChrom(String chrom) { try { nobeds = false; cancelfileread = false; if(!search) { FileRead.novars = false; } try { Main.drawCanvas.loading("Loading annotation..."); Main.drawCanvas.splits.get(0).setGenes(getExons(chrom)); Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } Main.drawCanvas.ready("Loading annotation..."); ArrayList<BedTrack> bigs = new ArrayList<BedTrack>(); if(Main.bedCanvas.bedTrack.size() > 0) { Main.drawCanvas.loading("Loading BED-files..."); Main.bedCanvas.bedOn = true; boolean ison = false; for(int i = 0 ; i<Main.bedCanvas.bedTrack.size();i++) { if(Main.bedCanvas.bedTrack.get(i).intersect) { ison = true; break; } } if(!ison) { Main.bedCanvas.bedOn = false; } //if(search) { for(int i = 0; i< Main.bedCanvas.bedTrack.size(); i++) { Main.bedCanvas.bedTrack.get(i).used = false; if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd); } else { if(search && searchEnd- searchStart < Settings.windowSize) { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), searchStart, searchEnd); } else { if(Main.bedCanvas.bedTrack.get(i).small) { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd); } } } if(Main.bedCanvas.bedTrack.get(i).intersect && (!Main.bedCanvas.bedTrack.get(i).small || Main.bedCanvas.bedTrack.get(i).getBBfileReader() != null)) { Main.bedCanvas.bedTrack.get(i).intersect = false; bigs.add(Main.bedCanvas.bedTrack.get(i)); } if(nobeds) { Main.drawCanvas.ready("Loading BED-files..."); return; } } } /* } else { for(int i = 0; i< Main.bedCanvas.bedTrack.size(); i++) { Main.bedCanvas.bedTrack.get(i).used = false; if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd); } else { Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd); } if(Main.bedCanvas.bedTrack.get(i).intersect && (!Main.bedCanvas.bedTrack.get(i).small || Main.bedCanvas.bedTrack.get(i).getBBfileReader() != null)) { Main.bedCanvas.bedTrack.get(i).intersect = false; bigs.add(Main.bedCanvas.bedTrack.get(i)); } if(nobeds) { Main.drawCanvas.ready("Loading BED-files..."); return; } } } */ //} Main.drawCanvas.ready("Loading BED-files..."); if(novars) { Main.drawCanvas.variantsStart= 0; Main.drawCanvas.variantsEnd = 0; } else { changing = true; } if(Main.varsamples > 0 && !novars && !bigcalc) { removeNonListVariants(); removeBedLinks(); Main.drawCanvas.loading("Loading variants..."); head.putNext(null); current = FileRead.head; if(FileRead.head.getPosition() > 0) { FileRead.head = new VarNode(0, (byte)0,"N", 0, 0, false,(float)0,(float)0,null,null, null, null, null); } Main.drawCanvas.current = head; Main.chromDraw.varnode = null; Main.chromDraw.vardraw = null; for(int i = 0; i<Main.samples; i++) { if(nobeds) { return; } if(cancelfileread || !Main.drawCanvas.loading) { cancelFileRead(); break; } if( Main.drawCanvas.sampleList.get(i).getTabixFile() == null || Main.drawCanvas.sampleList.get(i).multipart) { continue; } if(search) { getVariants(chrom, FileRead.searchStart, FileRead.searchEnd, Main.drawCanvas.sampleList.get(i)); } else { getVariants(chrom, 0, Main.drawCanvas.splits.get(0).chromEnd, Main.drawCanvas.sampleList.get(i)); } } annotate(); if(Main.drawCanvas.annotationOn) { SampleDialog.checkAnnotation(); } Main.drawCanvas.loading("Applying controls..."); if(Control.controlData.controlsOn) { Control.applyControl(); } Main.drawCanvas.ready("Applying controls..."); readFiles = false; Main.bedCanvas.intersected = false; if(bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head); } if(Main.bedCanvas.bedOn) { Main.drawCanvas.loadingtext = "Annotating variants"; int smalls = 0; for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) { if( Main.bedCanvas.bedTrack.get(i).intersect && !Main.bedCanvas.bedTrack.get(i).loading) { smalls++; Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(), FileRead.head.getNext()); Main.bedCanvas.intersected = true; } else if(Main.bedCanvas.bedTrack.get(i).intersect && Main.bedCanvas.bedTrack.get(i).loading) { Main.bedCanvas.bedTrack.get(i).waiting = true; } } //else if(Main.bedCanvas.bedTrack.get(i).intersect) { //bigs.add(Main.bedCanvas.bedTrack.get(i)); /*BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); Main.bedCanvas.intersected = true; */ //} } if(smalls == 0) { VarNode current = FileRead.head.getNext(); while(current != null) { current.bedhit = true; current = current.getNext(); } } for(int i =0;i<bigs.size(); i++) { bigs.get(i).intersect = true; BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(bigs.get(i)); annotator.annotateVars(); Main.bedCanvas.intersected = true; } bigs.clear(); } if(FileRead.bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head); } } Draw.updatevars = true; Main.drawCanvas.ready("Loading variants..."); if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } if(novars) { Main.drawCanvas.variantsStart= 0; Main.drawCanvas.variantsEnd = Main.drawCanvas.splits.get(0).chromEnd; } search = false; changing = false; current = null; Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } catch(Exception e) { e.printStackTrace(); ErrorLog.addError(e.getStackTrace()); changing = false; } Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; Main.drawCanvas.repaint(); } public ArrayList<Gene> getExons(String chrom) { ArrayList<Gene> transcriptsTemp = new ArrayList<Gene>(); try { if(Main.genomehash.size() == 0 || Main.genomehash.get(Main.defaultGenome).size() == 0) { return new ArrayList<Gene>(); } if(ChromDraw.exonReader != null) { ChromDraw.exonReader.close(); } ChromDraw.exonReader = new TabixReader(Main.genomehash.get(Main.defaultGenome).get(Main.annotation).getCanonicalPath()); if(chrom == null) { return null; } TabixReader.Iterator exonIterator = null; try { if(!ChromDraw.exonReader.getChromosomes().contains(chrom)) { String[] gene = { Main.chromosomeDropdown.getSelectedItem().toString(), "1", ""+Main.drawCanvas.splits.get(0).chromEnd, Main.chromosomeDropdown.getSelectedItem().toString(), "1", "+", "-", "-", "-", "-","-","1","1","1",""+Main.drawCanvas.splits.get(0).chromEnd,"-1,","-"}; Gene addGene = new Gene(gene); Transcript addtrans = null; try { addtrans = new Transcript(gene); } catch(Exception e) { e.printStackTrace(); } addGene.addTranscript(addtrans); addGene.setLongest(addtrans); addtrans.setGene(addGene); transcriptsTemp.add(addGene); return transcriptsTemp; //return new ArrayList<Gene>(); } else { exonIterator = ChromDraw.exonReader.query(chrom); } } catch(Exception e) { try { if(chrom.matches("\\w+")) { exonIterator = ChromDraw.exonReader.query("M"); } } catch(Exception ex) { System.out.println(chrom); e.printStackTrace(); } } String s; String[] exonSplit; Transcript addtrans = null; Hashtable<String, Gene> genes = new Hashtable<String, Gene>(); Gene setGene; while(exonIterator != null && (s = exonIterator.next()) != null) { exonSplit = s.split("\t"); if(exonSplit[0].equals("23")) { exonSplit[0] = "X"; } else if(exonSplit[0].equals("24")) { exonSplit[0] = "Y"; } else if (exonSplit[0].equals("25")) { exonSplit[0] = "MT"; } addtrans = new Transcript(exonSplit); if(!genes.containsKey(exonSplit[6])) { Gene addgene = new Gene(exonSplit); genes.put(exonSplit[6],addgene); addgene.addTranscript(addtrans); addgene.setLongest(addtrans); addtrans.setGene(addgene); transcriptsTemp.add(addgene); } else { setGene = genes.get(exonSplit[6]); setGene.addTranscript(addtrans); addtrans.setGene(setGene); if(addtrans.getLength() > setGene.getLongest().getLength()) { setGene.setLongest(addtrans); } } } genes.clear(); ChromDraw.exonReader.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } return transcriptsTemp; } static File[] readLinkFile(File linkfile) { File[] bamfiles = null; try { FileReader freader = new FileReader(linkfile); BufferedReader reader = new BufferedReader(freader); ArrayList<File> filetemp = new ArrayList<File>(); String line; while((line = reader.readLine()) != null) { File addfile = new File(line.trim()); if(addfile.exists()) { filetemp.add(addfile); } } if(freader != null) { freader.close(); } reader.close(); bamfiles = new File[filetemp.size()]; for(int i = 0; i<filetemp.size(); i++) { bamfiles[i] = filetemp.get(i); } } catch(Exception e) { e.printStackTrace(); } return bamfiles; } private void readBAM(File[] files) { try { File addFile =null; File[] addDir; Sample currentSample = null; Boolean added = false; if(files.length == 1 && files[0].getName().endsWith(".link")) { files = readLinkFile(files[0]); } for(int i = 0; i<files.length; i++) { if(files[i].isDirectory()) { addDir = files[i].listFiles(); for(int f = 0; f<addDir.length; f++) { if(addDir[f].getName().endsWith(".bam") ||addDir[f].getName().endsWith(".cram") ) { addFile = addDir[f]; break; } } } else { if(files[i].getName().endsWith(".bam") || files[i].getName().endsWith(".cram")) { addFile = files[i]; } else { continue; } } if(addFile != null) { Main.drawCanvas.bam = true; currentSample = new Sample(addFile.getName(), (short)Main.samples, null); Main.drawCanvas.sampleList.add(currentSample); currentSample.samFile = addFile; currentSample.resetreadHash(); if(addFile.getName().endsWith(".cram")) { currentSample.CRAM = true; } if(currentSample.samFile.getName().endsWith(".cram")) { currentSample.readString = "CRAM"; } else { currentSample.readString = "BAM"; } try { } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } added = true; Main.readsamples++; Main.samples++; } } if(!added) { return; } checkSamples(); Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.samples); // Main.drawCanvas.checkSampleZoom(); if(Main.drawScroll.getViewport().getHeight()/(Main.drawCanvas.sampleList.size()) > Draw.defaultSampleHeight) { Main.drawCanvas.drawVariables.sampleHeight = Main.drawScroll.getViewport().getHeight()/Main.drawCanvas.sampleList.size(); } else { Main.drawCanvas.drawVariables.sampleHeight = Draw.defaultSampleHeight; } if(Main.drawCanvas.getHeight() < (Main.drawCanvas.sampleList.size())*Main.drawCanvas.drawVariables.sampleHeight) { Main.drawCanvas.resizeCanvas(Main.drawCanvas.getWidth(), (int)((Main.drawCanvas.sampleList.size())*Main.drawCanvas.drawVariables.sampleHeight)); Main.drawCanvas.revalidate(); } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } Draw.updateReads = true; Draw.updatevars = true; Main.drawCanvas.repaint(); } static boolean checkIndex(File file) { try { if(file.getName().endsWith(".vcf")) { return new File(file.getCanonicalPath() +".idx").exists() || new File(file.getCanonicalPath() +".tbi").exists(); } else if(file.getName().toLowerCase().endsWith(".vcf.gz")) { return new File(file.getCanonicalPath() +".tbi").exists(); } else if(file.getName().toLowerCase().endsWith(".bam")) { if(!new File(file.getCanonicalPath() +".bai").exists()) { return new File(file.getCanonicalPath().replace(".bam", "") +".bai").exists(); } else { return true; } } else if(file.getName().toLowerCase().endsWith(".bed.gz") || file.getName().toLowerCase().endsWith(".gff.gz") || file.getName().toLowerCase().endsWith(".bed") || file.getName().toLowerCase().endsWith(".gff")) { return new File(file.getCanonicalPath() +".tbi").exists(); } else if(file.getName().toLowerCase().endsWith(".tsv.gz") || file.getName().toLowerCase().endsWith(".tsv.bgz") ) { return new File(file.getCanonicalPath() +".tbi").exists(); } else { return true; } } catch(Exception e) { e.printStackTrace(); } return false; } static void checkMulti(Sample sample) { try { Sample addSample; BufferedReader reader = null; GZIPInputStream gzip = null; FileReader freader = null; String line; Boolean somatic = Main.drawCanvas.drawVariables.somatic; String[] split; if(somatic != null && somatic) { asked = true; } if(sample.getTabixFile().endsWith(".gz")) { try { gzip = new GZIPInputStream(new FileInputStream(sample.getTabixFile())); reader = new BufferedReader(new InputStreamReader(gzip)); } catch(Exception e) { Main.showError("Could not read the file: " +sample.getTabixFile() +"\nCheck that you have permission to read the file or try to bgzip and recreate the index file.", "Error"); Main.drawCanvas.sampleList.remove(sample); Main.varsamples--; Main.samples--; } } else { freader = new FileReader(sample.getTabixFile()); reader = new BufferedReader(freader); } line = reader.readLine(); if(!sample.multipart && line != null) { while(line != null ) { try { if(line.startsWith("##INFO")) { if(line.contains("Type=Float") || line.contains("Type=Integer")) { VariantHandler.addMenuComponents(line); } } if(line.startsWith("##FILTER")) { if(line.contains("ID=") || line.contains("Description=")) { VariantHandler.addMenuComponents(line); } } if(line.toLowerCase().contains("#chrom")) { headersplit = line.split("\t+"); if(headersplit.length > 10) { if(headersplit.length == 11 && !asked) { if (JOptionPane.showConfirmDialog(Main.drawScroll, "Is this somatic project?", "Somatic?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ somatic = true; Main.drawCanvas.drawVariables.somatic = true; } asked = true; } if(!somatic) { sample.multiVCF = true; Main.varsamples--; for(int h = 9; h<headersplit.length; h++) { addSample = new Sample(headersplit[h], (short)(Main.samples), null); addSample.multipart = true; Main.drawCanvas.sampleList.add(addSample); Main.samples++; Main.varsamples++; if(sampleString == null) { sampleString = new StringBuffer(""); } sampleString.append(addSample.getName() +";"); } VariantHandler.commonSlider.setMaximum(Main.varsamples); VariantHandler.commonSlider.setUpperValue(Main.varsamples); VariantHandler.geneSlider.setMaximum(Main.varsamples); Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.drawCanvas.sampleList.size()); Main.drawCanvas.checkSampleZoom(); Main.drawCanvas.resizeCanvas(Main.drawScroll.getViewport().getWidth(),Main.drawScroll.getViewport().getHeight()); } } line = reader.readLine(); break; } split = line.split("\t"); if(split.length > 2 && split[1].matches("\\d+")) { break; } } catch(Exception ex) { ex.printStackTrace(); } line = reader.readLine(); } if (line == null) { return; } while(line != null && line.startsWith("#")) { line = reader.readLine(); } split = line.split("\t"); if(line.contains("\"")) { sample.oddchar = "\""; } if(split != null && split.length == 8) { sample.annoTrack = true; } if(line != null) { if(line.startsWith("chr")) { sample.vcfchr = "chr"; } } if(somatic != null && somatic) { line = reader.readLine(); if(line != null) { headersplit = line.split("\t"); if(headersplit.length == 11) { if(headersplit[10].startsWith("0:") || (headersplit[10].charAt(0) == '0' && headersplit[10].charAt(2) == '0')) { sample.somaticColumn = 9; } else { sample.somaticColumn = 10; } } } } checkSamples(); line = null; if(freader != null) { freader.close(); } reader.close(); if(gzip != null) { gzip.close(); } } else { reader.close(); if(gzip != null) { gzip.close(); } } } catch(Exception e) { e.printStackTrace(); } } public static class SearchBamFiles extends SwingWorker<String, Object> { boolean cram = false; //SamReader samFileReader; int sampletemp; CRAMFileReader CRAMReader = null; File[] files; ArrayList<File> bamdirs; public SearchBamFiles(File[] files, ArrayList<File> bamdirs, int sampletemp) { this.files = files; this.bamdirs = bamdirs; /*this.fileindex = fileindex;*/ this.sampletemp = sampletemp; } protected String doInBackground() { try { File[] bamfilestemp = null; ArrayList<File> bamfiles = new ArrayList<File>(); searchingBams = true; for(int i = 0 ; i<bamdirs.size(); i++) { bamfilestemp = bamdirs.get(i).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".bam") || name.toLowerCase().endsWith(".cram"); } }); if(bamfilestemp != null && bamfilestemp.length > 0) { for(int j = 0; j<bamfilestemp.length; j++) { bamfiles.add(bamfilestemp[j]); } } else { bamfilestemp = bamdirs.get(i).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".link"); } }); if(bamfilestemp != null && bamfilestemp.length > 0) { for(int j = 0; j<bamfilestemp.length; j++) { File[] fileTemp = readLinkFile(bamfilestemp[j]); for(int f = 0; f<fileTemp.length; f++) { bamfiles.add(fileTemp[f]); } } } } } /* if(fileindex > files.length) { bamfiles = files[0].listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".bam") || name.toLowerCase().endsWith(".cram"); } }); } else { bamfiles = files[fileindex].getParentFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".bam") || name.toLowerCase().endsWith(".cram"); } }); } /* File[] cramfiles = files[fileindex].getParentFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".cram"); } }); */ if(bamfiles.size() > 0) { int index = -1, sampleindex; for(int i = 0; i<bamfiles.size(); i++) { cram = false; sampleindex = 0; index = sampleString.indexOf(bamfiles.get(i).getName().substring(0,bamfiles.get(i).getName().indexOf("."))); if (index < 0) continue; if(!checkIndex(bamfiles.get(i))) { Main.putMessage("Check Tools->View log"); ErrorLog.addError("No index file found for " +bamfiles.get(i).getName()); continue; } for(char letter : sampleString.substring(0, index).toString().toCharArray()) { if(letter == ';') sampleindex++; } Main.drawCanvas.bam = true; Main.readsamples++; Main.drawCanvas.sampleList.get(sampleindex+sampletemp).samFile = new File(bamfiles.get(i).getCanonicalPath()); Main.drawCanvas.sampleList.get(sampleindex+sampletemp).resetreadHash(); if(Main.readsamples==1) { checkSamples(); } if(bamfiles.get(i).getName().endsWith(".cram")){ cram = true; } else { cram = false; } Main.drawCanvas.sampleList.get(sampleindex+sampletemp).CRAM = cram; if(cram) { Main.drawCanvas.sampleList.get(sampleindex+sampletemp).readString = "CRAM"; } else { Main.drawCanvas.sampleList.get(sampleindex+sampletemp).readString = "BAM"; } /* if(samFileReader != null) { samFileReader.close(); }*/ } } sampleString = null; files = null; } catch(Exception e) { searchingBams = false; e.printStackTrace(); } searchingBams = false; Main.drawCanvas.repaint(); return ""; } } private void readVCF(File[] files) { try { if(files.length == 1 && files[0].getName().endsWith(".tbi")) { Main.showError("Please select vcf.gz file, not the index (.tbi)", "Error"); return; } Main.drawCanvas.loading("Loading samples..."); File[] addDir; int sampletemp = Main.samples; Boolean added = false; Sample addSample = null; sampleString = new StringBuffer(""); int fileindex = -1; readFiles = true; cancelfileread = false; ArrayList<File> bamdirs = new ArrayList<File>(); if(Control.controlData.controlsOn) { Control.dismissControls(head); } int addnumber = 0; for(int fi = 0; fi<files.length; fi++) { if(Main.cancel || !Main.drawCanvas.loading) { current = null; FileRead.head.putNext(null); return; } if(!files[fi].exists()) { continue; } addDir = null; if(files[fi].isDirectory()) { addDir = files[fi].listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".vcf.gz") || name.toLowerCase().endsWith(".vcf"); } }); bamdirs.add(files[fi]); for(int f= 0; f<addDir.length; f++) { if(cancelfileread || !Main.drawCanvas.loading) { current = null; FileRead.head.putNext(null); return; } if(!checkIndex(addDir[f])) { Main.putMessage("Check Tools->View log"); ErrorLog.addError("No index file found for " +addDir[f].getName()); } addSample = new Sample(addDir[f].getName(), (short)Main.samples, addDir[f].getCanonicalPath()); Main.drawCanvas.sampleList.add(addSample); Main.varsamples++; Main.samples++; Main.drawCanvas.drawVariables.visiblesamples++; checkMulti(addSample); addnumber++; Main.drawCanvas.loadingtext = "Loading samples... " +addnumber; added = true; VariantHandler.commonSlider.setMaximum(Main.varsamples); VariantHandler.commonSlider.setUpperValue(Main.varsamples); VariantHandler.geneSlider.setMaximum(Main.varsamples); sampleString.append(addSample.getName() +";"); fileindex = f; } } else { if(!files[fi].getName().endsWith(".vcf") && !files[fi].getName().endsWith(".vcf.gz")) { continue; } if(!bamdirs.contains(files[fi].getParentFile())) { bamdirs.add(files[fi].getParentFile()); } File testfile = null; boolean testing = false; if(!checkIndex(files[fi])) { Main.putMessage("Check Tools->View log"); ErrorLog.addError("No index file found for " +files[fi].getName()); if (JOptionPane.showConfirmDialog(Main.drawScroll, "No index file found. Do you want to create one?", "Indexing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ Main.drawCanvas.loadingtext = "Creating index for " +files[fi].getName(); if(files[fi].getName().endsWith(".vcf.gz")) { testing = true; testfile = MethodLibrary.createVCFIndex(files[fi]); } else { MethodLibrary.createVCFIndex2(files[fi]); } } else { continue; } } if(testing && testfile != null) { files[fi] = testfile; } if(fileindex > -1) { if(!files[fi].getParent().equals(files[fileindex].getParent())) { // diffPaths = true; } } fileindex =fi; addSample = new Sample(files[fi].getName(), (short)Main.samples, files[fi].getCanonicalPath()); Main.drawCanvas.sampleList.add(addSample); Main.varsamples++; Main.samples++; Main.drawCanvas.drawVariables.visiblesamples = (short)Main.samples; sampleString.append(addSample.getName() +";"); checkMulti(addSample); addnumber++; Main.drawCanvas.loadingtext = "Loading samples... " +addnumber; added = true; VariantHandler.commonSlider.setMaximum(Main.varsamples); VariantHandler.commonSlider.setUpperValue(Main.varsamples); VariantHandler.geneSlider.setMaximum(Main.varsamples); } } if(!added) { Main.drawCanvas.ready("Loading samples..."); return; } if(bamdirs.size() > 0) { SearchBamFiles search = new SearchBamFiles(files, bamdirs, sampletemp); search.execute(); } Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.drawCanvas.sampleList.size()); Main.drawCanvas.checkSampleZoom(); Main.drawCanvas.resizeCanvas(Main.drawScroll.getViewport().getWidth(),Main.drawScroll.getViewport().getHeight()); int loading = 0; if(!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) { Main.drawCanvas.loadingtext = "Loading variants..."; for(int i = sampletemp; i < Main.drawCanvas.sampleList.size(); i++) { linecounter = 0; if(cancelfileread || !Main.drawCanvas.loading) { cancelFileRead(); break; } if(( Main.drawCanvas.sampleList.get(i).getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight < Main.drawScroll.getViewport().getHeight()+Main.drawCanvas.drawVariables.sampleHeight) { // Main.drawCanvas.drawVariables.visibleend = (short)(Main.drawCanvas.sampleList.get(i).getIndex()); // Main.drawCanvas.drawVariables.visiblesamples = (short)(Main.drawCanvas.sampleList.get(i).getIndex()+1); Main.drawCanvas.checkSampleZoom(); } Main.drawCanvas.loadbarAll = (int)((loading/(double)(Main.drawCanvas.sampleList.size()-sampletemp))*100); // if(!Main.drawCanvas.sampleList.get(i).multipart) { try { // vcfreader = new VCFFileReader(new File(Main.drawCanvas.sampleList.get(i).getTabixFile())); /* try { tabixreader = new TabixReader(Main.drawCanvas.sampleList.get(i).getTabixFile()); } catch(Exception ex) { JOptionPane.showMessageDialog(Main.chromDraw, "Index file (tbi) not found for " +Main.drawCanvas.sampleList.get(i).getName(), "Error", JOptionPane.ERROR_MESSAGE); ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); }*/ // iterator=null; if(Main.drawCanvas.sampleList.get(i).getTabixFile() == null) { continue; } if(start > 10000 && end < Main.drawCanvas.splits.get(0).chromEnd-10000) { if(Main.drawCanvas.variantsEnd > 0) { // iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString()+":" +Main.drawCanvas.variantsStart +"-" +Main.drawCanvas.variantsEnd); getVariants(Main.chromosomeDropdown.getSelectedItem().toString(), Main.drawCanvas.variantsStart,Main.drawCanvas.variantsEnd, Main.drawCanvas.sampleList.get(i)); } else { Main.drawCanvas.variantsStart = start; Main.drawCanvas.variantsEnd = end; // iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString()+":" +Main.drawCanvas.variantsStart +"-" +Main.drawCanvas.variantsEnd); getVariants(Main.chromosomeDropdown.getSelectedItem().toString(), Main.drawCanvas.variantsStart,Main.drawCanvas.variantsEnd, Main.drawCanvas.sampleList.get(i)); } } else { // iterator = tabixreader.query(Main.drawCanvas.sampleList.get(i).vcfchr +Main.chromosomeDropdown.getSelectedItem().toString()); Main.drawCanvas.variantsStart = 0; Main.drawCanvas.variantsEnd = Main.drawCanvas.splits.get(0).chromEnd; getVariants(Main.chromosomeDropdown.getSelectedItem().toString(), Main.drawCanvas.variantsStart,Main.drawCanvas.variantsEnd, Main.drawCanvas.sampleList.get(i)); } } catch(Exception e) { Main.showError( e.getMessage(), "Error"); ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } /* if(iterator == null) { tabixreader = null; continue; }*/ // } /* else { continue; } line = null; current = head; first = true; while(true) { try { if(cancelfileread) { cancelFileRead(); } try { line = iterator.next(); // vcfline = vcfIterator.next(); if(line == null) { break; } // line = vcfline.getSource(); } catch(Exception ex) { JOptionPane.showMessageDialog(Main.chromDraw, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); Main.cancel(); // tabixreader.mFp.close(); ex.printStackTrace(); break; } split = line.split("\\t+"); if(Main.drawCanvas.sampleList.get(i).multiVCF) { readLineMulti(split, Main.drawCanvas.sampleList.get(i)); } else { readLine(split, Main.drawCanvas.sampleList.get(i)); // readLine(vcfline, Main.drawCanvas.sampleList.get(i)); } if(first) { first = false; } } catch(Exception e) { e.printStackTrace(); // tabixreader.mFp.close(); } } // tabixreader.mFp.close(); Main.drawCanvas.current = FileRead.head.getNext(); if(Main.drawCanvas.splits.get(0).viewLength < 2000000) { Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } Draw.updatevars = true; Draw.updateReads = true; Main.drawCanvas.repaint(); loading++;*/ } } //Main.opensamples.setText("Add samples"); checkSamples(); annotate(); readFiles = false; // Main.drawCanvas.clusterCalc = true; if(Control.controlData.controlsOn) { Control.applyControl(); } Main.bedCanvas.intersected = false; if(bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head,1); } if(Main.bedCanvas.bedOn) { Main.drawCanvas.loadingtext = "Annotating variants"; for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).intersect && !Main.bedCanvas.bedTrack.get(i).loading) { if(Main.bedCanvas.bedTrack.get(i).small) { Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(), FileRead.head.getNext()); } else { BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); } } else if(Main.bedCanvas.bedTrack.get(i).intersect && Main.bedCanvas.bedTrack.get(i).loading) { Main.bedCanvas.bedTrack.get(i).waiting = true; } } Main.bedCanvas.intersected = true; } if(bigcalc) { Main.drawCanvas.calcClusters(FileRead.head); } else { Main.drawCanvas.calcClusters(FileRead.head,1); } if(Main.drawCanvas.splits.get(0).viewLength < 2000000) { Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } // Main.drawCanvas.drawVariables.visibleend = Main.samples; //Main.drawCanvas.drawVariables.visiblesamples = Main.samples; Main.drawCanvas.checkSampleZoom(); Main.drawCanvas.current = head; // Draw.updatevars = true; // Main.drawCanvas.repaint(); current = null; Main.drawCanvas.ready("Loading samples..."); Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; } catch(Exception e) { e.printStackTrace(); ErrorLog.addError(e.getStackTrace()); } } static void checkSamples() { /*if(Main.varsamples == 0) { Main.drawCanvas.varbuffer = MethodLibrary.toCompatibleImage(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.g2v = (Graphics2D)Main.drawCanvas.varbuffer.getGraphics(); } else {*/ // Main.drawCanvas.varbuffer = MethodLibrary.toCompatibleImage(new BufferedImage(Main.screenSize.width, Main.screenSize.height, BufferedImage.TYPE_INT_ARGB)); // Main.drawCanvas.g2v = (Graphics2D)Main.drawCanvas.varbuffer.getGraphics(); // } if(Main.varsamples < 2) { VariantHandler.commonSlider.setMaximum(1); VariantHandler.commonSlider.setValue(1); VariantHandler.commonSlider.setUpperValue(1); VariantHandler.geneSlider.setMaximum(1); VariantHandler.geneSlider.setValue(1); //VariantHandler.filterPanes.setEnabledAt(VariantHandler.filterPanes.getTabCount()-1, false); VariantHandler.filterPanes.setToolTipTextAt(VariantHandler.filterPanes.getTabCount()-1, "Open more samples to compare variants."); } else { VariantHandler.commonSlider.setMaximum(Main.varsamples); VariantHandler.commonSlider.setValue(1); VariantHandler.commonSlider.setUpperValue(Main.varsamples); VariantHandler.geneSlider.setMaximum(Main.varsamples); VariantHandler.geneSlider.setValue(1); VariantHandler.filterPanes.setEnabledAt(VariantHandler.filterPanes.getTabCount()-1, true); VariantHandler.filterPanes.setToolTipTextAt(VariantHandler.filterPanes.getTabCount()-1, "Compare variants."); } if(Main.readsamples > 0) { /* Main.drawCanvas.readbuffer = MethodLibrary.toCompatibleImage(new BufferedImage(Main.screenSize.width, Main.screenSize.height, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.rbuf = (Graphics2D)Main.drawCanvas.readbuffer.getGraphics(); Main.drawCanvas.backupr = Main.drawCanvas.rbuf.getComposite(); Main.drawCanvas.rbuf.setRenderingHints(Draw.rh); Main.drawCanvas.coveragebuffer = MethodLibrary.toCompatibleImage(new BufferedImage(Main.screenSize.width, Main.screenSize.height, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.cbuf = (Graphics2D)Main.drawCanvas.coveragebuffer.getGraphics(); Main.drawCanvas.backupc = Main.drawCanvas.cbuf.getComposite(); */ Main.average.setEnabled(true); Main.variantCaller.setEnabled(true); Main.peakCaller.setEnabled(true); if(caller) { if(Main.readsamples > 1) { VariantHandler.filterPanes.setEnabledAt(VariantHandler.filterPanes.getTabCount()-1, true); VariantHandler.commonSlider.setMaximum(Main.readsamples); VariantHandler.commonSlider.setUpperValue(Main.readsamples); VariantHandler.geneSlider.setMaximum(Main.readsamples); VariantHandler.geneSlider.setValue(1); } Main.manage.setEnabled(true); } } else { /* Main.drawCanvas.readbuffer = MethodLibrary.toCompatibleImage(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.rbuf = (Graphics2D)Main.drawCanvas.readbuffer.getGraphics(); Main.drawCanvas.backupr = Main.drawCanvas.rbuf.getComposite(); Main.drawCanvas.rbuf.setRenderingHints(Draw.rh); Main.drawCanvas.coveragebuffer = MethodLibrary.toCompatibleImage(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)); Main.drawCanvas.cbuf = (Graphics2D)Main.drawCanvas.coveragebuffer.getGraphics(); Main.drawCanvas.backupc = Main.drawCanvas.cbuf.getComposite(); */ Main.average.setEnabled(false); Main.average.setToolTipText("No bam/cram files opened"); Main.variantCaller.setEnabled(false); Main.variantCaller.setToolTipText("No bam/cram files opened"); } } static void annotate() { if(Main.drawCanvas.splits.get(0).getGenes().size() == 0) { return; } Transcript transcript; Gene gene, prevGene = Main.drawCanvas.splits.get(0).getGenes().get(0); VarNode current = FileRead.head.getNext(); Transcript.Exon exon; int position = 0, baselength; boolean intronic = true; try { if(current != null) { for(int g=0; g<Main.drawCanvas.splits.get(0).getGenes().size(); g++ ) { gene = Main.drawCanvas.splits.get(0).getGenes().get(g); /* while(current != null && current.getPosition() < gene.getStart()) { if(!current.isInGene()) { if(current.getTranscripts() == null) { current.setTranscripts(); } current.getTranscripts().add(prevGene.getTranscripts().get(0)); current.getTranscripts().add(gene.getTranscripts().get(0)); } current = current.getNext(); }*/ if(current == null) { break; } for(int t = 0; t<gene.getTranscripts().size(); t++) { transcript = gene.getTranscripts().get(t); if(current != null && current.getPrev() != null) { while(current.getPrev().getPosition() >= transcript.getStart()) { if(current.getPrev() != null) { current = current.getPrev(); } } } position = current.getPosition(); if(current.indel) { position++; baselength = MethodLibrary.getBaseLength(current.vars, 1); } while(position < transcript.getEnd()) { try { if(position >= transcript.getStart() && position <= transcript.getEnd()) { current.setInGene(); baselength = 0; intronic = true; for(int e=0;e<transcript.getExons().length; e++) { exon = transcript.getExons()[e]; if(position+baselength >= exon.getStart()-2 && position < exon.getEnd()+2) { if(current.getExons() == null) { current.setExons(); } intronic = false; if(!current.getExons().contains(exon)) { current.getExons().add(exon); if(exon.getStartPhase() > -1 && position+baselength >= exon.getTranscript().getCodingStart() && position < exon.getTranscript().getCodingEnd() ) { current.coding = true; } break; } } } if(intronic) { if(current.getTranscripts() == null) { current.setTranscripts(); } current.getTranscripts().add(transcript); } } if(!current.isInGene()) { if(current.getTranscripts() == null) { current.setTranscripts(); current.getTranscripts().add(prevGene.getTranscripts().get(0)); current.getTranscripts().add(gene.getTranscripts().get(0)); } } if(current.getNext() != null) { current = current.getNext(); position = current.getPosition(); } else { break; } } catch(Exception e) { System.out.println(position); e.printStackTrace(); break; } } } if(gene.getEnd() > prevGene.getEnd()) { prevGene = gene; } } while(current != null) { if(!current.isInGene()) { if(current.getTranscripts() == null) { current.setTranscripts(); current.getTranscripts().add(prevGene.getTranscripts().get(0)); current.getTranscripts().add(prevGene.getTranscripts().get(0)); } } current = current.getNext(); } } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } current = null; transcript = null; exon = null; } public void readLineMulti(String[] split, Sample sample) { samplecount = 0; try { pos = Integer.parseInt(split[1])-1; } catch(Exception e) { return; } if(pos < Main.drawCanvas.variantsStart) { return; } else if(pos >=Main.drawCanvas.variantsEnd) { stop = true; return; } /*else if(sample.getVCFInput().getFilePointer() > sample.vcfEndPos) { return; }*/ if(linecounter == 0 || pos -linecounter > (Main.drawCanvas.variantsEnd-Main.drawCanvas.variantsStart)/100) { Main.drawCanvas.loadBarSample = (int)(((pos-Main.drawCanvas.variantsStart)/(double)(Main.drawCanvas.variantsEnd-Main.drawCanvas.variantsStart))*100); Draw.updatevars = true; linecounter = pos; } first = true; while(current != null && current.getNext() != null && current.getPosition() < pos ){ current = current.getNext(); } if(current.getPosition() == pos) { first = false; } for(int s = 9; s < split.length;s++) { try { currentSample = Main.drawCanvas.sampleList.get(sample.getIndex()+1+s-9 ); if(currentSample.removed) { continue; } info = split[s].split(":"); noref = false; HashMap<String, Integer> infofield = new HashMap<String, Integer>(); String[] infos = split[8].split(":"); for(int i = 0; i<infos.length; i++) { infofield.put(infos[i], i); } if(infofield.containsKey("GT")) { gtindex = infofield.get("GT"); if(info[gtindex].contains(".") || info[gtindex].length() < 3) { continue; } firstallele = Short.parseShort(""+info[gtindex].split("/")[0]); secondallele = Short.parseShort(""+info[gtindex].split("/")[1]); genotype = firstallele == secondallele; if(genotype && firstallele == 0) { continue; } if(infofield.containsKey("AD")) { if(infofield.containsKey("RD")) { refcalls = Integer.parseInt(info[infofield.get("RD")]); altcalls = Integer.parseInt(info[infofield.get("AD")]); } else { try { coverages = info[infofield.get("AD")].split(","); calls1 = Integer.parseInt(coverages[firstallele]); calls2 = Integer.parseInt(coverages[secondallele]); } catch(Exception e) { return; } } } else { calls1 = 20; calls2 = 20; } if(!genotype) { if(firstallele == 0) { refallele = firstallele; refcalls = calls1; altallele = secondallele; altcalls = calls2; } else if(secondallele == 0){ refallele = secondallele; refcalls = calls2; altallele = firstallele; altcalls = calls1; } else { noref = true; refallele = firstallele; refcalls = calls1; altallele = secondallele; altcalls = calls2; } } else { refcalls = calls1; //(short)(Short.parseShort(coverages[0])); altallele = secondallele; altcalls = calls2; } } if(!split[4].contains(",")) { altbase = getVariant(split[3], split[4]); } else if(!noref){ altbase = getVariant(split[3], split[4].split(",")[altallele-1]); } else { altbase = getVariant(split[3], split[4].split(",")[altallele-1]); altbase2 = getVariant(split[3], split[4].split(",")[refallele-1]); } if(altbase.contains("*") || (altbase2!=null && altbase2.contains("*"))) { continue; } quality = null; if(split[8].contains("Q")) { if(infofield.containsKey("GQ") && !info[infofield.get("GQ")].equals(".")) { gq = (float)Double.parseDouble(info[split[8].indexOf("GQ")/3]); } else if(infofield.containsKey("BQ") && !info[infofield.get("BQ")].equals(".")) { quality = (float)Double.parseDouble(info[infofield.get("BQ")]); } else if(split[7].contains("SSC")) { quality = Float.parseFloat(split[7].substring(split[7].indexOf("SSC") +4).split(";")[0]); } } if(quality == null) { if(split[5].matches("\\d+.?.*")) { quality = (float)Double.parseDouble(split[5]); } } HashMap<String, Float> advancedQualities = null; if(VariantHandler.freeze.isSelected()) { if(refcalls+altcalls < VariantHandler.coverageSlider.getValue()) { continue; } if(quality != null && quality < VariantHandler.qualitySlider.getValue()) { continue; } if(gq != null && gq < VariantHandler.gqSlider.getValue()) { continue; } if(altcalls/(double)(refcalls+altcalls) < VariantHandler.callSlider.getValue()/100.0) { continue; } if(VariantHandler.hideSNVs.isSelected() && altbase.length() == 1 ) { continue; } if(VariantHandler.hideIndels.isSelected() && altbase.length() > 1) { continue; } if(VariantHandler.rscode.isSelected() && !split[2].equals(".")) { continue; } } if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { return; } } if(refcalls+altcalls > VariantHandler.maxCoverageSlider.getMaximum()) { VariantHandler.maxCoverageSlider.setMaximum(refcalls+altcalls); VariantHandler.maxCoverageSlider.setValue(refcalls+altcalls); } /* if(currentSample.getMaxCoverage() < calls1+calls2) { currentSample.setMaxCoverage((float)(calls1+calls2)); } */ if(first && current.getNext() == null) { if(!split[2].equals(".")) { current.putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, split[2], currentSample, current, null)); } else { current.putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase,refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, null, currentSample, current, null)); } if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.getNext().addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, currentSample); } current = current.getNext(); first = false; } else if(pos == current.getPosition()){ current.addSample(altbase, refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, currentSample); if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, currentSample); } if(current.isRscode() == null && !split[2].equals(".")) { current.setRscode(split[2]); } } else if(current.getPosition() > pos) { if(!split[2].equals(".")) { current.getPrev().putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, split[2], currentSample, current.getPrev(), current)); } else { current.getPrev().putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, null, currentSample, current.getPrev(), current)); } if(noref ) { if(split.length > 7) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.getPrev().addSample(altbase2,refcalls+altcalls, refcalls, genotype, quality, gq,advancedQualities, currentSample); } current.putPrev(current.getPrev().getNext()); current = current.getPrev(); } } catch(Exception ex) { ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); for(int i=0; i<split.length; i++) { System.out.print(split[i] +" "); } System.out.println(); break; } if(first) { first = false; } } } boolean checkAdvQuals(String split, boolean indel) { if(!VariantHandler.indelFilters.isSelected()) { if(Main.drawCanvas.drawVariables.advQDraw != null && Main.drawCanvas.drawVariables.advQDraw.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDraw.size(); i++) { if(split.contains(Main.drawCanvas.drawVariables.advQDraw.get(i).key)) { if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals("<")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) < Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals("<=")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) <= Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals(">")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) > Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) >= Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } } } } } else { if(indel) { if(Main.drawCanvas.drawVariables.advQDrawIndel != null && Main.drawCanvas.drawVariables.advQDrawIndel.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDrawIndel.size(); i++) { if(split.contains(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key)) { if(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).format.equals("<")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key.length()+1).split(";")[0].trim()) < Main.drawCanvas.drawVariables.advQDrawIndel.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).format.equals("<=")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key.length()+1).split(";")[0].trim()) <= Main.drawCanvas.drawVariables.advQDrawIndel.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).format.equals(">")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key.length()+1).split(";")[0].trim()) > Main.drawCanvas.drawVariables.advQDrawIndel.get(i).value) { return true; } } else { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key.length()+1).split(";")[0].trim()) >= Main.drawCanvas.drawVariables.advQDrawIndel.get(i).value) { return true; } } } } } } else { if(Main.drawCanvas.drawVariables.advQDraw != null && Main.drawCanvas.drawVariables.advQDraw.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDraw.size(); i++) { if(split.contains(Main.drawCanvas.drawVariables.advQDraw.get(i).key)) { if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals("<")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) < Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals("<=")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) <= Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else if(Main.drawCanvas.drawVariables.advQDraw.get(i).format.equals(">")) { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) > Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } else { if(Float.parseFloat(split.substring(split.indexOf(Main.drawCanvas.drawVariables.advQDraw.get(i).key+"=")+Main.drawCanvas.drawVariables.advQDraw.get(i).key.length()+1).split(";")[0].trim()) >= Main.drawCanvas.drawVariables.advQDraw.get(i).value) { return true; } } } } } } } return false; } boolean checkAdvFilters(String split, boolean indel) { if(!VariantHandler.indelFilters.isSelected()) { if(Main.drawCanvas.drawVariables.advQDraw != null && Main.drawCanvas.drawVariables.advQDraw.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDraw.size(); i++) { if(split.equals(Main.drawCanvas.drawVariables.advQDraw.get(i).key)) { return true; } } } } else { if(indel) { if(Main.drawCanvas.drawVariables.advQDrawIndel != null && Main.drawCanvas.drawVariables.advQDrawIndel.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDrawIndel.size(); i++) { if(split.equals(Main.drawCanvas.drawVariables.advQDrawIndel.get(i).key)) { return true; } } } } else { if(Main.drawCanvas.drawVariables.advQDraw != null && Main.drawCanvas.drawVariables.advQDraw.size() > 0) { for(int i = 0 ; i<Main.drawCanvas.drawVariables.advQDraw.size(); i++) { if(split.equals(Main.drawCanvas.drawVariables.advQDraw.get(i).key)) { return true; } } } } } return false; } public void readLine(String[] split, Sample sample) { try { if(split.length < 3) { return; } if(split[0].startsWith("#") || split[4].equals("*")) { return; } pos = Integer.parseInt(split[1])-1; if(pos < Main.drawCanvas.variantsStart) { return; } else if(pos >= Main.drawCanvas.variantsEnd) { stop = true; return; } if(linecounter == 0 || pos -linecounter > (Main.drawCanvas.variantsEnd-Main.drawCanvas.variantsStart)/100) { Main.drawCanvas.loadBarSample = (int)(((pos-Main.drawCanvas.variantsStart)/(double)(Main.drawCanvas.variantsEnd-Main.drawCanvas.variantsStart))*100); // Draw.updatevars = true; linecounter = pos; if(search) { if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } } } /* if(first) { info = split[split.length-1].split(":"); if(info[0].length() == 1 || info[0].charAt(0) == '0' && info[0].charAt(2) =='0') { info = split[split.length-2].split(":"); sample.infolocation = (short)(split.length-2); } else { sample.infolocation = (short)(split.length-1); } } else { */ //} if(sample.somaticColumn != null) { if(sample.somaticColumn > split.length-1) { sample.somaticColumn = null; info = split[split.length-1].split(":"); } else { info = split[sample.somaticColumn].split(":"); } } else { info = split[split.length-1].split(":"); } noref = false; multi = false; HashMap<String, Integer> infofield = new HashMap<String, Integer>(); if(split.length > 8) { String[] infos = split[8].split(":"); for(int i = 0; i<infos.length; i++) { infofield.put(infos[i], i); } } if(infofield.containsKey("GT")) { gtindex = infofield.get("GT"); if(info[gtindex].contains(".")) { return; } if(info[gtindex].contains("|")) { firstallele = Short.parseShort(""+info[gtindex].split("|")[0]); secondallele = Short.parseShort(""+info[gtindex].split("|")[2]); } else { firstallele = Short.parseShort(""+info[gtindex].split("/")[0]); secondallele = Short.parseShort(""+info[gtindex].split("/")[1]); } genotype = firstallele == secondallele; if(genotype && firstallele == 0) { return; } if(infofield.containsKey("AD")) { if(infofield.containsKey("RD")) { calls1 = Integer.parseInt(info[infofield.get("RD")]); try { if(info[infofield.get("AD")].contains(",")) { calls2 = Integer.parseInt(info[infofield.get("AD")].split(",")[1]); } else { calls2 = Integer.parseInt(info[infofield.get("AD")]); } } catch(Exception e) { System.out.println(info[infofield.get("AD")]); e.printStackTrace(); } } else { coverages = info[infofield.get("AD")].split(","); if(genotype) { calls1 = Integer.parseInt(coverages[0]); } else { try { calls1 = Integer.parseInt(coverages[firstallele]); } catch(Exception ex) { calls1 = Integer.parseInt(coverages[coverages.length-1]); //System.out.println(split[3] +" " +split[4] +" " +split[8] +" " +split[9] +" " +split[10]); } } try { calls2 = Integer.parseInt(coverages[secondallele]); } catch(Exception ex) { calls2 = Integer.parseInt(coverages[coverages.length-1]); //System.out.println(split[3] +" " +split[4] +" " +split[8] +" " +split[9] +" " +split[10]); } } if(!genotype) { if(firstallele == 0) { refallele = firstallele; refcalls = calls1; altallele = secondallele; altcalls = calls2; } else if(secondallele == 0){ refallele = secondallele; refcalls = calls2; altallele = firstallele; altcalls = calls1; } else { noref = true; refallele = firstallele; refcalls = calls1; altallele = secondallele; altcalls = calls2; } } else { try { refcalls =calls1; // Short.parseShort(info[split[8].indexOf("AD")/3].split(",")[0]); altallele = secondallele; altcalls = calls2; } catch(Exception e) { for(int i = 0 ; i<split.length; i++) { System.out.print(split[i] +"\t"); } System.out.println(); e.printStackTrace(); } } } else if (split[7].contains("DP4")) { coverages = split[7].substring(split[7].indexOf("DP4")+4).split(";")[0].split(","); refallele = firstallele; altallele = secondallele; refcalls = Integer.parseInt(coverages[0])+Integer.parseInt(coverages[1]); altcalls = Integer.parseInt(coverages[2])+Integer.parseInt(coverages[3]); } else { if(firstallele == 0) { refallele = firstallele; altallele = secondallele; } else if(secondallele == 0){ refallele = secondallele; altallele = firstallele; } else { refallele = firstallele; altallele = secondallele; } refcalls = 20; altcalls = 20; } } else { refcalls = 20; altcalls = 20; } if(!split[4].contains(",")) { altbase = getVariant(split[3], split[4]); } else if(!noref){ if (altallele > 0) { altbase = getVariant(split[3], split[4].split(",")[altallele-1]); } else { altbase = getVariant(split[3], split[4].split(",")[0]); multi = true; } } else { altbase = getVariant(split[3], split[4].split(",")[altallele-1]); altbase2 = getVariant(split[3], split[4].split(",")[refallele-1]); } quality = null; if(split.length > 8 && split[8].contains("Q")) { if(infofield.containsKey("GQ") && !info[infofield.get("GQ")].equals(".")) { gq = (float)Double.parseDouble(info[infofield.get("GQ")]); } else if(infofield.containsKey("BQ") && !info[infofield.get("BQ")].equals(".")) { quality = (float)Double.parseDouble(info[infofield.get("BQ")]); } else if(split[7].contains("SSC")) { quality = Float.parseFloat(split[7].substring(split[7].indexOf("SSC") +4).split(";")[0]); } } if(quality == null) { if(split.length > 5 && split[5].matches("\\d+.?.*")) { quality = (float)Double.parseDouble(split[5]); } } HashMap<String, Float> advancedQualities = null; if(VariantHandler.freeze.isSelected()) { if(!sample.annoTrack) { if(refcalls+altcalls < VariantHandler.coverageSlider.getValue()) { return; } if(quality != null && quality < VariantHandler.qualitySlider.getValue()) { return; } if(gq != null && gq < VariantHandler.gqSlider.getValue()) { return; } if(altcalls/(double)(refcalls+altcalls) < VariantHandler.callSlider.getValue()/100.0) { return; } } if(!sample.annotation) { if(VariantHandler.hideSNVs.isSelected() && altbase.length() == 1) { return; } if(VariantHandler.hideIndels.isSelected() && altbase.length() > 1) { return; } if(VariantHandler.rscode.isSelected() && !split[2].equals(".")) { return; } } } if(!sample.annoTrack) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { return; } } if(refcalls+altcalls > VariantHandler.maxCoverageSlider.getMaximum()) { VariantHandler.maxCoverageSlider.setMaximum(refcalls+altcalls); VariantHandler.maxCoverageSlider.setValue(refcalls+altcalls); } } while(current != null && current.getNext() != null && current.getPosition() < pos ){ current = current.getNext(); } if(current.getNext() == null && current.getPosition() < pos) { try { if(!split[2].equals(".")) { current.putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase,refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, split[2], sample, current, null)); } else { current.putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase,refcalls+altcalls, altcalls, genotype, quality, gq, advancedQualities, null, sample, current, null)); } if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.getNext().addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } if(multi) { String[] altsplit = split[4].split(","); for(int i = 1; i<altsplit.length; i++) { altbase = getVariant(split[3],altsplit[i]); if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { continue; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { continue; } } current.getNext().addSample(altbase, refcalls+altcalls, refcalls, genotype, quality, gq,advancedQualities, sample); } } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); //Main.drawCanvas.ready("all"); } } else if(current.getPosition() == pos) { current.addSample(altbase, refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, sample); if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } if(current.isRscode() == null && !split[2].equals(".")) { current.setRscode(split[2]); } if(multi) { String[] altsplit = split[4].split(","); for(int i = 1; i<altsplit.length; i++) { altbase = getVariant(split[3],altsplit[i]); if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { continue; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { continue; } } try { current.getNext().addSample(altbase, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } catch(Exception e) { System.out.println(current.getChrom() +":" +current.getPosition()); } } } } else if(current.getPosition() > pos) { if(!split[2].equals(".")) { current.getPrev().putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, split[2], sample, current.getPrev(), current)); } else { if(current.getPrev() == null) { System.out.println(current.getPosition()); Main.cancel(); } current.getPrev().putNext(new VarNode(pos, (byte)split[3].charAt(0), altbase, refcalls+altcalls, altcalls, genotype, quality, gq,advancedQualities, null, sample, current.getPrev(), current)); } current.putPrev(current.getPrev().getNext()); current = current.getPrev(); if(noref ) { if(split.length > 6) { if(checkAdvFilters(split[6], altbase2.length() > 1)) { return; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase2.length() > 1)) { return; } } current.addSample(altbase2, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } if(multi) { String[] altsplit = split[4].split(","); for(int i = 1; i<altsplit.length; i++) { altbase = getVariant(split[3],altsplit[i]); if(split.length > 6) { if(checkAdvFilters(split[6], altbase.length() > 1)) { continue; } } if(split.length > 7) { if(checkAdvQuals(split[7], altbase.length() > 1)) { continue; } } current.addSample(altbase, refcalls+altcalls, refcalls, genotype, quality, gq, advancedQualities, sample); } } } } catch(Exception ex) { //System.out.println(split[8] +" " +split[10] +" " +split[3] +" " +split[4]); ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); } } /* File getListFile(File listfile, String chrom) { try { if(!listfile.exists()) { return new File(listfile.getCanonicalPath().replace(".list", ".cram")); } BufferedReader reader = new BufferedReader(new FileReader(listfile)); String mnt = "/mnt"; if(!listfile.getAbsolutePath().startsWith("/mnt")) { if(listfile.getAbsolutePath().indexOf("\\cg") < 0) { if(listfile.getAbsolutePath().indexOf("/cg") > -1) { mnt = listfile.getAbsolutePath().substring(0,listfile.getAbsolutePath().indexOf("/cg")); } else { mnt = "X:"; } } else { mnt = listfile.getAbsolutePath().substring(0,listfile.getAbsolutePath().indexOf("\\cg")); } } String listline; while((listline = reader.readLine()) != null) { if(Main.selectedChrom > 24) { if(listline.contains("_" +"GL" +".")) { reader.close(); return new File(listline.replace("/mnt", mnt)); } } else if(listline.contains("_" +chrom +".")) { reader.close(); return new File(listline.replace("/mnt", mnt)); } } reader.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } return null; }*/ static String getVariant(String ref, String alt) { if(ref.length() == 1 && alt.length() == 1) { return alt; } else if (ref.length() == 1 || alt.length() == 1) { if(ref.length() == 2) { return "del" +ref.substring(1); } else if(alt.length() >= 2) { return "ins" +alt.substring(1); } else { return "del" +(ref.length()-1); } } else if(alt.length() == ref.length()) { if(ref.contains("-")) { return getVariant(ref, ""+alt.charAt(0)); } else if(alt.contains("-")) { return getVariant(ref, ""+alt.replaceAll("-", "")); } else { return "" +alt.charAt(0); } } else { if(ref.length() < alt.length()) { return "ins" +alt.substring(1, alt.length()-(ref.length()-1)); } else { if(ref.length() -alt.length() == 1) { return "del" +ref.substring(1, ref.length()-(alt.length()-1)); } else { return "del" +(ref.length() -alt.length()); } } } } void addToSequence(SplitClass split, StringBuffer buffer, int length) { /* if(length < 0) { buffer.insert(0, Main.chromDraw.getSeq(split.chrom, (int)(split.readSeqStart-length)-1, split.readSeqStart, Main.referenceFile)); split.readSeqStart = (int)(split.readSeqStart-length)-1; if(split.readSeqStart < 0) { split.readSeqStart = 0; } readSeqStart = split.readSeqStart; } else { split.readSequence.append(Main.chromDraw.getSeq(split.chrom, split.readSeqStart+split.readSequence.length(), (int)(split.readSeqStart+split.readSequence.length()+length+200), Main.referenceFile)); } */ } Iterator<SAMRecord> getBamIterator(Reads readClass, String chrom, int startpos, int endpos) { try { if(samFileReader != null) { samFileReader.close(); } if(CRAMReader != null) { CRAMReader.close(); } if(readClass.sample.CRAM) { CRAMReader = new CRAMFileReader(readClass.sample.samFile, new File(readClass.sample.samFile.getCanonicalFile() +".crai"),new ReferenceSource(Main.ref),/*Main.referenceFile, */ValidationStringency.SILENT); if(CRAMReader != null && !CRAMReader.hasIndex()) { Main.showError("Index file is missing (.crai) for " +readClass.sample.samFile.getName(), "Note"); return null; } } else { try { samFileReader = SamReaderFactory.make().open(readClass.sample.samFile); //samFileReader = new SAMFileReader(readClass.sample.samFile); if(samFileReader != null && !samFileReader.hasIndex()) { Main.showError("Index file is missing (.bai) for " +readClass.sample.samFile.getName(), "Note"); return null; } } catch(Exception e) { Main.showError(e.getMessage(), "Note"); e.printStackTrace(); } } } catch(Exception e) { if(readClass.sample.CRAM) { if(CRAMReader != null && !CRAMReader.hasIndex()) { Main.showError("Index file is missing (.crai) for " +readClass.sample.samFile.getName(), "Note"); return null; } } else { if(samFileReader != null && !samFileReader.hasIndex()) { Main.showError("Index file is missing (.bai) for " +readClass.sample.samFile.getName(), "Note"); return null; } } e.printStackTrace(); } try { if(readClass.sample.CRAM) { if(!readClass.sample.chrSet) { if(CRAMReader.getFileHeader().getSequence(0).getSAMString().contains("chr")) { readClass.sample.chr = "chr"; } readClass.sample.chrSet = true; } QueryInterval[] interval = { new QueryInterval(CRAMReader.getFileHeader().getSequence(readClass.sample.chr+chrom).getSequenceIndex(), startpos, endpos) }; Iterator<SAMRecord> value = CRAMReader.query(interval, false); return value; } else { Iterator<SAMRecord> value = null; // SAMReadGroupRecord record = new SAMReadGroupRecord("fixed_My6090N_sorted"); // samFileReader.getFileHeader().addReadGroup(record); try { //SAMFileReader.setDefaultValidationStringency(ValidationStringency.SILENT); if(!readClass.sample.chrSet) { if(samFileReader.getFileHeader().getSequence(0).getSAMString().contains("chr")) { readClass.sample.chr = "chr"; } readClass.sample.chrSet = true; } value = samFileReader.queryOverlapping(readClass.sample.chr+chrom, startpos, endpos); } catch(htsjdk.samtools.SAMFormatException e) { e.printStackTrace(); } return value; } } catch(Exception e) { try { if(readClass.sample.CRAM) { e.printStackTrace(); /*if(CRAMReader.getFileHeader().getSequence(readClass.sample.chr + "M") != null) { QueryInterval[] interval = { new QueryInterval(CRAMReader.getFileHeader().getSequence(readClass.sample.chr + "M").getSequenceIndex(), startpos, endpos) }; } Iterator<SAMRecord> value = CRAMReader.query(interval, false); if(!readClass.sample.chrSet) { if(!value.hasNext()) { QueryInterval[] interval2 = { new QueryInterval(CRAMReader.getFileHeader().getSequence("chrM").getSequenceIndex(), startpos, endpos) }; value = CRAMReader.query(interval2, false); if(value.hasNext()) { readClass.sample.chr = "chr"; readClass.sample.chrSet = true; } } else { readClass.sample.chrSet = true; } }*/ return null; //return value; } else { Iterator<SAMRecord> value = samFileReader.queryOverlapping(readClass.sample.chr+"M", startpos, endpos); if(!readClass.sample.chrSet) { if(!value.hasNext()) { value = samFileReader.queryOverlapping("chrM", startpos, endpos); if(value.hasNext()) { readClass.sample.chr = "chr"; readClass.sample.chrSet = true; } } else { readClass.sample.chrSet = true; } } return value; } } catch(Exception ex) { ex.printStackTrace(); ErrorLog.addError(e.getStackTrace()); return null; } } } public SAMRecord getRead(String chrom, int startpos, int endpos, String name, Reads readClass) { Iterator<SAMRecord> bamIterator = getBamIterator(readClass,chrom,startpos-1, endpos); SAMRecord samRecord = null; while(bamIterator != null && bamIterator.hasNext()) { try { samRecord = bamIterator.next(); if(samRecord.getUnclippedStart() < startpos) { continue; } if(samRecord.getUnclippedStart() == startpos && samRecord.getReadName().equals(name)) { return samRecord; } } catch(Exception e) { e.printStackTrace(); } } return null; } public ArrayList<ReadNode> getReads(String chrom, int startpos, int endpos, Reads readClass, SplitClass split) { // ReadAdder readrunner = null; try { //Sample sample = readClass.sample; if(Main.drawCanvas.drawVariables.sampleHeight > 100) { if(viewLength > Settings.readDrawDistance) { if(firstCov || readClass.getCoverageStart() == 0 || (readClass.getCoverageStart() < startpos && readClass.getCoverageEnd() > endpos) || (readClass.getCoverageStart() > startpos && readClass.getCoverageEnd() < endpos) ) { double[][] coverages = new double[(int)Main.frame.getWidth()][8]; readClass.setCoverages(coverages); readClass.setMaxcoverage(1); readClass.setCoverageStart(startpos); oldstart = endpos; readClass.setCoverageEnd(endpos); bamIterator = getBamIterator(readClass,chrom,startpos, endpos); firstCov = false; } else if(readClass.getCoverageStart() > startpos) { /* int[][] coverages = new int[(int)(readClass.getCoverages().length +((readClass.getCoverageStart()-startpos)*pixel))][8]; pointer = coverages.length-1; for(int i = readClass.getCoverages().length-1; i>=0; i--) { coverages[pointer][0] = readClass.getCoverages()[i][0]; pointer--; } left = true; oldstart = readClass.getCoverageStart(); bamIterator = getBamIterator(readClass,readClass.sample.chr + chrom,startpos, readClass.getCoverageStart()); readClass.setCoverageStart(startpos); readClass.setCoverages(coverages); */ double[][] coverages = new double[(int)Main.frame.getWidth()][8]; readClass.setCoverages(coverages); readClass.setMaxcoverage(1); bamIterator = getBamIterator(readClass,chrom,startpos, endpos); // readClass.setReadEnd(endpos); readClass.setCoverageStart(startpos); readClass.setCoverageEnd(endpos); oldstart = endpos; } else if(readClass.getCoverageEnd() < endpos) { double[][] coverages = new double[(int)Main.frame.getWidth()][8]; readClass.setCoverages(coverages); readClass.setMaxcoverage(1); bamIterator = getBamIterator(readClass,chrom,startpos, endpos); // readClass.setReadEnd(endpos); readClass.setCoverageStart(startpos); readClass.setCoverageEnd(endpos); oldstart = endpos; } else { return null; } } else { firstCov = true; if(readClass.getReads().isEmpty()) { right = false; left = false; if(!chrom.contains("M")) { searchwindow = viewLength +readClass.sample.longestRead; } else { searchwindow = 0; } /*if(firstSample) { splitIndex.setReference(new ReferenceSeq(splitIndex.chrom,startpos-searchwindow-1, endpos+searchwindow +200, Main.referenceFile)); }*/ try { bamIterator = getBamIterator(readClass,chrom,startpos-searchwindow, endpos+searchwindow ); } catch(Exception e) { e.printStackTrace(); /* try { } catch(java.lang.IllegalArgumentException ex) { readClass.loading = false; System.out.println("Chromosome " +chrom +" not found in " +readClass.sample.samFile.getName()); ErrorLog.addError(ex.getStackTrace()); return null; } */ } startpos = startpos - searchwindow; endpos = endpos + searchwindow; if(startpos < 1) { startpos = 1; } readClass.setCoverageStart(startpos); readClass.startpos = startpos; readClass.endpos = endpos; readClass.setReadStart(startpos); readClass.setReadEnd(endpos); if(splitIndex.getMinReadStart() > startpos) { splitIndex.setMinReadStart(startpos); } if(splitIndex.getMaxReadEnd() < endpos) { splitIndex.setMaxReadEnd(endpos); } double[][] coverages = new double[endpos-startpos+searchwindow*2][8]; readClass.setCoverageEnd(startpos + coverages.length); readClass.setCoverages(coverages); readClass.setMaxcoverage(1); } else if(!readClass.getReads().isEmpty() && readClass.getReadStart() /*(readClass.getFirstRead().getPosition()*/ < startpos && readClass.getReadEnd() /*readClass.getLastRead().getPosition()*/ > endpos){ left = false; right = false; if(!chrom.contains("M")) { searchwindow = viewLength +readClass.sample.longestRead; } else { searchwindow = 0; } return readClass.getReads(); } else if(readClass.getLastRead() != null && readClass.getReadEnd() < endpos) { if(!chrom.contains("M")) { searchwindow = viewLength; } else { searchwindow = 0; } right = true; left = false; startpos = readClass.getReadEnd(); endpos = endpos+searchwindow; addlength = 1000; // readClass.reference.append( endpos+200); /*if(firstSample) { System.out.println("jhou"); //if(splitIndex.getReadReference() == null) { splitIndex.setReference(new ReferenceSeq(splitIndex.chrom,startpos-searchwindow-1, endpos+searchwindow +200, Main.referenceFile)); // } //else { // splitIndex.getReadReference().append( endpos+200); // } }*/ bamIterator = getBamIterator(readClass,chrom,startpos, endpos ); if(readClass.getCoverageEnd() < endpos) { if(searchwindow < 1000) { addlength = 2000; } else if(searchwindow < 10000) { addlength = 20000; } else { addlength = 200000; } } double[][] coverages = new double[(int)(readClass.getCoverages().length +(addlength))][8]; for(int i =0; i<readClass.getCoverages().length; i++) { coverages[i][0] = readClass.getCoverages()[i][0]; coverages[i][1] = readClass.getCoverages()[i][1]; coverages[i][2] = readClass.getCoverages()[i][2]; coverages[i][3] = readClass.getCoverages()[i][3]; coverages[i][4] = readClass.getCoverages()[i][4]; coverages[i][5] = readClass.getCoverages()[i][5]; coverages[i][6] = readClass.getCoverages()[i][6]; coverages[i][7] = readClass.getCoverages()[i][7]; } readClass.endpos = endpos; if(splitIndex.getMaxReadEnd() < endpos) { splitIndex.setMaxReadEnd(endpos); } readClass.setReadEnd(endpos); readClass.setCoverageEnd(readClass.getCoverageStart()+coverages.length); readClass.setCoverages(coverages); } else if(readClass.getFirstRead() != null && readClass.getFirstRead().getPosition() > startpos) { left = true; right = false; if(!chrom.contains("M")) { searchwindow = viewLength+readClass.sample.longestRead; } else { searchwindow = 0; } endpos = readClass.getReadStart(); startpos = startpos-searchwindow; /* if(firstSample) { splitIndex.getReadReference().appendToStart( startpos-1); }*/ bamIterator = getBamIterator(readClass,chrom,startpos, endpos+100 ); addlength = 0; if(searchwindow < 1000) { addlength = 2000; } else if(searchwindow < 10000) { addlength = 20000; } else { addlength = 200000; } double[][] coverages = new double[(int)(readClass.getCoverages().length +addlength)][8]; readClass.setCoverageStart(readClass.getCoverageStart()-addlength); pointer = coverages.length-1; for(int i = readClass.getCoverages().length-1; i>=0; i--) { coverages[pointer][0] = readClass.getCoverages()[i][0]; coverages[pointer][1] = readClass.getCoverages()[i][1]; coverages[pointer][2] = readClass.getCoverages()[i][2]; coverages[pointer][3] = readClass.getCoverages()[i][3]; coverages[pointer][4] = readClass.getCoverages()[i][4]; coverages[pointer][5] = readClass.getCoverages()[i][5]; coverages[pointer][6] = readClass.getCoverages()[i][6]; coverages[pointer][7] = readClass.getCoverages()[i][7]; pointer--; } left = true; readClass.startpos = startpos; readClass.setReadStart(startpos); if(splitIndex.getMinReadStart() > startpos) { splitIndex.setMinReadStart(startpos); } readClass.setCoverages(coverages); } } coverageArray = readClass.getCoverages(); if(readClass.getReadStart() == null) { readClass.setReadStart(startpos); } while(bamIterator != null && bamIterator.hasNext()) { try { if(cancelreadread || !Main.drawCanvas.loading ||readClass.sample.getIndex() < Main.drawCanvas.drawVariables.visiblestart || readClass.sample.getIndex() > Main.drawCanvas.drawVariables.visiblestart + Main.drawCanvas.drawVariables.visiblesamples) { return null; } try { samRecord = bamIterator.next(); } catch(htsjdk.samtools.SAMFormatException ex) { ex.printStackTrace(); } if(samRecord.getReadUnmappedFlag()) { continue; } if(Draw.variantcalculator) { if(readClass.getHeadAndTail().size() > Settings.readDepthLimit) { break; } } //TODO jos on pienempi ku vika unclipped start if(samRecord.getUnclippedEnd() < startpos) { //this.readSeqStart+1) { continue; } if(samRecord.getUnclippedStart() >= endpos){ Main.drawCanvas.loadBarSample = 0; Main.drawCanvas.loadbarAll =0; break; } if(readClass.sample.longestRead <samRecord.getCigar().getReferenceLength()) { readClass.sample.longestRead = samRecord.getCigar().getReferenceLength(); } if(readClass.sample.getComplete() == null) { if(samRecord.getReadName().startsWith("GS")) { readClass.sample.setcomplete(true); } else { readClass.sample.setcomplete(false); } } if(viewLength < Settings.readDrawDistance) { /* if(splitIndex.reference == null) { splitIndex.reference = new ReferenceSeq(chrom, samRecord.getUnclippedStart()-2000, end+1000, Main.referenceFile); } else if(samRecord.getUnclippedStart()-1 < splitIndex.reference.getStartPos()) { splitIndex.reference.appendToStart(samRecord.getUnclippedStart()-1); } else if(samRecord.getUnclippedEnd() > splitIndex.reference.getEndPos()) { splitIndex.reference.append(samRecord.getUnclippedEnd()); } */ if(samRecord.getUnclippedEnd() > readClass.getCoverageEnd()-1) { double[][] coverages = new double[(int)(readClass.getCoverages().length +(samRecord.getUnclippedEnd()-samRecord.getUnclippedStart() + (int)splitIndex.viewLength))][8]; //pointer = coverages.length-1; for(int i =0; i<readClass.getCoverages().length; i++) { coverages[i][0] = readClass.getCoverages()[i][0]; coverages[i][1] = readClass.getCoverages()[i][1]; coverages[i][2] = readClass.getCoverages()[i][2]; coverages[i][3] = readClass.getCoverages()[i][3]; coverages[i][4] = readClass.getCoverages()[i][4]; coverages[i][5] = readClass.getCoverages()[i][5]; coverages[i][6] = readClass.getCoverages()[i][6]; coverages[i][7] = readClass.getCoverages()[i][7]; // pointer--; } readClass.setCoverageEnd(readClass.getCoverageStart()+coverages.length); readClass.setCoverages(coverages); coverageArray = readClass.getCoverages(); } else if(samRecord.getUnclippedStart() > 0 && samRecord.getUnclippedStart() < readClass.getCoverageStart() ) { /* double[][] coverages = null; if(readClass.getCoverageStart()-(readClass.getCoverageStart()-samRecord.getUnclippedStart())-1000 < 1) { coverages = new double[(int)(readClass.getCoverages().length + readClass.getCoverageStart())][8]; readClass.setCoverageStart(1); } else { coverages = new double[(int)(readClass.getCoverages().length + (readClass.getCoverageStart()-samRecord.getUnclippedStart())+1000)][8]; readClass.setCoverageStart(readClass.getCoverageStart()-(readClass.getCoverageStart()-samRecord.getUnclippedStart())-1000); } pointer = coverages.length-1; for(int i = readClass.getCoverages().length-1; i>=0; i--) { coverages[pointer][0] = readClass.getCoverages()[i][0]; coverages[pointer][1] = readClass.getCoverages()[i][1]; coverages[pointer][2] = readClass.getCoverages()[i][2]; coverages[pointer][3] = readClass.getCoverages()[i][3]; coverages[pointer][4] = readClass.getCoverages()[i][4]; coverages[pointer][5] = readClass.getCoverages()[i][5]; coverages[pointer][6] = readClass.getCoverages()[i][6]; coverages[pointer][7] = readClass.getCoverages()[i][7]; pointer--; } readClass.setCoverages(coverages); */ } } if(((viewLength < Settings.readDrawDistance && samRecord.getUnclippedStart() >= startpos) || (viewLength >= Settings.readDrawDistance && samRecord.getUnclippedEnd() >= startpos)) && samRecord.getUnclippedStart() <= endpos) { java.util.ArrayList<java.util.Map.Entry<Integer,Byte>> mismatches = null; if(samRecord.getMappingQuality() >= Settings.mappingQ) { if(viewLength > Settings.readDrawDistance) { if( Main.drawCanvas.loadBarSample != (int)(((samRecord.getUnclippedStart()-startpos)/(double)(oldstart-startpos))*100) ) { Main.drawCanvas.loadBarSample = (int)(((samRecord.getUnclippedStart()-startpos)/(double)(oldstart-startpos))*100); Main.drawCanvas.loadbarAll = (int)(((samRecord.getUnclippedStart()-startpos)/(double)(oldstart-startpos))*100); } for(int i = 0; i<(int)(samRecord.getReadLength()*splitIndex.pixel +1); i++) { if((samRecord.getUnclippedStart()-start)*splitIndex.pixel +i < 0) { continue; } if((samRecord.getUnclippedStart()-start)*splitIndex.pixel + i > coverageArray.length-1) { break; } if(samRecord.getReadLength()*splitIndex.pixel >= 1) { coverageArray[(int)((samRecord.getUnclippedStart()-start)*splitIndex.pixel+i)][0]+=(1/splitIndex.pixel); } else { coverageArray[(int)((samRecord.getUnclippedStart()-start)*splitIndex.pixel+i)][0]+=samRecord.getReadLength(); } if(coverageArray[(int)((samRecord.getUnclippedStart()-start)*splitIndex.pixel+i)][0]/*pixel*/ > readClass.getMaxcoverage()) { readClass.setMaxcoverage((coverageArray[(int)((samRecord.getUnclippedStart()-start)*splitIndex.pixel+i)][0]/*pixel*/)); } } } else { if( Main.drawCanvas.loadBarSample != (int)(((samRecord.getUnclippedStart()-startpos)/(double)(endpos-startpos))*100) ) { Main.drawCanvas.loadBarSample = (int)(((samRecord.getUnclippedStart()-startpos)/(double)(endpos-startpos))*100); Main.drawCanvas.loadbarAll = (int)(((samRecord.getUnclippedStart()-startpos)/(double)(endpos-startpos))*100); } } } if(viewLength <= Settings.readDrawDistance) { if(right && readClass.getLastRead() != null && (samRecord.getUnclippedStart() <= startpos)) { continue; } if(right && samRecord.getUnclippedStart() > endpos) { right = false; } try { mismatches = getMismatches(samRecord, readClass, coverageArray, split); } catch(Exception e) { e.printStackTrace(); } if(left) { if(readClass.getFirstRead().getPosition() > samRecord.getUnclippedStart()) { ReadNode addNode = new ReadNode(samRecord, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); readClass.setFirstRead(addNode); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-(readClass.readHeight+2))); addNode.setPrev(null); addNode.setNext(readClass.getHeadAndTail().get(0)[headnode]); readClass.getHeadAndTail().get(0)[headnode].setPrev(addNode); lastAdded = addNode; } else { ReadNode addNode = new ReadNode(samRecord, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-(readClass.readHeight+2))); addNode.setPrev(lastAdded); addNode.setNext(lastAdded.getNext()); lastAdded.setNext(addNode); lastAdded = addNode; readClass.getHeadAndTail().get(0)[headnode].setPrev(addNode); addNode.setNext(readClass.getHeadAndTail().get(0)[headnode]); } } else { try { if(samRecord.getAlignmentEnd() >= readClass.getCoverageEnd()) { coverageArray = coverageArrayAdd(readClass.sample.longestRead*2, coverageArray); } readSam(chrom, readClass, samRecord, mismatches); } catch(Exception e) { System.out.println(samRecord +" " +currentread); e.printStackTrace(); break; } } } } else { continue; } } catch(Exception e) { if(readClass.getReadStart() > startpos) { readClass.setReadStart(startpos); } if(readClass.getReadEnd() < endpos) { readClass.setReadEnd(endpos); } ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); break; } } if(left) { Main.drawCanvas.loadBarSample = 0; Main.drawCanvas.loadbarAll =0; setLevels(lastAdded, readClass.sample, readClass); lastAdded = null; } } } catch(Exception ex) { if(readClass == null) { sample.resetreadHash(); } if(readClass.getReadStart() == null) { readClass.setReadStart(startpos); } else if(readClass.getReadStart() > startpos) { readClass.setReadStart(startpos); } if(readClass.getReadEnd() < endpos) { readClass.setReadEnd(endpos); } ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); return null; // readrunner.end = true; } return null; } double[][] coverageArrayAdd(int addlength, double[][] coverageArray) { double[][] coverages = new double[(int)(coverageArray.length +(addlength)+1000)][8]; //pointer = coverages.length-1; for(int i =0; i<coverageArray.length; i++) { coverages[i][0] = coverageArray[i][0]; coverages[i][1] = coverageArray[i][1]; coverages[i][2] = coverageArray[i][2]; coverages[i][3] = coverageArray[i][3]; coverages[i][4] = coverageArray[i][4]; coverages[i][5] = coverageArray[i][5]; coverages[i][6] = coverageArray[i][6]; coverages[i][7] = coverageArray[i][7]; } Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; readClass.setCoverageEnd(readClass.getCoverageStart()+coverages.length); readClass.setCoverages(coverages); return coverages; } VariantCall[][] coverageArrayAdd(int addlength, VariantCall[][] coverageArray, Reads readClass) { VariantCall[][] coverages = new VariantCall[(int)(coverageArray.length +(addlength)+1000)][8]; //pointer = coverages.length-1; for(int i =0; i<coverageArray.length; i++) { coverages[i][0] = coverageArray[i][0]; coverages[i][1] = coverageArray[i][1]; coverages[i][2] = coverageArray[i][2]; coverages[i][3] = coverageArray[i][3]; coverages[i][4] = coverageArray[i][4]; coverages[i][5] = coverageArray[i][5]; coverages[i][6] = coverageArray[i][6]; coverages[i][7] = coverageArray[i][7]; } //Main.drawCanvas.loadbarAll = 0; // Main.drawCanvas.loadBarSample= 0; readClass.setCoverageEnd(readClass.getCoverageStart()+coverages.length); //readClass.setCoverages(coverages); return coverages; } java.util.ArrayList<java.util.Map.Entry<Integer,Byte>> getMismatches(SAMRecord samRecord, Reads readClass, double[][] coverageArray, SplitClass split) { if(readClass == null) { sample.resetreadHash(); } java.util.ArrayList<java.util.Map.Entry<Integer,Byte>> mismatches = null; String MD = samRecord.getStringAttribute("MD"); String SA = samRecord.getStringAttribute("SA"); if(samRecord.getReadBases().length == 0) { return null; } try { if(MD == null) { if(readClass.sample.MD) { readClass.sample.MD = false; } } if((readClass.sample.MD || MD!=null) && (samRecord.getCigarString().contains("S") && Settings.softClips == 0)/* && ((!samRecord.getCigarString().contains("S") && SA == null) || SA !=null)*/) { /*if(samRecord.getReadName().contains("1104:8947:11927")) { System.out.println(readClass.sample.MD +" " +MD +" " +samRecord.getCigarString().contains("S") +" " +Settings.softClips); }*/ if(!readClass.sample.MD) { readClass.sample.MD = true; } java.util.ArrayList<java.util.Map.Entry<Integer,Integer>> insertions = null; int softstart = 0; if(samRecord.getCigarLength() > 1) { readstart = samRecord.getUnclippedStart(); if(readClass.getCoverageStart()>readstart) { return null; } readpos= 0; for(int i = 0; i<samRecord.getCigarLength(); i++) { element = samRecord.getCigar().getCigarElement(i); if(element.getOperator().compareTo(CigarOperator.MATCH_OR_MISMATCH)== 0) { for(int r = readpos; r<readpos+element.getLength(); r++) { try { coverageArray[((readstart+r)-readClass.getCoverageStart())][0]++; } catch(Exception e) { //TODO } try { if(coverageArray[((readstart+r)-readClass.getCoverageStart())][0] > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverageArray[((readstart+r)-readClass.getCoverageStart())][0]); } } catch(Exception e) { //TODO } mispos++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.DELETION)== 0) { for(int d = 0; d<element.getLength(); d++) { readClass.getCoverages()[(readstart+readpos+d)- readClass.getCoverageStart()][Main.baseMap.get((byte)'D')]++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.INSERTION)== 0) { if(insertions == null) { insertions = new java.util.ArrayList<java.util.Map.Entry<Integer,Integer>>(); } java.util.Map.Entry<Integer, Integer> ins = new java.util.AbstractMap.SimpleEntry<>(readpos, element.getLength()); insertions.add(ins); readClass.getCoverages()[(readstart+readpos)- readClass.getCoverageStart()][Main.baseMap.get((byte)'I')]++; mispos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.SOFT_CLIP)== 0 ) { if(i==0 && SA == null) { softstart = element.getLength(); } if(Settings.softClips == 1) { for(int r = readpos; r<readpos+element.getLength(); r++) { if(SA == null) { coverageArray[((readstart+r)-readClass.getCoverageStart())][0]++; } mispos++; } readpos+=element.getLength(); } else { if(i == 0) { readstart = samRecord.getAlignmentStart(); mispos+=element.getLength(); } } } else if (element.getOperator().compareTo(CigarOperator.HARD_CLIP)== 0) { if(i == 0) { readstart = samRecord.getAlignmentStart(); } } else if(element.getOperator().compareTo(CigarOperator.SKIPPED_REGION)== 0) { readpos+=element.getLength(); } } } else { readstart = samRecord.getUnclippedStart(); for(int i = 0; i<samRecord.getReadLength(); i++) { try { if(readClass.getCoverageStart()>readstart) { break; } coverageArray[(readstart+i)-readClass.getCoverageStart()][0]++; if(coverageArray[(samRecord.getUnclippedStart()-readClass.getCoverageStart())+i][0] > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverageArray[(samRecord.getUnclippedStart()-readClass.getCoverageStart())+i][0]); } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); FileRead.cancelreadread = true; break; } } } if(MD != null) { try { Integer.parseInt(MD); return null; } catch(Exception ex) { readstart = samRecord.getAlignmentStart()-softstart; char[] chars = MD.toCharArray(); String bases = samRecord.getReadString(); String qualities = samRecord.getBaseQualityString(); if(SA == null) { softstart = 0; } int readpos = softstart; int mispos = softstart; int add =0; int digitpointer = 0, insertionpointer = 0; boolean first = true; for(int i = 0; i<chars.length; i++) { try { if(insertions != null) { if(insertionpointer < insertions.size() && insertions.get(insertionpointer).getKey() <= readpos) { while(insertionpointer < insertions.size() && insertions.get(insertionpointer).getKey() <= readpos) { mispos+=insertions.get(insertionpointer).getValue(); insertionpointer++; } } } if(Character.isDigit(chars[i])) { digitpointer = i+1; while(digitpointer < chars.length && Character.isDigit(chars[digitpointer])) { digitpointer++; } if(digitpointer== chars.length) { //System.out.println(MD.substring(i)); if((mispos +Integer.parseInt(MD.substring(i,digitpointer))) > samRecord.getReadLength()) { if(!first) { break; } first = false; readpos = 0; mispos = 0; i = -1; digitpointer = 0; insertionpointer = 0; mismatches.clear(); continue; } break; } else { add = Integer.parseInt(MD.substring(i,digitpointer)); readpos += add; mispos += add; } i = digitpointer-1; } else if(chars[i] != '^') { if(mismatches == null) { mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer,Byte>>(); } readClass.getCoverages()[(readstart+readpos)- readClass.getCoverageStart()][Main.baseMap.get((byte)bases.charAt(mispos))]++; if(samRecord.getBaseQualityString().length() != 1 && (int)qualities.charAt(mispos)-readClass.sample.phred < Settings.baseQ) { java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(readpos, (byte)Character.toLowerCase(bases.charAt(mispos))); mismatches.add(mismatch); } else { java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(readpos, (byte)bases.charAt(mispos)); mismatches.add(mismatch); } mispos++; readpos++; } else { digitpointer = i+1; while(!Character.isDigit(chars[digitpointer])) { digitpointer++; readpos++; } i=digitpointer-1; } } catch(Exception exc) { if(!first) { break; } first = false; readpos = 0; mispos = 0; i = -1; digitpointer = 0; insertionpointer = 0; mismatches.clear(); } } } } } else { /*if(split.getReference() == null) { readClass.setReference(new ReferenceSeq(splitIndex.chrom,start-500, end+500, Main.referenceFile)); //System.out.println(readClass.sample.getName() +" " +split.getReference().getStartPos() +" " +split.getReference().getSeq()[0]); }*/ //timecounter = 0; /*while(splitIndex.getReadReference() == null) { Thread.sleep(100); timecounter++; if(timecounter > 20) { break; } } Thread.sleep(0); */ // if(splitIndex.getReadReference() == null) { //splitIndex.setReference(new ReferenceSeq(splitIndex.chrom,startpos-searchwindow-1, endpos+searchwindow +200, Main.referenceFile)); // return null; //} if(samRecord.getCigarLength() > 1) { readstart = samRecord.getUnclippedStart(); readpos= 0; mispos= 0; /*if(readClass.getCoverageStart()>readstart) { return null; }*/ if(mismatches == null) { mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer,Byte>>(); } //testbranch for(int i = 0; i<samRecord.getCigarLength(); i++) { element = samRecord.getCigar().getCigarElement(i); if(element.getOperator().compareTo(CigarOperator.MATCH_OR_MISMATCH)== 0) { for(int r = readpos; r<readpos+element.getLength(); r++) { if(((readstart+r)-split.getReadReference().getStartPos()-1) > split.getReadReference().getSeq().length-1) { split.getReadReference().append(samRecord.getUnclippedEnd()+1000); } if(((readstart+r)-split.getReadReference().getStartPos()-1) < 0) { split.getReadReference().appendToStart(samRecord.getUnclippedStart()-1000); } try { if(samRecord.getReadBases()[mispos] != split.getReadReference().getSeq()[((readstart+r)-split.getReadReference().getStartPos()-1)]) { readClass.getCoverages()[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])]++; if(samRecord.getBaseQualityString().length() != 1 && (int)samRecord.getBaseQualityString().charAt(mispos)-readClass.sample.phred < Settings.baseQ ) { java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(r, (byte)Character.toLowerCase((char)samRecord.getReadBases()[mispos])); mismatches.add(mismatch); } else { java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(r, samRecord.getReadBases()[mispos]); mismatches.add(mismatch); } } } catch(Exception e) { System.out.println(samRecord.getReadBases().length); e.printStackTrace(); } try { coverageArray[((readstart+r)-readClass.getCoverageStart())][0]++; if(coverageArray[((readstart+r)-readClass.getCoverageStart())][0] > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverageArray[((readstart+r)-readClass.getCoverageStart())][0]); } } catch(Exception e) { //TODO } mispos++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.DELETION)== 0) { // readWidth+=element.getLength(); for(int d = 0; d<element.getLength(); d++) { readClass.getCoverages()[(readstart+readpos+d)- readClass.getCoverageStart()][Main.baseMap.get((byte)'D')]++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.INSERTION)== 0) { readClass.getCoverages()[(readstart+readpos)- readClass.getCoverageStart()][Main.baseMap.get((byte)'I')]++; mispos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.SOFT_CLIP)== 0 ) { if(Settings.softClips == 1) { for(int r = readpos; r<readpos+element.getLength(); r++) { if(((readstart+r)-split.getReadReference().getStartPos()-1) > split.getReadReference().getSeq().length-1) { split.getReadReference().append(samRecord.getUnclippedEnd()+1000); } if(((readstart+r)-splitIndex.getReadReference().getStartPos()-1) < 0) { split.getReadReference().appendToStart(samRecord.getUnclippedStart()-1000); } /* if(((readstart+r)-readClass.reference.getStartPos()-1) < 0) { continue; }*/ if(samRecord.getReadBases()[mispos] != split.getReadReference().getSeq()[((readstart+r)-split.getReadReference().getStartPos()-1)]) { if(SA == null) { readClass.getCoverages()[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get(samRecord.getReadBases()[mispos])]++; } if(mismatches == null) { mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer,Byte>>(); } java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(r, samRecord.getReadBases()[mispos]); mismatches.add(mismatch); } if(SA == null) { coverageArray[((readstart+r)-readClass.getCoverageStart())][0]++; } mispos++; } readpos+=element.getLength(); } else { if(i == 0) { readpos+=element.getLength(); mispos+=element.getLength(); } } } else if (element.getOperator().compareTo(CigarOperator.HARD_CLIP)== 0) { if(i == 0) { readstart = samRecord.getAlignmentStart(); } } else if(element.getOperator().compareTo(CigarOperator.SKIPPED_REGION)== 0) { readpos+=element.getLength(); // this.readWidth+=element.getLength(); } } } else { readstart = samRecord.getUnclippedStart(); /*if(readClass.getCoverageStart()>readstart) { return null; }*/ if((samRecord.getUnclippedEnd()-split.getReadReference().getStartPos()-1) > split.getReadReference().getSeq().length-1) { split.getReadReference().append(samRecord.getUnclippedEnd()+100); } if((samRecord.getUnclippedStart()-split.getReadReference().getStartPos()-1) < 0) { split.getReadReference().appendToStart(samRecord.getUnclippedStart()-100); } for(int r = 0; r<samRecord.getReadLength(); r++) { try { if(samRecord.getReadBases()[r] != split.getReadReference().getSeq()[((readstart+r)-split.getReadReference().getStartPos()-1)]) { if((readstart+r)-readClass.getCoverageStart() < readClass.getCoverages().length-1) { readClass.getCoverages()[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get(samRecord.getReadBases()[r])]++; if(mismatches == null) { mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer,Byte>>(); } java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(r, samRecord.getReadBases()[r]); mismatches.add(mismatch); } } try { coverageArray[(readstart+r)-readClass.getCoverageStart()][0]++; } catch(Exception e) { // System.out.println(readClass.getCoverageStart()); //TODO //e.printStackTrace(); continue; } if(coverageArray[(samRecord.getUnclippedStart()-readClass.getCoverageStart())+r][0] > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverageArray[(samRecord.getUnclippedStart()-readClass.getCoverageStart())+r][0]); } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); break; } } } } } catch(Exception e) { e.printStackTrace(); return null; } return mismatches; } /* public class ReadAdder extends SwingWorker<String, Object> { boolean end = false; String chrom; Reads readClass; ReadBuffer buffer; public ReadAdder(String chrom, Reads readClass, ReadBuffer buffer) { this.chrom = chrom; this.readClass = readClass; this.buffer = buffer; } protected String doInBackground() { while(true) { try { if(buffer.prev != null ) { readSam(chrom, readClass,buffer.record); // buffer.prev.next = null; buffer.prev = null; } if(buffer.next != null) { buffer = buffer.next; } if(end && buffer.next == null) { buffer.prev = null; break; } } catch(Exception e) { e.printStackTrace(); end = true; break; } } Draw.updateReads = true; buffer.prev = null; buffer = null; return ""; } } */ public static boolean isTrackFile(String file) { if(file.toLowerCase().endsWith(".bed") || file.toLowerCase().endsWith(".bed.gz")) { return true; } else if(file.toLowerCase().endsWith(".bedgraph.gz")) { return true; } else if(file.toLowerCase().endsWith("gff.gz")) { return true; } else if(file.toLowerCase().endsWith(".bigwig")) { return true; } else if(file.toLowerCase().endsWith(".bw")) { return true; } else if(file.toLowerCase().endsWith(".bigbed")) { return true; } else if(file.toLowerCase().endsWith(".bb")) { return true; } else if(file.toLowerCase().endsWith(".tsv.gz")) { return true; } else if(file.toLowerCase().endsWith(".tsv.bgz")) { return true; } return false; } public static boolean isTrackFile(File file) { if(file.getName().toLowerCase().endsWith(".bed") || file.getName().toLowerCase().endsWith(".bed.gz")) { return true; } else if(file.getName().toLowerCase().endsWith(".bedgraph.gz")) { return true; } else if(file.getName().toLowerCase().endsWith("gff.gz")) { return true; } else if(file.getName().toLowerCase().endsWith(".bigwig")) { return true; } else if(file.getName().toLowerCase().endsWith(".bw")) { return true; } else if(file.getName().toLowerCase().endsWith(".bigbed")) { return true; } else if(file.getName().toLowerCase().endsWith(".bb")) { return true; } else if(file.getName().toLowerCase().endsWith(".tsv.gz")) { return true; } else if(file.getName().toLowerCase().endsWith(".tsv.bgz")) { return true; } else if(file.getName().toLowerCase().endsWith(".txt")) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); String line, gene; int counter = 0, founds = 0; while((line = reader.readLine()) != null) { counter++; if(counter > 500) { break; } gene = line.replace(" ", ""); if(Main.searchTable.containsKey(gene.toUpperCase()) || Main.geneIDMap.containsKey(gene.toUpperCase())) { founds++; } } reader.close(); if(counter > 500) { Main.showError("Please give less than 500 genes in a txt-file.", "Error."); return false; } else if(founds == 0) { Main.showError("No genes could be identified from the " +file.getName(), "Error."); return false; } else { return true; } } catch(Exception e) { e.printStackTrace(); } } return false; } void readBED(File[] files) { try { File bedfile; Main.drawCanvas.loading("Loading tracks"); int addedfiles = 0; for(int i = 0; i<files.length; i++) { bedfile = files[i]; if(!isTrackFile(bedfile)) { continue; } if(!checkIndex(files[i])) { if(files[i].getName().endsWith(".tsv.gz") ||files[i].getName().endsWith(".tsv.bgz")) { Main.showError("No index file for the TSV file. Use Tools -> BED converter.", "Error"); continue; } if (JOptionPane.showConfirmDialog(Main.drawScroll, "No index file found. Do you want to create one?", "Indexing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ Main.drawCanvas.loadingtext = "Indexing " +files[i].getName(); if(files[i].getName().endsWith(".gz")) { MethodLibrary.createBEDIndex(files[i]); } else { MethodLibrary.createBEDIndex2(files[i]); } } } if(!checkIndex(files[i])) { Main.showError("Could not open file. Is the file sorted?", "Note"); continue; } BedTrack addTrack = new BedTrack(bedfile,Main.bedCanvas.bedTrack.size()); if(bedfile.getName().endsWith("tsv.gz") || bedfile.getName().endsWith("tsv.bgz")) { addTrack.getZerobased().setSelected(false); addTrack.iszerobased = 1; addTrack.getSelector().frame.setVisible(true); } Main.bedCanvas.bedTrack.add(addTrack); Main.bedCanvas.trackDivider.add(0.0); addTrack.minvalue = 0; if(bedfile.length() / 1048576 < Settings.settings.get("bigFile")) { addTrack.small = true; Main.bedCanvas.getBEDfeatures(addTrack, 1, Main.drawCanvas.splits.get(0).chromEnd); } if(bedfile.getName().toLowerCase().endsWith(".bedgraph") || bedfile.getName().toLowerCase().endsWith(".bedgraph.gz")) { Main.bedCanvas.pressGraph(addTrack); addTrack.getSelectorButton().setVisible(true); } else if(bedfile.getName().toLowerCase().endsWith("bigwig") || bedfile.getName().toLowerCase().endsWith("bw")) { addTrack.bigWig = true; addTrack.small = true; Main.bedCanvas.pressGraph(addTrack); addTrack.getSelectorButton().setVisible(false); Main.bedCanvas.getBEDfeatures(addTrack, (int)Main.drawCanvas.splits.get(0).start, (int)Main.drawCanvas.splits.get(0).end); } else { setBedTrack(addTrack); } addedfiles++; setTable(addTrack); } Main.drawCanvas.ready("Loading tracks"); if(Main.bedCanvas.bedTrack.size() == 0) { return; } if(!Main.trackPane.isVisible()) { Main.trackPane.setVisible(true); Main.varpane.setDividerSize(3); if(addedfiles < 5) { Main.varpane.setResizeWeight(addedfiles *0.1); Main.trackPane.setDividerLocation(addedfiles *0.1); Main.varpane.setDividerLocation(addedfiles *0.1); } else { Main.varpane.setResizeWeight(0.8); Main.trackPane.setDividerLocation(0.8); /*Main.bedCanvas.setPreferredSize(new Dimension(Main.drawWidth, Main.bedCanvas.bedTrack.size()*30 )); Main.bedCanvas.bufImage = MethodLibrary.toCompatibleImage(new BufferedImage((int)Main.screenSize.getWidth(), (int)Main.bedCanvas.bedTrack.size()*30, BufferedImage.TYPE_INT_ARGB)); Main.bedCanvas.buf = (Graphics2D)Main.bedCanvas.bufImage.getGraphics(); Main.bedCanvas.nodeImage = MethodLibrary.toCompatibleImage(new BufferedImage((int)Main.screenSize.getWidth(), (int)Main.bedCanvas.bedTrack.size()*30, BufferedImage.TYPE_INT_ARGB)); Main.bedCanvas.nodebuf = (Graphics2D)Main.bedCanvas.nodeImage.getGraphics(); */ Main.varpane.setDividerLocation(0.8); } Main.trackPane.revalidate(); Main.varpane.revalidate(); } else { Main.trackPane.setDividerLocation(Main.trackPane.getDividerLocation()+70); Main.varpane.setDividerLocation(Main.varpane.getDividerLocation()+70); Main.varpane.revalidate(); Main.trackPane.revalidate(); if(Main.controlScroll.isVisible()) { Main.trackPane.setDividerSize(3); } } Main.bedScroll.setVisible(true); Main.bedCanvas.setVisible(true); for(int i = 0 ; i<Main.bedCanvas.trackDivider.size(); i++) { Main.bedCanvas.trackDivider.set(i, ((i+1)*(Main.varpane.getDividerLocation()/(double)Main.bedCanvas.trackDivider.size()))); // System.out.println(((i+1)*(Main.varpane.getDividerLocation()/(double)Main.bedCanvas.trackDivider.size()))); } Main.trackPane.setDividerLocation((int)((Main.bedCanvas.trackDivider.size())*(Main.varpane.getDividerLocation()/(double)Main.bedCanvas.trackDivider.size()))); } catch(Exception e) { e.printStackTrace(); ErrorLog.addError(e.getStackTrace()); } } static void setBedTrack(BedTrack addTrack) { try { /* if(!addTrack.file.getName().endsWith(".gz")) { return; }*/ if(addTrack.getBBfileReader() != null) { return; } String name = ""; if(addTrack.file != null) { name = addTrack.file.getName().toLowerCase(); } else { name = addTrack.url.toString().toLowerCase(); } if(name.endsWith(".bw") ||name.endsWith(".bigwig") || name.endsWith(".bb") || name.endsWith(".bigbed")) { return; } InputStream in = null; String[] split; BufferedReader reader = null; GZIPInputStream gzip = null; FileReader freader = null; if(addTrack.file != null) { if(addTrack.file.getName().endsWith(".gz") || addTrack.file.getName().endsWith(".bgz")) { gzip = new GZIPInputStream(new FileInputStream(addTrack.file)); reader = new BufferedReader(new InputStreamReader(gzip)); } else { freader = new FileReader(addTrack.file); reader = new BufferedReader(freader); } } else { in = addTrack.url.openStream(); gzip = new GZIPInputStream(in); reader = new BufferedReader(new InputStreamReader(gzip)); } int count = 0; if(name.endsWith(".gff.gz")) { addTrack.iszerobased = 1; addTrack.getZerobased().setSelected(false); while(count < 10) { if(reader.readLine().startsWith("#")) { continue; } split = reader.readLine().split("\\t"); if(split.length > 5) { if(!Double.isNaN(Double.parseDouble(split[5]))) { addTrack.hasvalues = true; } } if(Main.SELEXhash.containsKey(split[2].replace(".pfm", ""))) { addTrack.selex = true; addTrack.getAffinityBox().setVisible(true); } count++; } } else if(name.endsWith(".bed.gz") || name.endsWith(".bed")) { while(count < 10) { if(reader.readLine().startsWith("#") || reader.readLine().startsWith("track")) { continue; } split = reader.readLine().split("\\t"); if(split.length > 4) { try { if(!Double.isNaN(Double.parseDouble(split[4]))) { addTrack.hasvalues = true; } } catch(Exception e) { } } if(split.length > 3 && Main.SELEXhash.containsKey(split[3])) { addTrack.selex = true; addTrack.getAffinityBox().setVisible(true); } count++; } } else if(name.endsWith(".tsv.gz") ||name.endsWith(".tsv.bgz")) { if(addTrack.valuecolumn != null) { while(count < 10) { if(reader.readLine().startsWith("#")) { continue; } split = reader.readLine().split("\\t"); if(!Double.isNaN(Double.parseDouble(split[addTrack.valuecolumn]))) { addTrack.hasvalues = true; break; } count++; } } } if(addTrack.getBBfileReader() == null && !addTrack.hasvalues) { addTrack.getLimitField().setVisible(false); } else { addTrack.getLimitField().setVisible(true); } if(gzip != null) { gzip.close(); } if(freader != null) { freader.close(); } if(in != null) { in.close(); } reader.close(); } catch(Exception e) { e.printStackTrace(); } } static String getInfoValue(HashMap<String, String> map, String key ) { if(map.containsKey(key)) { return map.get(key); } else { return "-"; } } static HashMap<String, String> makeHash(String[] line) { if(line == null || line.length < 9) { return null; } HashMap<String, String> hash = new HashMap<String, String>(); String[] infosplit = line[8].split(";"); hash.put("seqid", line[0].replace("chr", "")); hash.put("source", line[1]); hash.put("type", line[2]); hash.put("start", ""+(Integer.parseInt(line[3])-1)); hash.put("end", line[4]); hash.put("score", line[5]); hash.put("strand", line[6]); if(line[7].equals("2")) { line[7] = "1"; } else if(line[7].equals("1")) { line[7] = "2"; } hash.put("phase", line[7]); String[] split; for(int i = 0 ; i<infosplit.length; i++) { if(infosplit[i].contains("=")) { split = infosplit[i].split("="); hash.put(split[0].toLowerCase(),split[1]); } else { split = infosplit[i].trim().split(" "); hash.put(split[0].toLowerCase().replaceAll("\"", "").replace("name", "symbol"), split[1].replaceAll("\"", "")); } } return hash; } static void readGTF(File infile, String outfile, SAMSequenceDictionary dict) { BufferedReader reader = null; GZIPInputStream gzip = null; FileReader freader = null; String line= "", chrom = "-1"; HashMap<String, String> lineHash; HashMap<String,Gene> genes = new HashMap<String, Gene>(); HashMap<String,Transcript> transcripts = new HashMap<String, Transcript>(); Gene addgene; //Boolean found = false; Transcript addtranscript; try { if(infile.getName().endsWith(".gz")) { gzip = new GZIPInputStream(new FileInputStream(infile)); reader = new BufferedReader(new InputStreamReader(gzip)); } else { freader = new FileReader(infile); reader = new BufferedReader(freader); } // line = reader.readLine(); while((line = reader.readLine()) != null) { if(line.startsWith("#")) { continue; } /* if(!line.contains("Rp1h")) { if(found) { break; } continue; } found = true; */ lineHash = makeHash(line.split("\t")); chrom = lineHash.get("seqid"); if(!genes.containsKey(lineHash.get("gene_id"))) { /*if(genes.size() > 1) { break; }*/ Gene gene = new Gene(chrom, lineHash, true); genes.put(lineHash.get("gene_id"),gene); if(lineHash.get("transcript_id") == null) { continue; } //continue; } if(!transcripts.containsKey(lineHash.get("transcript_id"))) { addgene = genes.get(lineHash.get("gene_id")); transcripts.put(getInfoValue(lineHash, "transcript_id"), new Transcript(lineHash,addgene)); if(lineHash.get("type").equals("exon")) { addtranscript = transcripts.get(getInfoValue(lineHash, "transcript_id")); addtranscript.addExon(lineHash, addtranscript); } if(addgene.getDescription().equals("-")) { if(lineHash.containsKey("gene_symbol")) { addgene.setDescription(lineHash.get("gene_symbol")); } } continue; } if(transcripts.containsKey(lineHash.get("transcript_id"))) { if(lineHash.get("type").contains("UTR")) { continue; } addtranscript = transcripts.get(lineHash.get("transcript_id")); addtranscript.addExon(lineHash, addtranscript); continue; } } } catch(Exception e) { System.out.println(line); e.printStackTrace(); System.exit(0); } try { Transcript transcript; Gene gene; StringBuffer exStarts, exEnds, exPhases; Iterator<Map.Entry<String,Gene>> it = genes.entrySet().iterator(); ArrayList<String[]> geneArray = new ArrayList<String[]>(); while (it.hasNext()) { Map.Entry<String,Gene> pair = (Map.Entry<String,Gene>)it.next(); gene = pair.getValue(); for(int i = 0 ; i<gene.getTranscripts().size(); i++) { transcript = gene.getTranscripts().get(i); exStarts = new StringBuffer(""); exEnds = new StringBuffer(""); exPhases = new StringBuffer(""); for(int e =0;e<transcript.exonArray.size(); e++) { exStarts.append(transcript.exonArray.get(e).getStart() +","); exEnds.append(transcript.exonArray.get(e).getEnd() +","); exPhases.append(transcript.exonArray.get(e).getStartPhase()+","); } String[] row = {gene.getChrom(), ""+transcript.getStart(), ""+transcript.getEnd(), gene.getName(), ""+transcript.exonArray.size(), MethodLibrary.getStrand(gene.getStrand()), gene.getID(), transcript.getENST(), transcript.getUniprot(), "-", transcript.getBiotype(), ""+transcript.getCodingStart(), ""+transcript.getCodingEnd(), exStarts.toString(), exEnds.toString(), exPhases.toString(), transcript.getDescription() }; if(transcript.getCodingEnd() == -1) { row[11] = "" +gene.getEnd(); row[12] = "" +gene.getStart(); } /*for(int g = 0 ;g<row.length; g++) { System.out.print(row[g] +"\t"); } System.out.println(); */ geneArray.add(row); } it.remove(); } gffSorter gffsorter = new gffSorter(); Collections.sort(geneArray, gffsorter); if(outfile != null) { MethodLibrary.blockCompressAndIndex(geneArray, outfile, false, dict); } geneArray.clear(); if(freader != null) { freader.close(); } reader.close(); if(gzip != null) { gzip.close(); } } catch(Exception e) { e.printStackTrace(); } } static void readGFF(File infile, String outfile, SAMSequenceDictionary dict) { BufferedReader reader = null; GZIPInputStream gzip = null; FileReader freader = null; String line= "", chrom = "-1"; HashMap<String, String> lineHash; HashMap<String,Gene> genes = new HashMap<String, Gene>(); HashMap<String,Transcript> transcripts = new HashMap<String, Transcript>(); Gene addgene; Transcript addtranscript; try { if(infile.getName().endsWith(".gz")) { gzip = new GZIPInputStream(new FileInputStream(infile)); reader = new BufferedReader(new InputStreamReader(gzip)); } else { freader = new FileReader(infile); reader = new BufferedReader(freader); } // line = reader.readLine(); while((line = reader.readLine()) != null) { if(line.startsWith("#")) { continue; } lineHash = makeHash(line.split("\t")); if(lineHash.get("type").startsWith("region")) { if(line.contains("unlocalized")) { chrom = "unlocalized"; } else if(lineHash.get("chromosome") != null) { chrom = lineHash.get("chromosome").replace("chr", ""); } else if(lineHash.get("name") != null) { chrom = lineHash.get("name").replace("chr", ""); } continue; } if(!lineHash.containsKey("parent")) { /*if(!lineHash.get("type").contains("gene")) { continue; }*/ Gene gene = new Gene(chrom, lineHash); genes.put(getInfoValue(lineHash, "id"),gene); /*try { System.out.println(genes.get(genes.size()-1).getName()); } catch(Exception e) { System.out.println(line); }*/ continue; } if(genes.containsKey(lineHash.get("parent"))) { addgene = genes.get(lineHash.get("parent")); transcripts.put(getInfoValue(lineHash, "id"), new Transcript(lineHash,addgene)); if(lineHash.get("type").equals("exon")) { addtranscript = transcripts.get(getInfoValue(lineHash, "id")); addtranscript.addExon(lineHash, addtranscript); } if(addgene.getDescription().equals("-")) { if(lineHash.containsKey("product")) { addgene.setDescription(lineHash.get("product")); } } continue; } if(transcripts.containsKey(lineHash.get("parent"))) { addtranscript = transcripts.get(lineHash.get("parent")); addtranscript.addExon(lineHash, addtranscript); continue; } } } catch(Exception e) { System.out.println(line); e.printStackTrace(); System.exit(0); } try { Transcript transcript; Gene gene; StringBuffer exStarts, exEnds, exPhases; Iterator<Map.Entry<String,Gene>> it = genes.entrySet().iterator(); ArrayList<String[]> geneArray = new ArrayList<String[]>(); while (it.hasNext()) { Map.Entry<String,Gene> pair = (Map.Entry<String,Gene>)it.next(); gene = pair.getValue(); for(int i = 0 ; i<gene.getTranscripts().size(); i++) { transcript = gene.getTranscripts().get(i); exStarts = new StringBuffer(""); exEnds = new StringBuffer(""); exPhases = new StringBuffer(""); for(int e =0;e<transcript.exonArray.size(); e++) { exStarts.append(transcript.exonArray.get(e).getStart() +","); exEnds.append(transcript.exonArray.get(e).getEnd() +","); exPhases.append(transcript.exonArray.get(e).getStartPhase()+","); } String[] row = {gene.getChrom(), ""+transcript.getStart(), ""+transcript.getEnd(), gene.getName(), ""+transcript.exonArray.size(), MethodLibrary.getStrand(gene.getStrand()), gene.getID(), transcript.getENST(), transcript.getUniprot(), "-", transcript.getBiotype(), ""+transcript.getCodingStart(), ""+transcript.getCodingEnd(), exStarts.toString(), exEnds.toString(), exPhases.toString(), transcript.getDescription() }; geneArray.add(row); } it.remove(); } gffSorter gffsorter = new gffSorter(); Collections.sort(geneArray, gffsorter); if(outfile != null) { MethodLibrary.blockCompressAndIndex(geneArray, outfile, false, dict); } geneArray.clear(); if(freader != null) { freader.close(); } reader.close(); if(gzip != null) { gzip.close(); } } catch(Exception e) { e.printStackTrace(); } } public static class gffSorter implements Comparator<String[]> { public int compare(String[] o1, String[] o2) { if(o1[0].compareTo(o2[0]) == 0) { if(Integer.parseInt(o1[1]) < Integer.parseInt(o2[1])) { return -1; } else if(Integer.parseInt(o1[1]) > Integer.parseInt(o2[1])) { return 1; } else { return 0; } } else { return o1[0].compareTo(o2[0]); } } } public static class geneSorter implements Comparator<Gene> { public int compare(Gene o1, Gene o2) { if(o1.getChrom().compareTo(o2.getChrom()) == 0) { if(o1.getStart() < o2.getStart()) { return -1; } else if(o1.getStart() > o2.getStart()) { return 1; } else { return 0; } } else { return -o1.getChrom().compareTo(o2.getChrom()); } } } void readBED(String url, String index, boolean small) { try { if(!Main.trackPane.isVisible()) { Main.trackPane.setVisible(true); Main.varpane.setDividerSize(3); Main.varpane.setResizeWeight(0.1); Main.varpane.setDividerLocation(0.1); } else { Main.varpane.setDividerLocation(Main.varpane.getDividerLocation()+100); Main.varpane.revalidate(); Main.trackPane.setDividerLocation(Main.varpane.getDividerLocation()/2); if(Main.controlScroll.isVisible()) { Main.trackPane.setDividerSize(3); } } Main.bedScroll.setVisible(true); Main.bedCanvas.setVisible(true); BedTrack addTrack = null; if(index.equals("nan")) { addTrack = new BedTrack(new URL(url), null,Main.bedCanvas.bedTrack.size()); } else { addTrack = new BedTrack(new URL(url), new URL(index),Main.bedCanvas.bedTrack.size()); } //Main.bedCanvas.getBEDfeatures(addTrack, 1, Main.drawCanvas.splits.get(0).chromEnd); if(addTrack != null) { if(url.toLowerCase().endsWith("tsv.gz") || url.toLowerCase().endsWith("tsv.bgz")) { addTrack.getZerobased().setSelected(false); addTrack.iszerobased = 1; addTrack.getSelector().frame.setVisible(true); } addTrack.small = small; Main.bedCanvas.trackDivider.add(0.0); Main.bedCanvas.bedTrack.add(addTrack); setTable(addTrack); if(url.toLowerCase().endsWith(".bedgraph")) { Main.bedCanvas.pressGraph(addTrack); } if(url.toLowerCase().endsWith("bigwig") || url.toLowerCase().endsWith("bw")) { addTrack.small = true; addTrack.bigWig = true; addTrack.graph = true; //Main.bedCanvas.getBEDfeatures(addTrack, (int)Main.drawCanvas.splits.get(0).start, (int)Main.drawCanvas.splits.get(0).end); } setBedTrack(addTrack); if(addTrack.small) { // Main.drawCanvas.loading("loading"); Main.bedCanvas.getBEDfeatures(addTrack, 1, Main.drawCanvas.splits.get(0).chromEnd); //Main.drawCanvas.ready("loading"); } } } catch(Exception e) { e.printStackTrace(); ErrorLog.addError(e.getStackTrace()); } } static void setTable(BedTrack track) { JScrollPane addpane = new JScrollPane(); addpane.setPreferredSize(new Dimension(500,400)); BedTable add = new BedTable((int)Main.screenSize.width, (int)Main.screenSize.height, addpane, track); addpane.getViewport().add(add); addpane.getVerticalScrollBar().addAdjustmentListener( new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent event) { if(VariantHandler.tabs.getSelectedIndex() > 2) { VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).repaint(); } } } ); VariantHandler.tables.add(add); VariantHandler.tablescrolls.add(addpane); track.setTable(add); add.resizeTable(VariantHandler.tableScroll.getViewport().getWidth()); if(track.file != null) { /*if(track.file.getName().length() > 10) { VariantHandler.tabs.add(track.file.getName().substring(0, 10) +"...", addpane); add.setName(track.file.getName().substring(0, 10) +"..."); } else {*/ VariantHandler.tabs.add(track.file.getName().replace(".pfm", ""), addpane); add.setName(track.file.getName()); // } } else { /*if(FilenameUtils.getName(track.url.getFile()).length() > 10) { VariantHandler.tabs.add(FilenameUtils.getName(track.url.getFile()).substring(0, 10) +"...", addpane); add.setName(FilenameUtils.getName(track.url.getFile()).substring(0, 10) +"..."); } else {*/ VariantHandler.tabs.add(FilenameUtils.getName(track.url.getFile()), addpane); add.setName(FilenameUtils.getName(track.url.getFile())); // } } //VariantHandler.clusterTable.addHeaderColumn(track); MethodLibrary.addHeaderColumns(track); VariantHandler.tabs.revalidate(); } static void removeTable(BedTrack track) { try { if(VariantHandler.tables.indexOf(track.getTable()) > -1) { VariantHandler.tabs.remove(track.getTable().tablescroll); VariantHandler.tablescrolls.remove(track.getTable().tablescroll); VariantHandler.tables.remove(track.getTable()); VariantHandler.tabs.revalidate(); VariantHandler.tabs.repaint(); } } catch(Exception e) { e.printStackTrace(); } } /*int binarySearch(ArrayList<int[]> list, int value, int middle) { if(middle == 0) { return 0; } if(middle == list.size()-1) { return list.size()-1; } if(list.get(middle-1)[1] <= value) { middle = middle/2; return binarySearch(list, value, middle); } if(list.get(middle-1)[1] <= value && list.get(middle)[1] >= value) { return middle-1; } if(list.get(middle-1)[1] > value ) { return binarySearch(list, value, middle); } return -1; }*/ int searchIndex(ArrayList<int[]> list, int value, int low, int high) { middle = (high+low)/2; if(middle == list.size()-1) { return list.size(); } if(list.get(middle)[1] <= value && list.get(middle+1)[1] >= value) { return middle+1; } if(list.get(middle)[1] > value) { return searchIndex(list, value, low, middle); } if(list.get(middle)[1] < value) { return searchIndex(list, value, middle, high); } return -1; } void readSam(String chrom, Reads readClass, SAMRecord samRecordBuffer, java.util.ArrayList<java.util.Map.Entry<Integer,Byte>> mismatches) { try { if(readClass.getReads().isEmpty()) { addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); readClass.setFirstRead(addNode); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-(readClass.readHeight+2))); addNode.setRectBounds((int)((addNode.getPosition()-start)*pixel), startY, (int)(samRecordBuffer.getReadLength()*pixel), readClass.readHeight); readClass.getReads().add(addNode); ReadNode[] addList = new ReadNode[2]; addList[headnode] = addNode; addList[tailnode] = addNode; readClass.getHeadAndTail().add(addList); readClass.setLastRead(addNode); } else { mundane = null; found = false; isDiscordant = MethodLibrary.isDiscordant(samRecordBuffer, readClass.sample.getComplete()); if(samRecordBuffer.getCigarLength() > 1) { if(samRecordBuffer.getCigar().getCigarElement(0).getOperator().compareTo(CigarOperator.HARD_CLIP) == 0) { searchPos = samRecordBuffer.getAlignmentStart(); } else { searchPos = samRecordBuffer.getUnclippedStart(); } } else { searchPos = samRecordBuffer.getUnclippedStart(); } for(int i = 0; i<readClass.getHeadAndTail().size(); i++) { if(i>Settings.readDepthLimit) { found = true; mundane = null; addNode = null; break; } if(!isDiscordant) { if(readClass.getHeadAndTail().get(i)[tailnode].getPosition() +readClass.getHeadAndTail().get(i)[tailnode].getWidth() +2 < searchPos) { //.getPosition()) { try { if(mundane == null) { xpos = (int)((searchPos-start)*pixel); addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); readClass.setLastRead(addNode); } startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); addNode.setRectBounds(xpos, startY, (int)(addNode.getWidth()*pixel), readClass.readHeight); if(i > readClass.getHeadAndTail().size()-1) { return; } addNode.setPrev(readClass.getHeadAndTail().get(i)[tailnode]); readClass.getHeadAndTail().get(i)[tailnode].setNext(addNode); readClass.getHeadAndTail().get(i)[tailnode] = addNode; found = true; break; } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } } continue; } else { if(readClass.getHeadAndTail().get(i)[tailnode].getPosition()+readClass.getHeadAndTail().get(i)[tailnode].getWidth() +2 < searchPos) { /*if(readClass.readNames.containsKey(addNode.getName())) { readClass.readNames.get(addNode.getName())[1] = addNode; } else { ReadNode[] nameAdd = new ReadNode[2]; nameAdd[0] = addNode; nameAdd[1] = null; readClass.readNames.put(addNode.getName(), nameAdd); }*/ xpos = (int)((searchPos-start)*pixel); addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); addNode.setRectBounds(xpos, startY, (int)(addNode.getWidth()*pixel), readClass.readHeight); addNode.setPrev(readClass.getHeadAndTail().get(i)[tailnode]); readClass.getHeadAndTail().get(i)[tailnode].setNext(addNode); readClass.getHeadAndTail().get(i)[tailnode] = addNode; readClass.setLastRead(addNode); found = true; break; } else if(!readClass.getHeadAndTail().get(i)[tailnode].isDiscordant()) { xpos = (int)((searchPos-start)*pixel); addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); mundane = readClass.getHeadAndTail().get(i)[tailnode]; /* if(readClass.readNames.containsKey(addNode.getName())) { readClass.readNames.get(addNode.getName())[1] = addNode; } else { ReadNode[] nameAdd = new ReadNode[2]; nameAdd[0] = addNode; nameAdd[1] = null; readClass.readNames.put(addNode.getName(), nameAdd); }*/ startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); addNode.setRectBounds(xpos, startY, (int)(addNode.getWidth()*pixel), readClass.readHeight); if(mundane.getPrev() != null) { addNode.setPrev(mundane.getPrev()); mundane.getPrev().setNext(addNode); } if(readClass.getHeadAndTail().get(i)[headnode].equals(mundane)) { readClass.getHeadAndTail().get(i)[headnode] = addNode; } readClass.getHeadAndTail().get(i)[tailnode] = addNode; found = false; readClass.setLastRead(addNode); try { readClass.getReads().set(i,addNode); } catch(Exception e) { System.out.println(readClass.getHeadAndTail().size() +" " +readClass.getReads().size()); } addNode = mundane; searchPos = addNode.getPosition(); isDiscordant = false; addNode.setNext(null); addNode.setPrev(null); continue; } // continue; } } if(!found) { /* if(addNode.isDiscordant()) { if(readClass.readNames.containsKey(addNode.getName())) { readClass.readNames.get(addNode.getName())[1] = addNode; } else { ReadNode[] nameAdd = new ReadNode[2]; nameAdd[0] = addNode; nameAdd[1] = null; readClass.readNames.put(addNode.getName(), nameAdd); } }*/ if(mundane == null) { xpos = (int)((searchPos-start)*pixel); addNode = new ReadNode(samRecordBuffer, readClass.sample.getComplete(), chrom, readClass.sample, splitIndex,readClass, mismatches); } ReadNode[] addList = new ReadNode[2]; addList[headnode] = addNode; addList[tailnode] = addNode; addNode.setPrev(null); addNode.setNext(null); readClass.getHeadAndTail().add(addList); readClass.getReads().add(addNode); readClass.setLastRead(addNode); startY = (int)(((readClass.sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((readClass.getReads().size())*(readClass.readHeight+2)))); addNode.setRectBounds(xpos, startY, (int)(addNode.getWidth()*pixel), readClass.readHeight); } } //preRecord = readClass.samRecordBuffer; } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } } void setLevels(ReadNode node, Sample sample, Reads readClass) { try { while(node != null) { mundane = null; addNode = node.getPrev(); found = false; xpos = (int)((node.getPosition()-start)*pixel); for(int i = 0; i<readClass.getReads().size(); i++) { if(i > Settings.readDepthLimit) { if(node.getNext() != null) { node.getNext().setPrev(node.getPrev());; } if(node.getPrev() != null) { node.getPrev().setNext(node.getNext()); } mundane = null; node = null; // addNode = null; found = true; break; } if(!node.isDiscordant()) { if(node.getPosition()+node.getWidth()+2 < readClass.getHeadAndTail().get(i)[headnode].getPosition()) { if(i > 0) { startY = (int)(((sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); node.setRectBounds(xpos, startY, (int)(node.getWidth()*pixel), readClass.readHeight); if(mundane == null) { if(node.getPrev()!=null) { node.getPrev().setNext(node.getNext()); } node.getNext().setPrev(node.getPrev()); } node.setNext(readClass.getHeadAndTail().get(i)[headnode]); readClass.getHeadAndTail().get(i)[headnode].setPrev(node); //node.setPrev(sample.headAndTail.get(i)[headnode].getPrev()); readClass.getHeadAndTail().get(i)[headnode] = node; readClass.getHeadAndTail().get(i)[headnode].setPrev(null); } else { readClass.getHeadAndTail().get(i)[headnode] = node; } found = true; break; } continue; } else { if(node.getPosition()+node.getWidth()+2 < readClass.getHeadAndTail().get(i)[headnode].getPosition()) { if(i > 0) { startY = (int)(((sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); node.setRectBounds(xpos, startY, (int)(node.getWidth()*pixel), readClass.readHeight); /* if(node.getPrev()!=null) { node.getPrev().setNext(node.getNext()); } node.getNext().setPrev(node.getPrev()); */ node.setNext(readClass.getHeadAndTail().get(i)[headnode]); readClass.getHeadAndTail().get(i)[headnode].setPrev(node); node.setPrev(null); readClass.getHeadAndTail().get(i)[headnode] = node; } else { readClass.getHeadAndTail().get(i)[headnode] = node; } found = true; break; } else if(readClass.getHeadAndTail().get(i)[headnode].isDiscordant()) { if(i==0) { if(node.getPrev() != null) { readClass.getHeadAndTail().get(i)[headnode].setPrev(node.getPrev()); node.getPrev().setNext(readClass.getHeadAndTail().get(i)[headnode]); } } continue; } else { mundane = readClass.getHeadAndTail().get(i)[headnode]; startY = (int)(((sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((i+1)*(readClass.readHeight+2)))); node.setRectBounds(xpos, startY, (int)(node.getWidth()*pixel), readClass.readHeight); node.setNext(mundane.getNext()); if(mundane.getNext() != null) { mundane.getNext().setPrev(node); } mundane.setNext(null); mundane.setPrev(null); node.setPrev(null); readClass.getHeadAndTail().get(i)[headnode] = node; readClass.getReads().set(i, node); node = mundane; found = false; continue; } } } if(!found) { ReadNode[] addList = new ReadNode[2]; addList[headnode] = node; addList[tailnode] = node; readClass.getHeadAndTail().add(addList); if(node.getPrev() != null) { node.getPrev().setNext(node.getNext()); } if(node.getNext() != null) { node.getNext().setPrev(node.getPrev()); } node.setNext(null); node.setPrev(null); readClass.getReads().add(node); startY = (int)(((sample.getIndex()+1)*Main.drawCanvas.drawVariables.sampleHeight-Main.drawCanvas.bottom-((readClass.getReads().size())*(readClass.readHeight+2)))); node.setRectBounds(xpos, startY, (int)(node.getWidth()*pixel), readClass.readHeight); } node = addNode; } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } mundane = null; } void removeNonListBeds(BedNode node, int topos) { BedNode tempNode = null; if(node.equals(node.getTrack().getHead())) { node = node.getNext(); } while(node != null ) { if(node.getPosition() >= topos) { node = null; break; } if(!node.inVarlist) { if(node.getPosition()+node.getLength()+1 < topos) { tempNode = node.getNext(); node.removeNode(); node = tempNode; } else { node = node.getNext(); } continue; } else { node = node.getNext(); } } tempNode = null; } static void removeNonListVariants() { VarNode node = FileRead.head.getNext(); VarNode tempNode; Map.Entry<String, ArrayList<SampleNode>> entry; int mutcount = 0; while(node != null ) { if(!node.inVarList || Main.drawCanvas.hideNode(node)) { tempNode = node.getNext(); node.removeNode(); node = tempNode; } else { for(int v = 0; v<node.vars.size(); v++) { entry = node.vars.get(v); mutcount = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(!Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { if(VariantHandler.onlyselected.isSelected()) { if(!entry.getValue().get(m).getSample().equals(Main.drawCanvas.selectedSample)) { entry.getValue().remove(m); m--; continue; } } mutcount++; } else { entry.getValue().remove(m); m--; } } } if(mutcount == 0) { tempNode = node.getNext(); node.removeNode(); node = tempNode; } else { node = node.getNext(); } } } node = null; tempNode = null; entry = null; Main.drawCanvas.current = FileRead.head; Draw.updatevars = true; Main.drawCanvas.repaint(); } static void removeBedLinks() { for(int i = 0 ; i<Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).used) { BedNode node = Main.bedCanvas.bedTrack.get(i).getHead(); BedNode tempnode; try { while(node !=null) { if(node.varnodes != null) { for(int n = 0 ; n < node.varnodes.size(); n++) { if(Main.drawCanvas.hideNode(node.varnodes.get(n))) { node.varnodes.remove(n); n--; if(n == -1) { break; } } } } tempnode = node.getNext(); if(!bigcalc) { node.putPrev(null); node.putNext(null); } node = tempnode; } } catch(Exception e) { e.printStackTrace(); } } } } void varCalc() { try { /*array = new int[Main.drawCanvas.sampleList.size()][101]; for(int i = 0; i<array.length; i++) { for(int j = 0; j<array[i].length; j++) { array[i][j] = 0; } } */ FileRead.novars = false; boolean isfreeze = VariantHandler.freeze.isSelected(); if(!VariantHandler.none.isSelected()) { SampleDialog.checkFiles(); if(affected == 0) { Main.showError("Set at least one individual as affected. (click sample name or right click sample sidebar)", "Note"); return; } } else { VariantHandler.freeze.setSelected(true); } contexts = null; //contextQuals = null; Draw.calculateVars = false; Draw.variantcalculator = true; if(VariantHandler.writetofile.isSelected()) { lastWriteVar = FileRead.head; } clearVariantsFromGenes(); SplitClass split = Main.drawCanvas.splits.get(0); int chromcounter = 0; VariantHandler.outputStrings.clear(); if(Main.drawCanvas.clusterNodes == null) { Main.drawCanvas.clusterNodes = new ArrayList<ClusterNode>(); } else { Main.drawCanvas.clusterNodes.clear(); } Main.drawCanvas.clusterId = 1; VariantHandler.table.variants = 0; VariantHandler.stattable.variants = 0; VariantHandler.clusterTable.variants = 0; for(int i = 0 ; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).variants = 0; } cancelvarcount = false; VariantHandler.table.genearray.clear(); VariantHandler.table.aminoarray.clear(); VariantHandler.table.controlarray = null; VariantHandler.stattable.sampleArray.clear(); for(int i = 0; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).bedarray =null; VariantHandler.tables.get(i).aminoarray=null; VariantHandler.tables.get(i).vararray=null; VariantHandler.tables.get(i).controlarray = null; VariantHandler.tables.get(i).variants = 0; } VarNode vardraw = Main.drawCanvas.current; Object[] addobject; for(int i=0; i<Main.drawCanvas.sampleList.size(); i++) { if(Main.drawCanvas.sampleList.get(i).multiVCF || (Main.drawCanvas.sampleList.get(i).getTabixFile() == null && !Main.drawCanvas.sampleList.get(i).multipart) && (FileRead.caller && Main.drawCanvas.sampleList.get(i).samFile == null) && !Main.drawCanvas.sampleList.get(i).calledvariants) { continue; } addobject = new Object[VariantHandler.stattable.headerlengths.length]; addobject[0] = Main.drawCanvas.sampleList.get(i); for(int j = 1; j<addobject.length; j++) { addobject[j] = 0; } Main.drawCanvas.sampleList.get(i).mutationTypes = new double[6]; for(int j = 0; j<6; j++) { Main.drawCanvas.sampleList.get(i).mutationTypes[j] = 0.0; } VariantHandler.stattable.sampleArray.add(addobject); Main.drawCanvas.sampleList.get(i).heterozygotes = 0; Main.drawCanvas.sampleList.get(i).homozygotes = 0; Main.drawCanvas.sampleList.get(i).varcount = 0; Main.drawCanvas.sampleList.get(i).indels = 0; Main.drawCanvas.sampleList.get(i).snvs = 0; Main.drawCanvas.sampleList.get(i).sitioRate = 0; Main.drawCanvas.sampleList.get(i).versioRate = 0; Main.drawCanvas.sampleList.get(i).ins = 0; Main.drawCanvas.sampleList.get(i).callrates = 0.0; Main.drawCanvas.sampleList.get(i).coding = 0; Main.drawCanvas.sampleList.get(i).syn = 0; Main.drawCanvas.sampleList.get(i).nonsyn = 0; Main.drawCanvas.sampleList.get(i).missense = 0; Main.drawCanvas.sampleList.get(i).splice = 0; Main.drawCanvas.sampleList.get(i).nonsense = 0; Main.drawCanvas.sampleList.get(i).fshift = 0; Main.drawCanvas.sampleList.get(i).inframe = 0; } VariantHandler.stattable.setPreferredSize(new Dimension(VariantHandler.statsScroll.getViewport().getWidth(), (VariantHandler.stattable.sampleArray.size()+1)*VariantHandler.stattable.rowHeight)); VariantHandler.stattable.revalidate(); VariantHandler.stattable.repaint(); for(int g = 0 ; g<split.getGenes().size(); g++) { split.getGenes().get(g).mutations = 0; split.getGenes().get(g).missense = 0; split.getGenes().get(g).nonsense = 0; split.getGenes().get(g).synonymous = 0; split.getGenes().get(g).intronic = 0; split.getGenes().get(g).utr = 0; split.getGenes().get(g).samples.clear(); split.getGenes().get(g).varnodes.clear(); split.getGenes().get(g).intergenic = false; split.getGenes().get(g).transcriptString = new StringBuffer(); } if(VariantHandler.allChroms.isSelected() && !VariantHandler.xLinked.isSelected()) { for(int i = 0 ; i < Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).getVarcalc().isSelected()) { Main.bedCanvas.bedTrack.get(i).intersect = true; } } if(VariantHandler.allChromsfrom.isSelected()) { chromcounter = Main.chromosomeDropdown.getSelectedIndex(); Main.nothread = true; Main.chromosomeDropdown.setSelectedIndex(Main.chromosomeDropdown.getSelectedIndex()); Main.nothread = false; vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } else if(Main.drawCanvas.splits.get(0).start != 1 || Main.chromosomeDropdown.getSelectedIndex() != 0) { Main.nothread = true; Main.chromosomeDropdown.setSelectedIndex(0); Main.nothread = false; vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } else { vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } } else { if(VariantHandler.xLinked.isSelected()) { if(Main.chromModel.getIndexOf("X") != -1) { if(Main.drawCanvas.splits.get(0).start != 1 || Main.chromosomeDropdown.getSelectedIndex() != 0) { Main.nothread = true; Main.chromosomeDropdown.setSelectedItem("X"); Main.nothread = false; vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } } else { JOptionPane.showMessageDialog(Main.drawScroll, "No chromosome X available.", "Note", JOptionPane.INFORMATION_MESSAGE); return; } } for(int i = 0 ; i < Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).getVarcalc().isSelected()) { Main.bedCanvas.bedTrack.get(i).intersect = true; if(Main.bedCanvas.bedTrack.get(i).small && !Main.bedCanvas.bedTrack.get(i).bigWig) { Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(), FileRead.head.getNext()); Main.bedCanvas.intersected = true; } else { BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); Main.bedCanvas.intersected = true; } } } } if(caller && varc == null) { varc = new VariantCaller(true); varcal = varc.new VarCaller(); } Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; if(caller && FileRead.head.getNext() == null) { varcal.callVariants(); vardraw = FileRead.head.getNext(); } while(true) { if(cancelvarcount || !Main.drawCanvas.loading) { cancelFileRead(); vardraw = null; break; } if(vardraw == null) { if(VariantHandler.writetofile.isSelected()) { for(int i = 0;i<VariantHandler.table.genearray.size(); i++) { VariantHandler.writeTranscriptToFile(VariantHandler.table.genearray.get(i), output); } FileRead.lastpos = 0; Main.drawCanvas.clusterNodes.clear(); } VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(),(VariantHandler.table.getTableSize()+1)*(VariantHandler.table.rowHeight))); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); try { if(VariantHandler.commonSlider.getValue() > 1 && VariantHandler.clusterSize > 0) { VariantHandler.clusterTable.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (Main.drawCanvas.clusterNodes.size()+1)*VariantHandler.clusterTable.rowHeight)); VariantHandler.clusterTable.revalidate(); VariantHandler.clusterTable.repaint(); } for(int i = 0; i<VariantHandler.stattable.sampleArray.size(); i++) { sample = (Sample)VariantHandler.stattable.sampleArray.get(i)[0]; VariantHandler.stattable.sampleArray.get(i)[1] = sample.varcount; VariantHandler.stattable.sampleArray.get(i)[2] = sample.snvs; VariantHandler.stattable.sampleArray.get(i)[3] = sample.indels; VariantHandler.stattable.sampleArray.get(i)[4] = sample.ins; VariantHandler.stattable.sampleArray.get(i)[5] = sample.coding; VariantHandler.stattable.sampleArray.get(i)[6] = MethodLibrary.round(sample.heterozygotes/(double)sample.homozygotes,2); VariantHandler.stattable.sampleArray.get(i)[7] = MethodLibrary.round((int)sample.sitioRate/(double)sample.versioRate,2); for(int j = 0; j<6; j++) { VariantHandler.stattable.sampleArray.get(i)[8+j] = MethodLibrary.round(sample.mutationTypes[j]/(double)sample.snvs, 2); } VariantHandler.stattable.sampleArray.get(i)[14] = MethodLibrary.round(sample.callrates / (double)sample.varcount,2); VariantHandler.stattable.repaint(); } } catch(Exception e) { e.printStackTrace(); } if(VariantHandler.allChroms.isSelected() && !VariantHandler.xLinked.isSelected()) { for(int i = 0; i<Main.bedCanvas.bedTrack.size(); i++) { removeNonListBeds( Main.bedCanvas.bedTrack.get(i).getHead(), Main.drawCanvas.splits.get(0).chromEnd); } if(VariantHandler.writetofile.isSelected()) { FileRead.head.putNext(null); nullifyVarNodes(); clearVariantsFromGenes(); } if(cancelvarcount || !Main.drawCanvas.loading) { cancelFileRead(); break; } FileRead.lastpos = 0; if(chromcounter < Main.chromosomeDropdown.getItemCount()) { chromcounter++; if(chromcounter == Main.chromosomeDropdown.getItemCount()) {// || Main.chromosomeDropdown.getItemAt(chromcounter).toString().contains("X")) { break; } if(VariantHandler.onlyAutosomes.isSelected()) { if(Main.chromosomeDropdown.getItemAt(chromcounter).toString().equals("X") || Main.chromosomeDropdown.getItemAt(chromcounter).toString().equals("Y")) { break; } } Main.nothread = true; Main.chromosomeDropdown.setSelectedIndex(chromcounter); Main.nothread = false; if(nobeds) { continue; } for(int g = 0 ; g<split.getGenes().size(); g++) { split.getGenes().get(g).mutations = 0; split.getGenes().get(g).missense = 0; split.getGenes().get(g).nonsense = 0; split.getGenes().get(g).synonymous = 0; split.getGenes().get(g).intronic = 0; split.getGenes().get(g).utr = 0; split.getGenes().get(g).samples.clear(); split.getGenes().get(g).varnodes.clear(); split.getGenes().get(g).intergenic = false; split.getGenes().get(g).transcriptString = new StringBuffer(); } if(caller) { varcal.callVariants(); } Main.drawCanvas.calcClusters(FileRead.head.getNext()); vardraw = FileRead.head.getNext(); FileRead.head.putNext(null); if(vardraw == null) { continue; } if(lastVar == null) { lastVar = FileRead.head; } if(lastWriteVar == null) { lastWriteVar = FileRead.head; } vardraw.putPrev(lastVar); lastVar.putNext(vardraw); } else { Main.drawCanvas.ready("all"); break; } } else { break; } } try { if(!VariantHandler.allChroms.isSelected()) { if(vardraw != null && vardraw.getPosition() < Main.drawCanvas.splits.get(0).start) { vardraw = vardraw.getNext(); continue; } if(vardraw == null || vardraw.getPosition() > Main.drawCanvas.splits.get(0).end) { vardraw= null; continue; } } //STATS vardraw = annotateVariant(vardraw); } catch(Exception ex) { ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); } } nullifyVarNodes(); vardraw =null; Draw.calculateVars = true; Draw.updatevars = true; VariantHandler.table.revalidate(); VariantHandler.table.repaint(); for(int i = 0; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.tables.get(i).getTableSize()+1)*(VariantHandler.tables.get(i).rowHeight))); VariantHandler.tables.get(i).revalidate(); VariantHandler.tables.get(i).repaint(); } VariantHandler.clusterTable.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.clusterTable.getTableSize()+1)*(VariantHandler.clusterTable.rowHeight))); VariantHandler.clusterTable.revalidate(); VariantHandler.clusterTable.repaint(); VariantHandler.clusterTable.repaint(); VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.table.getTableSize()+1)*(VariantHandler.table.rowHeight))); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } try { if(output != null) { if(VariantHandler.onlyStats.isSelected() && VariantHandler.outputContexts.isSelected()) { for(int i = 0 ; i<VariantHandler.stattable.sampleArray.size(); i++) { sample = (Sample)VariantHandler.stattable.sampleArray.get(i)[0]; output.write(sample.getName()); for(int j = 1; j<VariantHandler.stattable.headerlengths.length; j++) { output.write("\t" +VariantHandler.stattable.sampleArray.get(i)[j]); } output.write("\t" +sample.syn +"\t" +sample.nonsyn +"\t" +sample.missense +"\t" +sample.splice +"\t" +sample.nonsense +"\t" +sample.fshift +"\t" +sample.inframe); output.write(Main.lineseparator); } if(contexts != null) { /*Iterator<Entry<String, Float[]>> iterQuals = contextQuals.entrySet().iterator(); while(iterQuals.hasNext()) { Entry<String, Float[]> entry = iterQuals.next(); Float[] values = entry.getValue(); System.out.println(entry.getKey().substring(1)+">" +entry.getKey().charAt(1) +entry.getKey().charAt(0) +entry.getKey().charAt(3) +"\t" +(values[1]/values[0]) +"\t" +values[0]); } */ Iterator<Entry<String, Integer[]>> iter = contexts.entrySet().iterator(); sigOutput.write("#mutType"); for(int i = 0 ; i<Main.drawCanvas.sampleList.size(); i++) { if(!Main.drawCanvas.sampleList.get(i).multiVCF && !Main.drawCanvas.sampleList.get(i).removed) { sigOutput.write("\t" +Main.drawCanvas.sampleList.get(i).getName()); } } sigOutput.write("\n"); //Main.lineseparator);Main.lineseparator); while(iter.hasNext()) { Entry<String, Integer[]> entry = iter.next(); Integer[] samples = entry.getValue(); sigOutput.write(entry.getKey().substring(1)+">" +entry.getKey().charAt(1) +entry.getKey().charAt(0) +entry.getKey().charAt(3)); for(int i = 0; i<Main.drawCanvas.sampleList.size(); i++) { if(!Main.drawCanvas.sampleList.get(i).multiVCF && !Main.drawCanvas.sampleList.get(i).removed) { if(samples[i] == null) { sigOutput.write("\t0"); } else { sigOutput.write("\t" +samples[i]); } } } sigOutput.write("\n"); //Main.lineseparator); } sigOutput.close(); } } output.close(); } if(outputgz != null) { for(int i = 0 ; i<VariantHandler.outputStrings.size(); i++) { outputgz.write(VariantHandler.outputStrings.get(i).getBytes()); Feature vcf = VariantHandler.vcfCodec.decode(VariantHandler.outputStrings.get(i)); FileRead.indexCreator.addFeature(vcf, FileRead.filepointer); FileRead.filepointer = outputgz.getFilePointer(); } VariantHandler.outputStrings.clear(); outputgz.flush(); Index index = indexCreator.finalizeIndex(outputgz.getFilePointer()); index.writeBasedOnFeatureFile(outFile); outputgz.close(); } } catch(Exception e) { e.printStackTrace(); } split = null; if(!isfreeze) { VariantHandler.freeze.setSelected(false); } Main.drawCanvas.ready("all"); if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } Draw.variantcalculator = false; Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; if(VariantHandler.allChroms.isSelected()) { Main.showError("Variant annotation ready!", "Note"); } } catch(Exception e) { e.printStackTrace(); } /*if(contexts != null) { Iterator<Entry<String, Integer[]>> iter = contexts.entrySet().iterator(); System.out.print("#mutType"); for(int i = 0 ; i<Main.samples; i++) { if(!Main.drawCanvas.sampleList.get(i).multiVCF) { System.out.print("\t" +Main.drawCanvas.sampleList.get(i).getName()); } } System.out.println(); while(iter.hasNext()) { Entry<String, Integer[]> entry = iter.next(); Integer[] samples = entry.getValue(); System.out.print(entry.getKey().substring(1)+">" +entry.getKey().charAt(1) +entry.getKey().charAt(0) +entry.getKey().charAt(3)); for(int i = 0; i<samples.length; i++) { if(!Main.drawCanvas.sampleList.get(i).multiVCF) { if(samples[i] == null) { System.out.print("\t0"); } else { System.out.print("\t" +samples[i]); } } } System.out.println(); } }*/ //boolean found = false; /* StringBuffer copy = new StringBuffer(""); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); String type = ""; for(int i = 0 ; i<VariantHandler.table.genearray.size(); i++) { if(VariantHandler.table.genearray.get(i).getName().equals(Main.searchField.getText().trim().toUpperCase())) { for(int j = 0; j<Main.drawCanvas.sampleList.size(); j++) { if(Main.drawCanvas.sampleList.get(j).multiVCF) { continue; } found = false; for(int s = 0; s < VariantHandler.table.genearray.get(i).samples.size(); s++) { if(VariantHandler.table.genearray.get(i).samples.get(s).getName().equals(Main.drawCanvas.sampleList.get(j).getName())) { found = true; break; } } if(found) { if(Main.drawCanvas.sampleList.get(j).fshift > 0) { type = "frameshift"; } else if(Main.drawCanvas.sampleList.get(j).nonsense > 0) { type = "nonsense"; } else if(Main.drawCanvas.sampleList.get(j).inframe > 0) { type = "inframe"; } else if(Main.drawCanvas.sampleList.get(j).splice > 0) { type = "splice"; } else if(Main.drawCanvas.sampleList.get(j).missense > 0) { type = "missense"; } else if(Main.drawCanvas.sampleList.get(j).syn > 0) { type = "synonymous"; } else { System.out.println(Main.drawCanvas.sampleList.get(j).getName() +" " +VariantHandler.table.genearray.get(i).getName()); } copy.append(Main.drawCanvas.sampleList.get(j).getName() +"\t" +type +"\n" ); } else { copy.append(Main.drawCanvas.sampleList.get(j).getName() +"\t0\n" ); } } break; } } StringSelection stringSelection= new StringSelection(copy.toString()); clpbrd.setContents(stringSelection, null);*/ } static void clearVariantsFromBeds() { for(int b = 0; b< Main.bedCanvas.bedTrack.size(); b++) { BedNode node = Main.bedCanvas.bedTrack.get(b).getHead(); while(node != null) { if(node.varnodes != null) { node.varnodes = null; } node = node.getNext(); } } } static void nullifyVarNodes() { lastVar = null; lastWriteVar = null; returnnode = null; } void clearVariantsFromGenes() { SplitClass split = Main.drawCanvas.splits.get(0); for(int g = 0 ; g<split.getGenes().size(); g++) { split.getGenes().get(g).mutations = 0; split.getGenes().get(g).missense = 0; split.getGenes().get(g).nonsense = 0; split.getGenes().get(g).synonymous = 0; split.getGenes().get(g).intronic = 0; split.getGenes().get(g).utr = 0; split.getGenes().get(g).samples.clear(); split.getGenes().get(g).varnodes.clear(); split.getGenes().get(g).intergenic = false; split.getGenes().get(g).transcriptString = new StringBuffer(); } split = null; } void varCalcBig() { boolean isfreeze = VariantHandler.freeze.isSelected(); FileRead.novars = false; if(!VariantHandler.none.isSelected()) { SampleDialog.checkFiles(); if(affected == 0) { Main.showError("Set at least one individual as affected. (right click sample sidebar)", "Note"); return; } } else { VariantHandler.freeze.setSelected(true); } bigcalc = true; Draw.calculateVars = false; Draw.variantcalculator = true; int adder = Settings.windowSize, presearchpos = 1; clearVariantsFromGenes(); int chromcounter = 0; clearVariantsFromBeds(); if(Main.drawCanvas.clusterNodes == null) { Main.drawCanvas.clusterNodes = new ArrayList<ClusterNode>(); } else { Main.drawCanvas.clusterNodes.clear(); } for(int i = 0 ; i < Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).getVarcalc().isSelected()) { Main.bedCanvas.bedTrack.get(i).intersect = true; } } Main.drawCanvas.clusterId = 1; VariantHandler.table.variants = 0; VariantHandler.stattable.variants = 0; VariantHandler.clusterTable.variants = 0; for(int i = 0 ; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).variants = 0; } cancelvarcount = false; VariantHandler.table.genearray.clear(); VariantHandler.table.aminoarray.clear(); VariantHandler.table.controlarray = null; VariantHandler.stattable.sampleArray.clear(); for(int i = 0; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).bedarray= null; VariantHandler.tables.get(i).aminoarray= null; VariantHandler.tables.get(i).vararray= null; VariantHandler.tables.get(i).controlarray= null; VariantHandler.tables.get(i).variants = 0; } head.putNext(null); VarNode vardraw; Object[] addobject; for(int i=0; i<Main.drawCanvas.sampleList.size(); i++) { if(Main.drawCanvas.sampleList.get(i).multiVCF || (Main.drawCanvas.sampleList.get(i).getTabixFile() == null && !Main.drawCanvas.sampleList.get(i).multipart)) { continue; } addobject = new Object[VariantHandler.stattable.headerlengths.length]; addobject[0] = Main.drawCanvas.sampleList.get(i); for(int j = 1; j<addobject.length; j++) { addobject[j] = 0; } Main.drawCanvas.sampleList.get(i).mutationTypes = new double[6]; for(int j = 0; j<6; j++) { Main.drawCanvas.sampleList.get(i).mutationTypes[j] = 0.0; } VariantHandler.stattable.sampleArray.add(addobject); Main.drawCanvas.sampleList.get(i).heterozygotes = 0; Main.drawCanvas.sampleList.get(i).homozygotes = 0; Main.drawCanvas.sampleList.get(i).varcount = 0; Main.drawCanvas.sampleList.get(i).indels = 0; Main.drawCanvas.sampleList.get(i).snvs = 0; Main.drawCanvas.sampleList.get(i).sitioRate = 0; Main.drawCanvas.sampleList.get(i).versioRate = 0; Main.drawCanvas.sampleList.get(i).ins = 0; Main.drawCanvas.sampleList.get(i).callrates = 0.0; Main.drawCanvas.sampleList.get(i).coding = 0; Main.drawCanvas.sampleList.get(i).syn = 0; Main.drawCanvas.sampleList.get(i).nonsyn = 0; Main.drawCanvas.sampleList.get(i).missense = 0; Main.drawCanvas.sampleList.get(i).splice = 0; Main.drawCanvas.sampleList.get(i).nonsense = 0; Main.drawCanvas.sampleList.get(i).fshift = 0; Main.drawCanvas.sampleList.get(i).inframe = 0; } VariantHandler.stattable.setPreferredSize(new Dimension(VariantHandler.statsScroll.getViewport().getWidth(), (VariantHandler.stattable.sampleArray.size()+1)*(Main.defaultFontSize+5)+2)); VariantHandler.stattable.revalidate(); VariantHandler.stattable.repaint(); clearVariantsFromGenes(); if(VariantHandler.allChroms.isSelected()) { if(VariantHandler.allChromsfrom.isSelected()) { chromcounter = Main.chromosomeDropdown.getSelectedIndex(); Main.nothread = true; search = true; searchStart = (int)Main.drawCanvas.splits.get(0).start; searchEnd = (int)Main.drawCanvas.splits.get(0).start+Settings.windowSize; Main.chromosomeDropdown.setSelectedIndex(Main.chromosomeDropdown.getSelectedIndex()); Main.nothread = false; Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); vardraw = FileRead.head.getNext(); } else if(Main.drawCanvas.splits.get(0).start > 10 || Main.chromosomeDropdown.getSelectedIndex() != 0) { Main.nothread = true; search = true; Main.chromosomeDropdown.setSelectedIndex(0); Main.nothread = false; vardraw = FileRead.head.getNext(); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); } else { searchStart = 0; searchEnd = searchStart+Settings.windowSize; getVariantWindow(Main.drawCanvas.splits.get(0).chrom,searchStart,searchEnd); Main.drawCanvas.clusterNodes.clear(); Main.drawCanvas.calcClusters(FileRead.head.getNext()); vardraw = FileRead.head.getNext(); } } else { searchStart = (int)Main.drawCanvas.splits.get(0).start; searchEnd = getNextIntergenic(searchStart+adder); if(searchEnd > (int)Main.drawCanvas.splits.get(0).end) { searchEnd = (int)Main.drawCanvas.splits.get(0).end; } getVariantWindow(Main.drawCanvas.splits.get(0).chrom,searchStart,searchEnd); vardraw = FileRead.head.getNext(); /* for(int i = 0 ; i < Main.bedCanvas.bedTrack.size(); i++) { if(Main.bedCanvas.bedTrack.get(i).getVarcalc().isSelected()) { Main.bedCanvas.bedTrack.get(i).intersect = true; if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) { Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead()); Main.bedCanvas.intersected = true; } else { BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i)); annotator.annotateVars(); Main.bedCanvas.intersected = true; } } } */ } presearchpos = searchEnd; lastVar = FileRead.head; if(VariantHandler.writetofile.isSelected()) { lastWriteVar = FileRead.head; } Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; while(true) { if(cancelvarcount || cancelfileread || !Main.drawCanvas.loading) { cancelFileRead(); nullifyVarNodes(); vardraw = null; break; } if(vardraw == null) { if(VariantHandler.writetofile.isSelected()) { if(VariantHandler.geneSlider.getValue() > 1) { flushVars(vardraw); } else { clearVariantsFromGenes(); } lastVar.putPrev(null); lastWriteVar.putPrev(null); } try { if(VariantHandler.commonSlider.getValue() > 1 && VariantHandler.clusterSize > 0 && Main.drawCanvas.clusterNodes.size() > 0) { Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).width = Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.get(Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.size()-1).getPosition() -Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.get(0).getPosition() +1; VariantHandler.clusterTable.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (Main.drawCanvas.clusterNodes.size()+1)*VariantHandler.clusterTable.rowHeight)); VariantHandler.clusterTable.revalidate(); VariantHandler.clusterTable.repaint(); } for(int i = 0; i<VariantHandler.stattable.sampleArray.size(); i++) { sample = (Sample)VariantHandler.stattable.sampleArray.get(i)[0]; VariantHandler.stattable.sampleArray.get(i)[1] = sample.varcount; VariantHandler.stattable.sampleArray.get(i)[2] = sample.snvs; VariantHandler.stattable.sampleArray.get(i)[3] = sample.indels; VariantHandler.stattable.sampleArray.get(i)[4] = sample.ins; VariantHandler.stattable.sampleArray.get(i)[5] = sample.coding; VariantHandler.stattable.sampleArray.get(i)[6] = MethodLibrary.round(sample.heterozygotes/(double)sample.homozygotes,2); VariantHandler.stattable.sampleArray.get(i)[7] = MethodLibrary.round((int)sample.sitioRate/(double)sample.versioRate,2); for(int j = 0; j<6; j++) { VariantHandler.stattable.sampleArray.get(i)[8+j] = MethodLibrary.round(sample.mutationTypes[j]/(double)sample.snvs, 2); } VariantHandler.stattable.sampleArray.get(i)[14] = MethodLibrary.round(sample.callrates / (double)sample.varcount,2); VariantHandler.stattable.repaint(); } } catch(Exception e) { e.printStackTrace(); } if(VariantHandler.allChroms.isSelected() && searchEnd > Main.drawCanvas.splits.get(0).chromEnd) { for(int i = 0; i<Main.bedCanvas.bedTrack.size(); i++) { removeNonListBeds( Main.bedCanvas.bedTrack.get(i).getHead(), Main.drawCanvas.splits.get(0).chromEnd); } if(cancelvarcount) { break; } if(Main.selectedChrom < Main.chromosomeDropdown.getItemCount()) { chromcounter++; if(chromcounter == Main.chromosomeDropdown.getItemCount()) { break; } if(VariantHandler.onlyAutosomes.isSelected()) { if(Main.chromosomeDropdown.getItemAt(chromcounter).toString().equals("X") || Main.chromosomeDropdown.getItemAt(chromcounter).toString().equals("Y")) { continue; } } //clearVariantsFromGenes(); Main.nothread = true; //search = true; Main.chromosomeDropdown.setSelectedIndex(chromcounter); searchStart = 1; searchEnd = adder; //search = false; Main.nothread = false; presearchpos = searchEnd; getVariantWindow(Main.drawCanvas.splits.get(0).chrom,searchStart,searchEnd); Main.drawCanvas.calcClusters(FileRead.head.getNext()); vardraw = head.getNext(); FileRead.head.putNext(null); if(vardraw == null) { continue; } vardraw.putPrev(lastVar); lastVar.putNext(vardraw); VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), VariantHandler.table.getTableSize()*VariantHandler.table.rowHeight)); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); } } else { VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), VariantHandler.table.getTableSize()*VariantHandler.table.rowHeight)); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); Main.chromDraw.varnode = null; Main.chromDraw.vardraw = null; if(searchEnd >= (int)Main.drawCanvas.splits.get(0).end) { break; } searchStart = presearchpos; searchEnd = searchStart + adder; //getNextIntergenic(presearchpos+adder); presearchpos = searchEnd; for(int i = 0; i<Main.bedCanvas.bedTrack.size(); i++) { removeNonListBeds( Main.bedCanvas.bedTrack.get(i).getHead(), searchStart); } getVariantWindow(Main.drawCanvas.splits.get(0).chrom,searchStart,searchEnd); vardraw = head.getNext(); head.putNext(null); if(vardraw == null) { continue; } vardraw.putPrev(lastVar); lastVar.putNext(vardraw); } } try { if(!VariantHandler.allChroms.isSelected()) { if(vardraw != null && vardraw.getPosition() < Main.drawCanvas.splits.get(0).start) { vardraw = vardraw.getNext(); } if(vardraw == null || vardraw.getPosition() > Main.drawCanvas.splits.get(0).end) { vardraw= null; continue; } } //STATS /* if(vardraw == null) { continue; } */ // Main.drawCanvas.loadbarAll = (int)((vardraw.getPosition()/(double)(Main.drawCanvas.splits.get(0).chromEnd))*100); /* coding = false; if(vardraw.getExons() != null) { for(int e = 0; e < vardraw.getExons().size(); e++) { if(vardraw.getPosition()+1 > vardraw.getExons().get(e).getTranscript().getCodingStart() && vardraw.getPosition()+1 < vardraw.getExons().get(e).getTranscript().getCodingEnd()) { if(vardraw.getPosition()+1 >= vardraw.getExons().get(e).getStart()-2 && vardraw.getPosition()+1 < vardraw.getExons().get(e).getEnd()+2) { coding = true; break; } } } } */ //if(!VariantHandler.vcf.isSelected()) { vardraw = annotateVariant(vardraw); /*} else { if(VariantHandler.writetofile.isSelected()) { VariantHandler.writeNodeToFile(vardraw,Main.chromosomeDropdown.getSelectedItem().toString(), output, outputgz); } else { annotateVariant(vardraw); } } */ //vardraw = vardraw.getNext(); } catch(Exception ex) { ErrorLog.addError(ex.getStackTrace()); ex.printStackTrace(); } } Draw.calculateVars = true; Draw.updatevars = true; Main.drawCanvas.repaint(); vardraw = null; for(int i = 0; i<VariantHandler.tables.size(); i++) { VariantHandler.tables.get(i).setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.tables.get(i).getTableSize()+1)*VariantHandler.tables.get(i).rowHeight)); VariantHandler.tables.get(i).revalidate(); VariantHandler.tables.get(i).repaint(); } VariantHandler.stattable.repaint(); VariantHandler.table.setPreferredSize(new Dimension(VariantHandler.tableScroll.getViewport().getWidth(), (VariantHandler.table.getTableSize()+1)*VariantHandler.table.rowHeight)); if(VariantHandler.tabs.getSelectedIndex() == 0) { VariantHandler.aminoCount.setText(VariantHandler.table.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 1) { VariantHandler.aminoCount.setText(VariantHandler.stattable.variants +" variants"); } else if(VariantHandler.tabs.getSelectedIndex() == 2) { VariantHandler.aminoCount.setText(VariantHandler.clusterTable.variants +" variants"); } else { VariantHandler.aminoCount.setText(VariantHandler.tables.get(VariantHandler.tabs.getSelectedIndex()-3).variants +" variants"); } try { if(output != null) { output.close(); } if(outputgz != null) { for(int i = 0 ; i<VariantHandler.outputStrings.size(); i++) { outputgz.write(VariantHandler.outputStrings.get(i).getBytes()); Feature vcf = VariantHandler.vcfCodec.decode(VariantHandler.outputStrings.get(i)); FileRead.indexCreator.addFeature(vcf, FileRead.filepointer); FileRead.filepointer = outputgz.getFilePointer(); } VariantHandler.outputStrings.clear(); outputgz.flush(); Index index = indexCreator.finalizeIndex(outputgz.getFilePointer()); index.writeBasedOnFeatureFile(outFile); outputgz.close(); } } catch(Exception e) { e.printStackTrace(); } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); if(!isfreeze) { VariantHandler.freeze.setSelected(false); } Main.drawCanvas.current = FileRead.head; if(!Main.drawCanvas.loading) { Draw.calculateVars = true; } Main.drawCanvas.ready("all"); nullifyVarNodes(); bigcalc = false; Draw.variantcalculator = false; Main.drawCanvas.loadbarAll = 0; Main.drawCanvas.loadBarSample= 0; if(VariantHandler.allChroms.isSelected()) { Main.showError("Variant annotation ready!", "Note"); } } int getNextIntergenic(int pos) { int returnpos = pos; int pointer = 0, gene = -1; while(true) { gene = MethodLibrary.getRegion(returnpos, Main.drawCanvas.splits.get(0), pointer); if(gene == -1) { break; } else { if(returnpos < Main.drawCanvas.splits.get(0).getGenes().get(gene).getEnd()+1) { returnpos = Main.drawCanvas.splits.get(0).getGenes().get(gene).getEnd()+1; } pointer = gene; } } return returnpos; } void writeToFile(VarNode vardraw, BufferedWriter output, BlockCompressedOutputStream outputgz) { if(VariantHandler.table.genearray.size() > 0) { if(VariantHandler.tsv.isSelected() || VariantHandler.compactTsv.isSelected()) { for(int i = 0 ; i<VariantHandler.table.genearray.size(); i++) { if(vardraw == null || vardraw.getPosition() > VariantHandler.table.genearray.get(i).getEnd()) { VariantHandler.writeTranscriptToFile(VariantHandler.table.genearray.get(i), output); if(VariantHandler.allChroms.isSelected() || bigcalc) { for(int s = 0; s<VariantHandler.table.genearray.get(i).varnodes.size(); s++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getExons() != null) { for(int e = 0 ; e<VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().size(); e++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().get(e).getTranscript().equals(VariantHandler.table.genearray.get(i))) { VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().remove(e); e--; } } } if(VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts() != null) { for(int e = 0 ; e<VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().size(); e++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().equals(VariantHandler.table.genearray.get(i))) { VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().remove(e); e--; } } } } } VariantHandler.table.genearray.get(i).samples.clear(); VariantHandler.table.genearray.get(i).varnodes.clear(); VariantHandler.table.genearray.remove(i); i--; } } } else if(VariantHandler.vcf.isSelected() || VariantHandler.oncodrive.isSelected()){ /* ArrayList<VarNode> nodes = new ArrayList<VarNode>(); String lastChrom; for(int v=0; v<VariantHandler.table.genearray.get(0).varnodes.size(); v++) { if(!nodes.contains(VariantHandler.table.genearray.get(0).varnodes.get(v))) { nodes.add(VariantHandler.table.genearray.get(0).varnodes.get(v)); } } if(lastpos < vardraw.getPosition()) { lastpos = vardraw.getPosition(); } else { return; } lastChrom = Main.chromosomeDropdown.getSelectedItem().toString(); */ /* if(bigcalc) { Main.drawCanvas.loadbarAll = (int)((lastpos/(double)(Main.drawCanvas.splits.get(0).chromEnd))*100); } else { Main.drawCanvas.loadbarAll = (int)((lastpos/(double)(Main.drawCanvas.variantsEnd))*100); } Main.drawCanvas.loadBarSample = Main.drawCanvas.loadbarAll; */ if(VariantHandler.geneSlider.getValue() > 1) { } else { VariantHandler.writeNodeToFile(vardraw,vardraw.getChrom(), output, outputgz); lastWriteVar = vardraw; } for(int i = 0 ; i< VariantHandler.table.genearray.size() ; i++) { if(vardraw == null || VariantHandler.table.genearray.get(i).getEnd() < vardraw.getPosition()) { if(VariantHandler.allChroms.isSelected() || bigcalc) { for(int s = 0; s<VariantHandler.table.genearray.get(i).varnodes.size(); s++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getExons() != null) { for(int e = 0 ; e<VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().size(); e++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().get(e).getTranscript().equals(VariantHandler.table.genearray.get(i))) { VariantHandler.table.genearray.get(i).varnodes.get(s).getExons().remove(e); e--; } } } if(VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts() != null) { for(int e = 0 ; e<VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().size(); e++) { if(VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().equals(VariantHandler.table.genearray.get(i))) { VariantHandler.table.genearray.get(i).varnodes.get(s).getTranscripts().remove(e); e--; } } } } } if(VariantHandler.geneSlider.getValue() == 1) { VariantHandler.table.genearray.get(i).samples.clear(); } VariantHandler.table.genearray.get(i).varnodes.clear(); VariantHandler.table.genearray.remove(i); i--; } } if(VariantHandler.geneSlider.getValue() > 1) { if(VariantHandler.table.genearray.size() == 0) { flushVars(vardraw); } } } } } void flushVars(VarNode vardraw) { if(VariantHandler.vcf.isSelected() || VariantHandler.oncodrive.isSelected()) { if(lastWriteVar != null) { if(lastWriteVar.getNext()== null) { found = false; if(lastWriteVar.isInGene()) { if(lastWriteVar.getExons() != null) { for(int i = 0 ; i<lastWriteVar.getExons().size(); i++) { if(lastWriteVar.getExons().get(i).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getExons().remove(i); i--; } } } else { for(int i = 0 ; i<lastWriteVar.getTranscripts().size(); i++) { if(lastWriteVar.getTranscripts().get(i).getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getTranscripts().remove(i); i--; } } } } if(found) { VariantHandler.writeNodeToFile(lastWriteVar,lastWriteVar.getChrom(), output, outputgz); } } else { lastWriteVar = lastWriteVar.getNext(); } } if(vardraw == null) { if(VariantHandler.table.genearray.size() > 0) { while(lastWriteVar != null) { found = false; if(lastWriteVar.isInGene()) { if(lastWriteVar.getExons() != null) { for(int i = 0 ; i<lastWriteVar.getExons().size(); i++) { if(lastWriteVar.getExons().get(i).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getExons().remove(i); i--; } } } else { for(int i = 0 ; i<lastWriteVar.getTranscripts().size(); i++) { if(lastWriteVar.getTranscripts().get(i).getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getTranscripts().remove(i); i--; } } } } if(found) { VariantHandler.writeNodeToFile(lastWriteVar,lastWriteVar.getChrom(), output, outputgz); } /*if(lastWriteVar.getNext() == null) { break; }*/ lastWriteVar = lastWriteVar.getNext(); } } } else { while(!lastWriteVar.equals(vardraw)) { found = false; if(lastWriteVar.isInGene()) { if(lastWriteVar.getExons() != null) { for(int i = 0 ; i<lastWriteVar.getExons().size(); i++) { if(lastWriteVar.getExons().get(i).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getExons().remove(i); i--; } } } else { for(int i = 0 ; i<lastWriteVar.getTranscripts().size(); i++) { if(lastWriteVar.getTranscripts().get(i).getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { found = true; } else { lastWriteVar.getTranscripts().remove(i); i--; } } } } if(found) { VariantHandler.writeNodeToFile(lastWriteVar,lastWriteVar.getChrom(), output, outputgz); } lastWriteVar = lastWriteVar.getNext(); } } } else { if(vardraw == null && VariantHandler.table.genearray.size() > 0) { for(int i =0;i< VariantHandler.table.genearray.size(); i++) { VariantHandler.writeTranscriptToFile(VariantHandler.table.genearray.get(i), output); } VariantHandler.table.genearray.clear(); } } } static boolean checkRecessiveHomo(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { boolean passed = true; int samples = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).getSample().affected) { //parentcount = entry.getValue().get(m).getSample().parents; if(!entry.getValue().get(m).isHomozygous()) { passed = false; break; } samples++; } else { if(entry.getValue().get(m).isHomozygous()) { passed = false; break; } } /*if(entry.getValue().get(m).getSample().children != null && entry.getValue().get(m).getSample().children.size() > 0) { if(entry.getValue().get(m).isHomozygous()) { passed = false; break; } parents++; }*/ entry.getValue().get(m).inheritance = true; } if(samples != FileRead.affected) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } /*if(parents != parentcount) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; }*/ if(!passed) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkDominant(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { boolean passed = true; int samples = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).isHomozygous()) { passed = false; break; } if(!entry.getValue().get(m).getSample().affected) { passed = false; break; } entry.getValue().get(m).inheritance = true; samples++; } if(samples != FileRead.affected) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } if(!passed) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkDeNovo(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { int samples = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).getSample().children != null) { samples = 0; break; } if(entry.getValue().get(m).getSample().parents != 2) { continue; } samples++; entry.getValue().get(m).inheritance = true; } if(samples != 1) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkXlinked(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { int samples = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).getSample().children != null && entry.getValue().get(m).getSample().children.size() > 0 && !entry.getValue().get(m).getSample().female) { samples = 0; break; } if(!entry.getValue().get(m).getSample().affected) { if(entry.getValue().get(m).isHomozygous()) { samples = 0; break; } } samples++; entry.getValue().get(m).inheritance = true; } if(samples != 2) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkCompound(VarNode node, Entry<String, ArrayList<SampleNode>> entry ) { try { boolean passed = true; int samples = 0, parentcount = 0, parents = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).getSample() == null) { continue; } if(entry.getValue().get(m).getSample().annotation) { entry.getValue().get(m).inheritance = true; continue; } if(entry.getValue().get(m).getSample().affected && Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } if(VariantHandler.freeze.isSelected()) { if(Main.drawCanvas.hideVar(entry.getValue().get(m),entry.getKey().length() > 1)) { continue; } } if(entry.getValue().get(m).isHomozygous()) { passed = false; break; } if(entry.getValue().get(m).getSample().children != null && entry.getValue().get(m).getSample().children.size() > 0) { parentcount++; } entry.getValue().get(m).inheritance = true; if(entry.getValue().get(m).getSample().affected) { if(parents < entry.getValue().get(m).getSample().parents) { parents =entry.getValue().get(m).getSample().parents; } samples++; } } if(!passed) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } if(parentcount == 2) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } if(parents != 0) { if(parentcount == 0) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } if(samples != FileRead.affected) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } return false; } } catch(Exception e) { e.printStackTrace(); } return true; } static boolean checkCompoundGene(Gene gene, VarNode vardraw) { if(gene.varnodes.size() < 1) { gene.compounds.clear(); return false; } Entry<String, ArrayList<SampleNode>> entry, entry2; Boolean found2 = null; for(int i = 0 ; i< gene.varnodes.size(); i++) { for(int v = 0 ; v<gene.varnodes.get(i).vars.size(); v++) { entry = gene.varnodes.get(i).vars.get(v); ArrayList<Sample> healthArray = new ArrayList<Sample>(); for(int s = 0; s<entry.getValue().size(); s++) { if(entry.getValue().get(s).getSample() == null) { continue; } if(entry.getValue().get(s).getSample().annotation) { entry.getValue().get(s).inheritance = true; continue; } /*if(!entry.getValue().get(s).inheritance) { continue; }*/ if(!entry.getValue().get(s).getSample().affected) { healthArray.add(entry.getValue().get(s).getSample()); } else { if(entry.getValue().get(s).isHomozygous()) { healthArray.clear(); break; } } } if(healthArray.size() > 0) { for(int var = 0 ; var<vardraw.vars.size(); var++) { entry2 = vardraw.vars.get(var); found2=null; for(int s = 0; s<entry2.getValue().size(); s++) { if(entry2.getValue().get(s).getSample() == null) { continue; } if(entry2.getValue().get(s).getSample().annotation) { entry2.getValue().get(s).inheritance = true; continue; } /*if(!entry2.getValue().get(s).inheritance) { continue; }*/ if(!entry2.getValue().get(s).getSample().affected) { if(healthArray.contains(entry2.getValue().get(s).getSample())) { found2 = true; break; } else { found2 = false; } } } if(found2 != null && !found2) { if(!gene.compounds.contains(vardraw)) { gene.compounds.add(vardraw); } if(!gene.compounds.contains(gene.varnodes.get(i))) { gene.compounds.add(gene.varnodes.get(i)); } //System.out.println(gene.compounds.size()); } } } } } /*if(gene.samples.size() < FileRead.affected) { return false; }*/ if(gene.compounds.size()== 0) { return false; } return true; } static void setUninherited(Entry<String, ArrayList<SampleNode>> entry) { for(int m = 0; m<entry.getValue().size(); m++) { entry.getValue().get(m).inheritance = false; } } VarNode annotateVariant(VarNode vardraw) { if(Main.drawCanvas.hideNode(vardraw)) { returnnode = vardraw.getNext(); if(VariantHandler.allChroms.isSelected()) { vardraw.removeNode(); } return returnnode; } Map.Entry<String, ArrayList<SampleNode>> entry = null; String base = null, amino = null; int pretrack = -1, preI = -1; Main.drawCanvas.loadbarAll = (int)((vardraw.getPosition()/(double)(Main.drawCanvas.splits.get(0).chromEnd))*100); Main.drawCanvas.loadBarSample = Main.drawCanvas.loadbarAll; boolean recessivefound = false; for(int v = 0; v<vardraw.vars.size(); v++) { entry = vardraw.vars.get(v); if(Main.drawCanvas.hideNodeVar(vardraw, entry)) { if(VariantHandler.allChroms.isSelected()) { vardraw.vars.remove(v); v--; } continue; } if(Main.drawCanvas.annotationOn) { if(vardraw.vars.size() == 1 && vardraw.vars.get(0).getValue().size() == 1 && vardraw.vars.get(0).getValue().get(0).getSample().annotation) { if(VariantHandler.allChroms.isSelected()) { vardraw.vars.remove(v); v--; } continue; } } recessivefound = false; base = entry.getKey(); mutcount = 0; if(!VariantHandler.none.isSelected()) { if(VariantHandler.recessiveHomo.isSelected()) { if(!checkRecessiveHomo(vardraw, entry)) continue; } else if(VariantHandler.denovo.isSelected()) { if(!checkDeNovo(vardraw, entry)) continue; } else if(VariantHandler.dominant.isSelected()) { if(!checkDominant(vardraw, entry)) continue; } else if(VariantHandler.xLinked.isSelected()) { if(!checkXlinked(vardraw, entry)) continue; } else if(VariantHandler.compound.isSelected()) { if(!checkCompound(vardraw, entry)) continue; } else if(VariantHandler.recessive.isSelected()) { recessivefound = checkRecessiveHomo(vardraw, entry); if(!recessivefound) { if(Main.chromosomeDropdown.getSelectedItem().equals("X")) { recessivefound = checkXlinked(vardraw, entry); } } if(!recessivefound) { if(!checkCompound(vardraw, entry)) { continue; } } } } for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { if(VariantHandler.allChroms.isSelected()) { entry.getValue().remove(m); m--; } continue; } if(entry.getValue().get(m).getSample().annotation) { continue; } sample = entry.getValue().get(m).getSample(); if(VariantHandler.onlyselected.isSelected()) { if(!sample.equals(Main.drawCanvas.selectedSample)) { continue; } } sample.varcount++; mutcount++; VariantHandler.stattable.variants++; if(vardraw.coding) { sample.coding++; } sample.callrates += entry.getValue().get(m).getAlleleFraction(); if(entry.getValue().get(m).isHomozygous()) { sample.homozygotes++; } else { sample.heterozygotes++; } if(entry.getKey().length() > 1) { if(entry.getKey().contains("del")) { sample.indels++; } else { sample.ins++; } } else { //TODO //System.out.println((int)(MethodLibrary.round(entry.getValue().get(m).getAlleleFraction(),4)*10000)); //array[entry.getValue().get(m).getSample().getIndex()][(int)(MethodLibrary.round(entry.getValue().get(m).getAlleleFraction(),5)*10000)]++; /*if(sample.getName().contains("161")) { if(Main.getBase.get(vardraw.getRefBase()).equals("C")) { if(base.equals("A")) { System.out.println(vardraw.getChrom() +":" +vardraw.getPosition()); } } }*/ if(VariantHandler.onlyStats.isSelected()) { if(VariantHandler.outputContexts.isSelected()) { String context = Main.chromDraw.getSeq(Main.drawCanvas.splits.get(0).chrom,vardraw.getPosition()-1, vardraw.getPosition()+2, Main.referenceFile).toString(); //boolean set = false; if(contexts == null) { contexts = new HashMap<String, Integer[]>(); //contextQuals = new HashMap<String, Float[]>(); } /* if(base.equals("T")) { if(context.endsWith("CG")) { set = true; } } if(base.equals("A")) { if(context.startsWith("CG")) { set = true; } }*/ // if(set) { basecontext = base+context; if(contexts.containsKey(base+context)) { if(contexts.get(base+context)[sample.getIndex()] == null) { contexts.get(base+context)[sample.getIndex()] = 1; //contextQuals.get(base+context)[0]++; // contextQuals.get(base+context)[1] += entry.getValue().get(m).getQuality(); } else { contexts.get(base+context)[sample.getIndex()]++; //contextQuals.get(base+context)[0]++; //contextQuals.get(base+context)[1] += entry.getValue().get(m).getQuality(); } } else { if(contexts.containsKey(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))) { if(contexts.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[sample.getIndex()] == null) { contexts.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[sample.getIndex()] = 1; //contextQuals.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[0] = 1F; //contextQuals.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[1] = entry.getValue().get(m).getQuality(); } else { contexts.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[sample.getIndex()]++; //contextQuals.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[0]++; //contextQuals.get(MethodLibrary.reverseComplement(base)+MethodLibrary.reverseComplement(context))[1] += entry.getValue().get(m).getQuality(); } } else { contexts.put(base+context, new Integer[Main.drawCanvas.sampleList.size()]); contexts.get(base+context)[sample.getIndex()] = 1; //contextQuals.put(base+context, new Float[2]); //contextQuals.get(base+context)[0] = 1F; //contextQuals.get(base+context)[1] = entry.getValue().get(m).getQuality(); } } } // } } sample.snvs++; try { if(!Main.getBase.get(vardraw.getRefBase()).equals("N") && !entry.getKey().equals("N") && !entry.getKey().equals(".")) { sample.mutationTypes[Main.mutTypes.get(Main.getBase.get(vardraw.getRefBase()) +entry.getKey())]++; } } catch(Exception e) { System.out.println(sample.getName() +" " +vardraw.getPosition() +" " +(char)vardraw.getRefBase() +" " +Main.getBase.get(vardraw.getRefBase()) +" " +entry.getKey()); e.printStackTrace(); } if(((char)vardraw.getRefBase() == 'A' && entry.getKey().equals("G")) || ((char)vardraw.getRefBase() == 'G' && entry.getKey().equals("A")) || ((char)vardraw.getRefBase() == 'C' && entry.getKey().equals("T")) || ((char)vardraw.getRefBase() == 'T' && entry.getKey().equals("C"))) { sample.sitioRate++; } else { sample.versioRate++; } } } if(mutcount == 0) { continue; } // INTRONIC if(VariantHandler.intronic.isSelected() && vardraw.isInGene() && vardraw.getTranscripts() != null && vardraw.getExons() == null) { for(int t = 0; t<vardraw.getTranscripts().size(); t++) { for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { if(VariantHandler.allChroms.isSelected()) { entry.getValue().remove(i); i--; } continue; } if(VariantHandler.onlyselected.isSelected()) { if(!entry.getValue().get(i).getSample().equals(Main.drawCanvas.selectedSample)) { continue; } } if(!vardraw.getTranscripts().get(t).getGene().samples.contains(entry.getValue().get(i).getSample())) { vardraw.getTranscripts().get(t).getGene().samples.add(entry.getValue().get(i).getSample()); } } if(!VariantHandler.onlyStats.isSelected()) { boolean add = true; if(VariantHandler.recessive.isSelected()) { if(!recessivefound) { add = checkCompoundGene(vardraw.getTranscripts().get(t).getGene(),vardraw); } } else if(VariantHandler.compound.isSelected()) { add = checkCompoundGene(vardraw.getTranscripts().get(t).getGene(),vardraw); } if(add && vardraw.getTranscripts().get(t).getGene().mutations == 0 && vardraw.getTranscripts().get(t).getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { VariantHandler.table.addEntry(vardraw.getTranscripts().get(t).getGene()); VariantHandler.table.revalidate(); VariantHandler.table.repaint(); } } vardraw.getTranscripts().get(t).getGene().intronic+=mutcount; vardraw.inVarList = true; if(vardraw.inVarList) { if(!vardraw.getTranscripts().get(t).getGene().varnodes.contains(vardraw)) { if(!VariantHandler.onlyStats.isSelected()) { vardraw.getTranscripts().get(t).getGene().varnodes.add(vardraw); } preI = -1; } if(v != preI) { VariantHandler.table.variants += mutcount; vardraw.getTranscripts().get(t).getGene().mutations+=mutcount; preI = v; } } } } /*if(vardraw.getPosition() == 70117871) { System.out.println(vardraw.getExons()); }*/ if(vardraw != null && vardraw.getExons() != null) { ArrayList<Gene> calcgene = new ArrayList<Gene>(); for(int exon = 0; exon<vardraw.getExons().size(); exon++) { amino = Main.chromDraw.getAminoChange(vardraw,base,vardraw.getExons().get(exon)); if(amino.contains("UTR")) { if(VariantHandler.utr.isSelected()) { if(!VariantHandler.table.genearray.contains(vardraw.getExons().get(exon).getTranscript().getGene()) && vardraw.getExons().get(exon).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue()) { if(!VariantHandler.onlyStats.isSelected()) { boolean add = true; if(VariantHandler.recessive.isSelected()) { if(!recessivefound) { add = checkCompoundGene(vardraw.getExons().get(exon).getTranscript().getGene(),vardraw); } } else if(VariantHandler.compound.isSelected()) { add = checkCompoundGene(vardraw.getExons().get(exon).getTranscript().getGene(),vardraw); } if(add) { VariantHandler.table.addEntry(vardraw.getExons().get(exon).getTranscript().getGene()); } } } vardraw.inVarList = true; vardraw.getExons().get(exon).getTranscript().getGene().utr +=mutcount; } else { continue; } } if(VariantHandler.nonsense.isSelected()) { if(!MethodLibrary.aminoEffect(amino).contains("nonsense")) { continue; } } if(VariantHandler.synonymous.isSelected()) { if(MethodLibrary.aminoEffect(amino).contains("synonymous") ) { continue; } } for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { continue; } if(VariantHandler.onlyselected.isSelected()) { if(!entry.getValue().get(i).getSample().equals(Main.drawCanvas.selectedSample)) { continue; } } if(!vardraw.getExons().get(exon).getTranscript().getGene().samples.contains(entry.getValue().get(i).getSample())) { if(!VariantHandler.onlyStats.isSelected()) { vardraw.getExons().get(exon).getTranscript().getGene().samples.add(entry.getValue().get(i).getSample()); } } } boolean add = true; if(!VariantHandler.onlyStats.isSelected()) { if(VariantHandler.recessive.isSelected()) { if(!recessivefound) { add = checkCompoundGene(vardraw.getExons().get(exon).getTranscript().getGene(),vardraw); } } else if(VariantHandler.compound.isSelected()) { add = checkCompoundGene(vardraw.getExons().get(exon).getTranscript().getGene(),vardraw); } if(add && !VariantHandler.table.genearray.contains(vardraw.getExons().get(exon).getTranscript().getGene()) && vardraw.getExons().get(exon).getTranscript().getGene().samples.size() >= VariantHandler.geneSlider.getValue() ) { VariantHandler.table.addEntry(vardraw.getExons().get(exon).getTranscript().getGene()); } } if(MethodLibrary.aminoEffect(amino).contains("nonsense")) { if(!calcgene.contains(vardraw.getExons().get(exon).getTranscript().getGene())) { for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { continue; } entry.getValue().get(i).getSample().nonsense++; if(entry.getKey().length() > 1) { entry.getValue().get(i).getSample().fshift++; } if(amino.contains("spl")) { entry.getValue().get(i).getSample().splice++; } else { entry.getValue().get(i).getSample().nonsyn++; } } } vardraw.getExons().get(exon).getTranscript().getGene().nonsense +=mutcount; } else if(MethodLibrary.aminoEffect(amino).contains("missense")) { if(!calcgene.contains(vardraw.getExons().get(exon).getTranscript().getGene())) { for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { continue; } if(entry.getKey().length() > 1) { entry.getValue().get(i).getSample().inframe++; } entry.getValue().get(i).getSample().missense++; entry.getValue().get(i).getSample().nonsyn++; } } vardraw.getExons().get(exon).getTranscript().getGene().missense +=mutcount; } else if(MethodLibrary.aminoEffect(amino).contains("synonymous")) { if(!calcgene.contains(vardraw.getExons().get(exon).getTranscript().getGene())) { for(int i = 0; i<entry.getValue().size(); i++) { if(entry.getValue().get(i).alleles != null) { break; } if(entry.getValue().get(i).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(i), entry.getKey().length() > 1)) { continue; } entry.getValue().get(i).getSample().syn++; } } vardraw.getExons().get(exon).getTranscript().getGene().synonymous +=mutcount; } vardraw.inVarList = true; if(!vardraw.getExons().get(exon).getTranscript().getGene().varnodes.contains(vardraw)) { if(!VariantHandler.onlyStats.isSelected()) { vardraw.getExons().get(exon).getTranscript().getGene().varnodes.add(vardraw); } preI = -1; } if(v != preI) { vardraw.getExons().get(exon).getTranscript().getGene().mutations+=mutcount; VariantHandler.table.variants +=mutcount; preI = v; } VariantHandler.table.revalidate(); VariantHandler.table.repaint(); if(!calcgene.contains(vardraw.getExons().get(exon).getTranscript().getGene())) { calcgene.add(vardraw.getExons().get(exon).getTranscript().getGene()); } } } preI = v; if(!vardraw.isInGene() && VariantHandler.intergenic.isSelected()) { /* for(int v = 0; v<vardraw.vars.size(); v++) { entry = vardraw.vars.get(v); if(Main.drawCanvas.hideNodeVar(vardraw, entry)) { continue; } base = entry.getKey(); mutcount = 0; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(Main.drawCanvas.hideVar(entry.getValue().get(m))) { continue; } mutcount++; } */ if(mutcount > 0) { if(VariantHandler.table.genearray.size() == 0 || !VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).intergenic || !VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).getName().equals(vardraw.getTranscripts().get(0).getGene().getName())) { Gene addgene =null; try { addgene = new Gene(vardraw.getTranscripts().get(0).getGene()); } catch(Exception e) { e.printStackTrace(); //Main.drawCanvas.ready("all"); break; } addgene.intergenic = true; addgene.mutations = mutcount; VariantHandler.table.variants += mutcount; if(!VariantHandler.onlyStats.isSelected()) { addgene.varnodes.add(vardraw); boolean add = true; if(VariantHandler.recessive.isSelected()) { if(!recessivefound) { add = checkCompoundGene(addgene,vardraw); } } else if(VariantHandler.compound.isSelected()) { add = checkCompoundGene(addgene,vardraw); } if(add) { VariantHandler.table.addEntry(addgene); } } for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(entry.getValue().get(m).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { continue; } if(!addgene.samples.contains(entry.getValue().get(m).getSample())) { if(!VariantHandler.onlyStats.isSelected()) { addgene.samples.add(entry.getValue().get(m).getSample()); } } } } else { if(!VariantHandler.onlyStats.isSelected()) { VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).mutations +=mutcount; if(!VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).varnodes.contains(vardraw)) { VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).varnodes.add(vardraw); } } VariantHandler.table.variants += mutcount; for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(entry.getValue().get(m).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { continue; } if(!VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).samples.contains(entry.getValue().get(m).getSample())) { if(!VariantHandler.onlyStats.isSelected()) { VariantHandler.table.genearray.get(VariantHandler.table.genearray.size()-1).samples.add(entry.getValue().get(m).getSample()); } } } // } } vardraw.inVarList = true; } } //TODO TAHAN // System.out.println(vardraw.getTranscripts().get(0).getGenename() +"..." +vardraw.getTranscripts().get(1).getGenename() ); } if(!vardraw.inVarList) { returnnode = vardraw.getNext(); if(VariantHandler.allChroms.isSelected()) { vardraw.removeNode(); } return returnnode; } else { mutcount = 0; for(int v = 0; v<vardraw.vars.size(); v++) { entry = vardraw.vars.get(v); if(Main.drawCanvas.hideNodeVar(vardraw, entry)) { if(VariantHandler.allChroms.isSelected()) { vardraw.vars.remove(v); v--; } continue; } base = entry.getKey(); for(int m = 0; m<entry.getValue().size(); m++) { if(entry.getValue().get(m).alleles != null) { break; } if(entry.getValue().get(m).getSample().annotation) { continue; } if(Main.drawCanvas.hideVar(entry.getValue().get(m), entry.getKey().length() > 1)) { if(VariantHandler.allChroms.isSelected()) { entry.getValue().remove(m); m--; } continue; } mutcount++; } } if(VariantHandler.commonSlider.getValue() > 1 && VariantHandler.clusterSize > 0) { if(Main.drawCanvas.clusterNodes.size() == 0) { ClusterNode cluster = new ClusterNode(); cluster.nodecount=mutcount; cluster.ID = vardraw.clusterId; vardraw.clusterNode = cluster; cluster.varnodes.add(vardraw); cluster.width = 1; Main.drawCanvas.clusterNodes.add(cluster); } else if(Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).ID != vardraw.clusterId) { Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).width = Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.get(Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.size()-1).getPosition() -Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.get(0).getPosition() +1; ClusterNode cluster = new ClusterNode(); cluster.nodecount+= mutcount; cluster.ID = vardraw.clusterId; vardraw.clusterNode = cluster; cluster.varnodes.add(vardraw); cluster.width = 1; Main.drawCanvas.clusterNodes.add(cluster); } else { vardraw.clusterNode = Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1); Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).nodecount+=mutcount; Main.drawCanvas.clusterNodes.get(Main.drawCanvas.clusterNodes.size()-1).varnodes.add(vardraw); } VariantHandler.clusterTable.variants+=mutcount; } if(!VariantHandler.writetofile.isSelected()) { if(vardraw != null && vardraw.inVarList && vardraw.bedhit && vardraw.getBedHits() != null) { pretrack = -1; for(int i = 0; i<vardraw.getBedHits().size(); i++) { vardraw.getBedHits().get(i).inVarlist = true; if(pretrack != vardraw.getBedHits().get(i).getTrack().trackIndex) { vardraw.getBedHits().get(i).getTrack().getTable().variants += mutcount; pretrack = vardraw.getBedHits().get(i).getTrack().trackIndex; } if(vardraw.getBedHits().get(i).getTrack().getTable().bedarray == null) { vardraw.getBedHits().get(i).getTrack().getTable().bedarray = new ArrayList<BedNode>(); } if(!vardraw.getBedHits().get(i).getTrack().getTable().bedarray.contains(vardraw.getBedHits().get(i))) { vardraw.getBedHits().get(i).mutations+=mutcount; vardraw.getBedHits().get(i).getTrack().getTable().bedarray.add(vardraw.getBedHits().get(i)); vardraw.getBedHits().get(i).getTrack().getTable().setPreferredSize(new Dimension(vardraw.getBedHits().get(i).getTrack().getTable().tablescroll.getViewport().getWidth(), (vardraw.getBedHits().get(i).getTrack().getTable().getTableSize()+2+samplecount)*vardraw.getBedHits().get(i).getTrack().getTable().rowHeight)); vardraw.getBedHits().get(i).getTrack().getTable().revalidate(); // vardraw.inVarList = true; } else { vardraw.getBedHits().get(i).mutations+=mutcount; // vardraw.inVarList = true; } } } } } if(VariantHandler.writetofile.isSelected()) { writeToFile(vardraw, output, outputgz); } lastVar = vardraw; return vardraw.getNext(); // } } /* static void fetchEnsembl2() { try { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser("genome"); dataSource.setPassword(""); dataSource.setServerName("genome-mysql.cse.ucsc.edu"); dataSource.setDatabaseName("hg19"); Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("select S.*,X.*,G.* from ensemblSource as S,ensGene as G,knownToEnsembl as KE, kgXref as X where S.name = G.name and G.name=KE.value and KE.name=X.kgID"); ResultSet rs = stmt.executeQuery("select E.chrom, E.txStart, E.txEnd, N.value, E.exonCount, E.strand, E.name2, E.name, X.spID, C.transcript, S.source, E.cdsStart, E.cdsEnd, E.exonStarts, E.exonEnds, E.exonFrames, X.description from " + "knownToEnsembl as K left outer join knownCanonical as C on K.name = C.transcript " + "left outer join ensGene as E on K.value = E.name " + "left outer join kgXref as X on K.name = X.kgID " + "left outer join ensemblSource as S on S.name = E.name " + "left outer join ensemblToGeneName as N on E.name = N.name"); BufferedWriter writer = new BufferedWriter(new FileWriter("exons.txt")); String header = "#Chrom\tGeneStart\tGeneEnd\tName\tExonCount\tStrand\tENSG\tENST\tUniProt\tCanonical\tBiotype\tCodingStart\tCodingEnd\tExonStarts\tExonEnds\tStartPhases\tDescription"; writer.write(header +"\n"); while(rs.next()) { writer.write(rs.getString(1).substring(3) +"\t"); for(int i = 2; i <= rs.getMetaData().getColumnCount(); i++) { if(rs.getString(i) == null || rs.getString(i).equals("")) { writer.write("-\t"); } else if(i == 10) { if(rs.getString(i).equals("null")) { writer.write("0\t"); } else { writer.write("1\t"); } } else { writer.write(rs.getString(i) +"\t"); } } writer.write("\n"); } writer.close(); rs.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } } static void fetchEnsembl() { try { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser("anonymous"); dataSource.setPassword(""); dataSource.setServerName("ensembldb.ensembl.org"); dataSource.setPort(3337); dataSource.setDatabaseName("homo_sapiens_core_84_37"); Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("select S.*,X.*,G.* from ensemblSource as S,ensGene as G,knownToEnsembl as KE, kgXref as X where S.name = G.name and G.name=KE.value and KE.name=X.kgID"); ResultSet rs = stmt.executeQuery("SELECT transcript.stable_id, seq_region.name, transcript.seq_region_strand, transcript.biotype, start_exon.stable_id AS start_exon_id, translation.seq_start, end_exon.stable_id AS end_exon_id ,translation.seq_end " + "FROM translation JOIN transcript ON translation.transcript_id=transcript.transcript_id " + "JOIN exon AS start_exon ON translation.start_exon_id = start_exon.exon_id "+ "JOIN exon AS end_exon ON translation.end_exon_id = end_exon.exon_id " + "JOIN gene ON transcript.gene_id = gene.gene_id " + "JOIN seq_region ON gene.seq_region_id = seq_region.seq_region_id " + "WHERE seq_region.coord_system_id = 2"); BufferedWriter writer = new BufferedWriter(new FileWriter("exons.txt")); String header = "#Chrom\tGeneStart\tGeneEnd\tName\tExonCount\tStrand\tENSG\tENST\tUniProt\tCanonical\tBiotype\tCodingStart\tCodingEnd\tExonStarts\tExonEnds\tStartPhases\tDescription"; writer.write(header +"\n"); while(rs.next()) { writer.write(rs.getString(1).substring(3) +"\t"); System.out.print(rs.getString(1).substring(3) +"\t"); for(int i = 2; i <= rs.getMetaData().getColumnCount(); i++) { if(rs.getString(i) == null || rs.getString(i).equals("")) { writer.write("-\t"); System.out.print("-\t"); } else if(i == 10) { if(rs.getString(i).equals("null")) { writer.write("0\t"); System.out.print("0\t"); } else { writer.write("1\t"); System.out.print("1\t"); } } else { writer.write(rs.getString(i) +"\t"); System.out.print(rs.getString(i) +"\t"); } } System.out.println(); writer.write("\n"); } writer.close(); rs.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } } static void fetchAnnotation() { try { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser("genome"); dataSource.setPassword(""); dataSource.setServerName("genome-mysql.cse.ucsc.edu"); // dataSource.setDatabaseName("hg19"); dataSource.setDatabaseName("mm10"); Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); // ResultSet rs = conn.getMetaData().getCatalogs(); // ResultSet rs = stmt.executeQuery("select S.*,X.*,G.* from ensemblSource as S,ensGene as G,knownToEnsembl as KE, kgXref as X where S.name = G.name and G.name=KE.value and KE.name=X.kgID"); System.out.println("Fetching..."); ResultSet rs = stmt.executeQuery("select E.chrom, E.txStart, E.txEnd, N.value, E.exonCount, E.strand, E.name2, E.name, E.name, E.name, S.source, E.cdsStart, E.cdsEnd, E.exonStarts, E.exonEnds, E.exonFrames, E.name from " //+ "knownToEnsembl as K left outer join knownCanonical as C on K.name = C.transcript " + "ensGene as E left outer join ensemblToGeneName as N on E.name = N.name " + "left outer join ensemblSource as S on S.name = E.name"); System.out.println("Fecthed"); BufferedWriter writer = new BufferedWriter(new FileWriter("exons.txt")); String header = "#Chrom\tGeneStart\tGeneEnd\tName\tExonCount\tStrand\tENSG\tENST\tUniProt\tCanonical\tBiotype\tCodingStart\tCodingEnd\tExonStarts\tExonEnds\tStartPhases\tDescription"; writer.write(header +"\n"); while(rs.next()) { //ResultSetMetaData joo = rs.getMetaData(); writer.write(rs.getString(1).substring(3) +"\t"); // System.out.print(rs.getString(1).substring(3) +"\t"); for(int i = 2; i <= rs.getMetaData().getColumnCount(); i++) { if(rs.getString(i) == null || rs.getString(i).equals("")) { // System.out.print("-\t"); writer.write("-\t"); } else if(i == 10) { if(rs.getString(i).equals("null")) { // System.out.print("0\t"); writer.write("0\t"); } else { // System.out.print("1\t"); writer.write("1\t"); } } else { // System.out.print(rs.getString(i) +"\t"); writer.write(rs.getString(i) +"\t"); } } // System.out.println(); writer.write("\n"); } writer.close(); rs.close(); } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } }*/ public VariantCall[][] variantCaller(String chrom, int startpos, int endpos, Reads readClass, int minBaseQuality, int minReadQuality, ReferenceSeq reference) { VariantCall[][] coverages = new VariantCall[endpos-startpos +300][8]; Iterator<SAMRecord> bamIterator = getBamIterator(readClass,chrom,startpos, endpos); String run; int scanner = 0, scannerEnd = 0, scanWindow = 10; Boolean strand, scanFail = false; HashMap<String, String> runs = new HashMap<String,String>(); try { readClass.setCoverageStart(startpos); readClass.startpos = startpos; readClass.endpos = endpos; readClass.setReadStart(startpos); readClass.setReadEnd(endpos); readClass.setCoverageEnd(startpos + coverages.length); while(bamIterator != null && bamIterator.hasNext()) { if(!Main.drawCanvas.loading) { Main.drawCanvas.ready("all"); break; } try { try { samRecord = bamIterator.next(); } catch(htsjdk.samtools.SAMFormatException ex) { ex.printStackTrace(); } if(samRecord.getMappingQuality() < minReadQuality) { continue; } if(samRecord.getReadUnmappedFlag()) { continue; } if(samRecord.getReadLength() == 0) { continue; } //TODO jos on pienempi ku vika unclipped start if(samRecord.getUnclippedEnd() < startpos) { //this.readSeqStart+1) { continue; } if(samRecord.getUnclippedStart() >= endpos) { break; } if(readClass.sample.longestRead <samRecord.getCigar().getReferenceLength()) { readClass.sample.longestRead = samRecord.getCigar().getReferenceLength(); } /*if(readClass.sample.getComplete() == null) { if(samRecord.getReadName().startsWith("GS")) { readClass.sample.setcomplete(true); } else { readClass.sample.setcomplete(false); } }*/ if(MethodLibrary.isDiscordant(samRecord, false)) { continue; } if(samRecord.getReadName().contains(":")) { run = samRecord.getReadName().split(":")[1]; } else { run = samRecord.getReadName(); } if(!runs.containsKey(run)) { runs.put(run, ""); } if(samRecord.getAlignmentEnd() >= readClass.getCoverageEnd()) { coverages = coverageArrayAdd(readClass.sample.longestRead*2, coverages, readClass); reference.append(reference.getEndPos()+readClass.sample.longestRead*2); } strand = samRecord.getReadNegativeStrandFlag(); if(samRecord.getCigarLength() > 1) { /*if(samRecord.getCigarString().contains("S")) { continue; }*/ readstart = samRecord.getUnclippedStart(); readpos= 0; mispos= 0; for(int i = 0; i<samRecord.getCigarLength(); i++) { scanFail = false; element = samRecord.getCigar().getCigarElement(i); if(element.getOperator().compareTo(CigarOperator.MATCH_OR_MISMATCH)== 0) { for(int r = readpos; r<readpos+element.getLength(); r++) { if(((readstart+r)-readClass.getCoverageStart()) < 0) { continue; } try { if(samRecord.getReadBases()[mispos] != reference.getSeq()[((readstart+r)-reference.getStartPos()-1)]) { if((readstart+r)-readClass.getCoverageStart() < coverages.length-1 && (readstart+r)- readClass.getCoverageStart() > -1) { readClass.sample.basequalsum+=(int)samRecord.getBaseQualityString().charAt(mispos)-readClass.sample.phred; readClass.sample.basequals++; if((int)samRecord.getBaseQualityString().charAt(mispos)-readClass.sample.phred >= minBaseQuality) { if(mispos > 5 && mispos < samRecord.getReadLength()-5) { /* if(r < scanWindow) { scanner = 0; } else { scanner = r-scanWindow; } if(r > samRecord.getReadLength()-scanWindow) { scannerEnd = samRecord.getReadLength(); } else { scannerEnd = r+scanWindow; } for(int s = scanner ; s<scannerEnd;s++) { if(s == r) { continue; } if(samRecord.getReadBases()[s] != reference.getSeq()[((readstart+s)-reference.getStartPos()-1)]) { scanFail = true; break; } } */ if(!scanFail) { if(coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])] == null) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])] = new VariantCall(); } coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].calls++; coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].qualities += (int)samRecord.getBaseQualityString().charAt(mispos)-readClass.sample.phred; //if(readstart+mispos == 73789324) { // System.out.println(coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].calls); //} if(!coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].runs.contains(run)) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].runs.add(run); } if(!coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].strands.contains(strand)) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[mispos])].strands.add(strand); } } } else { scanFail = true; } } else { scanFail = true; } } else { scanFail = true; } } } catch(Exception e) { System.out.println(samRecord.getSAMString()); System.out.println(samRecord.getReadLength() +" " +samRecord.getReadString().length()); e.printStackTrace(); return null; } if(!scanFail) { if(coverages[((readstart+r)-readClass.getCoverageStart())][0] == null) { coverages[((readstart+r)-readClass.getCoverageStart())][0] = new VariantCall(); } coverages[((readstart+r)-readClass.getCoverageStart())][0].calls++;; if(coverages[((readstart+r)-readClass.getCoverageStart())][0].calls > readClass.getMaxcoverage()) { readClass.setMaxcoverage(coverages[((readstart+r)-readClass.getCoverageStart())][0].calls); } } mispos++; } readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.DELETION)== 0) { scanFail = true; readpos+=element.getLength(); } else if(element.getOperator().compareTo(CigarOperator.INSERTION)== 0) { // coverages[(readstart+readpos)- readClass.getCoverageStart()][Main.baseMap.get((byte)'I')]++; mispos+=element.getLength(); scanFail = true; } else if(element.getOperator().compareTo(CigarOperator.SOFT_CLIP)== 0 ) { scanFail = true; if(i == 0) { /*if(element.getLength() > 1000) { System.out.println(samRecord.getReadLength() +" " +samRecord.getReadString().length() +"\n" +samRecord.getSAMString()); }*/ readstart = samRecord.getAlignmentStart(); mispos+=element.getLength(); } //} } else if (element.getOperator().compareTo(CigarOperator.HARD_CLIP)== 0) { scanFail = true; if(i == 0) { readstart = samRecord.getAlignmentStart(); } } else if(element.getOperator().compareTo(CigarOperator.SKIPPED_REGION)== 0) { scanFail = true; readpos+=element.getLength(); } } } else { readstart = samRecord.getUnclippedStart(); for(int r = 0; r<samRecord.getReadLength(); r++) { try { scanFail = false; if(samRecord.getReadBases()[r] != reference.getSeq()[((readstart+r)-reference.getStartPos()-1)]) { if((readstart+r)-readClass.getCoverageStart() < coverages.length-1 && (readstart+r)- readClass.getCoverageStart() > -1) { readClass.sample.basequalsum+=(int)samRecord.getBaseQualityString().charAt(r)-readClass.sample.phred; readClass.sample.basequals++; if((int)samRecord.getBaseQualityString().charAt(r)-readClass.sample.phred >= minBaseQuality) { if(r > 5 && r < samRecord.getReadLength()-5) { /*if(samRecord.getReadString().charAt(r) == 'C' && samRecord.getReadString().charAt(r-1) == 'C' && samRecord.getReadString().charAt(r+1) == 'C') { if(samRecord.getReadString().charAt(r-2) != 'C' && samRecord.getReadString().charAt(r+2) != 'C') { VariantCaller.qualities += (int)samRecord.getBaseQualityString().charAt(r)-readClass.sample.phred; VariantCaller.amount++; } }*/ /* if(r < scanWindow) { scanner = 0; } else { scanner = r-scanWindow; } if(r > samRecord.getReadLength()-scanWindow) { scannerEnd = samRecord.getReadLength(); } else { scannerEnd = r+scanWindow; } for(int i = scanner ; i<scannerEnd;i++) { if(i == r) { continue; } if(samRecord.getReadBases()[i] != reference.getSeq()[((readstart+i)-reference.getStartPos()-1)]) { scanFail = true; break; } }*/ if(!scanFail) { if(coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])] == null) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])] = new VariantCall(); } coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].calls++; coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].qualities += (int)samRecord.getBaseQualityString().charAt(r)-readClass.sample.phred; if(!coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].runs.contains(run)) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].runs.add(run); } if(!coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].strands.contains(strand)) { coverages[(readstart+r)- readClass.getCoverageStart()][Main.baseMap.get((byte)samRecord.getReadBases()[r])].strands.add(strand); } } } else { scanFail = true; } } else { scanFail = true; } } else { scanFail = true; } } if(!scanFail) { if((readstart+r)-readClass.getCoverageStart() < 0) { continue; } if(coverages[((readstart+r)-readClass.getCoverageStart())][0] == null) { coverages[((readstart+r)-readClass.getCoverageStart())][0] = new VariantCall(); } coverages[(readstart+r)-readClass.getCoverageStart()][0].calls++; } } catch(Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); break; } } } } catch(Exception e) { e.printStackTrace(); break; } } } catch(Exception ex) { ex.printStackTrace(); return null; } // readClass.setRuns(runs.size()); return coverages; } public static void main(String args[]) { /*String cram = "X:/cg7/Heikki/CRAMtest/cram3/Y_crc47_1_13-0818_cram3_test.cram"; String crai = cram + ".crai"; File ref = new File("C:/HY-Data/RKATAINE/BasePlayer/BasePlayer/genomes/Homo_sapiens_GRCh37/Homo_sapiens.GRCh37.dna.primary_assembly.fa"); */ try { File infile = new File("X:/cg8/Riku/temp/Homo_sapiens.GRCh37.87.chr.gff3.gz"); String outfile = "X:/cg8/Riku/temp/joo.bed.gz"; readGFF(infile, outfile, null); //AddGenome.updateEnsemblList(); //File file = new File("X:\\cg8\\Riku\\gtf\\Mus_musculus.NCBIM37.54.gtf.gz"); //File file = new File("X:\\cg8\\Riku\\gtf\\dmel-all-r6.19.gtf"); //FileRead.readGTF(file, file.getParent() +"/test.bed.gz", null); /* BufferedReader reader = new BufferedReader(new FileReader(file.replace(".idx", ""))); // VCFFileReader reader = new VCFFileReader(new File(file)); Index indexfile = IndexFactory.loadIndex(file); List<Block> list = indexfile.getBlocks("1", 100000000,100000000); System.out.println(list.get(0).getStartPosition()); reader.skip(list.get(0).getStartPosition()); int count = 0; while(count < 20) { System.out.println(reader.readLine()); count++; } reader.close(); /* while(iter.hasNext()) { System.out.println(iter.next().getStart()); } read.close(); */ /* RandomAccessFile random = new RandomAccessFile(ref, "r"); CRAMFileReader reader = new CRAMFileReader(new File(cram), new File(crai),new ReferenceSource(ref), random, ValidationStringency.SILENT); QueryInterval[] interval = { new QueryInterval(0, 1000000, 1010000) }; Iterator<SAMRecord> iter = reader.query(interval, true); System.out.println(iter.hasNext()); // while(iter.hasNext()) { // SAMRecord rec = iter.next(); // System.out.println(rec.getAlignmentStart() +" " +rec.getStringAttribute("MD")); // } /*SAMRecord record = iter.next(); do { System.out.println(record.getAlignmentStart()); record= iter.next(); } while(record != null); */ } catch(Exception e) { e.printStackTrace(); } } }
phased genotypes in multivcf
src/base/BasePlayer/FileRead.java
phased genotypes in multivcf
Java
lgpl-2.1
7ab135539869244accf892a71293aed819eabe7e
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * jETeL/Clover - Java based ETL application framework. * Copyright (C) 2002-04 David Pavlis <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.jetel.component; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Enumeration; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.FileRecordBuffer; import org.jetel.data.RecordKey; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.TransformException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.OutputPort; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.ComponentXMLAttributes; import org.w3c.dom.Element; /** * <h3>Sorted Join Component</h3> <!-- Changes / reformats the data between * pair of INPUT/OUTPUT ports This component is only a wrapper around * transformation class implementing org.jetel.component.RecordTransform * interface. The method transform is called for every record passing through * this component --> * <table border="1"> * * <th> * Component: * </th> * <tr><td> * <h4><i>Name:</i> </h4></td><td>MergeJoin</td> * </tr> * <tr><td><h4><i>Category:</i> </h4></td><td></td> * </tr> * <tr><td><h4><i>Description:</i> </h4></td> * <td> * Joins sorted records on input ports. It expects driver stream at port [0] and * slave streams at other input ports. * Each driver record is joined with corresponding slave records according * to join keys specification.<br> * The method <i>transform</i> is every tuple composed of driver and corresponding * slaves.<br> * There are three join modes available: inner, left outer, full outer.<br> * Inner mode processess only driver records for which all associated slaves are available. * Left outer mode furthermore processes driver records with missing slaves. * Full outer mode additionally calls transformation method for slaves without driver.<br> * In case you use outer mode, be sure your transformation code is able to handle null * input records. * </td> * </tr> * <tr><td><h4><i>Inputs:</i> </h4></td> * <td> * [0] - sorted driver record input<br> * [1+] - sorted slave record inputs<br> * </td></tr> * <tr><td> <h4><i>Outputs:</i> </h4> * </td> * <td> * [0] - sole output port * </td></tr> * <tr><td><h4><i>Comment:</i> </h4> * </td> * <td></td> * </tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"MERGE_JOIN"</td></tr> * <tr><td><b>id</b></td><td>component identification</td></tr> * <tr><td><b>joinKey</b></td><td>join key specification in format<br> * <tt>[driver_key_list1]{*[slave_key_list1]|[slave_key_list1]|...}</tt><br> * Each key list consists of comma-separated field names. In case any slave key list is missing, * the component will use the sole driver key list instead of it. * Order of slave key lists corresponds to order of slave input ports. * </td></tr> * <tr><td><b>libraryPath</b><br><i>optional</i></td><td>name of Java library file (.jar,.zip,...) where * to search for class to be used for transforming joined data specified in <tt>transformClass<tt> parameter.</td></tr> * <tr><td><b>transformClass</b><br><i>optional</i></td><td>name of the class to be used for transforming joined data<br> * If no class name is specified then it is expected that the transformation Java source code is embedded in XML - <i>see example * below</i></td></tr> * <tr><td><b>transform</b></td><td>contains definition of transformation in internal clover format </td></tr> * <tr><td><b>joinType</b><br><i>optional</i></td><td>inner/leftOuter/fullOuter Specifies type of join operation. Default is inner.</td></tr> * <tr><td><b>slaveDuplicates</b><br><i>optional</i></td><td>true/false - allow records on slave port with duplicate keys. Default is false - multiple * duplicate records are discarded - only the last one is used for join.</td></tr> * </table> * <h4>Example:</h4> <pre>&lt;Node id="JOIN" type="MERGE_JOIN" joinKey="CustomerID" transformClass="org.jetel.test.reformatOrders"/&gt;</pre> *<pre>&lt;Node id="JOIN" type="HASH_JOIN" joinKey="EmployeeID*EmployeeID" joinType="inner"&gt; *import org.jetel.component.DataRecordTransform; *import org.jetel.data.*; * *public class reformatJoinTest extends DataRecordTransform{ * * public boolean transform(DataRecord[] source, DataRecord[] target){ * * target[0].getField(0).setValue(source[0].getField(0).getValue()); * target[0].getField(1).setValue(source[0].getField(1).getValue()); * target[0].getField(2).setValue(source[0].getField(2).getValue()); * if (source[1]!=null){ * target[0].getField(3).setValue(source[1].getField(0).getValue()); * target[0].getField(4).setValue(source[1].getField(1).getValue()); * } * return true; * } *} * *&lt;/Node&gt;</pre> * @author dpavlis, Jan Hadrava * @since April 4, 2002 * @revision $Revision$ * @created 4. June 2003 */ /** * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ public class MergeJoin extends Node { public enum Join { INNER, LEFT_OUTER, FULL_OUTER, } private static final String XML_FULLOUTERJOIN_ATTRIBUTE = "fullOuterJoin"; private static final String XML_LEFTOUTERJOIN_ATTRIBUTE = "leftOuterJoin"; public static final String XML_SLAVEOVERRIDEKEY_ATTRIBUTE = "slaveOverrideKey"; private static final String XML_JOINTYPE_ATTRIBUTE = "joinType"; public static final String XML_JOINKEY_ATTRIBUTE = "joinKey"; private static final String XML_TRANSFORMCLASS_ATTRIBUTE = "transformClass"; private static final String XML_TRANSFORM_ATTRIBUTE = "transform"; private static final String XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE ="slaveDuplicates"; /** Description of the Field */ public final static String COMPONENT_TYPE = "MERGE_JOIN"; private final static int WRITE_TO_PORT = 0; private final static int DRIVER_ON_PORT = 0; private final static int FIRST_SLAVE_PORT = 1; private String transformClassName; private String transformSource = null; private RecordTransform transformation = null; private DataRecord[] inRecords; private DataRecord[] outRecords; private Properties transformationParameters; // private static Log logger = LogFactory.getLog(MergeJoin.class); static Log logger = LogFactory.getLog(HashJoin.class); private String[][] joiners; private Join join; private boolean slaveDuplicates; private int inputCnt; private int slaveCnt; private RecordKey driverKey; private RecordKey[] slaveKeys; InputReader[] reader; InputReader minReader; boolean[] minIndicator; int minCnt; OutputPort outPort; /** * Constructor for the SortedJoin object * * @param id id of component * @param joiners parsed join string (first element contains driver key list, following elements contain slave key lists) * @param transform * @param transformClass class (name) to be used for transforming data * @param join join type * @param slaveDuplicates enables/disables duplicate slaves */ public MergeJoin(String id, String[][] joiners, String transform, String transformClass, Join join, boolean slaveDuplicates) { super(id); this.joiners = joiners; this.transformSource = transform; this.transformClassName = transformClass; this.join = join; this.slaveDuplicates = slaveDuplicates; } /** * Replace minimal record runs with the following ones. Change min indicator array * to reflect new set of runs. * @return Number of minimal runs, zero when no more data are available. * @throws InterruptedException * @throws IOException */ private int loadNext() throws InterruptedException, IOException { minCnt = 0; int minIdx = 0; for (int i = 0; i < inputCnt; i++) { if (minIndicator[i]) { reader[i].loadNextRun(); } switch (reader[minIdx].compare(reader[i])) { case -1: // current is greater than minimal minIndicator[i] = false; break; case 0: // current is equal to minimal minCnt++; minIndicator[i] = true; break; case 1: // current is lesser than minimal minCnt = 1; minIdx = i; minIndicator[i] = true; break; // all previous indicators will be reset later } } // for for (int i = minIdx - 1; i >= 0; i--) { minIndicator[i] = false; } minReader = reader[minIdx]; if (reader[minIdx].getSample() == null) { // no more data minCnt = 0; } return minCnt; } /** * Tranform all tuples created from minimal input runs. * @return * @throws IOException * @throws InterruptedException * @throws TransformException */ private boolean flushMin() throws IOException, InterruptedException, TransformException { // create initial combination for (int i = 0; i < inputCnt; i++) { inRecords[i] = minIndicator[i] ? reader[i].next() : null; } while (true) { outRecords[0].reset(); if (!transformation.transform(inRecords, outRecords)) { return false; } outPort.writeRecord(outRecords[0]); // generate next combination int chngCnt = 0; for (int i = inputCnt - 1; i >= 0; i--) { if (!minIndicator[i]) { continue; } chngCnt++; inRecords[i] = reader[i].next(); if (inRecords[i] != null) { // have new combination break; } if (chngCnt == minCnt) { // no more combinations available return true; } // need rewind reader[i].rewindRun(); inRecords[i] = reader[i].next(); // this is supposed to return non-null value } } } /* (non-Javadoc) * @see org.jetel.graph.Node#run() */ public void run() { try { for (loadNext(); minCnt > 0 && runIt; loadNext()) { if (join == Join.INNER && minCnt != inputCnt) { // not all records for current key available continue; } if (join == Join.LEFT_OUTER && !minIndicator[0]) { // driver record for current key not available continue; } if (!flushMin()) { resultCode = Node.RESULT_ERROR; resultMsg = transformation.getMessage(); transformation.finished(); broadcastEOF(); return; } } } catch (TransformException ex) { resultMsg = "Error occurred in nested transformation: " + ex.getMessage(); resultCode = Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (IOException ex) { resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (Exception ex) { resultMsg = ex.getClass().getName()+" : "+ ex.getMessage(); resultCode = Node.RESULT_FATAL_ERROR; //closeAllOutputPorts(); return; } // signal end of records stream to transformation function transformation.finished(); broadcastEOF(); if (runIt) { resultMsg = "OK"; } else { resultMsg = "STOPPED"; } resultCode = Node.RESULT_OK; } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ public void init() throws ComponentNotReadyException { // test that we have at least one input port and one output if (inPorts.size() < 1) { throw new ComponentNotReadyException("At least one input port have to be defined!"); } else if (outPorts.size() < 1) { throw new ComponentNotReadyException("At least one output port has to be defined!"); } inputCnt = inPorts.size(); slaveCnt = inputCnt - 1; if (joiners.length < 1) { throw new ComponentNotReadyException("not enough join keys specified"); } else if (joiners.length < inputCnt) { logger.warn("Join keys aren't specified for all slave inputs - deducing missing keys"); String[][] replJoiners = new String[inputCnt][]; for (int i = 0; i < joiners.length; i++) { replJoiners[i] = joiners[i]; } // use driver key list for all missing slave key specifications for (int i = joiners.length; i < inputCnt; i++) { replJoiners[i] = joiners[0]; } joiners = replJoiners; } driverKey = new RecordKey(joiners[0], getInputPort(DRIVER_ON_PORT).getMetadata()); driverKey.init(); slaveKeys = new RecordKey[slaveCnt]; for (int idx = 0; idx < slaveCnt; idx++) { slaveKeys[idx] = new RecordKey(joiners[1 + idx], getInputPort(FIRST_SLAVE_PORT + idx).getMetadata()); slaveKeys[idx].init(); } reader = new InputReader[inputCnt]; reader[0] = new DriverReader(getInputPort(DRIVER_ON_PORT), driverKey); if (slaveDuplicates) { for (int i = 0; i < slaveCnt; i++) { reader[i + 1] = new SlaveReaderDup(getInputPort(FIRST_SLAVE_PORT + i), slaveKeys[i]); } } else { for (int i = 0; i < slaveCnt; i++) { reader[i + 1] = new SlaveReader(getInputPort(FIRST_SLAVE_PORT + i), slaveKeys[i]); } } minReader = reader[0]; minIndicator = new boolean[inputCnt]; for (int i = 0; i < inputCnt; i++) { minIndicator[i] = true; } inRecords = new DataRecord[inputCnt]; outRecords = new DataRecord[]{new DataRecord(getOutputPort(WRITE_TO_PORT).getMetadata())}; outRecords[0].init(); outPort = getOutputPort(WRITE_TO_PORT); // init transformation DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { getOutputPort(WRITE_TO_PORT).getMetadata()}; DataRecordMetadata[] inMetadata = new DataRecordMetadata[inputCnt]; for (int idx = 0; idx < inputCnt; idx++) { inMetadata[idx] = getInputPort(idx).getMetadata(); } try { transformation = RecordTransformFactory.createTransform( transformSource, transformClassName, this, inMetadata, outMetadata, transformationParameters); } catch(Exception e) { throw new ComponentNotReadyException(this, e); } } /** * @param transformationParameters The transformationParameters to set. */ public void setTransformationParameters(Properties transformationParameters) { this.transformationParameters = transformationParameters; } /** * Description of the Method * * @return Description of the Returned Value * @since May 21, 2002 */ public void toXML(Element xmlElement) { super.toXML(xmlElement); if (transformClassName != null) { xmlElement.setAttribute(XML_TRANSFORMCLASS_ATTRIBUTE, transformClassName); } if (transformSource!=null){ xmlElement.setAttribute(XML_TRANSFORM_ATTRIBUTE,transformSource); } String joinStr = ""; for (int i = 0; true; i++) { for (int j = 0; true; j++) { joinStr += joiners[i][j]; if (j == joiners[i].length - 1) { break; // leave inner loop } joinStr += ","; } if (i == joiners.length - 1) { break; } joinStr += i == 0 ? "*" : "|"; } xmlElement.setAttribute(XML_JOINKEY_ATTRIBUTE, joinStr); xmlElement.setAttribute(XML_JOINTYPE_ATTRIBUTE, join == Join.FULL_OUTER ? "fullOuter" : join == Join.LEFT_OUTER ? "leftOuter" : "inner"); xmlElement.setAttribute(XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE, String.valueOf(slaveDuplicates)); if (transformationParameters != null) { Enumeration propertyAtts = transformationParameters.propertyNames(); while (propertyAtts.hasMoreElements()) { String attName = (String)propertyAtts.nextElement(); xmlElement.setAttribute(attName,transformationParameters.getProperty(attName)); } } } /** * Parses join string. * @param joinBy Join string * @return Array of arrays of strings. Each subarray represents one driver/slave key list * @throws XMLConfigurationException */ private static String[][] parseJoiners(String joinBy) throws XMLConfigurationException { String[] spl = joinBy.split("\\*", 2); String[] slaveKeys = new String[0]; if (spl.length > 1) { slaveKeys = spl[1].split("\\|"); } String[] keys = new String[1 + slaveKeys.length]; keys[0] = spl[0]; for (int i = 0; i < slaveKeys.length; i++) { keys[1 + i] = slaveKeys[i]; } String[][] res = new String[keys.length][]; for (int i = 0; i < keys.length; i++) { res[i] = keys[i].split(","); } return res; } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); MergeJoin join; try { String joinStr = xattribs.getString(XML_JOINTYPE_ATTRIBUTE, "inner"); Join joinType; if (joinStr == null || joinStr.equalsIgnoreCase("inner")) { joinType = Join.INNER; } else if (joinStr.equalsIgnoreCase("leftOuter")) { joinType = Join.LEFT_OUTER; } else if (joinStr.equalsIgnoreCase("fullOuter")) { joinType = Join.FULL_OUTER; } else { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + "Invalid joinType specification: " + joinStr); } String[][] joiners = parseJoiners(xattribs.getString(XML_JOINKEY_ATTRIBUTE, "")); join = new MergeJoin( xattribs.getString(XML_ID_ATTRIBUTE), joiners, xattribs.getString(XML_TRANSFORM_ATTRIBUTE, null), xattribs.getString(XML_TRANSFORMCLASS_ATTRIBUTE, null), joinType, xattribs.getBoolean(XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE, true)); join.setTransformationParameters(xattribs.attributes2Properties( new String[]{XML_ID_ATTRIBUTE,XML_JOINKEY_ATTRIBUTE, XML_TRANSFORM_ATTRIBUTE,XML_TRANSFORMCLASS_ATTRIBUTE, XML_LEFTOUTERJOIN_ATTRIBUTE,XML_SLAVEOVERRIDEKEY_ATTRIBUTE, XML_FULLOUTERJOIN_ATTRIBUTE})); return join; } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } } /** Description of the Method */ public boolean checkConfig() { return true; } public String getType(){ return COMPONENT_TYPE; } /** * Interface specifying operations for reading ordered record input. * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ private interface InputReader { /** * Loads next run (set of records with identical keys) * @return * @throws InterruptedException * @throws IOException */ public boolean loadNextRun() throws InterruptedException, IOException; /** * Retrieves one record from current run. Modifies internal data so that next call * of this operation will return following record. * @return null on end of run, retrieved record otherwise * @throws IOException * @throws InterruptedException */ public DataRecord next() throws IOException, InterruptedException; /** * Resets current run so that it can be read again. */ public void rewindRun(); /** * Retrieves one record from current run. Doesn't affect results of sebsequent next() operations. * @return */ public DataRecord getSample(); /** * Returns key used to compare data records. * @return */ public RecordKey getKey(); /** * Compares reader with another one. The comparison is based on key values of record in the current run * @param other * @return */ public int compare(InputReader other); } /** * Reader for driver input. Doesn't use record buffer but also doesn't support rewind operation. * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ private static class DriverReader implements InputReader { private static final int CURRENT = 0; private static final int NEXT = 1; private InputPort inPort; private RecordKey key; private DataRecord[] rec = new DataRecord[2]; private int recCounter; private boolean blocked; public DriverReader(InputPort inPort, RecordKey key) { this.inPort = inPort; this.key = key; this.rec[CURRENT] = new DataRecord(inPort.getMetadata()); this.rec[NEXT] = new DataRecord(inPort.getMetadata()); this.rec[CURRENT].init(); this.rec[NEXT].init(); recCounter = 0; blocked = false; } public boolean loadNextRun() throws InterruptedException, IOException { if (inPort == null) { return false; } if (recCounter == 0) { // first call of this function // load first record of the run if (inPort.readRecord(rec[NEXT]) == null) { inPort = null; rec[NEXT] = rec[CURRENT] = null; return false; } recCounter = 1; return true; } if (blocked) { blocked = false; return true; } do { swap(); if (inPort.readRecord(rec[NEXT]) == null) { inPort = null; rec[NEXT] = rec[CURRENT] = null; return false; } recCounter++; } while (key.compare(rec[CURRENT], rec[NEXT]) == 0); return true; } public void rewindRun() { throw new UnsupportedOperationException(); } public DataRecord getSample() { return blocked ? rec[CURRENT] : rec[NEXT]; } public DataRecord next() throws IOException, InterruptedException { if (blocked || inPort == null) { return null; } swap(); if (inPort.readRecord(rec[NEXT]) == null) { inPort = null; rec[NEXT] = null; blocked = false; } else { recCounter++; blocked = key.compare(rec[CURRENT], rec[NEXT]) != 0; } return rec[CURRENT]; } private void swap() { DataRecord tmp = rec[CURRENT]; rec[CURRENT] = rec[NEXT]; rec[NEXT] = tmp; } public RecordKey getKey() { return key; } public int compare(InputReader other) { DataRecord rec1 = getSample(); DataRecord rec2 = other.getSample(); if (rec1 == null) { return rec2 == null ? 0 : 1; // null is greater than any other reader } else if (rec2 == null) { return -1; } return key.compare(other.getKey(), rec1, rec2); } } /** * Slave reader with duplicates support. Uses file buffer to store duplicate records. Support rewind operation. * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ private static class SlaveReaderDup implements InputReader { private static final int CURRENT = 0; private static final int NEXT = 1; private InputPort inPort; private RecordKey key; private DataRecord[] rec = new DataRecord[2]; private FileRecordBuffer recBuf; private ByteBuffer rawRec = ByteBuffer.allocateDirect(Defaults.Record.MAX_RECORD_SIZE); private boolean firstRun; private boolean getFirst; DataRecord deserializedRec; public SlaveReaderDup(InputPort inPort, RecordKey key) { this.inPort = inPort; this.key = key; this.deserializedRec = new DataRecord(inPort.getMetadata()); this.deserializedRec.init(); this.rec[CURRENT] = new DataRecord(inPort.getMetadata()); this.rec[NEXT] = new DataRecord(inPort.getMetadata()); this.rec[CURRENT].init(); this.rec[NEXT].init(); this.recBuf = new FileRecordBuffer(null); this.firstRun = true; } private void swap() { DataRecord tmp = rec[CURRENT]; rec[CURRENT] = rec[NEXT]; rec[NEXT] = tmp; } public boolean loadNextRun() throws InterruptedException, IOException { getFirst = true; if (inPort == null) { rec[CURRENT] = rec[NEXT] = null; return false; } if (firstRun) { // first call of this function firstRun = false; // load first record of the run if (inPort.readRecord(rec[NEXT]) == null) { rec[CURRENT] = rec[NEXT] = null; inPort = null; return false; } } recBuf.clear(); swap(); while (true) { rec[NEXT].reset(); if (inPort.readRecord(rec[NEXT]) == null) { rec[NEXT] = null; inPort = null; return true; } if (key.compare(rec[CURRENT], rec[NEXT]) != 0) { // beginning of new run return true; } // move record to buffer rawRec.clear(); rec[NEXT].serialize(rawRec); rawRec.flip(); recBuf.push(rawRec); } } public void rewindRun() { getFirst = true; recBuf.rewind(); } public DataRecord getSample() { if (firstRun) { return null; } return rec[CURRENT]; } public DataRecord next() throws IOException { if (firstRun) { return null; } if (getFirst) { getFirst = false; return rec[CURRENT]; } rawRec.clear(); if (recBuf.shift(rawRec) == null) { return null; } rawRec.flip(); deserializedRec.deserialize(rawRec); return deserializedRec; } public RecordKey getKey() { return key; } public int compare(InputReader other) { DataRecord rec1 = getSample(); DataRecord rec2 = other.getSample(); if (rec1 == null) { return rec2 == null ? 0 : -1; } else if (rec2 == null) { return 1; } return key.compare(other.getKey(), rec1, rec2); } } /** * Slave reader without duplicates support. Pretends that all runs contain only one record. * Doesn't use buffer, supports rewind operation. * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ private static class SlaveReader implements InputReader { private static final int CURRENT = 0; private static final int NEXT = 1; private InputPort inPort; private RecordKey key; private DataRecord[] rec = new DataRecord[2]; private boolean firstRun; private boolean needsRewind; public SlaveReader(InputPort inPort, RecordKey key) { this.inPort = inPort; this.key = key; this.rec[CURRENT] = new DataRecord(inPort.getMetadata()); this.rec[NEXT] = new DataRecord(inPort.getMetadata()); this.rec[CURRENT].init(); this.rec[NEXT].init(); this.firstRun = true; this.needsRewind = true; } private void swap() { DataRecord tmp = rec[CURRENT]; rec[CURRENT] = rec[NEXT]; rec[NEXT] = tmp; } public boolean loadNextRun() throws InterruptedException, IOException { if (inPort == null) { rec[CURRENT] = rec[NEXT] = null; return false; } if (firstRun) { // first call of this function firstRun = false; // load first record of the run if (inPort.readRecord(rec[NEXT]) == null) { rec[CURRENT] = rec[NEXT] = null; inPort = null; return false; } } swap(); while (true) { // current record is now the first one from the run to be loaded // set current record to the last one from the run to be loaded and next record to the first one // from the following run needsRewind = false; rec[NEXT].reset(); if (inPort.readRecord(rec[NEXT]) == null) { rec[NEXT] = null; inPort = null; return true; } if (key.compare(rec[CURRENT], rec[NEXT]) != 0) { // beginning of new run return true; } swap(); } } public void rewindRun() { } public DataRecord getSample() { if (firstRun) { return null; } return rec[CURRENT]; } public DataRecord next() throws IOException { if (firstRun || needsRewind) { return null; } needsRewind = true; return rec[CURRENT]; } public RecordKey getKey() { return key; } public int compare(InputReader other) { DataRecord rec1 = getSample(); DataRecord rec2 = other.getSample(); if (rec1 == null) { return rec2 == null ? 0 : -1; } else if (rec2 == null) { return 1; } return key.compare(other.getKey(), rec1, rec2); } } }
cloveretl.component/src/org/jetel/component/MergeJoin.java
/* * jETeL/Clover - Java based ETL application framework. * Copyright (C) 2002-04 David Pavlis <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.jetel.component; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Enumeration; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.FileRecordBuffer; import org.jetel.data.RecordKey; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.TransformException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.OutputPort; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.ComponentXMLAttributes; import org.w3c.dom.Element; /** * <h3>Sorted Join Component</h3> <!-- Changes / reformats the data between * pair of INPUT/OUTPUT ports This component is only a wrapper around * transformation class implementing org.jetel.component.RecordTransform * interface. The method transform is called for every record passing through * this component --> * <table border="1"> * * <th> * Component: * </th> * <tr><td> * <h4><i>Name:</i> </h4></td><td>MergeJoin</td> * </tr> * <tr><td><h4><i>Category:</i> </h4></td><td></td> * </tr> * <tr><td><h4><i>Description:</i> </h4></td> * <td> * Joins sorted records on input ports. It expects driver stream at port [0] and * slave streams at other input ports. * Each driver record is joined with corresponding slave records according * to join keys specification.<br> * The method <i>transform</i> is every tuple composed of driver and corresponding * slaves.<br> * There are three join modes available: inner, left outer, full outer.<br> * Inner mode processess only driver records for which all associated slaves are available. * Left outer mode furthermore processes driver records with missing slaves. * Full outer mode additionally calls transformation method for slaves without driver.<br> * In case you use outer mode, be sure your transformation code is able to handle null * input records. * </td> * </tr> * <tr><td><h4><i>Inputs:</i> </h4></td> * <td> * [0] - sorted driver record input<br> * [1+] - sorted slave record inputs<br> * </td></tr> * <tr><td> <h4><i>Outputs:</i> </h4> * </td> * <td> * [0] - sole output port * </td></tr> * <tr><td><h4><i>Comment:</i> </h4> * </td> * <td></td> * </tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"MERGE_JOIN"</td></tr> * <tr><td><b>id</b></td><td>component identification</td></tr> * <tr><td><b>joinKey</b></td><td>join key specification in format<br> * <tt>[driver_key_list1]{*[slave_key_list1]|[slave_key_list1]|...}</tt><br> * Each key list consists of comma-separated field names. In case any slave key list is missing, * the component will use the sole driver key list instead of it. * Order of slave key lists corresponds to order of slave input ports. * </td></tr> * <tr><td><b>libraryPath</b><br><i>optional</i></td><td>name of Java library file (.jar,.zip,...) where * to search for class to be used for transforming joined data specified in <tt>transformClass<tt> parameter.</td></tr> * <tr><td><b>transformClass</b><br><i>optional</i></td><td>name of the class to be used for transforming joined data<br> * If no class name is specified then it is expected that the transformation Java source code is embedded in XML - <i>see example * below</i></td></tr> * <tr><td><b>transform</b></td><td>contains definition of transformation in internal clover format </td></tr> * <tr><td><b>joinType</b><br><i>optional</i></td><td>inner/leftOuter/fullOuter Specifies type of join operation. Default is inner.</td></tr> * <tr><td><b>slaveDuplicates</b><br><i>optional</i></td><td>true/false - allow records on slave port with duplicate keys. Default is false - multiple * duplicate records are discarded - only the last one is used for join.</td></tr> * </table> * <h4>Example:</h4> <pre>&lt;Node id="JOIN" type="MERGE_JOIN" joinKey="CustomerID" transformClass="org.jetel.test.reformatOrders"/&gt;</pre> *<pre>&lt;Node id="JOIN" type="HASH_JOIN" joinKey="EmployeeID*EmployeeID" joinType="inner"&gt; *import org.jetel.component.DataRecordTransform; *import org.jetel.data.*; * *public class reformatJoinTest extends DataRecordTransform{ * * public boolean transform(DataRecord[] source, DataRecord[] target){ * * target[0].getField(0).setValue(source[0].getField(0).getValue()); * target[0].getField(1).setValue(source[0].getField(1).getValue()); * target[0].getField(2).setValue(source[0].getField(2).getValue()); * if (source[1]!=null){ * target[0].getField(3).setValue(source[1].getField(0).getValue()); * target[0].getField(4).setValue(source[1].getField(1).getValue()); * } * return true; * } *} * *&lt;/Node&gt;</pre> * @author dpavlis, Jan Hadrava * @since April 4, 2002 * @revision $Revision$ * @created 4. June 2003 */ /** * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ public class MergeJoin extends Node { public enum Join { INNER, LEFT_OUTER, FULL_OUTER, } private static final String XML_FULLOUTERJOIN_ATTRIBUTE = "fullOuterJoin"; private static final String XML_LEFTOUTERJOIN_ATTRIBUTE = "leftOuterJoin"; private static final String XML_SLAVEOVERRIDEKEY_ATTRIBUTE = "slaveOverrideKey"; private static final String XML_JOINTYPE_ATTRIBUTE = "joinType"; private static final String XML_JOINKEY_ATTRIBUTE = "joinKey"; private static final String XML_TRANSFORMCLASS_ATTRIBUTE = "transformClass"; private static final String XML_TRANSFORM_ATTRIBUTE = "transform"; private static final String XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE ="slaveDuplicates"; /** Description of the Field */ public final static String COMPONENT_TYPE = "MERGE_JOIN"; private final static int WRITE_TO_PORT = 0; private final static int DRIVER_ON_PORT = 0; private final static int FIRST_SLAVE_PORT = 1; private String transformClassName; private String transformSource = null; private RecordTransform transformation = null; private DataRecord[] inRecords; private DataRecord[] outRecords; private Properties transformationParameters; // private static Log logger = LogFactory.getLog(MergeJoin.class); static Log logger = LogFactory.getLog(HashJoin.class); private String[][] joiners; private Join join; private boolean slaveDuplicates; private int inputCnt; private int slaveCnt; private RecordKey driverKey; private RecordKey[] slaveKeys; InputReader[] reader; InputReader minReader; boolean[] minIndicator; int minCnt; OutputPort outPort; /** * Constructor for the SortedJoin object * * @param id id of component * @param joiners parsed join string (first element contains driver key list, following elements contain slave key lists) * @param transform * @param transformClass class (name) to be used for transforming data * @param join join type * @param slaveDuplicates enables/disables duplicate slaves */ public MergeJoin(String id, String[][] joiners, String transform, String transformClass, Join join, boolean slaveDuplicates) { super(id); this.joiners = joiners; this.transformSource = transform; this.transformClassName = transformClass; this.join = join; this.slaveDuplicates = slaveDuplicates; } /** * Replace minimal record runs with the following ones. Change min indicator array * to reflect new set of runs. * @return Number of minimal runs, zero when no more data are available. * @throws InterruptedException * @throws IOException */ private int loadNext() throws InterruptedException, IOException { minCnt = 0; int minIdx = 0; for (int i = 0; i < inputCnt; i++) { if (minIndicator[i]) { reader[i].loadNextRun(); } switch (reader[minIdx].compare(reader[i])) { case -1: // current is greater than minimal minIndicator[i] = false; break; case 0: // current is equal to minimal minCnt++; minIndicator[i] = true; break; case 1: // current is lesser than minimal minCnt = 1; minIdx = i; minIndicator[i] = true; break; // all previous indicators will be reset later } } // for for (int i = minIdx - 1; i >= 0; i--) { minIndicator[i] = false; } minReader = reader[minIdx]; if (reader[minIdx].getSample() == null) { // no more data minCnt = 0; } return minCnt; } /** * Tranform all tuples created from minimal input runs. * @return * @throws IOException * @throws InterruptedException * @throws TransformException */ private boolean flushMin() throws IOException, InterruptedException, TransformException { // create initial combination for (int i = 0; i < inputCnt; i++) { inRecords[i] = minIndicator[i] ? reader[i].next() : null; } while (true) { outRecords[0].reset(); if (!transformation.transform(inRecords, outRecords)) { return false; } outPort.writeRecord(outRecords[0]); // generate next combination int chngCnt = 0; for (int i = inputCnt - 1; i >= 0; i--) { if (!minIndicator[i]) { continue; } chngCnt++; inRecords[i] = reader[i].next(); if (inRecords[i] != null) { // have new combination break; } if (chngCnt == minCnt) { // no more combinations available return true; } // need rewind reader[i].rewindRun(); inRecords[i] = reader[i].next(); // this is supposed to return non-null value } } } /* (non-Javadoc) * @see org.jetel.graph.Node#run() */ public void run() { try { for (loadNext(); minCnt > 0 && runIt; loadNext()) { if (join == Join.INNER && minCnt != inputCnt) { // not all records for current key available continue; } if (join == Join.LEFT_OUTER && !minIndicator[0]) { // driver record for current key not available continue; } if (!flushMin()) { resultCode = Node.RESULT_ERROR; resultMsg = transformation.getMessage(); transformation.finished(); broadcastEOF(); return; } } } catch (TransformException ex) { resultMsg = "Error occurred in nested transformation: " + ex.getMessage(); resultCode = Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (IOException ex) { resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (Exception ex) { resultMsg = ex.getClass().getName()+" : "+ ex.getMessage(); resultCode = Node.RESULT_FATAL_ERROR; //closeAllOutputPorts(); return; } // signal end of records stream to transformation function transformation.finished(); broadcastEOF(); if (runIt) { resultMsg = "OK"; } else { resultMsg = "STOPPED"; } resultCode = Node.RESULT_OK; } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ public void init() throws ComponentNotReadyException { // test that we have at least one input port and one output if (inPorts.size() < 1) { throw new ComponentNotReadyException("At least one input port have to be defined!"); } else if (outPorts.size() < 1) { throw new ComponentNotReadyException("At least one output port has to be defined!"); } inputCnt = inPorts.size(); slaveCnt = inputCnt - 1; if (joiners.length < 1) { throw new ComponentNotReadyException("not enough join keys specified"); } else if (joiners.length < inputCnt) { logger.warn("Join keys aren't specified for all slave inputs - deducing missing keys"); String[][] replJoiners = new String[inputCnt][]; for (int i = 0; i < joiners.length; i++) { replJoiners[i] = joiners[i]; } // use driver key list for all missing slave key specifications for (int i = joiners.length; i < inputCnt; i++) { replJoiners[i] = joiners[0]; } joiners = replJoiners; } driverKey = new RecordKey(joiners[0], getInputPort(DRIVER_ON_PORT).getMetadata()); driverKey.init(); slaveKeys = new RecordKey[slaveCnt]; for (int idx = 0; idx < slaveCnt; idx++) { slaveKeys[idx] = new RecordKey(joiners[1 + idx], getInputPort(FIRST_SLAVE_PORT + idx).getMetadata()); slaveKeys[idx].init(); } reader = new InputReader[inputCnt]; reader[0] = new DriverReader(getInputPort(DRIVER_ON_PORT), driverKey); if (slaveDuplicates) { for (int i = 0; i < slaveCnt; i++) { reader[i + 1] = new SlaveReaderDup(getInputPort(FIRST_SLAVE_PORT + i), slaveKeys[i]); } } else { for (int i = 0; i < slaveCnt; i++) { reader[i + 1] = new SlaveReader(getInputPort(FIRST_SLAVE_PORT + i), slaveKeys[i]); } } minReader = reader[0]; minIndicator = new boolean[inputCnt]; for (int i = 0; i < inputCnt; i++) { minIndicator[i] = true; } inRecords = new DataRecord[inputCnt]; outRecords = new DataRecord[]{new DataRecord(getOutputPort(WRITE_TO_PORT).getMetadata())}; outRecords[0].init(); outPort = getOutputPort(WRITE_TO_PORT); // init transformation DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { getOutputPort(WRITE_TO_PORT).getMetadata()}; DataRecordMetadata[] inMetadata = new DataRecordMetadata[inputCnt]; for (int idx = 0; idx < inputCnt; idx++) { inMetadata[idx] = getInputPort(idx).getMetadata(); } try { transformation = RecordTransformFactory.createTransform( transformSource, transformClassName, this, inMetadata, outMetadata, transformationParameters); } catch(Exception e) { throw new ComponentNotReadyException(this, e); } } /** * @param transformationParameters The transformationParameters to set. */ public void setTransformationParameters(Properties transformationParameters) { this.transformationParameters = transformationParameters; } /** * Description of the Method * * @return Description of the Returned Value * @since May 21, 2002 */ public void toXML(Element xmlElement) { super.toXML(xmlElement); if (transformClassName != null) { xmlElement.setAttribute(XML_TRANSFORMCLASS_ATTRIBUTE, transformClassName); } if (transformSource!=null){ xmlElement.setAttribute(XML_TRANSFORM_ATTRIBUTE,transformSource); } String joinStr = ""; for (int i = 0; true; i++) { for (int j = 0; true; j++) { joinStr += joiners[i][j]; if (j == joiners[i].length - 1) { break; // leave inner loop } joinStr += ","; } if (i == joiners.length - 1) { break; } joinStr += i == 0 ? "*" : "|"; } xmlElement.setAttribute(XML_JOINKEY_ATTRIBUTE, joinStr); xmlElement.setAttribute(XML_JOINTYPE_ATTRIBUTE, join == Join.FULL_OUTER ? "fullOuter" : join == Join.LEFT_OUTER ? "leftOuter" : "inner"); xmlElement.setAttribute(XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE, String.valueOf(slaveDuplicates)); if (transformationParameters != null) { Enumeration propertyAtts = transformationParameters.propertyNames(); while (propertyAtts.hasMoreElements()) { String attName = (String)propertyAtts.nextElement(); xmlElement.setAttribute(attName,transformationParameters.getProperty(attName)); } } } /** * Parses join string. * @param joinBy Join string * @return Array of arrays of strings. Each subarray represents one driver/slave key list * @throws XMLConfigurationException */ private static String[][] parseJoiners(String joinBy) throws XMLConfigurationException { String[] spl = joinBy.split("\\*", 2); String[] slaveKeys = new String[0]; if (spl.length > 1) { slaveKeys = spl[1].split("\\|"); } String[] keys = new String[1 + slaveKeys.length]; keys[0] = spl[0]; for (int i = 0; i < slaveKeys.length; i++) { keys[1 + i] = slaveKeys[i]; } String[][] res = new String[keys.length][]; for (int i = 0; i < keys.length; i++) { res[i] = keys[i].split(","); } return res; } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); MergeJoin join; try { String joinStr = xattribs.getString(XML_JOINTYPE_ATTRIBUTE, "inner"); Join joinType; if (joinStr == null || joinStr.equalsIgnoreCase("inner")) { joinType = Join.INNER; } else if (joinStr.equalsIgnoreCase("leftOuter")) { joinType = Join.LEFT_OUTER; } else if (joinStr.equalsIgnoreCase("fullOuter")) { joinType = Join.FULL_OUTER; } else { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + "Invalid joinType specification: " + joinStr); } String[][] joiners = parseJoiners(xattribs.getString(XML_JOINKEY_ATTRIBUTE, "")); join = new MergeJoin( xattribs.getString(XML_ID_ATTRIBUTE), joiners, xattribs.getString(XML_TRANSFORM_ATTRIBUTE, null), xattribs.getString(XML_TRANSFORMCLASS_ATTRIBUTE, null), joinType, xattribs.getBoolean(XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE, true)); join.setTransformationParameters(xattribs.attributes2Properties( new String[]{XML_ID_ATTRIBUTE,XML_JOINKEY_ATTRIBUTE, XML_TRANSFORM_ATTRIBUTE,XML_TRANSFORMCLASS_ATTRIBUTE, XML_LEFTOUTERJOIN_ATTRIBUTE,XML_SLAVEOVERRIDEKEY_ATTRIBUTE, XML_FULLOUTERJOIN_ATTRIBUTE})); return join; } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } } /** Description of the Method */ public boolean checkConfig() { return true; } public String getType(){ return COMPONENT_TYPE; } /** * Interface specifying operations for reading ordered record input. * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ private interface InputReader { /** * Loads next run (set of records with identical keys) * @return * @throws InterruptedException * @throws IOException */ public boolean loadNextRun() throws InterruptedException, IOException; /** * Retrieves one record from current run. Modifies internal data so that next call * of this operation will return following record. * @return null on end of run, retrieved record otherwise * @throws IOException * @throws InterruptedException */ public DataRecord next() throws IOException, InterruptedException; /** * Resets current run so that it can be read again. */ public void rewindRun(); /** * Retrieves one record from current run. Doesn't affect results of sebsequent next() operations. * @return */ public DataRecord getSample(); /** * Returns key used to compare data records. * @return */ public RecordKey getKey(); /** * Compares reader with another one. The comparison is based on key values of record in the current run * @param other * @return */ public int compare(InputReader other); } /** * Reader for driver input. Doesn't use record buffer but also doesn't support rewind operation. * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ private static class DriverReader implements InputReader { private static final int CURRENT = 0; private static final int NEXT = 1; private InputPort inPort; private RecordKey key; private DataRecord[] rec = new DataRecord[2]; private int recCounter; private boolean blocked; public DriverReader(InputPort inPort, RecordKey key) { this.inPort = inPort; this.key = key; this.rec[CURRENT] = new DataRecord(inPort.getMetadata()); this.rec[NEXT] = new DataRecord(inPort.getMetadata()); this.rec[CURRENT].init(); this.rec[NEXT].init(); recCounter = 0; blocked = false; } public boolean loadNextRun() throws InterruptedException, IOException { if (inPort == null) { return false; } if (recCounter == 0) { // first call of this function // load first record of the run if (inPort.readRecord(rec[NEXT]) == null) { inPort = null; rec[NEXT] = rec[CURRENT] = null; return false; } recCounter = 1; return true; } if (blocked) { blocked = false; return true; } do { swap(); if (inPort.readRecord(rec[NEXT]) == null) { inPort = null; rec[NEXT] = rec[CURRENT] = null; return false; } recCounter++; } while (key.compare(rec[CURRENT], rec[NEXT]) == 0); return true; } public void rewindRun() { throw new UnsupportedOperationException(); } public DataRecord getSample() { return blocked ? rec[CURRENT] : rec[NEXT]; } public DataRecord next() throws IOException, InterruptedException { if (blocked || inPort == null) { return null; } swap(); if (inPort.readRecord(rec[NEXT]) == null) { inPort = null; rec[NEXT] = null; blocked = false; } else { recCounter++; blocked = key.compare(rec[CURRENT], rec[NEXT]) != 0; } return rec[CURRENT]; } private void swap() { DataRecord tmp = rec[CURRENT]; rec[CURRENT] = rec[NEXT]; rec[NEXT] = tmp; } public RecordKey getKey() { return key; } public int compare(InputReader other) { DataRecord rec1 = getSample(); DataRecord rec2 = other.getSample(); if (rec1 == null) { return rec2 == null ? 0 : 1; // null is greater than any other reader } else if (rec2 == null) { return -1; } return key.compare(other.getKey(), rec1, rec2); } } /** * Slave reader with duplicates support. Uses file buffer to store duplicate records. Support rewind operation. * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ private static class SlaveReaderDup implements InputReader { private static final int CURRENT = 0; private static final int NEXT = 1; private InputPort inPort; private RecordKey key; private DataRecord[] rec = new DataRecord[2]; private FileRecordBuffer recBuf; private ByteBuffer rawRec = ByteBuffer.allocateDirect(Defaults.Record.MAX_RECORD_SIZE); private boolean firstRun; private boolean getFirst; DataRecord deserializedRec; public SlaveReaderDup(InputPort inPort, RecordKey key) { this.inPort = inPort; this.key = key; this.deserializedRec = new DataRecord(inPort.getMetadata()); this.deserializedRec.init(); this.rec[CURRENT] = new DataRecord(inPort.getMetadata()); this.rec[NEXT] = new DataRecord(inPort.getMetadata()); this.rec[CURRENT].init(); this.rec[NEXT].init(); this.recBuf = new FileRecordBuffer(null); this.firstRun = true; } private void swap() { DataRecord tmp = rec[CURRENT]; rec[CURRENT] = rec[NEXT]; rec[NEXT] = tmp; } public boolean loadNextRun() throws InterruptedException, IOException { getFirst = true; if (inPort == null) { rec[CURRENT] = rec[NEXT] = null; return false; } if (firstRun) { // first call of this function firstRun = false; // load first record of the run if (inPort.readRecord(rec[NEXT]) == null) { rec[CURRENT] = rec[NEXT] = null; inPort = null; return false; } } recBuf.clear(); swap(); while (true) { rec[NEXT].reset(); if (inPort.readRecord(rec[NEXT]) == null) { rec[NEXT] = null; inPort = null; return true; } if (key.compare(rec[CURRENT], rec[NEXT]) != 0) { // beginning of new run return true; } // move record to buffer rawRec.clear(); rec[NEXT].serialize(rawRec); rawRec.flip(); recBuf.push(rawRec); } } public void rewindRun() { getFirst = true; recBuf.rewind(); } public DataRecord getSample() { if (firstRun) { return null; } return rec[CURRENT]; } public DataRecord next() throws IOException { if (firstRun) { return null; } if (getFirst) { getFirst = false; return rec[CURRENT]; } rawRec.clear(); if (recBuf.shift(rawRec) == null) { return null; } rawRec.flip(); deserializedRec.deserialize(rawRec); return deserializedRec; } public RecordKey getKey() { return key; } public int compare(InputReader other) { DataRecord rec1 = getSample(); DataRecord rec2 = other.getSample(); if (rec1 == null) { return rec2 == null ? 0 : -1; } else if (rec2 == null) { return 1; } return key.compare(other.getKey(), rec1, rec2); } } /** * Slave reader without duplicates support. Pretends that all runs contain only one record. * Doesn't use buffer, supports rewind operation. * @author Jan Hadrava, Javlin Consulting (www.javlinconsulting.cz) * */ private static class SlaveReader implements InputReader { private static final int CURRENT = 0; private static final int NEXT = 1; private InputPort inPort; private RecordKey key; private DataRecord[] rec = new DataRecord[2]; private boolean firstRun; private boolean needsRewind; public SlaveReader(InputPort inPort, RecordKey key) { this.inPort = inPort; this.key = key; this.rec[CURRENT] = new DataRecord(inPort.getMetadata()); this.rec[NEXT] = new DataRecord(inPort.getMetadata()); this.rec[CURRENT].init(); this.rec[NEXT].init(); this.firstRun = true; this.needsRewind = true; } private void swap() { DataRecord tmp = rec[CURRENT]; rec[CURRENT] = rec[NEXT]; rec[NEXT] = tmp; } public boolean loadNextRun() throws InterruptedException, IOException { if (inPort == null) { rec[CURRENT] = rec[NEXT] = null; return false; } if (firstRun) { // first call of this function firstRun = false; // load first record of the run if (inPort.readRecord(rec[NEXT]) == null) { rec[CURRENT] = rec[NEXT] = null; inPort = null; return false; } } swap(); while (true) { // current record is now the first one from the run to be loaded // set current record to the last one from the run to be loaded and next record to the first one // from the following run needsRewind = false; rec[NEXT].reset(); if (inPort.readRecord(rec[NEXT]) == null) { rec[NEXT] = null; inPort = null; return true; } if (key.compare(rec[CURRENT], rec[NEXT]) != 0) { // beginning of new run return true; } swap(); } } public void rewindRun() { } public DataRecord getSample() { if (firstRun) { return null; } return rec[CURRENT]; } public DataRecord next() throws IOException { if (firstRun || needsRewind) { return null; } needsRewind = true; return rec[CURRENT]; } public RecordKey getKey() { return key; } public int compare(InputReader other) { DataRecord rec1 = getSample(); DataRecord rec2 = other.getSample(); if (rec1 == null) { return rec2 == null ? 0 : -1; } else if (rec2 == null) { return 1; } return key.compare(other.getKey(), rec1, rec2); } } }
some xml atributes constants changed to public git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@1866 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.component/src/org/jetel/component/MergeJoin.java
some xml atributes constants changed to public
Java
apache-2.0
32ab37d5da87b22e42ebef9d756a3ffa69154a12
0
bmckinney/dataverse-canonical,bmckinney/dataverse-canonical,majorseitan/dataverse,bmckinney/dataverse-canonical,JayanthyChengan/dataverse,jacksonokuhn/dataverse,majorseitan/dataverse,ekoi/DANS-DVN-4.6.1,leeper/dataverse-1,quarian/dataverse,JayanthyChengan/dataverse,quarian/dataverse,ekoi/DANS-DVN-4.6.1,ekoi/DANS-DVN-4.6.1,quarian/dataverse,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,leeper/dataverse-1,leeper/dataverse-1,bmckinney/dataverse-canonical,majorseitan/dataverse,majorseitan/dataverse,ekoi/DANS-DVN-4.6.1,bmckinney/dataverse-canonical,leeper/dataverse-1,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,majorseitan/dataverse,quarian/dataverse,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,quarian/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,leeper/dataverse-1,leeper/dataverse-1,ekoi/DANS-DVN-4.6.1,quarian/dataverse,leeper/dataverse-1,majorseitan/dataverse,majorseitan/dataverse,jacksonokuhn/dataverse,quarian/dataverse,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,majorseitan/dataverse,leeper/dataverse-1,bmckinney/dataverse-canonical,quarian/dataverse
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.util.StringUtil; import edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUserServiceBean; import edu.harvard.iq.dataverse.search.SearchFields; import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean; import edu.harvard.iq.dataverse.datavariable.DataVariable; import edu.harvard.iq.dataverse.search.IndexResponse; import edu.harvard.iq.dataverse.search.IndexableDataset; import edu.harvard.iq.dataverse.search.IndexableObject; import edu.harvard.iq.dataverse.search.SearchException; import edu.harvard.iq.dataverse.search.SearchPermissionsServiceBean; import edu.harvard.iq.dataverse.search.SolrIndexServiceBean; import edu.harvard.iq.dataverse.util.FileUtil; import edu.harvard.iq.dataverse.util.SystemConfig; import java.io.IOException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.logging.Logger; import javax.ejb.AsyncResult; import javax.ejb.Asynchronous; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.inject.Named; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; @Stateless @Named public class IndexServiceBean { private static final Logger logger = Logger.getLogger(IndexServiceBean.class.getCanonicalName()); @EJB DvObjectServiceBean dvObjectService; @EJB DataverseServiceBean dataverseService; @EJB DatasetServiceBean datasetService; @EJB BuiltinUserServiceBean dataverseUserServiceBean; @EJB PermissionServiceBean permissionService; @EJB AuthenticationServiceBean userServiceBean; @EJB SystemConfig systemConfig; @EJB SearchPermissionsServiceBean searchPermissionsService; @EJB SolrIndexServiceBean solrIndexService; @EJB DatasetLinkingServiceBean dsLinkingService; @EJB DataverseLinkingServiceBean dvLinkingService; public static final String solrDocIdentifierDataverse = "dataverse_"; public static final String solrDocIdentifierFile = "datafile_"; public static final String solrDocIdentifierDataset = "dataset_"; public static final String draftSuffix = "_draft"; public static final String deaccessionedSuffix = "_deaccessioned"; public static final String discoverabilityPermissionSuffix = "_permission"; private static final String groupPrefix = "group_"; private static final String groupPerUserPrefix = "group_user"; private static final String publicGroupIdString = "public"; private static final String publicGroupString = groupPrefix + "public"; private static final String PUBLISHED_STRING = "Published"; private static final String UNPUBLISHED_STRING = "Unpublished"; private static final String DRAFT_STRING = "Draft"; private static final String DEACCESSIONED_STRING = "Deaccessioned"; private Dataverse rootDataverseCached; @Asynchronous public Future<String> indexAll() { long indexAllTimeBegin = System.currentTimeMillis(); String status; SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); logger.info("attempting to delete all Solr documents before a complete re-index"); try { server.deleteByQuery("*:*");// CAUTION: deletes everything! } catch (SolrServerException | IOException ex) { status = ex.toString(); logger.info(status); return new AsyncResult<>(status); } try { server.commit(); } catch (SolrServerException | IOException ex) { status = ex.toString(); logger.info(status); return new AsyncResult<>(status); } List<Dataverse> dataverses = dataverseService.findAll(); int dataverseIndexCount = 0; for (Dataverse dataverse : dataverses) { logger.info("indexing dataverse " + dataverseIndexCount + " of " + dataverses.size() + ": " + indexDataverse(dataverse)); dataverseIndexCount++; } int datasetIndexCount = 0; List<Dataset> datasets = datasetService.findAll(); for (Dataset dataset : datasets) { datasetIndexCount++; logger.info("indexing dataset " + datasetIndexCount + " of " + datasets.size() + ": " + indexDataset(dataset)); } // logger.info("advanced search fields: " + advancedSearchFields); // logger.info("not advanced search fields: " + notAdvancedSearchFields); logger.info("done iterating through all datasets"); long indexAllTimeEnd = System.currentTimeMillis(); String timeElapsed = "index all took " + (indexAllTimeEnd - indexAllTimeBegin) + " milliseconds"; logger.info(timeElapsed); status = dataverseIndexCount + " dataverses and " + datasetIndexCount + " datasets indexed " + timeElapsed + "\n"; return new AsyncResult<>(status); } @Asynchronous public Future<String> indexDataverse(Dataverse dataverse) { logger.info("indexDataverse called on dataverse id " + dataverse.getId() + "(" + dataverse.getAlias() + ")"); if (dataverse.getId() == null) { String msg = "unable to index dataverse. id was null (alias: " + dataverse.getAlias() + ")"; logger.info(msg); return new AsyncResult<>(msg); } Dataverse rootDataverse = findRootDataverseCached(); if (dataverse.getId() == rootDataverse.getId()) { String msg = "The root dataverse shoud not be indexed."; return new AsyncResult<>(msg); } Collection<SolrInputDocument> docs = new ArrayList<>(); SolrInputDocument solrInputDocument = new SolrInputDocument(); solrInputDocument.addField(SearchFields.ID, solrDocIdentifierDataverse + dataverse.getId()); solrInputDocument.addField(SearchFields.ENTITY_ID, dataverse.getId()); solrInputDocument.addField(SearchFields.IDENTIFIER, dataverse.getAlias()); solrInputDocument.addField(SearchFields.TYPE, "dataverses"); solrInputDocument.addField(SearchFields.NAME, dataverse.getName()); solrInputDocument.addField(SearchFields.NAME_SORT, dataverse.getName()); solrInputDocument.addField(SearchFields.DATAVERSE_NAME, dataverse.getName()); solrInputDocument.addField(SearchFields.DATAVERSE_CATEGORY, dataverse.getFriendlyCategoryName()); if (dataverse.isReleased()) { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, PUBLISHED_STRING); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, dataverse.getPublicationDate()); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT, convertToFriendlyDate(dataverse.getPublicationDate())); } else { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, UNPUBLISHED_STRING); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, dataverse.getCreateDate()); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT, convertToFriendlyDate(dataverse.getCreateDate())); } addDataverseReleaseDateToSolrDoc(solrInputDocument, dataverse); // if (dataverse.getOwner() != null) { // solrInputDocument.addField(SearchFields.HOST_DATAVERSE, dataverse.getOwner().getName()); // } solrInputDocument.addField(SearchFields.DESCRIPTION, StringUtil.html2text(dataverse.getDescription())); solrInputDocument.addField(SearchFields.DATAVERSE_DESCRIPTION, StringUtil.html2text(dataverse.getDescription())); // logger.info("dataverse affiliation: " + dataverse.getAffiliation()); if (dataverse.getAffiliation() != null && !dataverse.getAffiliation().isEmpty()) { /** * @todo: stop using affiliation as category */ // solrInputDocument.addField(SearchFields.CATEGORY, dataverse.getAffiliation()); solrInputDocument.addField(SearchFields.AFFILIATION, dataverse.getAffiliation()); solrInputDocument.addField(SearchFields.DATAVERSE_AFFILIATION, dataverse.getAffiliation()); } for (ControlledVocabularyValue dataverseSubject : dataverse.getDataverseSubjects()) { String subject = dataverseSubject.getStrValue(); solrInputDocument.addField(SearchFields.DATAVERSE_SUBJECT, subject); // collapse into shared "subject" field used as a facet solrInputDocument.addField(SearchFields.SUBJECT, subject); } // checking for NPE is important so we can create the root dataverse if (rootDataverse != null && !dataverse.equals(rootDataverse)) { // important when creating root dataverse if (dataverse.getOwner() != null) { solrInputDocument.addField(SearchFields.PARENT_ID, dataverse.getOwner().getId()); solrInputDocument.addField(SearchFields.PARENT_NAME, dataverse.getOwner().getName()); } } List<String> dataversePathSegmentsAccumulator = new ArrayList<>(); List<String> dataverseSegments = findPathSegments(dataverse, dataversePathSegmentsAccumulator); List<String> dataversePaths = getDataversePathsFromSegments(dataverseSegments); if (dataversePaths.size() > 0) { // don't show yourself while indexing or in search results: https://redmine.hmdc.harvard.edu/issues/3613 // logger.info(dataverse.getName() + " size " + dataversePaths.size()); dataversePaths.remove(dataversePaths.size() - 1); } //Add paths for linking dataverses for (Dataverse linkingDataverse : dvLinkingService.findLinkingDataverses(dataverse.getId())) { List<String> linkingDataversePathSegmentsAccumulator = new ArrayList<>(); List<String> linkingdataverseSegments = findPathSegments(linkingDataverse, linkingDataversePathSegmentsAccumulator); List<String> linkingDataversePaths = getDataversePathsFromSegments(linkingdataverseSegments); for (String dvPath : linkingDataversePaths) { dataversePaths.add(dvPath); } } solrInputDocument.addField(SearchFields.SUBTREE, dataversePaths); docs.add(solrInputDocument); SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); String status; try { if (dataverse.getId() != null) { server.add(docs); } else { logger.info("WARNING: indexing of a dataverse with no id attempted"); } } catch (SolrServerException | IOException ex) { status = ex.toString(); logger.info(status); return new AsyncResult<>(status); } try { server.commit(); } catch (SolrServerException | IOException ex) { status = ex.toString(); logger.info(status); return new AsyncResult<>(status); } dvObjectService.updateContentIndexTime(dataverse); String msg = "indexed dataverse " + dataverse.getId() + ":" + dataverse.getAlias(); return new AsyncResult<>(msg); } @Asynchronous public Future<String> indexDataset(Dataset dataset) { logger.info("indexing dataset " + dataset.getId()); /** * @todo should we use solrDocIdentifierDataset or * IndexableObject.IndexableTypes.DATASET.getName() + "_" ? */ // String solrIdPublished = solrDocIdentifierDataset + dataset.getId(); String solrIdPublished = determinePublishedDatasetSolrDocId(dataset); String solrIdDraftDataset = IndexableObject.IndexableTypes.DATASET.getName() + "_" + dataset.getId() + IndexableDataset.DatasetState.WORKING_COPY.getSuffix(); // String solrIdDeaccessioned = IndexableObject.IndexableTypes.DATASET.getName() + "_" + dataset.getId() + IndexableDataset.DatasetState.DEACCESSIONED.getSuffix(); String solrIdDeaccessioned = determineDeaccessionedDatasetId(dataset); StringBuilder debug = new StringBuilder(); debug.append("\ndebug:\n"); int numPublishedVersions = 0; List<DatasetVersion> versions = dataset.getVersions(); List<String> solrIdsOfFilesToDelete = new ArrayList<>(); for (DatasetVersion datasetVersion : versions) { Long versionDatabaseId = datasetVersion.getId(); String versionTitle = datasetVersion.getTitle(); String semanticVersion = datasetVersion.getSemanticVersion(); DatasetVersion.VersionState versionState = datasetVersion.getVersionState(); if (versionState.equals(DatasetVersion.VersionState.RELEASED)) { numPublishedVersions += 1; } debug.append("version found with database id " + versionDatabaseId + "\n"); debug.append("- title: " + versionTitle + "\n"); debug.append("- semanticVersion-VersionState: " + semanticVersion + "-" + versionState + "\n"); List<FileMetadata> fileMetadatas = datasetVersion.getFileMetadatas(); List<String> fileInfo = new ArrayList<>(); for (FileMetadata fileMetadata : fileMetadatas) { String solrIdOfPublishedFile = solrDocIdentifierFile + fileMetadata.getDataFile().getId(); /** * It sounds weird but the first thing we'll do is preemptively * delete the Solr documents of all published files. Don't * worry, published files will be re-indexed later along with * the dataset. We do this so users can delete files from * published versions of datasets and then re-publish a new * version without fear that their old published files (now * deleted from the latest published version) will be * searchable. See also * https://github.com/IQSS/dataverse/issues/762 */ solrIdsOfFilesToDelete.add(solrIdOfPublishedFile); fileInfo.add(fileMetadata.getDataFile().getId() + ":" + fileMetadata.getLabel()); } int numFiles = 0; if (fileMetadatas != null) { numFiles = fileMetadatas.size(); } debug.append("- files: " + numFiles + " " + fileInfo.toString() + "\n"); } debug.append("numPublishedVersions: " + numPublishedVersions + "\n"); IndexResponse resultOfAttemptToPremptivelyDeletePublishedFiles = solrIndexService.deleteMultipleSolrIds(solrIdsOfFilesToDelete); debug.append("result of attempt to premptively deleted published files before reindexing: " + resultOfAttemptToPremptivelyDeletePublishedFiles + "\n"); DatasetVersion latestVersion = dataset.getLatestVersion(); String latestVersionStateString = latestVersion.getVersionState().name(); DatasetVersion.VersionState latestVersionState = latestVersion.getVersionState(); DatasetVersion releasedVersion = dataset.getReleasedVersion(); boolean atLeastOnePublishedVersion = false; if (releasedVersion != null) { atLeastOnePublishedVersion = true; } else { atLeastOnePublishedVersion = false; } Map<DatasetVersion.VersionState, Boolean> desiredCards = new LinkedHashMap<>(); /** * @todo refactor all of this below and have a single method that takes * the map of desired cards (which correspond to Solr documents) as one * of the arguments and does all the operations necessary to achieve the * desired state. */ StringBuilder results = new StringBuilder(); if (atLeastOnePublishedVersion == false) { results.append("No published version, nothing will be indexed as ") .append(solrIdPublished).append("\n"); if (latestVersionState.equals(DatasetVersion.VersionState.DRAFT)) { desiredCards.put(DatasetVersion.VersionState.DRAFT, true); IndexableDataset indexableDraftVersion = new IndexableDataset(latestVersion); String indexDraftResult = addOrUpdateDataset(indexableDraftVersion); results.append("The latest version is a working copy (latestVersionState: ") .append(latestVersionStateString).append(") and indexing was attempted for ") .append(solrIdDraftDataset).append(" (limited discoverability). Result: ") .append(indexDraftResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.DEACCESSIONED, false); String deleteDeaccessionedResult = removeDeaccessioned(dataset); results.append("Draft exists, no need for deaccessioned version. Deletion attempted for ") .append(solrIdDeaccessioned).append(" (and files). Result: ") .append(deleteDeaccessionedResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.RELEASED, false); String deletePublishedResults = removePublished(dataset); results.append("No published version. Attempting to delete traces of published version from index. Result: "). append(deletePublishedResults).append("\n"); /** * Desired state for existence of cards: {DRAFT=true, * DEACCESSIONED=false, RELEASED=false} * * No published version, nothing will be indexed as dataset_17 * * The latest version is a working copy (latestVersionState: * DRAFT) and indexing was attempted for dataset_17_draft * (limited discoverability). Result: indexed dataset 17 as * dataset_17_draft. filesIndexed: [datafile_18_draft] * * Draft exists, no need for deaccessioned version. Deletion * attempted for dataset_17_deaccessioned (and files). Result: * Attempted to delete dataset_17_deaccessioned from Solr index. * updateReponse was: * {responseHeader={status=0,QTime=1}}Attempted to delete * datafile_18_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}} * * No published version. Attempting to delete traces of * published version from index. Result: Attempted to delete * dataset_17 from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}}Attempted to delete * datafile_18 from Solr index. updateReponse was: * {responseHeader={status=0,QTime=0}} */ String result = getDesiredCardState(desiredCards) + results.toString() + debug.toString(); logger.info(result); indexDatasetPermissions(dataset); return new AsyncResult<>(result); } else if (latestVersionState.equals(DatasetVersion.VersionState.DEACCESSIONED)) { desiredCards.put(DatasetVersion.VersionState.DEACCESSIONED, true); IndexableDataset indexableDeaccessionedVersion = new IndexableDataset(latestVersion); String indexDeaccessionedVersionResult = addOrUpdateDataset(indexableDeaccessionedVersion); results.append("No draft version. Attempting to index as deaccessioned. Result: ").append(indexDeaccessionedVersionResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.RELEASED, false); String deletePublishedResults = removePublished(dataset); results.append("No published version. Attempting to delete traces of published version from index. Result: "). append(deletePublishedResults).append("\n"); desiredCards.put(DatasetVersion.VersionState.DRAFT, false); List<String> solrDocIdsForDraftFilesToDelete = findSolrDocIdsForDraftFilesToDelete(dataset); String deleteDraftDatasetVersionResult = removeSolrDocFromIndex(solrIdDraftDataset); String deleteDraftFilesResults = deleteDraftFiles(solrDocIdsForDraftFilesToDelete); results.append("Attempting to delete traces of drafts. Result: ") .append(deleteDraftDatasetVersionResult).append(deleteDraftFilesResults).append("\n"); /** * Desired state for existence of cards: {DEACCESSIONED=true, * RELEASED=false, DRAFT=false} * * No published version, nothing will be indexed as dataset_17 * * No draft version. Attempting to index as deaccessioned. * Result: indexed dataset 17 as dataset_17_deaccessioned. * filesIndexed: [] * * No published version. Attempting to delete traces of * published version from index. Result: Attempted to delete * dataset_17 from Solr index. updateReponse was: * {responseHeader={status=0,QTime=0}}Attempted to delete * datafile_18 from Solr index. updateReponse was: * {responseHeader={status=0,QTime=3}} * * Attempting to delete traces of drafts. Result: Attempted to * delete dataset_17_draft from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}} */ String result = getDesiredCardState(desiredCards) + results.toString() + debug.toString(); logger.info(result); indexDatasetPermissions(dataset); return new AsyncResult<>(result); } else { String result = "No-op. Unexpected condition reached: No released version and latest version is neither draft nor deaccessioned"; return new AsyncResult<>(result); } } else if (atLeastOnePublishedVersion == true) { results.append("Published versions found. ") .append("Will attempt to index as ").append(solrIdPublished).append(" (discoverable by anonymous)\n"); if (latestVersionState.equals(DatasetVersion.VersionState.RELEASED) || latestVersionState.equals(DatasetVersion.VersionState.DEACCESSIONED)) { desiredCards.put(DatasetVersion.VersionState.RELEASED, true); IndexableDataset indexableReleasedVersion = new IndexableDataset(releasedVersion); String indexReleasedVersionResult = addOrUpdateDataset(indexableReleasedVersion); results.append("Attempted to index " + solrIdPublished).append(". Result: ").append(indexReleasedVersionResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.DRAFT, false); List<String> solrDocIdsForDraftFilesToDelete = findSolrDocIdsForDraftFilesToDelete(dataset); String deleteDraftDatasetVersionResult = removeSolrDocFromIndex(solrIdDraftDataset); String deleteDraftFilesResults = deleteDraftFiles(solrDocIdsForDraftFilesToDelete); results.append("The latest version is published. Attempting to delete drafts. Result: ") .append(deleteDraftDatasetVersionResult).append(deleteDraftFilesResults).append("\n"); desiredCards.put(DatasetVersion.VersionState.DEACCESSIONED, false); String deleteDeaccessionedResult = removeDeaccessioned(dataset); results.append("No need for deaccessioned version. Deletion attempted for ") .append(solrIdDeaccessioned).append(". Result: ").append(deleteDeaccessionedResult); /** * Desired state for existence of cards: {RELEASED=true, * DRAFT=false, DEACCESSIONED=false} * * Released versions found: 1. Will attempt to index as * dataset_17 (discoverable by anonymous) * * Attempted to index dataset_17. Result: indexed dataset 17 as * dataset_17. filesIndexed: [datafile_18] * * The latest version is published. Attempting to delete drafts. * Result: Attempted to delete dataset_17_draft from Solr index. * updateReponse was: {responseHeader={status=0,QTime=1}} * * No need for deaccessioned version. Deletion attempted for * dataset_17_deaccessioned. Result: Attempted to delete * dataset_17_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}}Attempted to delete * datafile_18_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=0}} */ String result = getDesiredCardState(desiredCards) + results.toString() + debug.toString(); logger.info(result); indexDatasetPermissions(dataset); return new AsyncResult<>(result); } else if (latestVersionState.equals(DatasetVersion.VersionState.DRAFT)) { IndexableDataset indexableDraftVersion = new IndexableDataset(latestVersion); desiredCards.put(DatasetVersion.VersionState.DRAFT, true); String indexDraftResult = addOrUpdateDataset(indexableDraftVersion); results.append("The latest version is a working copy (latestVersionState: ") .append(latestVersionStateString).append(") and will be indexed as ") .append(solrIdDraftDataset).append(" (limited visibility). Result: ").append(indexDraftResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.RELEASED, true); IndexableDataset indexableReleasedVersion = new IndexableDataset(releasedVersion); String indexReleasedVersionResult = addOrUpdateDataset(indexableReleasedVersion); results.append("There is a published version we will attempt to index. Result: ").append(indexReleasedVersionResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.DEACCESSIONED, false); String deleteDeaccessionedResult = removeDeaccessioned(dataset); results.append("No need for deaccessioned version. Deletion attempted for ") .append(solrIdDeaccessioned).append(". Result: ").append(deleteDeaccessionedResult); /** * Desired state for existence of cards: {DRAFT=true, * RELEASED=true, DEACCESSIONED=false} * * Released versions found: 1. Will attempt to index as * dataset_17 (discoverable by anonymous) * * The latest version is a working copy (latestVersionState: * DRAFT) and will be indexed as dataset_17_draft (limited * visibility). Result: indexed dataset 17 as dataset_17_draft. * filesIndexed: [datafile_18_draft] * * There is a published version we will attempt to index. * Result: indexed dataset 17 as dataset_17. filesIndexed: * [datafile_18] * * No need for deaccessioned version. Deletion attempted for * dataset_17_deaccessioned. Result: Attempted to delete * dataset_17_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}}Attempted to delete * datafile_18_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=0}} */ String result = getDesiredCardState(desiredCards) + results.toString() + debug.toString(); logger.info(result); indexDatasetPermissions(dataset); return new AsyncResult<>(result); } else { String result = "No-op. Unexpected condition reached: There is at least one published version but the latest version is neither published nor draft"; logger.info(result); return new AsyncResult<>(result); } } else { String result = "No-op. Unexpected condition reached: Has a version been published or not?"; logger.info(result); return new AsyncResult<>(result); } } private String deleteDraftFiles(List<String> solrDocIdsForDraftFilesToDelete) { String deleteDraftFilesResults = ""; IndexResponse indexResponse = solrIndexService.deleteMultipleSolrIds(solrDocIdsForDraftFilesToDelete); deleteDraftFilesResults = indexResponse.toString(); return deleteDraftFilesResults; } private IndexResponse indexDatasetPermissions(Dataset dataset) { IndexResponse indexResponse = solrIndexService.indexPermissionsOnSelfAndChildren(dataset); return indexResponse; } private String addOrUpdateDataset(IndexableDataset indexableDataset) { IndexableDataset.DatasetState state = indexableDataset.getDatasetState(); Dataset dataset = indexableDataset.getDatasetVersion().getDataset(); logger.info("adding or updating Solr document for dataset id " + dataset.getId()); Collection<SolrInputDocument> docs = new ArrayList<>(); List<String> dataversePathSegmentsAccumulator = new ArrayList<>(); List<String> dataverseSegments = new ArrayList<>(); try { dataverseSegments = findPathSegments(dataset.getOwner(), dataversePathSegmentsAccumulator); } catch (Exception ex) { logger.info("failed to find dataverseSegments for dataversePaths for " + SearchFields.SUBTREE + ": " + ex); } List<String> dataversePaths = getDataversePathsFromSegments(dataverseSegments); //Add Paths for linking dataverses for (Dataverse linkingDataverse : dsLinkingService.findLinkingDataverses(dataset.getId())) { List<String> linkingDataversePathSegmentsAccumulator = new ArrayList<>(); List<String> linkingdataverseSegments = findPathSegments(linkingDataverse, linkingDataversePathSegmentsAccumulator); List<String> linkingDataversePaths = getDataversePathsFromSegments(linkingdataverseSegments); for (String dvPath : linkingDataversePaths) { dataversePaths.add(dvPath); } } SolrInputDocument solrInputDocument = new SolrInputDocument(); String datasetSolrDocId = indexableDataset.getSolrDocId(); solrInputDocument.addField(SearchFields.ID, datasetSolrDocId); solrInputDocument.addField(SearchFields.ENTITY_ID, dataset.getId()); solrInputDocument.addField(SearchFields.IDENTIFIER, dataset.getGlobalId()); solrInputDocument.addField(SearchFields.PERSISTENT_URL, dataset.getPersistentURL()); solrInputDocument.addField(SearchFields.TYPE, "datasets"); Date datasetSortByDate = new Date(); Date majorVersionReleaseDate = dataset.getMostRecentMajorVersionReleaseDate(); if (majorVersionReleaseDate != null) { if (true) { String msg = "major release date found: " + majorVersionReleaseDate.toString(); logger.fine(msg); } datasetSortByDate = majorVersionReleaseDate; } else { if (indexableDataset.getDatasetState().equals(IndexableDataset.DatasetState.WORKING_COPY)) { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, UNPUBLISHED_STRING); } else if (indexableDataset.getDatasetState().equals(IndexableDataset.DatasetState.DEACCESSIONED)) { // uncomment this if we change our mind and want a deaccessioned facet after all // solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, DEACCESSIONED_STRING); } Date createDate = dataset.getCreateDate(); if (createDate != null) { if (true) { String msg = "can't find major release date, using create date: " + createDate; logger.info(msg); } datasetSortByDate = createDate; } else { String msg = "can't find major release date or create date, using \"now\""; logger.info(msg); datasetSortByDate = new Date(); } } solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, datasetSortByDate); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT, convertToFriendlyDate(datasetSortByDate)); if (state.equals(indexableDataset.getDatasetState().PUBLISHED)) { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, PUBLISHED_STRING); // solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, dataset.getPublicationDate()); } else if (state.equals(indexableDataset.getDatasetState().WORKING_COPY)) { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, DRAFT_STRING); } addDatasetReleaseDateToSolrDoc(solrInputDocument, dataset); DatasetVersion datasetVersion = indexableDataset.getDatasetVersion(); String parentDatasetTitle = "TBD"; if (datasetVersion != null) { solrInputDocument.addField(SearchFields.DATASET_VERSION_ID, datasetVersion.getId()); System.out.print(datasetVersion.getCitation(true)); solrInputDocument.addField(SearchFields.DATASET_CITATION, datasetVersion.getCitation(true)); for (DatasetField dsf : datasetVersion.getFlatDatasetFields()) { DatasetFieldType dsfType = dsf.getDatasetFieldType(); String solrFieldSearchable = dsfType.getSolrField().getNameSearchable(); String solrFieldFacetable = dsfType.getSolrField().getNameFacetable(); if (dsf.getValues() != null && !dsf.getValues().isEmpty() && dsf.getValues().get(0) != null && solrFieldSearchable != null) { logger.fine("indexing " + dsf.getDatasetFieldType().getName() + ":" + dsf.getValues() + " into " + solrFieldSearchable + " and maybe " + solrFieldFacetable); // if (dsfType.getSolrField().getSolrType().equals(SolrField.SolrType.INTEGER)) { if (dsfType.getSolrField().getSolrType().equals(SolrField.SolrType.EMAIL)) { //no-op. we want to keep email address out of Solr per https://github.com/IQSS/dataverse/issues/759 } else if (dsfType.getSolrField().getSolrType().equals(SolrField.SolrType.DATE)) { String dateAsString = dsf.getValues().get(0); logger.fine("date as string: " + dateAsString); if (dateAsString != null && !dateAsString.isEmpty()) { SimpleDateFormat inputDateyyyy = new SimpleDateFormat("yyyy", Locale.ENGLISH); try { /** * @todo when bean validation is working we * won't have to convert strings into dates */ logger.fine("Trying to convert " + dateAsString + " to a YYYY date from dataset " + dataset.getId()); Date dateAsDate = inputDateyyyy.parse(dateAsString); SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy"); String datasetFieldFlaggedAsDate = yearOnly.format(dateAsDate); logger.fine("YYYY only: " + datasetFieldFlaggedAsDate); // solrInputDocument.addField(solrFieldSearchable, Integer.parseInt(datasetFieldFlaggedAsDate)); solrInputDocument.addField(solrFieldSearchable, datasetFieldFlaggedAsDate); if (dsfType.getSolrField().isFacetable()) { // solrInputDocument.addField(solrFieldFacetable, Integer.parseInt(datasetFieldFlaggedAsDate)); solrInputDocument.addField(solrFieldFacetable, datasetFieldFlaggedAsDate); } } catch (Exception ex) { logger.info("unable to convert " + dateAsString + " into YYYY format and couldn't index it (" + dsfType.getName() + ")"); } } } else { // _s (dynamic string) and all other Solr fields if (dsf.getDatasetFieldType().getName().equals("authorAffiliation")) { /** * @todo think about how to tie the fact that this * needs to be multivalued (_ss) because a * multivalued facet (authorAffilition_ss) is being * collapsed into here at index time. The business * logic to determine if a data-driven metadata * field should be indexed into Solr as a single or * multiple value lives in the getSolrField() method * of DatasetField.java */ solrInputDocument.addField(SearchFields.AFFILIATION, dsf.getValues()); } else if (dsf.getDatasetFieldType().getName().equals("title")) { // datasets have titles not names but index title under name as well so we can sort datasets by name along dataverses and files List<String> possibleTitles = dsf.getValues(); String firstTitle = possibleTitles.get(0); if (firstTitle != null) { parentDatasetTitle = firstTitle; } solrInputDocument.addField(SearchFields.NAME_SORT, dsf.getValues()); } if (dsfType.isControlledVocabulary()) { for (ControlledVocabularyValue controlledVocabularyValue : dsf.getControlledVocabularyValues()) { solrInputDocument.addField(solrFieldSearchable, controlledVocabularyValue.getStrValue()); if (dsfType.getSolrField().isFacetable()) { solrInputDocument.addField(solrFieldFacetable, controlledVocabularyValue.getStrValue()); } } } else { if (dsfType.getFieldType().equals(DatasetFieldType.FieldType.TEXTBOX)) { // strip HTML List<String> htmlFreeText = StringUtil.htmlArray2textArray(dsf.getValues()); solrInputDocument.addField(solrFieldSearchable, htmlFreeText); if (dsfType.getSolrField().isFacetable()) { solrInputDocument.addField(solrFieldFacetable, htmlFreeText); } } else { // do not strip HTML solrInputDocument.addField(solrFieldSearchable, dsf.getValues()); if (dsfType.getSolrField().isFacetable()) { solrInputDocument.addField(solrFieldFacetable, dsf.getValues()); } } } } } } } solrInputDocument.addField(SearchFields.SUBTREE, dataversePaths); // solrInputDocument.addField(SearchFields.HOST_DATAVERSE, dataset.getOwner().getName()); solrInputDocument.addField(SearchFields.PARENT_ID, dataset.getOwner().getId()); solrInputDocument.addField(SearchFields.PARENT_NAME, dataset.getOwner().getName()); docs.add(solrInputDocument); List<String> filesIndexed = new ArrayList<>(); if (datasetVersion != null) { List<FileMetadata> fileMetadatas = datasetVersion.getFileMetadatas(); boolean checkForDuplicateMetadata = false; if (datasetVersion.isDraft() && dataset.isReleased()) { checkForDuplicateMetadata = true; logger.fine("We are indexing a draft version of a dataset that has a released version. We'll be checking file metadatas if they are exact clones of the released versions."); } for (FileMetadata fileMetadata : fileMetadatas) { boolean indexThisMetadata = true; if (checkForDuplicateMetadata) { logger.fine("Checking if this file metadata is a duplicate."); for (FileMetadata releasedFileMetadata : dataset.getReleasedVersion().getFileMetadatas()) { if (fileMetadata.getDataFile() != null && fileMetadata.getDataFile().equals(releasedFileMetadata.getDataFile())) { if (fileMetadata.contentEquals(releasedFileMetadata)) { indexThisMetadata = false; logger.fine("This file metadata hasn't changed since the released version; skipping indexing."); } else { logger.fine("This file metadata has changed since the released version; we want to index it!"); } break; } } } if (indexThisMetadata) { SolrInputDocument datafileSolrInputDocument = new SolrInputDocument(); Long fileEntityId = fileMetadata.getDataFile().getId(); datafileSolrInputDocument.addField(SearchFields.ENTITY_ID, fileEntityId); datafileSolrInputDocument.addField(SearchFields.IDENTIFIER, fileEntityId); datafileSolrInputDocument.addField(SearchFields.PERSISTENT_URL, dataset.getPersistentURL()); datafileSolrInputDocument.addField(SearchFields.TYPE, "files"); String filenameCompleteFinal = ""; if (fileMetadata != null) { String filenameComplete = fileMetadata.getLabel(); if (filenameComplete != null) { String filenameWithoutExtension = ""; // String extension = ""; int i = filenameComplete.lastIndexOf('.'); if (i > 0) { // extension = filenameComplete.substring(i + 1); try { filenameWithoutExtension = filenameComplete.substring(0, i); datafileSolrInputDocument.addField(SearchFields.FILENAME_WITHOUT_EXTENSION, filenameWithoutExtension); datafileSolrInputDocument.addField(SearchFields.FILE_NAME, filenameWithoutExtension); } catch (IndexOutOfBoundsException ex) { filenameWithoutExtension = ""; } } else { logger.info("problem with filename '" + filenameComplete + "': no extension? empty string as filename?"); filenameWithoutExtension = filenameComplete; } filenameCompleteFinal = filenameComplete; } } datafileSolrInputDocument.addField(SearchFields.NAME, filenameCompleteFinal); datafileSolrInputDocument.addField(SearchFields.NAME_SORT, filenameCompleteFinal); datafileSolrInputDocument.addField(SearchFields.FILE_NAME, filenameCompleteFinal); datafileSolrInputDocument.addField(SearchFields.DATASET_VERSION_ID, datasetVersion.getId()); /** * for rules on sorting files see * https://docs.google.com/a/harvard.edu/document/d/1DWsEqT8KfheKZmMB3n_VhJpl9nIxiUjai_AIQPAjiyA/edit?usp=sharing * via https://redmine.hmdc.harvard.edu/issues/3701 */ Date fileSortByDate = new Date(); DataFile datafile = fileMetadata.getDataFile(); if (datafile != null) { boolean fileHasBeenReleased = datafile.isReleased(); if (fileHasBeenReleased) { logger.info("indexing file with filePublicationTimestamp. " + fileMetadata.getId() + " (file id " + datafile.getId() + ")"); Timestamp filePublicationTimestamp = datafile.getPublicationDate(); if (filePublicationTimestamp != null) { fileSortByDate = filePublicationTimestamp; } else { String msg = "filePublicationTimestamp was null for fileMetadata id " + fileMetadata.getId() + " (file id " + datafile.getId() + ")"; logger.info(msg); } } else { logger.info("indexing file with fileCreateTimestamp. " + fileMetadata.getId() + " (file id " + datafile.getId() + ")"); Timestamp fileCreateTimestamp = datafile.getCreateDate(); if (fileCreateTimestamp != null) { fileSortByDate = fileCreateTimestamp; } else { String msg = "fileCreateTimestamp was null for fileMetadata id " + fileMetadata.getId() + " (file id " + datafile.getId() + ")"; logger.info(msg); } } } if (fileSortByDate == null) { if (datasetSortByDate != null) { logger.info("fileSortByDate was null, assigning datasetSortByDate"); fileSortByDate = datasetSortByDate; } else { logger.info("fileSortByDate and datasetSortByDate were null, assigning 'now'"); fileSortByDate = new Date(); } } datafileSolrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, fileSortByDate); datafileSolrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT, convertToFriendlyDate(fileSortByDate)); if (majorVersionReleaseDate == null) { datafileSolrInputDocument.addField(SearchFields.PUBLICATION_STATUS, UNPUBLISHED_STRING); } String fileSolrDocId = solrDocIdentifierFile + fileEntityId; if (indexableDataset.getDatasetState().equals(indexableDataset.getDatasetState().PUBLISHED)) { fileSolrDocId = solrDocIdentifierFile + fileEntityId; datafileSolrInputDocument.addField(SearchFields.PUBLICATION_STATUS, PUBLISHED_STRING); // datafileSolrInputDocument.addField(SearchFields.PERMS, publicGroupString); addDatasetReleaseDateToSolrDoc(datafileSolrInputDocument, dataset); } else if (indexableDataset.getDatasetState().equals(indexableDataset.getDatasetState().WORKING_COPY)) { fileSolrDocId = solrDocIdentifierFile + fileEntityId + indexableDataset.getDatasetState().getSuffix(); datafileSolrInputDocument.addField(SearchFields.PUBLICATION_STATUS, DRAFT_STRING); } datafileSolrInputDocument.addField(SearchFields.ID, fileSolrDocId); // For the mime type, we are going to index the "friendly" version, e.g., // "PDF File" instead of "application/pdf", "MS Excel" instead of // "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" (!), etc., // if available: datafileSolrInputDocument.addField(SearchFields.FILE_TYPE_MIME, fileMetadata.getDataFile().getFriendlyType()); datafileSolrInputDocument.addField(SearchFields.FILE_TYPE_SEARCHABLE, fileMetadata.getDataFile().getFriendlyType()); // For the file type facets, we have a property file that maps mime types // to facet-friendly names; "application/fits" should become "FITS", etc.: datafileSolrInputDocument.addField(SearchFields.FILE_TYPE, FileUtil.getFacetFileType(fileMetadata.getDataFile())); datafileSolrInputDocument.addField(SearchFields.FILE_TYPE_SEARCHABLE, FileUtil.getFacetFileType(fileMetadata.getDataFile())); datafileSolrInputDocument.addField(SearchFields.FILE_SIZE_IN_BYTES, fileMetadata.getDataFile().getFilesize()); datafileSolrInputDocument.addField(SearchFields.FILE_MD5, fileMetadata.getDataFile().getmd5()); datafileSolrInputDocument.addField(SearchFields.DESCRIPTION, fileMetadata.getDescription()); datafileSolrInputDocument.addField(SearchFields.FILE_DESCRIPTION, fileMetadata.getDescription()); datafileSolrInputDocument.addField(SearchFields.UNF, fileMetadata.getDataFile().getUnf()); datafileSolrInputDocument.addField(SearchFields.SUBTREE, dataversePaths); // datafileSolrInputDocument.addField(SearchFields.HOST_DATAVERSE, dataFile.getOwner().getOwner().getName()); // datafileSolrInputDocument.addField(SearchFields.PARENT_NAME, dataFile.getDataset().getTitle()); datafileSolrInputDocument.addField(SearchFields.PARENT_ID, fileMetadata.getDataFile().getOwner().getId()); datafileSolrInputDocument.addField(SearchFields.PARENT_IDENTIFIER, fileMetadata.getDataFile().getOwner().getGlobalId()); datafileSolrInputDocument.addField(SearchFields.PARENT_CITATION, fileMetadata.getDataFile().getOwner().getCitation()); datafileSolrInputDocument.addField(SearchFields.PARENT_NAME, parentDatasetTitle); // If this is a tabular data file -- i.e., if there are data // variables associated with this file, we index the variable // names and labels: if (fileMetadata.getDataFile().isTabularData()) { List<DataVariable> variables = fileMetadata.getDataFile().getDataTable().getDataVariables(); for (DataVariable var : variables) { // Hard-coded search fields, for now: // TODO: eventually: review, decide how datavariables should // be handled for indexing purposes. (should it be a fixed // setup, defined in the code? should it be flexible? unlikely // that this needs to be domain-specific... since these data // variables are quite specific to tabular data, which in turn // is something social science-specific... // anyway -- needs to be reviewed. -- L.A. 4.0alpha1 if (var.getName() != null && !var.getName().equals("")) { datafileSolrInputDocument.addField(SearchFields.VARIABLE_NAME, var.getName()); } if (var.getLabel() != null && !var.getLabel().equals("")) { datafileSolrInputDocument.addField(SearchFields.VARIABLE_LABEL, var.getLabel()); } } } if (indexableDataset.isFilesShouldBeIndexed()) { filesIndexed.add(fileSolrDocId); docs.add(datafileSolrInputDocument); } } } } SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); try { server.add(docs); } catch (SolrServerException | IOException ex) { return ex.toString(); } try { server.commit(); } catch (SolrServerException | IOException ex) { return ex.toString(); } dvObjectService.updateContentIndexTime(dataset); // return "indexed dataset " + dataset.getId() + " as " + solrDocId + "\nindexFilesResults for " + solrDocId + ":" + fileInfo.toString(); return "indexed dataset " + dataset.getId() + " as " + datasetSolrDocId + ". filesIndexed: " + filesIndexed; } public List<String> findPathSegments(Dataverse dataverse, List<String> segments) { Dataverse rootDataverse = findRootDataverseCached(); if (!dataverse.equals(rootDataverse)) { // important when creating root dataverse if (dataverse.getOwner() != null) { findPathSegments(dataverse.getOwner(), segments); } segments.add(dataverse.getId().toString()); return segments; } else { // base case return segments; } } List<String> getDataversePathsFromSegments(List<String> dataversePathSegments) { List<String> subtrees = new ArrayList<>(); for (int i = 0; i < dataversePathSegments.size(); i++) { StringBuilder pathBuilder = new StringBuilder(); int numSegments = dataversePathSegments.size(); for (int j = 0; j < numSegments; j++) { if (j <= i) { pathBuilder.append("/" + dataversePathSegments.get(j)); } } subtrees.add(pathBuilder.toString()); } return subtrees; } private void addDataverseReleaseDateToSolrDoc(SolrInputDocument solrInputDocument, Dataverse dataverse) { if (dataverse.getPublicationDate() != null) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(dataverse.getPublicationDate().getTime()); int YYYY = calendar.get(Calendar.YEAR); solrInputDocument.addField(SearchFields.PUBLICATION_DATE, YYYY); } } private void addDatasetReleaseDateToSolrDoc(SolrInputDocument solrInputDocument, Dataset dataset) { if (dataset.getPublicationDate() != null) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(dataset.getPublicationDate().getTime()); int YYYY = calendar.get(Calendar.YEAR); solrInputDocument.addField(SearchFields.PUBLICATION_DATE, YYYY); solrInputDocument.addField(SearchFields.DATASET_PUBLICATION_DATE, YYYY); } } public static String getGroupPrefix() { return groupPrefix; } public static String getGroupPerUserPrefix() { return groupPerUserPrefix; } public static String getPublicGroupString() { return publicGroupString; } public static String getPUBLISHED_STRING() { return PUBLISHED_STRING; } public static String getUNPUBLISHED_STRING() { return UNPUBLISHED_STRING; } public static String getDRAFT_STRING() { return DRAFT_STRING; } public static String getDEACCESSIONED_STRING() { return DEACCESSIONED_STRING; } public String delete(Dataverse doomed) { SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); logger.info("deleting Solr document for dataverse " + doomed.getId()); UpdateResponse updateResponse; try { updateResponse = server.deleteById(solrDocIdentifierDataverse + doomed.getId()); } catch (SolrServerException | IOException ex) { return ex.toString(); } try { server.commit(); } catch (SolrServerException | IOException ex) { return ex.toString(); } String response = "Successfully deleted dataverse " + doomed.getId() + " from Solr index. updateReponse was: " + updateResponse.toString(); logger.info(response); return response; } /** * @todo call this in fewer places, favoring * SolrIndexServiceBeans.deleteMultipleSolrIds instead to operate in batches * * https://github.com/IQSS/dataverse/issues/142 */ public String removeSolrDocFromIndex(String doomed) { SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); logger.info("deleting Solr document: " + doomed); UpdateResponse updateResponse; try { updateResponse = server.deleteById(doomed); } catch (SolrServerException | IOException ex) { return ex.toString(); } try { server.commit(); } catch (SolrServerException | IOException ex) { return ex.toString(); } String response = "Attempted to delete " + doomed + " from Solr index. updateReponse was: " + updateResponse.toString(); logger.info(response); return response; } public String convertToFriendlyDate(Date dateAsDate) { if (dateAsDate == null) { dateAsDate = new Date(); } // using DateFormat.MEDIUM for May 5, 2014 to match what's in DVN 3.x DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); String friendlyDate = format.format(dateAsDate); return friendlyDate; } private List<String> findSolrDocIdsForDraftFilesToDelete(Dataset datasetWithDraftFilesToDelete) { Long datasetId = datasetWithDraftFilesToDelete.getId(); SolrServer solrServer = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); SolrQuery solrQuery = new SolrQuery(); solrQuery.setRows(Integer.MAX_VALUE); solrQuery.setQuery(SearchFields.PARENT_ID + ":" + datasetId); solrQuery.addFilterQuery(SearchFields.ID + ":" + "*" + draftSuffix); List<String> solrIdsOfFilesToDelete = new ArrayList<>(); try { // i.e. rows=2147483647&q=parentid%3A16&fq=id%3A*_draft logger.info("passing this Solr query to find draft files to delete: " + solrQuery); QueryResponse queryResponse = solrServer.query(solrQuery); SolrDocumentList results = queryResponse.getResults(); for (SolrDocument solrDocument : results) { String id = (String) solrDocument.getFieldValue(SearchFields.ID); if (id != null) { solrIdsOfFilesToDelete.add(id); } } } catch (SolrServerException ex) { logger.info("error in findSolrDocIdsForDraftFilesToDelete method: " + ex.toString()); } return solrIdsOfFilesToDelete; } private List<String> findSolrDocIdsForFilesToDelete(Dataset dataset, IndexableDataset.DatasetState state) { List<String> solrIdsOfFilesToDelete = new ArrayList<>(); for (DataFile file : dataset.getFiles()) { solrIdsOfFilesToDelete.add(solrDocIdentifierFile + file.getId() + state.getSuffix()); } return solrIdsOfFilesToDelete; } private String removeMultipleSolrDocs(List<String> docIds) { IndexResponse indexResponse = solrIndexService.deleteMultipleSolrIds(docIds); return indexResponse.toString(); } private String determinePublishedDatasetSolrDocId(Dataset dataset) { return IndexableObject.IndexableTypes.DATASET.getName() + "_" + dataset.getId() + IndexableDataset.DatasetState.PUBLISHED.getSuffix(); } private String determineDeaccessionedDatasetId(Dataset dataset) { return IndexableObject.IndexableTypes.DATASET.getName() + "_" + dataset.getId() + IndexableDataset.DatasetState.DEACCESSIONED.getSuffix(); } private String removeDeaccessioned(Dataset dataset) { StringBuilder result = new StringBuilder(); String deleteDeaccessionedResult = removeSolrDocFromIndex(determineDeaccessionedDatasetId(dataset)); result.append(deleteDeaccessionedResult); List<String> docIds = findSolrDocIdsForFilesToDelete(dataset, IndexableDataset.DatasetState.DEACCESSIONED); String deleteFilesResult = removeMultipleSolrDocs(docIds); result.append(deleteFilesResult); return result.toString(); } private String removePublished(Dataset dataset) { StringBuilder result = new StringBuilder(); String deletePublishedResult = removeSolrDocFromIndex(determinePublishedDatasetSolrDocId(dataset)); result.append(deletePublishedResult); List<String> docIds = findSolrDocIdsForFilesToDelete(dataset, IndexableDataset.DatasetState.PUBLISHED); String deleteFilesResult = removeMultipleSolrDocs(docIds); result.append(deleteFilesResult); return result.toString(); } private Dataverse findRootDataverseCached() { if (true) { /** * @todo Is the code below working at all? We don't want the root * dataverse to be indexed into Solr. Specifically, we don't want a * dataverse "card" to show up while browsing. * * Let's just find the root dataverse and be done with it. We'll * figure out the caching later. */ return dataverseService.findRootDataverse(); } /** * @todo Why isn't this code working? */ if (rootDataverseCached != null) { return rootDataverseCached; } else { rootDataverseCached = dataverseService.findRootDataverse(); if (rootDataverseCached != null) { return rootDataverseCached; } else { throw new RuntimeException("unable to determine root dataverse"); } } } private String getDesiredCardState(Map<DatasetVersion.VersionState, Boolean> desiredCards) { /** * @todo make a JVM option to enforce sanity checks? Call it dev=true? */ boolean sanityCheck = true; if (sanityCheck) { Set<DatasetVersion.VersionState> expected = new HashSet<>(); expected.add(DatasetVersion.VersionState.DRAFT); expected.add(DatasetVersion.VersionState.RELEASED); expected.add(DatasetVersion.VersionState.DEACCESSIONED); if (!desiredCards.keySet().equals(expected)) { throw new RuntimeException("Mismatch between expected version states (" + expected + ") and version states passed in (" + desiredCards.keySet() + ")"); } } return "Desired state for existence of cards: " + desiredCards + "\n"; } /** * @return Dataverses that should be reindexed either because they have * never been indexed or their index time is before their modification time. */ public List findStaleOrMissingDataverses() { List<Dataverse> staleDataverses = new ArrayList<>(); for (Dataverse dataverse : dataverseService.findAll()) { if (dataverse.equals(dataverseService.findRootDataverse())) { continue; } if (stale(dataverse)) { staleDataverses.add(dataverse); } } return staleDataverses; } /** * @return Datasets that should be reindexed either because they have never * been indexed or their index time is before their modification time. */ public List findStaleOrMissingDatasets() { List<Dataset> staleDatasets = new ArrayList<>(); for (Dataset dataset : datasetService.findAll()) { if (stale(dataset)) { staleDatasets.add(dataset); } } return staleDatasets; } private boolean stale(DvObject dvObject) { Timestamp indexTime = dvObject.getIndexTime(); Timestamp modificationTime = dvObject.getModificationTime(); if (indexTime == null) { return true; } else { if (indexTime.before(modificationTime)) { return true; } } return false; } public List<Long> findDataversesInSolrOnly() throws SearchException { try { /** * @todo define this centrally and statically */ return findDvObjectInSolrOnly("dataverses"); } catch (SearchException ex) { throw ex; } } public List<Long> findDatasetsInSolrOnly() throws SearchException { try { /** * @todo define this centrally and statically */ return findDvObjectInSolrOnly("datasets"); } catch (SearchException ex) { throw ex; } } private List<Long> findDvObjectInSolrOnly(String type) throws SearchException { SolrServer solrServer = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*"); solrQuery.setRows(Integer.SIZE); solrQuery.addFilterQuery(SearchFields.TYPE + ":" + type); List<Long> dvObjectInSolrOnly = new ArrayList<>(); QueryResponse queryResponse = null; try { queryResponse = solrServer.query(solrQuery); } catch (SolrServerException ex) { throw new SearchException("Error searching Solr for " + type, ex); } SolrDocumentList results = queryResponse.getResults(); for (SolrDocument solrDocument : results) { Object idObject = solrDocument.getFieldValue(SearchFields.ENTITY_ID); if (idObject != null) { try { long id = (Long) idObject; DvObject dvobject = dvObjectService.findDvObject(id); if (dvobject == null) { dvObjectInSolrOnly.add(id); } } catch (ClassCastException ex) { throw new SearchException("Found " + SearchFields.ENTITY_ID + " but error casting " + idObject + " to long", ex); } } } return dvObjectInSolrOnly; } }
src/main/java/edu/harvard/iq/dataverse/IndexServiceBean.java
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.util.StringUtil; import edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUserServiceBean; import edu.harvard.iq.dataverse.search.SearchFields; import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean; import edu.harvard.iq.dataverse.datavariable.DataVariable; import edu.harvard.iq.dataverse.search.IndexResponse; import edu.harvard.iq.dataverse.search.IndexableDataset; import edu.harvard.iq.dataverse.search.IndexableObject; import edu.harvard.iq.dataverse.search.SearchException; import edu.harvard.iq.dataverse.search.SearchPermissionsServiceBean; import edu.harvard.iq.dataverse.search.SolrIndexServiceBean; import edu.harvard.iq.dataverse.util.FileUtil; import edu.harvard.iq.dataverse.util.SystemConfig; import java.io.IOException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.logging.Logger; import javax.ejb.AsyncResult; import javax.ejb.Asynchronous; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.inject.Named; import javax.ws.rs.container.AsyncResponse; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; @Stateless @Named public class IndexServiceBean { private static final Logger logger = Logger.getLogger(IndexServiceBean.class.getCanonicalName()); @EJB DvObjectServiceBean dvObjectService; @EJB DataverseServiceBean dataverseService; @EJB DatasetServiceBean datasetService; @EJB BuiltinUserServiceBean dataverseUserServiceBean; @EJB PermissionServiceBean permissionService; @EJB AuthenticationServiceBean userServiceBean; @EJB SystemConfig systemConfig; @EJB SearchPermissionsServiceBean searchPermissionsService; @EJB SolrIndexServiceBean solrIndexService; @EJB DatasetLinkingServiceBean dsLinkingService; @EJB DataverseLinkingServiceBean dvLinkingService; public static final String solrDocIdentifierDataverse = "dataverse_"; public static final String solrDocIdentifierFile = "datafile_"; public static final String solrDocIdentifierDataset = "dataset_"; public static final String draftSuffix = "_draft"; public static final String deaccessionedSuffix = "_deaccessioned"; public static final String discoverabilityPermissionSuffix = "_permission"; private static final String groupPrefix = "group_"; private static final String groupPerUserPrefix = "group_user"; private static final String publicGroupIdString = "public"; private static final String publicGroupString = groupPrefix + "public"; private static final String PUBLISHED_STRING = "Published"; private static final String UNPUBLISHED_STRING = "Unpublished"; private static final String DRAFT_STRING = "Draft"; private static final String DEACCESSIONED_STRING = "Deaccessioned"; private Dataverse rootDataverseCached; @Asynchronous public Future<String> indexAll() { String status; SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); logger.info("attempting to delete all Solr documents before a complete re-index"); try { server.deleteByQuery("*:*");// CAUTION: deletes everything! } catch (SolrServerException | IOException ex) { status = ex.toString(); logger.info(status); return new AsyncResult<>(status); } try { server.commit(); } catch (SolrServerException | IOException ex) { status = ex.toString(); logger.info(status); return new AsyncResult<>(status); } List<Dataverse> dataverses = dataverseService.findAll(); int dataverseIndexCount = 0; for (Dataverse dataverse : dataverses) { logger.info("indexing dataverse " + dataverseIndexCount + " of " + dataverses.size() + ": " + indexDataverse(dataverse)); dataverseIndexCount++; } int datasetIndexCount = 0; List<Dataset> datasets = datasetService.findAll(); for (Dataset dataset : datasets) { datasetIndexCount++; logger.info("indexing dataset " + datasetIndexCount + " of " + datasets.size() + ": " + indexDataset(dataset)); } // logger.info("advanced search fields: " + advancedSearchFields); // logger.info("not advanced search fields: " + notAdvancedSearchFields); logger.info("done iterating through all datasets"); status = dataverseIndexCount + " dataverses and " + datasetIndexCount + " datasets indexed\n"; return new AsyncResult<>(status); } @Asynchronous public Future<String> indexDataverse(Dataverse dataverse) { logger.info("indexDataverse called on dataverse id " + dataverse.getId() + "(" + dataverse.getAlias() + ")"); if (dataverse.getId() == null) { String msg = "unable to index dataverse. id was null (alias: " + dataverse.getAlias() + ")"; logger.info(msg); return new AsyncResult<>(msg); } Dataverse rootDataverse = findRootDataverseCached(); if (dataverse.getId() == rootDataverse.getId()) { String msg = "The root dataverse shoud not be indexed."; return new AsyncResult<>(msg); } Collection<SolrInputDocument> docs = new ArrayList<>(); SolrInputDocument solrInputDocument = new SolrInputDocument(); solrInputDocument.addField(SearchFields.ID, solrDocIdentifierDataverse + dataverse.getId()); solrInputDocument.addField(SearchFields.ENTITY_ID, dataverse.getId()); solrInputDocument.addField(SearchFields.IDENTIFIER, dataverse.getAlias()); solrInputDocument.addField(SearchFields.TYPE, "dataverses"); solrInputDocument.addField(SearchFields.NAME, dataverse.getName()); solrInputDocument.addField(SearchFields.NAME_SORT, dataverse.getName()); solrInputDocument.addField(SearchFields.DATAVERSE_NAME, dataverse.getName()); solrInputDocument.addField(SearchFields.DATAVERSE_CATEGORY, dataverse.getFriendlyCategoryName()); if (dataverse.isReleased()) { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, PUBLISHED_STRING); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, dataverse.getPublicationDate()); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT, convertToFriendlyDate(dataverse.getPublicationDate())); } else { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, UNPUBLISHED_STRING); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, dataverse.getCreateDate()); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT, convertToFriendlyDate(dataverse.getCreateDate())); } addDataverseReleaseDateToSolrDoc(solrInputDocument, dataverse); // if (dataverse.getOwner() != null) { // solrInputDocument.addField(SearchFields.HOST_DATAVERSE, dataverse.getOwner().getName()); // } solrInputDocument.addField(SearchFields.DESCRIPTION, StringUtil.html2text(dataverse.getDescription())); solrInputDocument.addField(SearchFields.DATAVERSE_DESCRIPTION, StringUtil.html2text(dataverse.getDescription())); // logger.info("dataverse affiliation: " + dataverse.getAffiliation()); if (dataverse.getAffiliation() != null && !dataverse.getAffiliation().isEmpty()) { /** * @todo: stop using affiliation as category */ // solrInputDocument.addField(SearchFields.CATEGORY, dataverse.getAffiliation()); solrInputDocument.addField(SearchFields.AFFILIATION, dataverse.getAffiliation()); solrInputDocument.addField(SearchFields.DATAVERSE_AFFILIATION, dataverse.getAffiliation()); } for (ControlledVocabularyValue dataverseSubject : dataverse.getDataverseSubjects()) { String subject = dataverseSubject.getStrValue(); solrInputDocument.addField(SearchFields.DATAVERSE_SUBJECT, subject); // collapse into shared "subject" field used as a facet solrInputDocument.addField(SearchFields.SUBJECT, subject); } // checking for NPE is important so we can create the root dataverse if (rootDataverse != null && !dataverse.equals(rootDataverse)) { // important when creating root dataverse if (dataverse.getOwner() != null) { solrInputDocument.addField(SearchFields.PARENT_ID, dataverse.getOwner().getId()); solrInputDocument.addField(SearchFields.PARENT_NAME, dataverse.getOwner().getName()); } } List<String> dataversePathSegmentsAccumulator = new ArrayList<>(); List<String> dataverseSegments = findPathSegments(dataverse, dataversePathSegmentsAccumulator); List<String> dataversePaths = getDataversePathsFromSegments(dataverseSegments); if (dataversePaths.size() > 0) { // don't show yourself while indexing or in search results: https://redmine.hmdc.harvard.edu/issues/3613 // logger.info(dataverse.getName() + " size " + dataversePaths.size()); dataversePaths.remove(dataversePaths.size() - 1); } //Add paths for linking dataverses for (Dataverse linkingDataverse : dvLinkingService.findLinkingDataverses(dataverse.getId())) { List<String> linkingDataversePathSegmentsAccumulator = new ArrayList<>(); List<String> linkingdataverseSegments = findPathSegments(linkingDataverse, linkingDataversePathSegmentsAccumulator); List<String> linkingDataversePaths = getDataversePathsFromSegments(linkingdataverseSegments); for (String dvPath : linkingDataversePaths) { dataversePaths.add(dvPath); } } solrInputDocument.addField(SearchFields.SUBTREE, dataversePaths); docs.add(solrInputDocument); SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); String status; try { if (dataverse.getId() != null) { server.add(docs); } else { logger.info("WARNING: indexing of a dataverse with no id attempted"); } } catch (SolrServerException | IOException ex) { status = ex.toString(); logger.info(status); return new AsyncResult<>(status); } try { server.commit(); } catch (SolrServerException | IOException ex) { status = ex.toString(); logger.info(status); return new AsyncResult<>(status); } dvObjectService.updateContentIndexTime(dataverse); String msg = "indexed dataverse " + dataverse.getId() + ":" + dataverse.getAlias(); return new AsyncResult<>(msg); } @Asynchronous public Future<String> indexDataset(Dataset dataset) { logger.info("indexing dataset " + dataset.getId()); /** * @todo should we use solrDocIdentifierDataset or * IndexableObject.IndexableTypes.DATASET.getName() + "_" ? */ // String solrIdPublished = solrDocIdentifierDataset + dataset.getId(); String solrIdPublished = determinePublishedDatasetSolrDocId(dataset); String solrIdDraftDataset = IndexableObject.IndexableTypes.DATASET.getName() + "_" + dataset.getId() + IndexableDataset.DatasetState.WORKING_COPY.getSuffix(); // String solrIdDeaccessioned = IndexableObject.IndexableTypes.DATASET.getName() + "_" + dataset.getId() + IndexableDataset.DatasetState.DEACCESSIONED.getSuffix(); String solrIdDeaccessioned = determineDeaccessionedDatasetId(dataset); StringBuilder debug = new StringBuilder(); debug.append("\ndebug:\n"); int numPublishedVersions = 0; List<DatasetVersion> versions = dataset.getVersions(); List<String> solrIdsOfFilesToDelete = new ArrayList<>(); for (DatasetVersion datasetVersion : versions) { Long versionDatabaseId = datasetVersion.getId(); String versionTitle = datasetVersion.getTitle(); String semanticVersion = datasetVersion.getSemanticVersion(); DatasetVersion.VersionState versionState = datasetVersion.getVersionState(); if (versionState.equals(DatasetVersion.VersionState.RELEASED)) { numPublishedVersions += 1; } debug.append("version found with database id " + versionDatabaseId + "\n"); debug.append("- title: " + versionTitle + "\n"); debug.append("- semanticVersion-VersionState: " + semanticVersion + "-" + versionState + "\n"); List<FileMetadata> fileMetadatas = datasetVersion.getFileMetadatas(); List<String> fileInfo = new ArrayList<>(); for (FileMetadata fileMetadata : fileMetadatas) { String solrIdOfPublishedFile = solrDocIdentifierFile + fileMetadata.getDataFile().getId(); /** * It sounds weird but the first thing we'll do is preemptively * delete the Solr documents of all published files. Don't * worry, published files will be re-indexed later along with * the dataset. We do this so users can delete files from * published versions of datasets and then re-publish a new * version without fear that their old published files (now * deleted from the latest published version) will be * searchable. See also * https://github.com/IQSS/dataverse/issues/762 */ solrIdsOfFilesToDelete.add(solrIdOfPublishedFile); fileInfo.add(fileMetadata.getDataFile().getId() + ":" + fileMetadata.getLabel()); } int numFiles = 0; if (fileMetadatas != null) { numFiles = fileMetadatas.size(); } debug.append("- files: " + numFiles + " " + fileInfo.toString() + "\n"); } debug.append("numPublishedVersions: " + numPublishedVersions + "\n"); IndexResponse resultOfAttemptToPremptivelyDeletePublishedFiles = solrIndexService.deleteMultipleSolrIds(solrIdsOfFilesToDelete); debug.append("result of attempt to premptively deleted published files before reindexing: " + resultOfAttemptToPremptivelyDeletePublishedFiles + "\n"); DatasetVersion latestVersion = dataset.getLatestVersion(); String latestVersionStateString = latestVersion.getVersionState().name(); DatasetVersion.VersionState latestVersionState = latestVersion.getVersionState(); DatasetVersion releasedVersion = dataset.getReleasedVersion(); boolean atLeastOnePublishedVersion = false; if (releasedVersion != null) { atLeastOnePublishedVersion = true; } else { atLeastOnePublishedVersion = false; } Map<DatasetVersion.VersionState, Boolean> desiredCards = new LinkedHashMap<>(); /** * @todo refactor all of this below and have a single method that takes * the map of desired cards (which correspond to Solr documents) as one * of the arguments and does all the operations necessary to achieve the * desired state. */ StringBuilder results = new StringBuilder(); if (atLeastOnePublishedVersion == false) { results.append("No published version, nothing will be indexed as ") .append(solrIdPublished).append("\n"); if (latestVersionState.equals(DatasetVersion.VersionState.DRAFT)) { desiredCards.put(DatasetVersion.VersionState.DRAFT, true); IndexableDataset indexableDraftVersion = new IndexableDataset(latestVersion); String indexDraftResult = addOrUpdateDataset(indexableDraftVersion); results.append("The latest version is a working copy (latestVersionState: ") .append(latestVersionStateString).append(") and indexing was attempted for ") .append(solrIdDraftDataset).append(" (limited discoverability). Result: ") .append(indexDraftResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.DEACCESSIONED, false); String deleteDeaccessionedResult = removeDeaccessioned(dataset); results.append("Draft exists, no need for deaccessioned version. Deletion attempted for ") .append(solrIdDeaccessioned).append(" (and files). Result: ") .append(deleteDeaccessionedResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.RELEASED, false); String deletePublishedResults = removePublished(dataset); results.append("No published version. Attempting to delete traces of published version from index. Result: "). append(deletePublishedResults).append("\n"); /** * Desired state for existence of cards: {DRAFT=true, * DEACCESSIONED=false, RELEASED=false} * * No published version, nothing will be indexed as dataset_17 * * The latest version is a working copy (latestVersionState: * DRAFT) and indexing was attempted for dataset_17_draft * (limited discoverability). Result: indexed dataset 17 as * dataset_17_draft. filesIndexed: [datafile_18_draft] * * Draft exists, no need for deaccessioned version. Deletion * attempted for dataset_17_deaccessioned (and files). Result: * Attempted to delete dataset_17_deaccessioned from Solr index. * updateReponse was: * {responseHeader={status=0,QTime=1}}Attempted to delete * datafile_18_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}} * * No published version. Attempting to delete traces of * published version from index. Result: Attempted to delete * dataset_17 from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}}Attempted to delete * datafile_18 from Solr index. updateReponse was: * {responseHeader={status=0,QTime=0}} */ String result = getDesiredCardState(desiredCards) + results.toString() + debug.toString(); logger.info(result); indexDatasetPermissions(dataset); return new AsyncResult<>(result); } else if (latestVersionState.equals(DatasetVersion.VersionState.DEACCESSIONED)) { desiredCards.put(DatasetVersion.VersionState.DEACCESSIONED, true); IndexableDataset indexableDeaccessionedVersion = new IndexableDataset(latestVersion); String indexDeaccessionedVersionResult = addOrUpdateDataset(indexableDeaccessionedVersion); results.append("No draft version. Attempting to index as deaccessioned. Result: ").append(indexDeaccessionedVersionResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.RELEASED, false); String deletePublishedResults = removePublished(dataset); results.append("No published version. Attempting to delete traces of published version from index. Result: "). append(deletePublishedResults).append("\n"); desiredCards.put(DatasetVersion.VersionState.DRAFT, false); List<String> solrDocIdsForDraftFilesToDelete = findSolrDocIdsForDraftFilesToDelete(dataset); String deleteDraftDatasetVersionResult = removeSolrDocFromIndex(solrIdDraftDataset); String deleteDraftFilesResults = deleteDraftFiles(solrDocIdsForDraftFilesToDelete); results.append("Attempting to delete traces of drafts. Result: ") .append(deleteDraftDatasetVersionResult).append(deleteDraftFilesResults).append("\n"); /** * Desired state for existence of cards: {DEACCESSIONED=true, * RELEASED=false, DRAFT=false} * * No published version, nothing will be indexed as dataset_17 * * No draft version. Attempting to index as deaccessioned. * Result: indexed dataset 17 as dataset_17_deaccessioned. * filesIndexed: [] * * No published version. Attempting to delete traces of * published version from index. Result: Attempted to delete * dataset_17 from Solr index. updateReponse was: * {responseHeader={status=0,QTime=0}}Attempted to delete * datafile_18 from Solr index. updateReponse was: * {responseHeader={status=0,QTime=3}} * * Attempting to delete traces of drafts. Result: Attempted to * delete dataset_17_draft from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}} */ String result = getDesiredCardState(desiredCards) + results.toString() + debug.toString(); logger.info(result); indexDatasetPermissions(dataset); return new AsyncResult<>(result); } else { String result = "No-op. Unexpected condition reached: No released version and latest version is neither draft nor deaccessioned"; return new AsyncResult<>(result); } } else if (atLeastOnePublishedVersion == true) { results.append("Published versions found. ") .append("Will attempt to index as ").append(solrIdPublished).append(" (discoverable by anonymous)\n"); if (latestVersionState.equals(DatasetVersion.VersionState.RELEASED) || latestVersionState.equals(DatasetVersion.VersionState.DEACCESSIONED)) { desiredCards.put(DatasetVersion.VersionState.RELEASED, true); IndexableDataset indexableReleasedVersion = new IndexableDataset(releasedVersion); String indexReleasedVersionResult = addOrUpdateDataset(indexableReleasedVersion); results.append("Attempted to index " + solrIdPublished).append(". Result: ").append(indexReleasedVersionResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.DRAFT, false); List<String> solrDocIdsForDraftFilesToDelete = findSolrDocIdsForDraftFilesToDelete(dataset); String deleteDraftDatasetVersionResult = removeSolrDocFromIndex(solrIdDraftDataset); String deleteDraftFilesResults = deleteDraftFiles(solrDocIdsForDraftFilesToDelete); results.append("The latest version is published. Attempting to delete drafts. Result: ") .append(deleteDraftDatasetVersionResult).append(deleteDraftFilesResults).append("\n"); desiredCards.put(DatasetVersion.VersionState.DEACCESSIONED, false); String deleteDeaccessionedResult = removeDeaccessioned(dataset); results.append("No need for deaccessioned version. Deletion attempted for ") .append(solrIdDeaccessioned).append(". Result: ").append(deleteDeaccessionedResult); /** * Desired state for existence of cards: {RELEASED=true, * DRAFT=false, DEACCESSIONED=false} * * Released versions found: 1. Will attempt to index as * dataset_17 (discoverable by anonymous) * * Attempted to index dataset_17. Result: indexed dataset 17 as * dataset_17. filesIndexed: [datafile_18] * * The latest version is published. Attempting to delete drafts. * Result: Attempted to delete dataset_17_draft from Solr index. * updateReponse was: {responseHeader={status=0,QTime=1}} * * No need for deaccessioned version. Deletion attempted for * dataset_17_deaccessioned. Result: Attempted to delete * dataset_17_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}}Attempted to delete * datafile_18_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=0}} */ String result = getDesiredCardState(desiredCards) + results.toString() + debug.toString(); logger.info(result); indexDatasetPermissions(dataset); return new AsyncResult<>(result); } else if (latestVersionState.equals(DatasetVersion.VersionState.DRAFT)) { IndexableDataset indexableDraftVersion = new IndexableDataset(latestVersion); desiredCards.put(DatasetVersion.VersionState.DRAFT, true); String indexDraftResult = addOrUpdateDataset(indexableDraftVersion); results.append("The latest version is a working copy (latestVersionState: ") .append(latestVersionStateString).append(") and will be indexed as ") .append(solrIdDraftDataset).append(" (limited visibility). Result: ").append(indexDraftResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.RELEASED, true); IndexableDataset indexableReleasedVersion = new IndexableDataset(releasedVersion); String indexReleasedVersionResult = addOrUpdateDataset(indexableReleasedVersion); results.append("There is a published version we will attempt to index. Result: ").append(indexReleasedVersionResult).append("\n"); desiredCards.put(DatasetVersion.VersionState.DEACCESSIONED, false); String deleteDeaccessionedResult = removeDeaccessioned(dataset); results.append("No need for deaccessioned version. Deletion attempted for ") .append(solrIdDeaccessioned).append(". Result: ").append(deleteDeaccessionedResult); /** * Desired state for existence of cards: {DRAFT=true, * RELEASED=true, DEACCESSIONED=false} * * Released versions found: 1. Will attempt to index as * dataset_17 (discoverable by anonymous) * * The latest version is a working copy (latestVersionState: * DRAFT) and will be indexed as dataset_17_draft (limited * visibility). Result: indexed dataset 17 as dataset_17_draft. * filesIndexed: [datafile_18_draft] * * There is a published version we will attempt to index. * Result: indexed dataset 17 as dataset_17. filesIndexed: * [datafile_18] * * No need for deaccessioned version. Deletion attempted for * dataset_17_deaccessioned. Result: Attempted to delete * dataset_17_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=1}}Attempted to delete * datafile_18_deaccessioned from Solr index. updateReponse was: * {responseHeader={status=0,QTime=0}} */ String result = getDesiredCardState(desiredCards) + results.toString() + debug.toString(); logger.info(result); indexDatasetPermissions(dataset); return new AsyncResult<>(result); } else { String result = "No-op. Unexpected condition reached: There is at least one published version but the latest version is neither published nor draft"; logger.info(result); return new AsyncResult<>(result); } } else { String result = "No-op. Unexpected condition reached: Has a version been published or not?"; logger.info(result); return new AsyncResult<>(result); } } private String deleteDraftFiles(List<String> solrDocIdsForDraftFilesToDelete) { String deleteDraftFilesResults = ""; IndexResponse indexResponse = solrIndexService.deleteMultipleSolrIds(solrDocIdsForDraftFilesToDelete); deleteDraftFilesResults = indexResponse.toString(); return deleteDraftFilesResults; } private IndexResponse indexDatasetPermissions(Dataset dataset) { IndexResponse indexResponse = solrIndexService.indexPermissionsOnSelfAndChildren(dataset); return indexResponse; } private String addOrUpdateDataset(IndexableDataset indexableDataset) { IndexableDataset.DatasetState state = indexableDataset.getDatasetState(); Dataset dataset = indexableDataset.getDatasetVersion().getDataset(); logger.info("adding or updating Solr document for dataset id " + dataset.getId()); Collection<SolrInputDocument> docs = new ArrayList<>(); List<String> dataversePathSegmentsAccumulator = new ArrayList<>(); List<String> dataverseSegments = new ArrayList<>(); try { dataverseSegments = findPathSegments(dataset.getOwner(), dataversePathSegmentsAccumulator); } catch (Exception ex) { logger.info("failed to find dataverseSegments for dataversePaths for " + SearchFields.SUBTREE + ": " + ex); } List<String> dataversePaths = getDataversePathsFromSegments(dataverseSegments); //Add Paths for linking dataverses for (Dataverse linkingDataverse : dsLinkingService.findLinkingDataverses(dataset.getId())) { List<String> linkingDataversePathSegmentsAccumulator = new ArrayList<>(); List<String> linkingdataverseSegments = findPathSegments(linkingDataverse, linkingDataversePathSegmentsAccumulator); List<String> linkingDataversePaths = getDataversePathsFromSegments(linkingdataverseSegments); for (String dvPath : linkingDataversePaths) { dataversePaths.add(dvPath); } } SolrInputDocument solrInputDocument = new SolrInputDocument(); String datasetSolrDocId = indexableDataset.getSolrDocId(); solrInputDocument.addField(SearchFields.ID, datasetSolrDocId); solrInputDocument.addField(SearchFields.ENTITY_ID, dataset.getId()); solrInputDocument.addField(SearchFields.IDENTIFIER, dataset.getGlobalId()); solrInputDocument.addField(SearchFields.PERSISTENT_URL, dataset.getPersistentURL()); solrInputDocument.addField(SearchFields.TYPE, "datasets"); Date datasetSortByDate = new Date(); Date majorVersionReleaseDate = dataset.getMostRecentMajorVersionReleaseDate(); if (majorVersionReleaseDate != null) { if (true) { String msg = "major release date found: " + majorVersionReleaseDate.toString(); logger.fine(msg); } datasetSortByDate = majorVersionReleaseDate; } else { if (indexableDataset.getDatasetState().equals(IndexableDataset.DatasetState.WORKING_COPY)) { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, UNPUBLISHED_STRING); } else if (indexableDataset.getDatasetState().equals(IndexableDataset.DatasetState.DEACCESSIONED)) { // uncomment this if we change our mind and want a deaccessioned facet after all // solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, DEACCESSIONED_STRING); } Date createDate = dataset.getCreateDate(); if (createDate != null) { if (true) { String msg = "can't find major release date, using create date: " + createDate; logger.info(msg); } datasetSortByDate = createDate; } else { String msg = "can't find major release date or create date, using \"now\""; logger.info(msg); datasetSortByDate = new Date(); } } solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, datasetSortByDate); solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT, convertToFriendlyDate(datasetSortByDate)); if (state.equals(indexableDataset.getDatasetState().PUBLISHED)) { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, PUBLISHED_STRING); // solrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, dataset.getPublicationDate()); } else if (state.equals(indexableDataset.getDatasetState().WORKING_COPY)) { solrInputDocument.addField(SearchFields.PUBLICATION_STATUS, DRAFT_STRING); } addDatasetReleaseDateToSolrDoc(solrInputDocument, dataset); DatasetVersion datasetVersion = indexableDataset.getDatasetVersion(); String parentDatasetTitle = "TBD"; if (datasetVersion != null) { solrInputDocument.addField(SearchFields.DATASET_VERSION_ID, datasetVersion.getId()); System.out.print(datasetVersion.getCitation(true)); solrInputDocument.addField(SearchFields.DATASET_CITATION, datasetVersion.getCitation(true)); for (DatasetField dsf : datasetVersion.getFlatDatasetFields()) { DatasetFieldType dsfType = dsf.getDatasetFieldType(); String solrFieldSearchable = dsfType.getSolrField().getNameSearchable(); String solrFieldFacetable = dsfType.getSolrField().getNameFacetable(); if (dsf.getValues() != null && !dsf.getValues().isEmpty() && dsf.getValues().get(0) != null && solrFieldSearchable != null) { logger.fine("indexing " + dsf.getDatasetFieldType().getName() + ":" + dsf.getValues() + " into " + solrFieldSearchable + " and maybe " + solrFieldFacetable); // if (dsfType.getSolrField().getSolrType().equals(SolrField.SolrType.INTEGER)) { if (dsfType.getSolrField().getSolrType().equals(SolrField.SolrType.EMAIL)) { //no-op. we want to keep email address out of Solr per https://github.com/IQSS/dataverse/issues/759 } else if (dsfType.getSolrField().getSolrType().equals(SolrField.SolrType.DATE)) { String dateAsString = dsf.getValues().get(0); logger.fine("date as string: " + dateAsString); if (dateAsString != null && !dateAsString.isEmpty()) { SimpleDateFormat inputDateyyyy = new SimpleDateFormat("yyyy", Locale.ENGLISH); try { /** * @todo when bean validation is working we * won't have to convert strings into dates */ logger.fine("Trying to convert " + dateAsString + " to a YYYY date from dataset " + dataset.getId()); Date dateAsDate = inputDateyyyy.parse(dateAsString); SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy"); String datasetFieldFlaggedAsDate = yearOnly.format(dateAsDate); logger.fine("YYYY only: " + datasetFieldFlaggedAsDate); // solrInputDocument.addField(solrFieldSearchable, Integer.parseInt(datasetFieldFlaggedAsDate)); solrInputDocument.addField(solrFieldSearchable, datasetFieldFlaggedAsDate); if (dsfType.getSolrField().isFacetable()) { // solrInputDocument.addField(solrFieldFacetable, Integer.parseInt(datasetFieldFlaggedAsDate)); solrInputDocument.addField(solrFieldFacetable, datasetFieldFlaggedAsDate); } } catch (Exception ex) { logger.info("unable to convert " + dateAsString + " into YYYY format and couldn't index it (" + dsfType.getName() + ")"); } } } else { // _s (dynamic string) and all other Solr fields if (dsf.getDatasetFieldType().getName().equals("authorAffiliation")) { /** * @todo think about how to tie the fact that this * needs to be multivalued (_ss) because a * multivalued facet (authorAffilition_ss) is being * collapsed into here at index time. The business * logic to determine if a data-driven metadata * field should be indexed into Solr as a single or * multiple value lives in the getSolrField() method * of DatasetField.java */ solrInputDocument.addField(SearchFields.AFFILIATION, dsf.getValues()); } else if (dsf.getDatasetFieldType().getName().equals("title")) { // datasets have titles not names but index title under name as well so we can sort datasets by name along dataverses and files List<String> possibleTitles = dsf.getValues(); String firstTitle = possibleTitles.get(0); if (firstTitle != null) { parentDatasetTitle = firstTitle; } solrInputDocument.addField(SearchFields.NAME_SORT, dsf.getValues()); } if (dsfType.isControlledVocabulary()) { for (ControlledVocabularyValue controlledVocabularyValue : dsf.getControlledVocabularyValues()) { solrInputDocument.addField(solrFieldSearchable, controlledVocabularyValue.getStrValue()); if (dsfType.getSolrField().isFacetable()) { solrInputDocument.addField(solrFieldFacetable, controlledVocabularyValue.getStrValue()); } } } else { if (dsfType.getFieldType().equals(DatasetFieldType.FieldType.TEXTBOX)) { // strip HTML List<String> htmlFreeText = StringUtil.htmlArray2textArray(dsf.getValues()); solrInputDocument.addField(solrFieldSearchable, htmlFreeText); if (dsfType.getSolrField().isFacetable()) { solrInputDocument.addField(solrFieldFacetable, htmlFreeText); } } else { // do not strip HTML solrInputDocument.addField(solrFieldSearchable, dsf.getValues()); if (dsfType.getSolrField().isFacetable()) { solrInputDocument.addField(solrFieldFacetable, dsf.getValues()); } } } } } } } solrInputDocument.addField(SearchFields.SUBTREE, dataversePaths); // solrInputDocument.addField(SearchFields.HOST_DATAVERSE, dataset.getOwner().getName()); solrInputDocument.addField(SearchFields.PARENT_ID, dataset.getOwner().getId()); solrInputDocument.addField(SearchFields.PARENT_NAME, dataset.getOwner().getName()); docs.add(solrInputDocument); List<String> filesIndexed = new ArrayList<>(); if (datasetVersion != null) { List<FileMetadata> fileMetadatas = datasetVersion.getFileMetadatas(); boolean checkForDuplicateMetadata = false; if (datasetVersion.isDraft() && dataset.isReleased()) { checkForDuplicateMetadata = true; logger.fine("We are indexing a draft version of a dataset that has a released version. We'll be checking file metadatas if they are exact clones of the released versions."); } for (FileMetadata fileMetadata : fileMetadatas) { boolean indexThisMetadata = true; if (checkForDuplicateMetadata) { logger.fine("Checking if this file metadata is a duplicate."); for (FileMetadata releasedFileMetadata : dataset.getReleasedVersion().getFileMetadatas()) { if (fileMetadata.getDataFile() != null && fileMetadata.getDataFile().equals(releasedFileMetadata.getDataFile())) { if (fileMetadata.contentEquals(releasedFileMetadata)) { indexThisMetadata = false; logger.fine("This file metadata hasn't changed since the released version; skipping indexing."); } else { logger.fine("This file metadata has changed since the released version; we want to index it!"); } break; } } } if (indexThisMetadata) { SolrInputDocument datafileSolrInputDocument = new SolrInputDocument(); Long fileEntityId = fileMetadata.getDataFile().getId(); datafileSolrInputDocument.addField(SearchFields.ENTITY_ID, fileEntityId); datafileSolrInputDocument.addField(SearchFields.IDENTIFIER, fileEntityId); datafileSolrInputDocument.addField(SearchFields.PERSISTENT_URL, dataset.getPersistentURL()); datafileSolrInputDocument.addField(SearchFields.TYPE, "files"); String filenameCompleteFinal = ""; if (fileMetadata != null) { String filenameComplete = fileMetadata.getLabel(); if (filenameComplete != null) { String filenameWithoutExtension = ""; // String extension = ""; int i = filenameComplete.lastIndexOf('.'); if (i > 0) { // extension = filenameComplete.substring(i + 1); try { filenameWithoutExtension = filenameComplete.substring(0, i); datafileSolrInputDocument.addField(SearchFields.FILENAME_WITHOUT_EXTENSION, filenameWithoutExtension); datafileSolrInputDocument.addField(SearchFields.FILE_NAME, filenameWithoutExtension); } catch (IndexOutOfBoundsException ex) { filenameWithoutExtension = ""; } } else { logger.info("problem with filename '" + filenameComplete + "': no extension? empty string as filename?"); filenameWithoutExtension = filenameComplete; } filenameCompleteFinal = filenameComplete; } } datafileSolrInputDocument.addField(SearchFields.NAME, filenameCompleteFinal); datafileSolrInputDocument.addField(SearchFields.NAME_SORT, filenameCompleteFinal); datafileSolrInputDocument.addField(SearchFields.FILE_NAME, filenameCompleteFinal); datafileSolrInputDocument.addField(SearchFields.DATASET_VERSION_ID, datasetVersion.getId()); /** * for rules on sorting files see * https://docs.google.com/a/harvard.edu/document/d/1DWsEqT8KfheKZmMB3n_VhJpl9nIxiUjai_AIQPAjiyA/edit?usp=sharing * via https://redmine.hmdc.harvard.edu/issues/3701 */ Date fileSortByDate = new Date(); DataFile datafile = fileMetadata.getDataFile(); if (datafile != null) { boolean fileHasBeenReleased = datafile.isReleased(); if (fileHasBeenReleased) { logger.info("indexing file with filePublicationTimestamp. " + fileMetadata.getId() + " (file id " + datafile.getId() + ")"); Timestamp filePublicationTimestamp = datafile.getPublicationDate(); if (filePublicationTimestamp != null) { fileSortByDate = filePublicationTimestamp; } else { String msg = "filePublicationTimestamp was null for fileMetadata id " + fileMetadata.getId() + " (file id " + datafile.getId() + ")"; logger.info(msg); } } else { logger.info("indexing file with fileCreateTimestamp. " + fileMetadata.getId() + " (file id " + datafile.getId() + ")"); Timestamp fileCreateTimestamp = datafile.getCreateDate(); if (fileCreateTimestamp != null) { fileSortByDate = fileCreateTimestamp; } else { String msg = "fileCreateTimestamp was null for fileMetadata id " + fileMetadata.getId() + " (file id " + datafile.getId() + ")"; logger.info(msg); } } } if (fileSortByDate == null) { if (datasetSortByDate != null) { logger.info("fileSortByDate was null, assigning datasetSortByDate"); fileSortByDate = datasetSortByDate; } else { logger.info("fileSortByDate and datasetSortByDate were null, assigning 'now'"); fileSortByDate = new Date(); } } datafileSolrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE, fileSortByDate); datafileSolrInputDocument.addField(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT, convertToFriendlyDate(fileSortByDate)); if (majorVersionReleaseDate == null) { datafileSolrInputDocument.addField(SearchFields.PUBLICATION_STATUS, UNPUBLISHED_STRING); } String fileSolrDocId = solrDocIdentifierFile + fileEntityId; if (indexableDataset.getDatasetState().equals(indexableDataset.getDatasetState().PUBLISHED)) { fileSolrDocId = solrDocIdentifierFile + fileEntityId; datafileSolrInputDocument.addField(SearchFields.PUBLICATION_STATUS, PUBLISHED_STRING); // datafileSolrInputDocument.addField(SearchFields.PERMS, publicGroupString); addDatasetReleaseDateToSolrDoc(datafileSolrInputDocument, dataset); } else if (indexableDataset.getDatasetState().equals(indexableDataset.getDatasetState().WORKING_COPY)) { fileSolrDocId = solrDocIdentifierFile + fileEntityId + indexableDataset.getDatasetState().getSuffix(); datafileSolrInputDocument.addField(SearchFields.PUBLICATION_STATUS, DRAFT_STRING); } datafileSolrInputDocument.addField(SearchFields.ID, fileSolrDocId); // For the mime type, we are going to index the "friendly" version, e.g., // "PDF File" instead of "application/pdf", "MS Excel" instead of // "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" (!), etc., // if available: datafileSolrInputDocument.addField(SearchFields.FILE_TYPE_MIME, fileMetadata.getDataFile().getFriendlyType()); datafileSolrInputDocument.addField(SearchFields.FILE_TYPE_SEARCHABLE, fileMetadata.getDataFile().getFriendlyType()); // For the file type facets, we have a property file that maps mime types // to facet-friendly names; "application/fits" should become "FITS", etc.: datafileSolrInputDocument.addField(SearchFields.FILE_TYPE, FileUtil.getFacetFileType(fileMetadata.getDataFile())); datafileSolrInputDocument.addField(SearchFields.FILE_TYPE_SEARCHABLE, FileUtil.getFacetFileType(fileMetadata.getDataFile())); datafileSolrInputDocument.addField(SearchFields.FILE_SIZE_IN_BYTES, fileMetadata.getDataFile().getFilesize()); datafileSolrInputDocument.addField(SearchFields.FILE_MD5, fileMetadata.getDataFile().getmd5()); datafileSolrInputDocument.addField(SearchFields.DESCRIPTION, fileMetadata.getDescription()); datafileSolrInputDocument.addField(SearchFields.FILE_DESCRIPTION, fileMetadata.getDescription()); datafileSolrInputDocument.addField(SearchFields.UNF, fileMetadata.getDataFile().getUnf()); datafileSolrInputDocument.addField(SearchFields.SUBTREE, dataversePaths); // datafileSolrInputDocument.addField(SearchFields.HOST_DATAVERSE, dataFile.getOwner().getOwner().getName()); // datafileSolrInputDocument.addField(SearchFields.PARENT_NAME, dataFile.getDataset().getTitle()); datafileSolrInputDocument.addField(SearchFields.PARENT_ID, fileMetadata.getDataFile().getOwner().getId()); datafileSolrInputDocument.addField(SearchFields.PARENT_IDENTIFIER, fileMetadata.getDataFile().getOwner().getGlobalId()); datafileSolrInputDocument.addField(SearchFields.PARENT_CITATION, fileMetadata.getDataFile().getOwner().getCitation()); datafileSolrInputDocument.addField(SearchFields.PARENT_NAME, parentDatasetTitle); // If this is a tabular data file -- i.e., if there are data // variables associated with this file, we index the variable // names and labels: if (fileMetadata.getDataFile().isTabularData()) { List<DataVariable> variables = fileMetadata.getDataFile().getDataTable().getDataVariables(); for (DataVariable var : variables) { // Hard-coded search fields, for now: // TODO: eventually: review, decide how datavariables should // be handled for indexing purposes. (should it be a fixed // setup, defined in the code? should it be flexible? unlikely // that this needs to be domain-specific... since these data // variables are quite specific to tabular data, which in turn // is something social science-specific... // anyway -- needs to be reviewed. -- L.A. 4.0alpha1 if (var.getName() != null && !var.getName().equals("")) { datafileSolrInputDocument.addField(SearchFields.VARIABLE_NAME, var.getName()); } if (var.getLabel() != null && !var.getLabel().equals("")) { datafileSolrInputDocument.addField(SearchFields.VARIABLE_LABEL, var.getLabel()); } } } if (indexableDataset.isFilesShouldBeIndexed()) { filesIndexed.add(fileSolrDocId); docs.add(datafileSolrInputDocument); } } } } SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); try { server.add(docs); } catch (SolrServerException | IOException ex) { return ex.toString(); } try { server.commit(); } catch (SolrServerException | IOException ex) { return ex.toString(); } dvObjectService.updateContentIndexTime(dataset); // return "indexed dataset " + dataset.getId() + " as " + solrDocId + "\nindexFilesResults for " + solrDocId + ":" + fileInfo.toString(); return "indexed dataset " + dataset.getId() + " as " + datasetSolrDocId + ". filesIndexed: " + filesIndexed; } public List<String> findPathSegments(Dataverse dataverse, List<String> segments) { Dataverse rootDataverse = findRootDataverseCached(); if (!dataverse.equals(rootDataverse)) { // important when creating root dataverse if (dataverse.getOwner() != null) { findPathSegments(dataverse.getOwner(), segments); } segments.add(dataverse.getId().toString()); return segments; } else { // base case return segments; } } List<String> getDataversePathsFromSegments(List<String> dataversePathSegments) { List<String> subtrees = new ArrayList<>(); for (int i = 0; i < dataversePathSegments.size(); i++) { StringBuilder pathBuilder = new StringBuilder(); int numSegments = dataversePathSegments.size(); for (int j = 0; j < numSegments; j++) { if (j <= i) { pathBuilder.append("/" + dataversePathSegments.get(j)); } } subtrees.add(pathBuilder.toString()); } return subtrees; } private void addDataverseReleaseDateToSolrDoc(SolrInputDocument solrInputDocument, Dataverse dataverse) { if (dataverse.getPublicationDate() != null) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(dataverse.getPublicationDate().getTime()); int YYYY = calendar.get(Calendar.YEAR); solrInputDocument.addField(SearchFields.PUBLICATION_DATE, YYYY); } } private void addDatasetReleaseDateToSolrDoc(SolrInputDocument solrInputDocument, Dataset dataset) { if (dataset.getPublicationDate() != null) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(dataset.getPublicationDate().getTime()); int YYYY = calendar.get(Calendar.YEAR); solrInputDocument.addField(SearchFields.PUBLICATION_DATE, YYYY); solrInputDocument.addField(SearchFields.DATASET_PUBLICATION_DATE, YYYY); } } public static String getGroupPrefix() { return groupPrefix; } public static String getGroupPerUserPrefix() { return groupPerUserPrefix; } public static String getPublicGroupString() { return publicGroupString; } public static String getPUBLISHED_STRING() { return PUBLISHED_STRING; } public static String getUNPUBLISHED_STRING() { return UNPUBLISHED_STRING; } public static String getDRAFT_STRING() { return DRAFT_STRING; } public static String getDEACCESSIONED_STRING() { return DEACCESSIONED_STRING; } public String delete(Dataverse doomed) { SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); logger.info("deleting Solr document for dataverse " + doomed.getId()); UpdateResponse updateResponse; try { updateResponse = server.deleteById(solrDocIdentifierDataverse + doomed.getId()); } catch (SolrServerException | IOException ex) { return ex.toString(); } try { server.commit(); } catch (SolrServerException | IOException ex) { return ex.toString(); } String response = "Successfully deleted dataverse " + doomed.getId() + " from Solr index. updateReponse was: " + updateResponse.toString(); logger.info(response); return response; } /** * @todo call this in fewer places, favoring * SolrIndexServiceBeans.deleteMultipleSolrIds instead to operate in batches * * https://github.com/IQSS/dataverse/issues/142 */ public String removeSolrDocFromIndex(String doomed) { SolrServer server = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); logger.info("deleting Solr document: " + doomed); UpdateResponse updateResponse; try { updateResponse = server.deleteById(doomed); } catch (SolrServerException | IOException ex) { return ex.toString(); } try { server.commit(); } catch (SolrServerException | IOException ex) { return ex.toString(); } String response = "Attempted to delete " + doomed + " from Solr index. updateReponse was: " + updateResponse.toString(); logger.info(response); return response; } public String convertToFriendlyDate(Date dateAsDate) { if (dateAsDate == null) { dateAsDate = new Date(); } // using DateFormat.MEDIUM for May 5, 2014 to match what's in DVN 3.x DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); String friendlyDate = format.format(dateAsDate); return friendlyDate; } private List<String> findSolrDocIdsForDraftFilesToDelete(Dataset datasetWithDraftFilesToDelete) { Long datasetId = datasetWithDraftFilesToDelete.getId(); SolrServer solrServer = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); SolrQuery solrQuery = new SolrQuery(); solrQuery.setRows(Integer.MAX_VALUE); solrQuery.setQuery(SearchFields.PARENT_ID + ":" + datasetId); solrQuery.addFilterQuery(SearchFields.ID + ":" + "*" + draftSuffix); List<String> solrIdsOfFilesToDelete = new ArrayList<>(); try { // i.e. rows=2147483647&q=parentid%3A16&fq=id%3A*_draft logger.info("passing this Solr query to find draft files to delete: " + solrQuery); QueryResponse queryResponse = solrServer.query(solrQuery); SolrDocumentList results = queryResponse.getResults(); for (SolrDocument solrDocument : results) { String id = (String) solrDocument.getFieldValue(SearchFields.ID); if (id != null) { solrIdsOfFilesToDelete.add(id); } } } catch (SolrServerException ex) { logger.info("error in findSolrDocIdsForDraftFilesToDelete method: " + ex.toString()); } return solrIdsOfFilesToDelete; } private List<String> findSolrDocIdsForFilesToDelete(Dataset dataset, IndexableDataset.DatasetState state) { List<String> solrIdsOfFilesToDelete = new ArrayList<>(); for (DataFile file : dataset.getFiles()) { solrIdsOfFilesToDelete.add(solrDocIdentifierFile + file.getId() + state.getSuffix()); } return solrIdsOfFilesToDelete; } private String removeMultipleSolrDocs(List<String> docIds) { IndexResponse indexResponse = solrIndexService.deleteMultipleSolrIds(docIds); return indexResponse.toString(); } private String determinePublishedDatasetSolrDocId(Dataset dataset) { return IndexableObject.IndexableTypes.DATASET.getName() + "_" + dataset.getId() + IndexableDataset.DatasetState.PUBLISHED.getSuffix(); } private String determineDeaccessionedDatasetId(Dataset dataset) { return IndexableObject.IndexableTypes.DATASET.getName() + "_" + dataset.getId() + IndexableDataset.DatasetState.DEACCESSIONED.getSuffix(); } private String removeDeaccessioned(Dataset dataset) { StringBuilder result = new StringBuilder(); String deleteDeaccessionedResult = removeSolrDocFromIndex(determineDeaccessionedDatasetId(dataset)); result.append(deleteDeaccessionedResult); List<String> docIds = findSolrDocIdsForFilesToDelete(dataset, IndexableDataset.DatasetState.DEACCESSIONED); String deleteFilesResult = removeMultipleSolrDocs(docIds); result.append(deleteFilesResult); return result.toString(); } private String removePublished(Dataset dataset) { StringBuilder result = new StringBuilder(); String deletePublishedResult = removeSolrDocFromIndex(determinePublishedDatasetSolrDocId(dataset)); result.append(deletePublishedResult); List<String> docIds = findSolrDocIdsForFilesToDelete(dataset, IndexableDataset.DatasetState.PUBLISHED); String deleteFilesResult = removeMultipleSolrDocs(docIds); result.append(deleteFilesResult); return result.toString(); } private Dataverse findRootDataverseCached() { if (true) { /** * @todo Is the code below working at all? We don't want the root * dataverse to be indexed into Solr. Specifically, we don't want a * dataverse "card" to show up while browsing. * * Let's just find the root dataverse and be done with it. We'll * figure out the caching later. */ return dataverseService.findRootDataverse(); } /** * @todo Why isn't this code working? */ if (rootDataverseCached != null) { return rootDataverseCached; } else { rootDataverseCached = dataverseService.findRootDataverse(); if (rootDataverseCached != null) { return rootDataverseCached; } else { throw new RuntimeException("unable to determine root dataverse"); } } } private String getDesiredCardState(Map<DatasetVersion.VersionState, Boolean> desiredCards) { /** * @todo make a JVM option to enforce sanity checks? Call it dev=true? */ boolean sanityCheck = true; if (sanityCheck) { Set<DatasetVersion.VersionState> expected = new HashSet<>(); expected.add(DatasetVersion.VersionState.DRAFT); expected.add(DatasetVersion.VersionState.RELEASED); expected.add(DatasetVersion.VersionState.DEACCESSIONED); if (!desiredCards.keySet().equals(expected)) { throw new RuntimeException("Mismatch between expected version states (" + expected + ") and version states passed in (" + desiredCards.keySet() + ")"); } } return "Desired state for existence of cards: " + desiredCards + "\n"; } /** * @return Dataverses that should be reindexed either because they have * never been indexed or their index time is before their modification time. */ public List findStaleOrMissingDataverses() { List<Dataverse> staleDataverses = new ArrayList<>(); for (Dataverse dataverse : dataverseService.findAll()) { if (dataverse.equals(dataverseService.findRootDataverse())) { continue; } if (stale(dataverse)) { staleDataverses.add(dataverse); } } return staleDataverses; } /** * @return Datasets that should be reindexed either because they have never * been indexed or their index time is before their modification time. */ public List findStaleOrMissingDatasets() { List<Dataset> staleDatasets = new ArrayList<>(); for (Dataset dataset : datasetService.findAll()) { if (stale(dataset)) { staleDatasets.add(dataset); } } return staleDatasets; } private boolean stale(DvObject dvObject) { Timestamp indexTime = dvObject.getIndexTime(); Timestamp modificationTime = dvObject.getModificationTime(); if (indexTime == null) { return true; } else { if (indexTime.before(modificationTime)) { return true; } } return false; } public List<Long> findDataversesInSolrOnly() throws SearchException { try { /** * @todo define this centrally and statically */ return findDvObjectInSolrOnly("dataverses"); } catch (SearchException ex) { throw ex; } } public List<Long> findDatasetsInSolrOnly() throws SearchException { try { /** * @todo define this centrally and statically */ return findDvObjectInSolrOnly("datasets"); } catch (SearchException ex) { throw ex; } } private List<Long> findDvObjectInSolrOnly(String type) throws SearchException { SolrServer solrServer = new HttpSolrServer("http://" + systemConfig.getSolrHostColonPort() + "/solr"); SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*"); solrQuery.setRows(Integer.SIZE); solrQuery.addFilterQuery(SearchFields.TYPE + ":" + type); List<Long> dvObjectInSolrOnly = new ArrayList<>(); QueryResponse queryResponse = null; try { queryResponse = solrServer.query(solrQuery); } catch (SolrServerException ex) { throw new SearchException("Error searching Solr for " + type, ex); } SolrDocumentList results = queryResponse.getResults(); for (SolrDocument solrDocument : results) { Object idObject = solrDocument.getFieldValue(SearchFields.ENTITY_ID); if (idObject != null) { try { long id = (Long) idObject; DvObject dvobject = dvObjectService.findDvObject(id); if (dvobject == null) { dvObjectInSolrOnly.add(id); } } catch (ClassCastException ex) { throw new SearchException("Found " + SearchFields.ENTITY_ID + " but error casting " + idObject + " to long", ex); } } } return dvObjectInSolrOnly; } }
show milliseconds spent doing indexAll #50
src/main/java/edu/harvard/iq/dataverse/IndexServiceBean.java
show milliseconds spent doing indexAll #50
Java
apache-2.0
a1514c5cd6342571464ad686d14474101c97960d
0
sbt/ivy,apache/ant-ivy,twogee/ant-ivy,jaikiran/ant-ivy,sbt/ivy,apache/ant-ivy,apache/ant-ivy,jaikiran/ant-ivy,apache/ant-ivy,twogee/ant-ivy,twogee/ant-ivy,twogee/ant-ivy,jaikiran/ant-ivy,jaikiran/ant-ivy
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.core; import java.io.File; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import org.apache.ivy.Ivy; import org.apache.ivy.core.cache.CacheManager; import org.apache.ivy.core.event.EventManager; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.plugins.circular.CircularDependencyStrategy; import org.apache.ivy.plugins.resolver.DependencyResolver; import org.apache.ivy.util.MessageImpl; /** * This class represents an execution context of an Ivy action. * It contains several getters to retrieve information, like the used Ivy instance, the * cache location... * * @see IvyThread * * @author Xavier Hanin * @author Maarten Coene */ public class IvyContext { private static ThreadLocal _current = new ThreadLocal(); private Ivy _defaultIvy; private WeakReference _ivy = new WeakReference(null); private File _cache; private MessageImpl _messageImpl; private Stack _resolver = new Stack(); // Stack(DependencyResolver) private Map _contextMap = new HashMap(); private Thread _operatingThread; public static IvyContext getContext() { IvyContext cur = (IvyContext)_current.get(); if (cur == null) { cur = new IvyContext(); _current.set(cur); } return cur; } /** * Changes the context associated with this thread. * This is especially useful when launching a new thread, to associate it with the same context as the initial one. * * @param context the new context to use in this thread. */ public static void setContext(IvyContext context) { _current.set(context); } /** * Returns the current ivy instance. * When calling any public ivy method on an ivy instance, a reference to this instance is * put in this context, and thus accessible using this method, until no code reference * this instance and the garbage collector collects it. * Then, or if no ivy method has been called, a default ivy instance is returned * by this method, so that it never returns null. * @return the current ivy instance */ public Ivy getIvy() { Ivy ivy = (Ivy)_ivy.get(); return ivy == null ? getDefaultIvy() : ivy; } private Ivy getDefaultIvy() { if (_defaultIvy == null) { _defaultIvy = Ivy.newInstance(); try { _defaultIvy.configureDefault(); } catch (Exception e) { } } return _defaultIvy; } public void setIvy(Ivy ivy) { _ivy = new WeakReference(ivy); _operatingThread = Thread.currentThread(); } public File getCache() { return _cache == null ? getSettings().getDefaultCache() : _cache; } public void setCache(File cache) { _cache = cache; } public IvySettings getSettings() { return getIvy().getSettings(); } public CircularDependencyStrategy getCircularDependencyStrategy() { return getSettings().getCircularDependencyStrategy(); } public Object get(String key) { WeakReference ref = (WeakReference) _contextMap.get(key); return ref == null ? null : ref.get(); } public void set(String key, Object value) { _contextMap.put(key, new WeakReference(value)); } /** * Reads the first object from the list saved under given key in the context. * If value under key represents non List object then a RuntimeException is thrown. * @param key context key for the string * @return top object from the list (index 0) or null if no key or list empty */ public Object peek(String key){ synchronized(_contextMap){ Object o=_contextMap.get(key); if(o==null) return null; if(o instanceof List){ if(((List)o).size()==0) return null; Object ret=((List)o).get(0); return ret; } else { throw new RuntimeException("Cannot top from non List object "+o); } } } /** * Removes and returns first object from the list saved under given key in the context. * If value under key represents non List object then a RuntimeException is thrown. * @param key context key for the string * @return top object from the list (index 0) or null if no key or list empty */ public Object pop(String key){ synchronized(_contextMap){ Object o=_contextMap.get(key); if(o==null) return null; if(o instanceof List){ if(((List)o).size()==0) return null; Object ret=((List)o).remove(0); return ret; } else { throw new RuntimeException("Cannot pop from non List object "+o); } } } /** * Removes and returns first object from the list saved under given key in the context * but only if it equals the given expectedValue - if not a false value is returned. * If value under key represents non List object then a RuntimeException is thrown. * @param key context key for the string * @return true if the r */ public boolean pop(String key, Object expectedValue){ synchronized(_contextMap){ Object o=_contextMap.get(key); if(o==null) return false; if(o instanceof List){ if(((List)o).size()==0) return false; Object top=((List)o).get(0); if(!top.equals(expectedValue)) return false; ((List)o).remove(0); return true; } else { throw new RuntimeException("Cannot pop from non List object "+o); } } } /** * Puts a new object at the start of the list saved under given key in the context. * If value under key represents non List object then a RuntimeException is thrown. * If no list exists under given key a new LinkedList is created. This is kept * without WeakReference in opposite to the put() results. * @param key key context key for the string * @param value value to be saved under the key */ public void push(String key, Object value){ synchronized(_contextMap){ if(!_contextMap.containsKey(key)) _contextMap.put(key, new LinkedList()); Object o=_contextMap.get(key); if(o instanceof List){ ((List)o).add(0,value); } else { throw new RuntimeException("Cannot push to non List object "+o); } } } public Thread getOperatingThread() { return _operatingThread; } /* NB : The messageImpl is only used by Message. It should be better to place it there. * Alternatively, the Message itself could be placed here, bu this is has a major impact * because Message is used at a lot of place. */ public MessageImpl getMessageImpl() { return _messageImpl; } public void setMessageImpl(MessageImpl impl) { _messageImpl = impl; } public EventManager getEventManager() { return getIvy().getEventManager(); } public CacheManager getCacheManager() { return CacheManager.getInstance(getSettings(), getCache()); } public void checkInterrupted() { getIvy().checkInterrupted(); } public DependencyResolver getResolver() { return (DependencyResolver) _resolver.peek(); } public void pushResolver(DependencyResolver resolver) { _resolver.push(resolver); } public void popResolver() { _resolver.pop(); } // should be better to use context to store this kind of information, but not yet ready to do so... // private WeakReference _root = new WeakReference(null); // private String _rootModuleConf = null; // public IvyNode getRoot() { // return (IvyNode) _root.get(); // } // // public void setRoot(IvyNode root) { // _root = new WeakReference(root); // } // // public String getRootModuleConf() { // return _rootModuleConf; // } // // public void setRootModuleConf(String rootModuleConf) { // _rootModuleConf = rootModuleConf; // } }
src/java/org/apache/ivy/core/IvyContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.core; import java.io.File; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import org.apache.ivy.Ivy; import org.apache.ivy.core.cache.CacheManager; import org.apache.ivy.core.event.EventManager; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.plugins.circular.CircularDependencyStrategy; import org.apache.ivy.plugins.resolver.DependencyResolver; import org.apache.ivy.util.MessageImpl; /** * This class represents an execution context of an Ivy action. * It contains several getters to retrieve information, like the used Ivy instance, the * cache location... * * @see IvyThread * * @author Xavier Hanin * @author Maarten Coene */ public class IvyContext { private static ThreadLocal _current = new ThreadLocal(); private Ivy _defaultIvy; private WeakReference _ivy = new WeakReference(null); private File _cache; private MessageImpl _messageImpl; private Stack _resolver = new Stack(); // Stack(DependencyResolver) private Map _contextMap = new HashMap(); private Thread _operatingThread; public static IvyContext getContext() { IvyContext cur = (IvyContext)_current.get(); if (cur == null) { cur = new IvyContext(); _current.set(cur); } return cur; } /** * Changes the context associated with this thread. * This is especially useful when launching a new thread, to associate it with the same context as the initial one. * * @param context the new context to use in this thread. */ public static void setContext(IvyContext context) { _current.set(context); } /** * Returns the current ivy instance. * When calling any public ivy method on an ivy instance, a reference to this instance is * put in this context, and thus accessible using this method, until no code reference * this instance and the garbage collector collects it. * Then, or if no ivy method has been called, a default ivy instance is returned * by this method, so that it never returns null. * @return the current ivy instance */ public Ivy getIvy() { Ivy ivy = (Ivy)_ivy.get(); return ivy == null ? getDefaultIvy() : ivy; } private Ivy getDefaultIvy() { if (_defaultIvy == null) { _defaultIvy = Ivy.newInstance(); try { _defaultIvy.configureDefault(); } catch (Exception e) { } } return _defaultIvy; } public void setIvy(Ivy ivy) { _ivy = new WeakReference(ivy); _operatingThread = Thread.currentThread(); } public File getCache() { return _cache == null ? getSettings().getDefaultCache() : _cache; } public void setCache(File cache) { _cache = cache; } public IvySettings getSettings() { return getIvy().getSettings(); } public CircularDependencyStrategy getCircularDependencyStrategy() { return getSettings().getCircularDependencyStrategy(); } public Object get(String key) { WeakReference ref = (WeakReference) _contextMap.get(key); return ref == null ? null : ref.get(); } public void set(String key, Object value) { _contextMap.put(key, new WeakReference(value)); } /** * Reads the first object from the list saved under given key in the context. * If value under key represents non List object then a RuntimeException is thrown. * @param key context key for the string * @return top object from the list (index 0) or null if no key or list empty */ public Object peek(String key){ synchronized(_contextMap){ Object o=_contextMap.get(key); if(o==null) return null; if(o instanceof List){ if(((List)o).size()==0) return null; Object ret=((List)o).get(0); return ret; } else { throw new RuntimeException("Cannot top from non List object "+o); } } } /** * Removes and returns first object from the list saved under given key in the context. * If value under key represents non List object then a RuntimeException is thrown. * @param key context key for the string * @return top object from the list (index 0) or null if no key or list empty */ public Object pop(String key){ synchronized(_contextMap){ Object o=_contextMap.get(key); if(o==null) return null; if(o instanceof List){ if(((List)o).size()==0) return null; Object ret=((List)o).remove(0); return ret; } else { throw new RuntimeException("Cannot pop from non List object "+o); } } } /** * Removes and returns first object from the list saved under given key in the context * but only if it equals the given expectedValue - if not a false value is returned. * If value under key represents non List object then a RuntimeException is thrown. * @param key context key for the string * @return true if the r */ public boolean pop(String key, Object expectedValue){ synchronized(_contextMap){ Object o=_contextMap.get(key); if(o==null) return false; if(!o.equals(expectedValue)) return false; if(o instanceof List){ if(((List)o).size()==0) return false; ((List)o).remove(0); return true; } else { throw new RuntimeException("Cannot pop from non List object "+o); } } } /** * Puts a new object at the start of the list saved under given key in the context. * If value under key represents non List object then a RuntimeException is thrown. * If no list exists under given key a new LinkedList is created. This is kept * without WeakReference in opposite to the put() results. * @param key key context key for the string * @param value value to be saved under the key */ public void push(String key, Object value){ synchronized(_contextMap){ if(!_contextMap.containsKey(key)) _contextMap.put(key, new LinkedList()); Object o=_contextMap.get(key); if(o instanceof List){ ((List)o).add(0,value); } else { throw new RuntimeException("Cannot push to non List object "+o); } } } public Thread getOperatingThread() { return _operatingThread; } /* NB : The messageImpl is only used by Message. It should be better to place it there. * Alternatively, the Message itself could be placed here, bu this is has a major impact * because Message is used at a lot of place. */ public MessageImpl getMessageImpl() { return _messageImpl; } public void setMessageImpl(MessageImpl impl) { _messageImpl = impl; } public EventManager getEventManager() { return getIvy().getEventManager(); } public CacheManager getCacheManager() { return CacheManager.getInstance(getSettings(), getCache()); } public void checkInterrupted() { getIvy().checkInterrupted(); } public DependencyResolver getResolver() { return (DependencyResolver) _resolver.peek(); } public void pushResolver(DependencyResolver resolver) { _resolver.push(resolver); } public void popResolver() { _resolver.pop(); } // should be better to use context to store this kind of information, but not yet ready to do so... // private WeakReference _root = new WeakReference(null); // private String _rootModuleConf = null; // public IvyNode getRoot() { // return (IvyNode) _root.get(); // } // // public void setRoot(IvyNode root) { // _root = new WeakReference(root); // } // // public String getRootModuleConf() { // return _rootModuleConf; // } // // public void setRootModuleConf(String rootModuleConf) { // _rootModuleConf = rootModuleConf; // } }
FIX on pop implementation (IVY-497) (thanks to Jaroslaw Wypychowski) git-svn-id: 4757cb15a840ff1a58eff8144c368923fad328dd@537003 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/ivy/core/IvyContext.java
FIX on pop implementation (IVY-497) (thanks to Jaroslaw Wypychowski)
Java
apache-2.0
ea194e5b1ba6feb95c4ee46d477ed160e2b13a2c
0
bozimmerman/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud
package com.planet_ink.coffee_mud.application; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.core.database.DBConnector; import com.planet_ink.coffee_mud.core.database.DBConnection; import com.planet_ink.coffee_mud.core.database.DBInterface; import com.planet_ink.coffee_mud.core.http.HTTPserver; import com.planet_ink.coffee_mud.core.http.ProcessHTTPrequest; import com.planet_ink.coffee_mud.core.threads.ServiceEngine; import com.planet_ink.coffee_mud.core.threads.Tick; import com.planet_ink.coffee_mud.core.smtp.SMTPserver; import com.planet_ink.coffee_mud.core.intermud.IMudClient; import com.planet_ink.coffee_mud.core.intermud.cm1.CM1Server; import com.planet_ink.coffee_mud.core.intermud.i3.IMudInterface; import com.planet_ink.coffee_mud.core.intermud.imc2.IMC2Driver; import com.planet_ink.coffee_mud.core.intermud.i3.server.I3Server; import java.io.PrintWriter; // for writing to sockets import java.io.IOException; import java.net.*; import java.util.*; import java.sql.*; /* Copyright 2000-2011 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class MUD extends Thread implements MudHost { private static final float HOST_VERSION_MAJOR=(float)5.7; private static final long HOST_VERSION_MINOR=2; private final static String[] STATE_STRING={"waiting","accepting","allowing"}; private static boolean serverIsRunning = false; private static boolean isOK = false; private int state=0; private ServerSocket servsock=null; private boolean acceptConnections=false; private String host="MyHost"; private int port=5555; private final long startupTime = System.currentTimeMillis(); private static boolean bringDown=false; private static String execExternalCommand=null; private static I3Server i3server=null; private static IMC2Driver imc2server=null; private static List<HTTPserver> webServers=new Vector<HTTPserver>(); private static SMTPserver smtpServerThread=null; private static DVector accessed=new DVector(2); private static List<String> autoblocked=new Vector<String>(); private static List<DBConnector>databases=new Vector<DBConnector>(); private static List<CM1Server> cm1Servers=new Vector<CM1Server>(); public MUD(String name) { super(name); } public static void fatalStartupError(Thread t, int type) { String str=null; switch(type) { case 1: str="ERROR: initHost() will not run without properties. Exiting."; break; case 2: str="Map is empty?! Exiting."; break; case 3: str="Database init failed. Exiting."; break; case 4: str="Fatal exception. Exiting."; break; case 5: str="MUD Server did not start. Exiting."; break; default: str="Fatal error loading classes. Make sure you start up coffeemud from the directory containing the class files."; break; } Log.errOut(Thread.currentThread().getName(),str); bringDown=true; CMProps.setBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN,true); CMLib.killThread(t,100,1); } protected static boolean initHost(Thread t) { if (!isOK) { CMLib.killThread(t,100,1); return false; } CMProps page=CMProps.instance(); if ((page == null) || (!page.isLoaded())) { fatalStartupError(t,1); return false; } char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); Vector<String> privacyV=new Vector<String>(1); if(tCode!=MAIN_HOST) privacyV=CMParms.parseCommas(CMProps.getVar(CMProps.SYSTEM_PRIVATERESOURCES).toUpperCase(),true); long startWait=System.currentTimeMillis(); while (!serverIsRunning && isOK && ((System.currentTimeMillis() - startWait)< 90000)) { try{ Thread.sleep(500); }catch(Exception e){ isOK=false;} } if((!isOK)||(!serverIsRunning)) { fatalStartupError(t,5); return false; } Vector<String> compress=CMParms.parseCommas(page.getStr("COMPRESS").toUpperCase(),true); CMProps.setBoolVar(CMProps.SYSTEMB_ITEMDCOMPRESS,compress.contains("ITEMDESC")); CMProps.setBoolVar(CMProps.SYSTEMB_MOBCOMPRESS,compress.contains("GENMOBS")); CMProps.setBoolVar(CMProps.SYSTEMB_ROOMDCOMPRESS,compress.contains("ROOMDESC")); CMProps.setBoolVar(CMProps.SYSTEMB_MOBDCOMPRESS,compress.contains("MOBDESC")); Resources.setCompression(compress.contains("RESOURCES")); Vector<String> nocache=CMParms.parseCommas(page.getStr("NOCACHE").toUpperCase(),true); CMProps.setBoolVar(CMProps.SYSTEMB_MOBNOCACHE,nocache.contains("GENMOBS")); CMProps.setBoolVar(CMProps.SYSTEMB_ROOMDNOCACHE,nocache.contains("ROOMDESC")); CMProps.setBoolVar(CMProps.SYSTEMB_FILERESOURCENOCACHE, nocache.contains("FILERESOURCES")); CMProps.setBoolVar(CMProps.SYSTEMB_CATALOGNOCACHE, nocache.contains("CATALOG")); DBConnector currentDBconnector=null; String dbClass=page.getStr("DBCLASS"); if(tCode!=MAIN_HOST) { DatabaseEngine baseEngine=(DatabaseEngine)CMLib.library(MAIN_HOST,CMLib.LIBRARY_DATABASE); while((!MUD.bringDown) &&((baseEngine==null)||(!baseEngine.isConnected()))) { try {Thread.sleep(500);}catch(Exception e){ break;} baseEngine=(DatabaseEngine)CMLib.library(MAIN_HOST,CMLib.LIBRARY_DATABASE); } if(MUD.bringDown) return false; if(page.getPrivateStr("DBCLASS").length()==0) { CMLib.registerLibrary(baseEngine); dbClass=""; } } if(dbClass.length()>0) { String dbService=page.getStr("DBSERVICE"); String dbUser=page.getStr("DBUSER"); String dbPass=page.getStr("DBPASS"); int dbConns=page.getInt("DBCONNECTIONS"); boolean dbReuse=page.getBoolean("DBREUSE"); boolean useQue=!CMSecurity.isDisabled(CMSecurity.DisFlag.DBERRORQUE); boolean useQueStart=!CMSecurity.isDisabled(CMSecurity.DisFlag.DBERRORQUESTART); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: connecting to database"); currentDBconnector=new DBConnector(dbClass,dbService,dbUser,dbPass,dbConns,dbReuse,useQue,useQueStart); currentDBconnector.reconnect(); CMLib.registerLibrary(new DBInterface(currentDBconnector,CMParms.parseCommas(CMProps.getVar(CMProps.SYSTEM_PRIVATERESOURCES).toUpperCase(),true))); DBConnection DBTEST=currentDBconnector.DBFetch(); if(DBTEST!=null) currentDBconnector.DBDone(DBTEST); if((DBTEST!=null)&&(currentDBconnector.amIOk())&&(CMLib.database().isConnected())) { Log.sysOut(Thread.currentThread().getName(),"Connected to "+currentDBconnector.service()); databases.add(currentDBconnector); } else { String DBerrors=currentDBconnector.errorStatus().toString(); Log.errOut(Thread.currentThread().getName(),"Fatal database error: "+DBerrors); System.exit(-1); } } else if(CMLib.database()==null) { Log.errOut(Thread.currentThread().getName(),"No registered database!"); System.exit(-1); } // test the database try { CMFile F = new CMFile("/test.the.database",null,false); if(F.exists()) Log.sysOut(Thread.currentThread().getName(),"Test file found .. hmm.. that was unexpected."); } catch(Throwable e) { Log.errOut(Thread.currentThread().getName(),e.getMessage()); Log.errOut(Thread.currentThread().getName(),"Database error! Panic shutdown!"); System.exit(-1); } String webServersList=page.getPrivateStr("RUNWEBSERVERS"); if(webServersList.equalsIgnoreCase("true")) webServersList="pub,admin"; if((webServersList.length()>0)&&(!webServersList.equalsIgnoreCase("false"))) { Vector<String> serverNames=CMParms.parseCommas(webServersList,true); for(int s=0;s<serverNames.size();s++) { String serverName=(String)serverNames.elementAt(s); try { HTTPserver webServerThread = new HTTPserver(CMLib.mud(0),serverName,0); webServerThread.start(); webServers.add(webServerThread); int numToDo=webServerThread.totalPorts(); while((--numToDo)>0) { webServerThread = new HTTPserver(CMLib.mud(0),"pub",numToDo); webServerThread.start(); webServers.add(webServerThread); } } catch(Exception e) { Log.errOut("MUD","HTTP server "+serverName+"NOT started: "+e.getMessage()); } } CMLib.registerLibrary(new ProcessHTTPrequest(null,(webServers.size()>0)?(HTTPserver)webServers.get(0):null,null,true)); } if(page.getPrivateStr("RUNSMTPSERVER").equalsIgnoreCase("true")) { smtpServerThread = new SMTPserver(CMLib.mud(0)); smtpServerThread.start(); CMLib.threads().startTickDown(smtpServerThread,Tickable.TICKID_EMAIL,(int)CMProps.getTicksPerMinute() * 5); } CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: loading base classes"); if(!CMClass.loadClasses(page)) { fatalStartupError(t,0); return false; } CMLib.lang().setLocale(CMLib.props().getStr("LANGUAGE"),CMLib.props().getStr("COUNTRY")); CMLib.time().globalClock().initializeINIClock(page); if((tCode==MAIN_HOST)||(privacyV.contains("FACTIONS"))) CMLib.factions().reloadFactions(CMProps.getVar(CMProps.SYSTEM_PREFACTIONS)); if((tCode==MAIN_HOST)||(page.getRawPrivateStr("SYSOPMASK")!=null)) { CMSecurity.setSysOp(page.getStr("SYSOPMASK")); // requires all classes be loaded CMSecurity.parseGroups(page); } if((tCode==MAIN_HOST)||(privacyV.contains("CHANNELS"))||(privacyV.contains("JOURNALS"))) { int numChannelsLoaded=0; int numJournalsLoaded=0; if((tCode==MAIN_HOST)||(privacyV.contains("CHANNELS"))) numChannelsLoaded=CMLib.channels().loadChannels(page.getStr("CHANNELS"), page.getStr("ICHANNELS"), page.getStr("IMC2CHANNELS")); if((tCode==MAIN_HOST)||(privacyV.contains("JOURNALS"))) { numJournalsLoaded=CMLib.journals().loadCommandJournals(page.getStr("COMMANDJOURNALS")); numJournalsLoaded+=CMLib.journals().loadForumJournals(page.getStr("FORUMJOURNALS")); } Log.sysOut(Thread.currentThread().getName(),"Channels loaded : "+(numChannelsLoaded+numJournalsLoaded)); } if((tCode==MAIN_HOST)||(privacyV.contains("SOCIALS"))) { CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: loading socials"); CMLib.socials().unloadSocials(); if(CMLib.socials().numSocialSets()==0) Log.errOut(Thread.currentThread().getName(),"WARNING: Unable to load socials from socials.txt!"); else Log.sysOut(Thread.currentThread().getName(),"Socials loaded : "+CMLib.socials().numSocialSets()); } if((tCode==MAIN_HOST)||(privacyV.contains("CLANS"))) { CMLib.database().DBReadAllClans(); Log.sysOut(Thread.currentThread().getName(),"Clans loaded : "+CMLib.clans().numClans()); } if((tCode==MAIN_HOST)||(privacyV.contains("FACTIONS"))) CMLib.threads().startTickDown(CMLib.factions(),Tickable.TICKID_MOB,10); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Starting CM1"); startCM1(); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Starting I3"); startIntermud3(); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Starting IMC2"); startIntermud2(); try{Thread.sleep(500);}catch(Exception e){} if((tCode==MAIN_HOST)||(privacyV.contains("CATALOG"))) { Log.sysOut(Thread.currentThread().getName(),"Loading catalog..."); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: loading catalog...."); CMLib.database().DBReadCatalogs(); } if((tCode==MAIN_HOST)||(privacyV.contains("MAP"))) { Log.sysOut(Thread.currentThread().getName(),"Loading map..."); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: loading rooms...."); CMLib.database().DBReadAllRooms(null); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: preparing map...."); Log.sysOut(Thread.currentThread().getName(),"Preparing map..."); CMLib.database().DBReadArtifacts(); for(Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { Area A=(Area)a.nextElement(); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: filling map ("+A.Name()+")"); A.fillInAreaRooms(); } Log.sysOut(Thread.currentThread().getName(),"Mapped rooms : "+CMLib.map().numRooms()+" in "+CMLib.map().numAreas()+" areas"); if(!CMLib.map().roomIDs().hasMoreElements()) { Log.sysOut("NO MAPPED ROOM?! I'll make ya one!"); String id="START";//New Area#0"; Area newArea=CMClass.getAreaType("StdArea"); newArea.setName("New Area"); CMLib.map().addArea(newArea); CMLib.database().DBCreateArea(newArea); Room room=CMClass.getLocale("StdRoom"); room.setRoomID(id); room.setArea(newArea); room.setDisplayText("New Room"); room.setDescription("Brand new database room! You need to change this text with the MODIFY ROOM command. If your character is not an Archon, pick up the book you see here and read it immediately!"); CMLib.database().DBCreateRoom(room); Item I=CMClass.getMiscMagic("ManualArchon"); room.addItem(I); CMLib.database().DBUpdateItems(room); } CMLib.login().initStartRooms(page); CMLib.login().initDeathRooms(page); CMLib.login().initBodyRooms(page); } if((tCode==MAIN_HOST)||(privacyV.contains("QUESTS"))) { CMLib.database().DBReadQuests(CMLib.mud(0)); if(CMLib.quests().numQuests()>0) Log.sysOut(Thread.currentThread().getName(),"Quests loaded : "+CMLib.quests().numQuests()); } if(tCode!=MAIN_HOST) { CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Waiting for HOST0"); while((!MUD.bringDown) &&(!CMProps.getBoolVar0(CMProps.SYSTEMB_MUDSTARTED)) &&(!CMProps.getBoolVar0(CMProps.SYSTEMB_MUDSHUTTINGDOWN))) try{Thread.sleep(500);}catch(Exception e){ break;} if((MUD.bringDown) ||(!CMProps.getBoolVar0(CMProps.SYSTEMB_MUDSTARTED)) ||(CMProps.getBoolVar0(CMProps.SYSTEMB_MUDSHUTTINGDOWN))) return false; } CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: readying for connections."); try { CMLib.activateLibraries(); Log.sysOut(Thread.currentThread().getName(),"Utility threads started"); } catch (Throwable th) { Log.errOut(Thread.currentThread().getName(),"CoffeeMud Server initHost() failed"); Log.errOut(Thread.currentThread().getName(),th); fatalStartupError(t,4); return false; } for(int i=0;i<CMLib.hosts().size();i++) ((MudHost)CMLib.hosts().get(i)).setAcceptConnections(true); Log.sysOut(Thread.currentThread().getName(),"Initialization complete."); CMProps.setBoolVar(CMProps.SYSTEMB_MUDSTARTED,true); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"OK"); return true; } public void acceptConnection(Socket sock) throws SocketException, IOException { sock.setSoLinger(true,3); state=1; if (acceptConnections) { String address="unknown"; try{address=sock.getInetAddress().getHostAddress().trim();}catch(Exception e){} Log.sysOut(Thread.currentThread().getName(),"Connection from "+address); int proceed=0; if(CMSecurity.isBanned(address)) proceed=1; int numAtThisAddress=0; long ConnectionWindow=(180*1000); long LastConnectionDelay=(5*60*1000); boolean anyAtThisAddress=false; int maxAtThisAddress=6; if(!CMSecurity.isDisabled(CMSecurity.DisFlag.CONNSPAMBLOCK)) { try{ for(int a=accessed.size()-1;a>=0;a--) { if((((Long)accessed.elementAt(a,2)).longValue()+LastConnectionDelay)<System.currentTimeMillis()) accessed.removeElementAt(a); else if(((String)accessed.elementAt(a,1)).trim().equalsIgnoreCase(address)) { anyAtThisAddress=true; if((((Long)accessed.elementAt(a,2)).longValue()+ConnectionWindow)>System.currentTimeMillis()) numAtThisAddress++; } } if(autoblocked.contains(address.toUpperCase())) { if(!anyAtThisAddress) autoblocked.remove(address.toUpperCase()); else proceed=2; } else if(numAtThisAddress>=maxAtThisAddress) { autoblocked.add(address.toUpperCase()); proceed=2; } }catch(java.lang.ArrayIndexOutOfBoundsException e){} accessed.addElement(address,Long.valueOf(System.currentTimeMillis())); } if(proceed!=0) { Log.sysOut(Thread.currentThread().getName(),"Blocking a connection from "+address); PrintWriter out = new PrintWriter(sock.getOutputStream()); out.println("\n\rOFFLINE: Blocked\n\r"); out.flush(); if(proceed==2) out.println("\n\rYour address has been blocked temporarily due to excessive invalid connections. Please try back in " + (LastConnectionDelay/60000) + " minutes, and not before.\n\r\n\r"); else out.println("\n\rYou are unwelcome. No one likes you here. Go away.\n\r\n\r"); out.flush(); try{Thread.sleep(250);}catch(Exception e){} out.close(); sock = null; } else { state=2; // also the intro page CMFile introDir=new CMFile(Resources.makeFileResourceName("text"),null,false,true); String introFilename="text/intro.txt"; if(introDir.isDirectory()) { CMFile[] files=introDir.listFiles(); Vector<String> choices=new Vector<String>(); for(int f=0;f<files.length;f++) if(files[f].getName().toLowerCase().startsWith("intro") &&files[f].getName().toLowerCase().endsWith(".txt")) choices.addElement("text/"+files[f].getName()); if(choices.size()>0) introFilename=(String)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1)); } StringBuffer introText=Resources.getFileResource(introFilename,true); try { introText = CMLib.httpUtils().doVirtualPage(introText);}catch(Exception ex){} Session S=(Session)CMClass.getCommon("DefaultSession"); S.initializeSession(sock, introText != null ? introText.toString() : null); S.start(); CMLib.sessions().add(S); sock = null; } } else if((CMLib.database()!=null)&&(CMLib.database().isConnected())&&(CMLib.encoder()!=null)) { StringBuffer rejectText; try { rejectText = Resources.getFileResource("text/offline.txt",true); } catch(java.lang.NullPointerException npe) { rejectText=new StringBuffer("");} PrintWriter out = new PrintWriter(sock.getOutputStream()); out.println("\n\rOFFLINE: " + CMProps.getVar(CMProps.SYSTEM_MUDSTATUS)+"\n\r"); out.println(rejectText); out.flush(); try{Thread.sleep(1000);}catch(Exception e){} out.close(); sock = null; } else { sock.close(); sock = null; } } public String getLanguage() { String lang = CMProps.instance().getStr("LANGUAGE").toUpperCase().trim(); if(lang.length()==0) return "English"; for(int i=0;i<LanguageLibrary.ISO_LANG_CODES.length;i++) if(lang.equals(LanguageLibrary.ISO_LANG_CODES[i][0])) return LanguageLibrary.ISO_LANG_CODES[i][1]; return "English"; } public void run() { int q_len = 6; Socket sock=null; serverIsRunning = false; if (!isOK) return; InetAddress bindAddr = null; if (CMProps.getIntVar(CMProps.SYSTEMI_MUDBACKLOG) > 0) q_len = CMProps.getIntVar(CMProps.SYSTEMI_MUDBACKLOG); if (CMProps.getVar(CMProps.SYSTEM_MUDBINDADDRESS).length() > 0) { try { bindAddr = InetAddress.getByName(CMProps.getVar(CMProps.SYSTEM_MUDBINDADDRESS)); } catch (UnknownHostException e) { Log.errOut(Thread.currentThread().getName(),"ERROR: MUD Server could not bind to address " + CMProps.getVar(CMProps.SYSTEM_MUDBINDADDRESS)); } } try { servsock=new ServerSocket(port, q_len, bindAddr); Log.sysOut(Thread.currentThread().getName(),"MUD Server started on port: "+port); if (bindAddr != null) Log.sysOut(Thread.currentThread().getName(),"MUD Server bound to: "+bindAddr.toString()); serverIsRunning = true; while(true) { state=0; if(servsock==null) break; sock=servsock.accept(); acceptConnection(sock); } } catch(Throwable t) { if((!(t instanceof java.net.SocketException)) ||(t.getMessage()==null) ||(t.getMessage().toLowerCase().indexOf("socket closed")<0)) { Log.errOut(Thread.currentThread().getName(),t); } if (!serverIsRunning) isOK = false; } Log.sysOut(Thread.currentThread().getName(),"CoffeeMud Server cleaning up."); try { if(servsock!=null) servsock.close(); if(sock!=null) sock.close(); } catch(IOException e) { } Log.sysOut(Thread.currentThread().getName(),"MUD on port "+port+" stopped!"); } public String getStatus() { if(CMProps.getBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN)) return CMProps.getVar(CMProps.SYSTEM_MUDSTATUS); if(!CMProps.getBoolVar(CMProps.SYSTEMB_MUDSTARTED)) return CMProps.getVar(CMProps.SYSTEM_MUDSTATUS); return STATE_STRING[state]; } public void shutdown(Session S, boolean keepItDown, String externalCommand) { globalShutdown(S,keepItDown,externalCommand); interrupt(); // kill the damn archon thread. } public static void defaultShutdown() { globalShutdown(null,true,null); } public static void globalShutdown(Session S, boolean keepItDown, String externalCommand) { CMProps.setBoolVar(CMProps.SYSTEMB_MUDSTARTED,false); CMProps.setBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN,true); CMLib.threads().suspendAll(); if(S!=null)S.print("Closing MUD listeners to new connections..."); for(int i=0;i<CMLib.hosts().size();i++) ((MudHost)CMLib.hosts().get(i)).setAcceptConnections(false); Log.sysOut(Thread.currentThread().getName(),"New Connections are now closed"); if(S!=null)S.println("Done."); if(!CMSecurity.isSaveFlag("NOPLAYERS")) { if(S!=null)S.print("Saving players..."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Saving players..."); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_SESSIONS);e.hasMoreElements();) { SessionsList list=((SessionsList)e.nextElement()); for(Session S2 : list.allIterable()) { MOB M = S2.mob(); if((M!=null)&&(M.playerStats()!=null)) { M.playerStats().setLastDateTime(System.currentTimeMillis()); // important! shutdown their affects! for(int a=M.numAllEffects()-1;a>=0;a--) // reverse enumeration { Ability A=M.fetchEffect(a); try { if((A!=null)&&(A.canBeUninvoked())) A.unInvoke(); M.delEffect(A); } catch(Exception ex) {Log.errOut("MUD",ex);} } } } } for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_PLAYERS);e.hasMoreElements();) ((PlayerLibrary)e.nextElement()).savePlayers(); if(S!=null)S.println("done"); Log.sysOut(Thread.currentThread().getName(),"All users saved."); } if(S!=null)S.print("Saving stats..."); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_STATS);e.hasMoreElements();) ((StatisticsLibrary)e.nextElement()).update(); if(S!=null)S.println("done"); Log.sysOut(Thread.currentThread().getName(),"Stats saved."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down" + (keepItDown? "..." : " and restarting...")); Log.sysOut(Thread.currentThread().getName(),"Notifying all objects of shutdown..."); if(S!=null)S.print("Notifying all objects of shutdown..."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Notifying Objects"); MOB mob=null; if(S!=null) mob=S.mob(); if(mob==null) mob=CMClass.getMOB("StdMOB"); CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_SHUTDOWN,null); Vector<Room> roomSet=new Vector<Room>(); try { for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_MAP);e.hasMoreElements();) { WorldMap map=((WorldMap)e.nextElement()); for(Enumeration<Area> a=map.areas();a.hasMoreElements();) ((Area)a.nextElement()).setAreaState(Area.STATE_STOPPED); } for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_MAP);e.hasMoreElements();) { WorldMap map=((WorldMap)e.nextElement()); for(Enumeration<Room> r=map.rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); R.send(mob,msg); roomSet.addElement(R); } } }catch(NoSuchElementException e){} if(S!=null)S.println("done"); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Quests"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_QUEST);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); if(S!=null)S.println("Save thread stopped"); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Session Thread"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_SESSIONS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); if(CMSecurity.isSaveFlag("ROOMMOBS") ||CMSecurity.isSaveFlag("ROOMITEMS") ||CMSecurity.isSaveFlag("ROOMSHOPS")) { if(S!=null)S.print("Saving room data..."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Rejuving the dead"); CMLib.threads().tickAllTickers(null); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Map Update"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_MAP);e.hasMoreElements();) { WorldMap map=((WorldMap)e.nextElement()); for(Enumeration<Area> a=map.areas();a.hasMoreElements();) ((Area)a.nextElement()).setAreaState(Area.STATE_STOPPED); } int roomCounter=0; Room R=null; for(Enumeration<Room> e=roomSet.elements();e.hasMoreElements();) { if(((++roomCounter)%200)==0) { if(S!=null) S.print("."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Map Update ("+roomCounter+")"); } R=(Room)e.nextElement(); if(R.roomID().length()>0) R.executeMsg(mob,CMClass.getMsg(mob,R,null,CMMsg.MSG_EXPIRE,null)); } if(S!=null)S.println("done"); Log.sysOut(Thread.currentThread().getName(),"Map data saved."); } CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...CM1Servers"); for(CM1Server cm1server : cm1Servers) { try { cm1server.shutdown(); } finally { if(S!=null)S.println(cm1server.getName()+" stopped"); Log.sysOut(Thread.currentThread().getName(),cm1server.getName()+" stopped"); } } cm1Servers.clear(); if(i3server!=null) { CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...I3Server"); I3Server.shutdown(); i3server=null; if(S!=null)S.println("I3Server stopped"); Log.sysOut(Thread.currentThread().getName(),"I3Server stopped"); } if(imc2server!=null) { CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...IMC2Server"); imc2server.shutdown(); imc2server=null; if(S!=null)S.println("IMC2Server stopped"); Log.sysOut(Thread.currentThread().getName(),"IMC2Server stopped"); } if(S!=null)S.print("Stopping player Sessions..."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Stopping sessions"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_SESSIONS);e.hasMoreElements();) { SessionsList list=((SessionsList)e.nextElement()); for(Session S2 : list.allIterable()) { if((S!=null)&&(S2==S)) list.remove(S2); else { CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Stopping session "+S2.getAddress()); S2.kill(true,true,true); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Done stopping session "+S2.getAddress()); } if(S!=null)S.print("."); } } if(S!=null)S.println("All users logged off"); try{Thread.sleep(3000);}catch(Exception e){/* give sessions a few seconds to inform the map */} Log.sysOut(Thread.currentThread().getName(),"All users logged off."); if(smtpServerThread!=null) { CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...smtp server"); smtpServerThread.shutdown(S); smtpServerThread = null; Log.sysOut(Thread.currentThread().getName(),"SMTP Server stopped."); if(S!=null)S.println("SMTP Server stopped"); } if(S!=null)S.print("Stopping all threads..."); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_THREADS);e.hasMoreElements();) { CMLibrary lib=(CMLibrary)e.nextElement(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...shutting down Service Engine: " + lib.ID()); lib.shutdown(); } if(S!=null)S.println("done"); Log.sysOut(Thread.currentThread().getName(),"Map Threads Stopped."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...closing db connections"); for(int d=0;d<databases.size();d++) ((DBConnector)databases.get(d)).killConnections(); if(S!=null)S.println("Database connections closed"); Log.sysOut(Thread.currentThread().getName(),"Database connections closed."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Clearing socials, clans, channels"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_SOCIALS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_CLANS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_CHANNELS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_JOURNALS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_POLLS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_HELP);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...unloading classes"); CMClass.shutdown(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...unloading map"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_CATALOG);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_MAP);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_PLAYERS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...unloading resources"); Resources.clearResources(); Log.sysOut(Thread.currentThread().getName(),"Resources Cleared."); if(S!=null)S.println("All resources unloaded"); for(int i=0;i<webServers.size();i++) { HTTPserver webServerThread=(HTTPserver)webServers.get(i); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down web server "+webServerThread.getName()+"..."); webServerThread.shutdown(S); Log.sysOut(Thread.currentThread().getName(),"Web server "+webServerThread.getName()+" stopped."); if(S!=null)S.println("Web server "+webServerThread.getName()+" stopped"); } webServers.clear(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...unloading macros"); CMLib.lang().clear(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down" + (keepItDown? "..." : " and restarting...")); try{Thread.sleep(500);}catch(Exception i){} Log.sysOut(Thread.currentThread().getName(),"CoffeeMud shutdown complete."); if(S!=null)S.println("CoffeeMud shutdown complete."); bringDown=keepItDown; CMLib.threads().resumeAll(); if(!keepItDown) if(S!=null)S.println("Restarting..."); if(S!=null)S.kill(true,true,false); try{Thread.sleep(500);}catch(Exception i){} System.gc(); System.runFinalization(); try{Thread.sleep(500);}catch(Exception i){} execExternalCommand=externalCommand; CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutdown: you are the special lucky chosen one!"); for(int m=CMLib.hosts().size()-1;m>=0;m--) if(CMLib.hosts().get(m) instanceof Thread) { try{ CMLib.killThread((Thread)CMLib.hosts().get(m),100,1); } catch(Throwable t){} } if(!keepItDown) CMProps.setBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN,false); } private static void startIntermud3() { char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); CMProps page=CMProps.instance(); try { if(page.getBoolean("RUNI3SERVER")&&(tCode==MAIN_HOST)) { if(i3server!=null) I3Server.shutdown(); i3server=null; String playstate=page.getStr("MUDSTATE"); if((playstate==null)||(playstate.length()==0)) playstate=page.getStr("I3STATE"); if((playstate==null)||(!CMath.isInteger(playstate))) playstate="Development"; else switch(CMath.s_int(playstate.trim())) { case 0: playstate = "MudLib Development"; break; case 1: playstate = "Restricted Access"; break; case 2: playstate = "Beta Testing"; break; case 3: playstate = "Open for public"; break; default: playstate = "MudLib Development"; break; } IMudInterface imud=new IMudInterface(CMProps.getVar(CMProps.SYSTEM_MUDNAME), "CoffeeMud v"+CMProps.getVar(CMProps.SYSTEM_MUDVER), CMLib.mud(0).getPort(), playstate, CMLib.channels().iChannelsArray()); i3server=new I3Server(); int i3port=page.getInt("I3PORT"); if(i3port==0) i3port=27766; I3Server.start(CMProps.getVar(CMProps.SYSTEM_MUDNAME),i3port,imud); } } catch(Exception e) { if(i3server!=null) I3Server.shutdown(); i3server=null; } } private static void startCM1() { char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); CMProps page=CMProps.instance(); CM1Server cm1server = null; try { if(page.getBoolean("RUNCM1SERVER")) { String iniFile = page.getStr("CM1CONFIG"); for(CM1Server s : cm1Servers) if(s.getINIFilename().equalsIgnoreCase(iniFile)) { s.shutdown(); cm1Servers.remove(s); } cm1server=new CM1Server("CM1Server"+tCode,iniFile); cm1server.start(); cm1Servers.add(cm1server); } } catch(Exception e) { if(cm1server!=null) { cm1server.shutdown(); cm1Servers.remove(cm1server); } } } private static void startIntermud2() { char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); CMProps page=CMProps.instance(); try { if(page.getBoolean("RUNIMC2CLIENT")&&(tCode==MAIN_HOST)) { imc2server=new IMC2Driver(); if(!imc2server.imc_startup(false, page.getStr("IMC2LOGIN").trim(), CMProps.getVar(CMProps.SYSTEM_MUDNAME), page.getStr("IMC2MYEMAIL").trim(), page.getStr("IMC2MYWEB").trim(), page.getStr("IMC2HUBNAME").trim(), page.getInt("IMC2HUBPORT"), page.getStr("IMC2PASS1").trim(), page.getStr("IMC2PASS2").trim(), imc2server.buildChannelMap(page.getStr("IMC2CHANNELS").trim()))) { Log.errOut(Thread.currentThread().getName(),"IMC2 Failed to start!"); imc2server=null; } else { CMLib.intermud().registerIMC2(imc2server); imc2server.start(); } } } catch(Exception e) { Log.errOut("IMC2",e.getMessage()); } } public void interrupt() { if(servsock!=null) { try { servsock.close(); servsock = null; } catch(IOException e) { } } super.interrupt(); } public static int activeThreadCount(ThreadGroup tGroup) { int realAC=0; int ac = tGroup.activeCount(); Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive()) realAC++; } return realAC; } private static int killCount(ThreadGroup tGroup, Thread thisOne) { int killed=0; int ac = tGroup.activeCount(); Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive() && (tArray[i] != thisOne)) { CMLib.killThread(tArray[i],500,1); killed++; } } return killed; } private static void threadList(ThreadGroup tGroup) { int ac = tGroup.activeCount(); Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive()) { if(tArray[i] instanceof Session) { Session S=(Session)tArray[i]; Log.sysOut(Thread.currentThread().getName(), "-->Thread: Session status "+S.getStatus()+"-"+CMParms.combine(S.previousCMD(),0) + "\n\r"); } else if(tArray[i] instanceof Tickable) { Tickable T=(Tickable)tArray[i]; Log.sysOut(Thread.currentThread().getName(), "-->Thread: "+T.ID()+"-"+T.name()+"-"+T.getTickStatus() + "\n\r"); } else if((tArray[i] instanceof Tick) &&(((Tick)tArray[i]).lastClient!=null) &&(((Tick)tArray[i]).lastClient.clientObject!=null)) Log.sysOut(Thread.currentThread().getName(), "-->Thread: "+tArray[i].getName()+" "+((Tick)tArray[i]).lastClient.clientObject.ID()+"-"+((Tick)tArray[i]).lastClient.clientObject.name()+"-"+((Tick)tArray[i]).lastClient.clientObject.getTickStatus() + "\n\r"); else Log.sysOut(Thread.currentThread().getName(), "-->Thread: "+tArray[i].getName() + "\n\r"); } } } public String getHost() { return host; } public int getPort() { return port; } private static class HostGroup extends Thread { private static int grpid=0; private String name=null; private String iniFile=null; private String logName=null; private char threadCode=MAIN_HOST; public HostGroup(ThreadGroup G, String mudName, String iniFileName) { super(G,"HOST"+grpid); synchronized("HostGroupInit".intern()) { logName="mud"+((grpid>0)?("."+grpid):""); grpid++; iniFile=iniFileName; name=mudName; setDaemon(true); threadCode=G.getName().charAt(0); } } public void run() { new CMLib(); // initialize the lib new CMClass(); // initialize the classes Log.shareWith(MudHost.MAIN_HOST); // wait for ini to be loaded, and for other matters if(threadCode!=MAIN_HOST) { while((CMLib.library(MAIN_HOST,CMLib.LIBRARY_INTERMUD)==null)&&(!MUD.bringDown)) { try {Thread.sleep(500);}catch(Exception e){ break;} } if(MUD.bringDown) return; } CMProps page=CMProps.loadPropPage("//"+iniFile); if ((page==null)||(!page.isLoaded())) { Log.errOut(Thread.currentThread().getName(),"ERROR: Unable to read ini file: '"+iniFile+"'."); System.out.println("MUD/ERROR: Unable to read ini file: '"+iniFile+"'."); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"A terminal error has occured!"); return; } page.resetSystemVars(); CMProps.setBoolVar(CMProps.SYSTEMB_MUDSTARTED,false); if(threadCode!=MAIN_HOST) { if(CMath.isInteger(page.getPrivateStr("NUMLOGS"))) { Log.newInstance(); Log.instance().startLogFiles(logName,page.getInt("NUMLOGS")); Log.instance().setLogOutput(page.getStr("SYSMSGS"),page.getStr("ERRMSGS"),page.getStr("WRNMSGS"),page.getStr("DBGMSGS"),page.getStr("HLPMSGS"),page.getStr("KILMSGS"),page.getStr("CBTMSGS")); } if(page.getRawPrivateStr("SYSOPMASK")!=null) page.resetSecurityVars(); else CMSecurity.instance().markShared(); } if(page.getStr("DISABLE").trim().length()>0) Log.sysOut(Thread.currentThread().getName(),"Disabled subsystems: "+page.getStr("DISABLE")); if(page.getStr("DEBUG").trim().length()>0) { Log.sysOut(Thread.currentThread().getName(),"Debugging messages: "+page.getStr("DEBUG")); if(!Log.debugChannelOn()) Log.errOut(Thread.currentThread().getName(),"Debug logging is disabled! Check your DBGMSGS flag!"); } DBConnector currentDBconnector=new DBConnector(); CMLib.registerLibrary(new DBInterface(currentDBconnector,CMParms.parseCommas(CMProps.getVar(CMProps.SYSTEM_PRIVATERESOURCES).toUpperCase(),true))); CMLib.registerLibrary(new ProcessHTTPrequest(null,null,null,true)); CMProps.setVar(CMProps.SYSTEM_MUDVER,HOST_VERSION_MAJOR + "." + HOST_VERSION_MINOR); // an arbitrary dividing line. After threadCode 0 if(threadCode==MAIN_HOST) { CMLib.registerLibrary(new ServiceEngine()); CMLib.registerLibrary(new IMudClient()); } else { CMLib.registerLibrary(CMLib.library(MAIN_HOST,CMLib.LIBRARY_THREADS)); CMLib.registerLibrary(CMLib.library(MAIN_HOST,CMLib.LIBRARY_INTERMUD)); } CMProps.setVar(CMProps.SYSTEM_INIPATH,iniFile,false); CMProps.setUpLowVar(CMProps.SYSTEM_MUDNAME,name.replace('\'','`')); try { isOK = true; CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting"); CMProps.setVar(CMProps.SYSTEM_MUDBINDADDRESS,page.getStr("BIND")); CMProps.setIntVar(CMProps.SYSTEMI_MUDBACKLOG,page.getInt("BACKLOG")); if(MUD.isOK) { String ports=page.getProperty("PORT"); int pdex=ports.indexOf(','); while(pdex>0) { MUD mud=new MUD("MUD@"+ports.substring(0,pdex)); mud.acceptConnections=false; mud.port=CMath.s_int(ports.substring(0,pdex)); ports=ports.substring(pdex+1); mud.start(); CMLib.hosts().add(mud); pdex=ports.indexOf(','); } MUD mud=new MUD("MUD@"+ports); mud.acceptConnections=false; mud.port=CMath.s_int(ports); mud.start(); CMLib.hosts().add(mud); } StringBuffer str=new StringBuffer(""); for(int m=0;m<CMLib.hosts().size();m++) { MudHost mud=(MudHost)CMLib.hosts().get(m); str.append(" "+mud.getPort()); } CMProps.setVar(CMProps.SYSTEM_MUDPORTS,str.toString()); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if(!CMProps.getBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN)) MUD.globalShutdown(null,true,null); } }); if(initHost(Thread.currentThread())) { Thread joinable=null; for(int i=0;i<CMLib.hosts().size();i++) if(CMLib.hosts().get(i) instanceof Thread) { joinable=(Thread)CMLib.hosts().get(i); break; } if(joinable!=null) joinable.join(); else System.exit(-1); } } catch(InterruptedException e) { Log.errOut(Thread.currentThread().getName(),e); } } } public List<Runnable> getOverdueThreads() { Vector<Runnable> V=new Vector<Runnable>(); for(int w=0;w<webServers.size();w++) V.addAll(((HTTPserver)webServers.get(w)).getOverdueThreads()); return V; } public static void main(String a[]) { String nameID=""; Vector<String> iniFiles=new Vector<String>(); if(a.length>0) { for(int i=0;i<a.length;i++) nameID+=" "+a[i]; nameID=nameID.trim(); Vector<String> V=CMParms.paramParse(nameID); for(int v=0;v<V.size();v++) { String s=(String)V.elementAt(v); if(s.toUpperCase().startsWith("BOOT=")&&(s.length()>5)) { iniFiles.addElement(s.substring(5)); V.removeElementAt(v); v--; } } nameID=CMParms.combine(V,0); } new CMLib(); // initialize this threads libs if(iniFiles.size()==0) iniFiles.addElement("coffeemud.ini"); if(nameID.length()==0) nameID="Unnamed CoffeeMud"; String iniFile=(String)iniFiles.firstElement(); CMProps page=CMProps.loadPropPage("//"+iniFile); if ((page==null)||(!page.isLoaded())) { Log.instance().startLogFiles("mud",1); Log.instance().setLogOutput("BOTH","BOTH","BOTH","BOTH","BOTH","BOTH","BOTH"); Log.errOut(Thread.currentThread().getName(),"ERROR: Unable to read ini file: '"+iniFile+"'."); System.out.println("MUD/ERROR: Unable to read ini file: '"+iniFile+"'."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"A terminal error has occured!"); System.exit(-1); return; } Log.shareWith(MudHost.MAIN_HOST); Log.instance().startLogFiles("mud",page.getInt("NUMLOGS")); Log.instance().setLogOutput(page.getStr("SYSMSGS"),page.getStr("ERRMSGS"),page.getStr("WRNMSGS"),page.getStr("DBGMSGS"),page.getStr("HLPMSGS"),page.getStr("KILMSGS"),page.getStr("CBTMSGS")); while(!bringDown) { System.out.println(); Log.sysOut(Thread.currentThread().getName(),"CoffeeMud v"+HOST_VERSION_MAJOR + "." + HOST_VERSION_MINOR); Log.sysOut(Thread.currentThread().getName(),"(C) 2000-2011 Bo Zimmerman"); Log.sysOut(Thread.currentThread().getName(),"http://www.coffeemud.org"); HostGroup joinable=null; CMLib.hosts().clear(); for(int i=0;i<iniFiles.size();i++) { iniFile=(String)iniFiles.elementAt(i); ThreadGroup G=new ThreadGroup(i+"-MUD"); HostGroup H=new HostGroup(G,nameID,iniFile); H.start(); if(joinable==null) joinable=H; } if(joinable!=null) try{joinable.join();}catch(Exception e){e.printStackTrace(); Log.errOut(Thread.currentThread().getName(),e); } System.gc(); try{Thread.sleep(1000);}catch(Exception e){} System.runFinalization(); try{Thread.sleep(1000);}catch(Exception e){} if(activeThreadCount(Thread.currentThread().getThreadGroup())>1) { try{ Thread.sleep(1000);}catch(Exception e){} killCount(Thread.currentThread().getThreadGroup(),Thread.currentThread()); try{ Thread.sleep(1000);}catch(Exception e){} if(activeThreadCount(Thread.currentThread().getThreadGroup())>1) { Log.sysOut(Thread.currentThread().getName(),"WARNING: " + activeThreadCount(Thread.currentThread().getThreadGroup()) +" other thread(s) are still active!"); threadList(Thread.currentThread().getThreadGroup()); } } if(!bringDown) { if(execExternalCommand!=null) { //Runtime r=Runtime.getRuntime(); //Process p=r.exec(external); Log.sysOut("Attempted to execute '"+execExternalCommand+"'."); execExternalCommand=null; bringDown=true; } } } } public void setAcceptConnections(boolean truefalse){ acceptConnections=truefalse;} public boolean isAcceptingConnections(){ return acceptConnections;} public long getUptimeSecs() { return (System.currentTimeMillis()-startupTime)/1000;} public String executeCommand(String cmd) throws Exception { Vector<String> V=CMParms.parse(cmd); if(V.size()==0) throw new CMException("Unknown command!"); String word=(String)V.firstElement(); if(word.equalsIgnoreCase("START")&&(V.size()>1)) { String what=(String)V.elementAt(1); if(what.equalsIgnoreCase("I3")) { startIntermud3(); return "Done"; } else if(what.equalsIgnoreCase("IMC2")) { startIntermud2(); return "Done"; } } throw new CMException("Unknown command: "+word); } }
com/planet_ink/coffee_mud/application/MUD.java
package com.planet_ink.coffee_mud.application; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.core.database.DBConnector; import com.planet_ink.coffee_mud.core.database.DBConnection; import com.planet_ink.coffee_mud.core.database.DBInterface; import com.planet_ink.coffee_mud.core.http.HTTPserver; import com.planet_ink.coffee_mud.core.http.ProcessHTTPrequest; import com.planet_ink.coffee_mud.core.threads.ServiceEngine; import com.planet_ink.coffee_mud.core.threads.Tick; import com.planet_ink.coffee_mud.core.smtp.SMTPserver; import com.planet_ink.coffee_mud.core.intermud.IMudClient; import com.planet_ink.coffee_mud.core.intermud.cm1.CM1Server; import com.planet_ink.coffee_mud.core.intermud.i3.IMudInterface; import com.planet_ink.coffee_mud.core.intermud.imc2.IMC2Driver; import com.planet_ink.coffee_mud.core.intermud.i3.server.I3Server; import java.io.PrintWriter; // for writing to sockets import java.io.IOException; import java.net.*; import java.util.*; import java.sql.*; /* Copyright 2000-2011 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class MUD extends Thread implements MudHost { private static final float HOST_VERSION_MAJOR=(float)5.7; private static final long HOST_VERSION_MINOR=1; private final static String[] STATE_STRING={"waiting","accepting","allowing"}; private static boolean serverIsRunning = false; private static boolean isOK = false; private int state=0; private ServerSocket servsock=null; private boolean acceptConnections=false; private String host="MyHost"; private int port=5555; private final long startupTime = System.currentTimeMillis(); private static boolean bringDown=false; private static String execExternalCommand=null; private static I3Server i3server=null; private static IMC2Driver imc2server=null; private static List<HTTPserver> webServers=new Vector<HTTPserver>(); private static SMTPserver smtpServerThread=null; private static DVector accessed=new DVector(2); private static List<String> autoblocked=new Vector<String>(); private static List<DBConnector>databases=new Vector<DBConnector>(); private static List<CM1Server> cm1Servers=new Vector<CM1Server>(); public MUD(String name) { super(name); } public static void fatalStartupError(Thread t, int type) { String str=null; switch(type) { case 1: str="ERROR: initHost() will not run without properties. Exiting."; break; case 2: str="Map is empty?! Exiting."; break; case 3: str="Database init failed. Exiting."; break; case 4: str="Fatal exception. Exiting."; break; case 5: str="MUD Server did not start. Exiting."; break; default: str="Fatal error loading classes. Make sure you start up coffeemud from the directory containing the class files."; break; } Log.errOut(Thread.currentThread().getName(),str); bringDown=true; CMProps.setBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN,true); CMLib.killThread(t,100,1); } protected static boolean initHost(Thread t) { if (!isOK) { CMLib.killThread(t,100,1); return false; } CMProps page=CMProps.instance(); if ((page == null) || (!page.isLoaded())) { fatalStartupError(t,1); return false; } char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); Vector<String> privacyV=new Vector<String>(1); if(tCode!=MAIN_HOST) privacyV=CMParms.parseCommas(CMProps.getVar(CMProps.SYSTEM_PRIVATERESOURCES).toUpperCase(),true); long startWait=System.currentTimeMillis(); while (!serverIsRunning && isOK && ((System.currentTimeMillis() - startWait)< 90000)) { try{ Thread.sleep(500); }catch(Exception e){ isOK=false;} } if((!isOK)||(!serverIsRunning)) { fatalStartupError(t,5); return false; } Vector<String> compress=CMParms.parseCommas(page.getStr("COMPRESS").toUpperCase(),true); CMProps.setBoolVar(CMProps.SYSTEMB_ITEMDCOMPRESS,compress.contains("ITEMDESC")); CMProps.setBoolVar(CMProps.SYSTEMB_MOBCOMPRESS,compress.contains("GENMOBS")); CMProps.setBoolVar(CMProps.SYSTEMB_ROOMDCOMPRESS,compress.contains("ROOMDESC")); CMProps.setBoolVar(CMProps.SYSTEMB_MOBDCOMPRESS,compress.contains("MOBDESC")); Resources.setCompression(compress.contains("RESOURCES")); Vector<String> nocache=CMParms.parseCommas(page.getStr("NOCACHE").toUpperCase(),true); CMProps.setBoolVar(CMProps.SYSTEMB_MOBNOCACHE,nocache.contains("GENMOBS")); CMProps.setBoolVar(CMProps.SYSTEMB_ROOMDNOCACHE,nocache.contains("ROOMDESC")); CMProps.setBoolVar(CMProps.SYSTEMB_FILERESOURCENOCACHE, nocache.contains("FILERESOURCES")); CMProps.setBoolVar(CMProps.SYSTEMB_CATALOGNOCACHE, nocache.contains("CATALOG")); DBConnector currentDBconnector=null; String dbClass=page.getStr("DBCLASS"); if(tCode!=MAIN_HOST) { DatabaseEngine baseEngine=(DatabaseEngine)CMLib.library(MAIN_HOST,CMLib.LIBRARY_DATABASE); while((!MUD.bringDown) &&((baseEngine==null)||(!baseEngine.isConnected()))) { try {Thread.sleep(500);}catch(Exception e){ break;} baseEngine=(DatabaseEngine)CMLib.library(MAIN_HOST,CMLib.LIBRARY_DATABASE); } if(MUD.bringDown) return false; if(page.getPrivateStr("DBCLASS").length()==0) { CMLib.registerLibrary(baseEngine); dbClass=""; } } if(dbClass.length()>0) { String dbService=page.getStr("DBSERVICE"); String dbUser=page.getStr("DBUSER"); String dbPass=page.getStr("DBPASS"); int dbConns=page.getInt("DBCONNECTIONS"); boolean dbReuse=page.getBoolean("DBREUSE"); boolean useQue=!CMSecurity.isDisabled(CMSecurity.DisFlag.DBERRORQUE); boolean useQueStart=!CMSecurity.isDisabled(CMSecurity.DisFlag.DBERRORQUESTART); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: connecting to database"); currentDBconnector=new DBConnector(dbClass,dbService,dbUser,dbPass,dbConns,dbReuse,useQue,useQueStart); currentDBconnector.reconnect(); CMLib.registerLibrary(new DBInterface(currentDBconnector,CMParms.parseCommas(CMProps.getVar(CMProps.SYSTEM_PRIVATERESOURCES).toUpperCase(),true))); DBConnection DBTEST=currentDBconnector.DBFetch(); if(DBTEST!=null) currentDBconnector.DBDone(DBTEST); if((DBTEST!=null)&&(currentDBconnector.amIOk())&&(CMLib.database().isConnected())) { Log.sysOut(Thread.currentThread().getName(),"Connected to "+currentDBconnector.service()); databases.add(currentDBconnector); } else { String DBerrors=currentDBconnector.errorStatus().toString(); Log.errOut(Thread.currentThread().getName(),"Fatal database error: "+DBerrors); System.exit(-1); } } else if(CMLib.database()==null) { Log.errOut(Thread.currentThread().getName(),"No registered database!"); System.exit(-1); } // test the database try { CMFile F = new CMFile("/test.the.database",null,false); if(F.exists()) Log.sysOut(Thread.currentThread().getName(),"Test file found .. hmm.. that was unexpected."); } catch(Throwable e) { Log.errOut(Thread.currentThread().getName(),e.getMessage()); Log.errOut(Thread.currentThread().getName(),"Database error! Panic shutdown!"); System.exit(-1); } String webServersList=page.getPrivateStr("RUNWEBSERVERS"); if(webServersList.equalsIgnoreCase("true")) webServersList="pub,admin"; if((webServersList.length()>0)&&(!webServersList.equalsIgnoreCase("false"))) { Vector<String> serverNames=CMParms.parseCommas(webServersList,true); for(int s=0;s<serverNames.size();s++) { String serverName=(String)serverNames.elementAt(s); try { HTTPserver webServerThread = new HTTPserver(CMLib.mud(0),serverName,0); webServerThread.start(); webServers.add(webServerThread); int numToDo=webServerThread.totalPorts(); while((--numToDo)>0) { webServerThread = new HTTPserver(CMLib.mud(0),"pub",numToDo); webServerThread.start(); webServers.add(webServerThread); } } catch(Exception e) { Log.errOut("MUD","HTTP server "+serverName+"NOT started: "+e.getMessage()); } } CMLib.registerLibrary(new ProcessHTTPrequest(null,(webServers.size()>0)?(HTTPserver)webServers.get(0):null,null,true)); } if(page.getPrivateStr("RUNSMTPSERVER").equalsIgnoreCase("true")) { smtpServerThread = new SMTPserver(CMLib.mud(0)); smtpServerThread.start(); CMLib.threads().startTickDown(smtpServerThread,Tickable.TICKID_EMAIL,(int)CMProps.getTicksPerMinute() * 5); } CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: loading base classes"); if(!CMClass.loadClasses(page)) { fatalStartupError(t,0); return false; } CMLib.lang().setLocale(CMLib.props().getStr("LANGUAGE"),CMLib.props().getStr("COUNTRY")); CMLib.time().globalClock().initializeINIClock(page); if((tCode==MAIN_HOST)||(privacyV.contains("FACTIONS"))) CMLib.factions().reloadFactions(CMProps.getVar(CMProps.SYSTEM_PREFACTIONS)); if((tCode==MAIN_HOST)||(page.getRawPrivateStr("SYSOPMASK")!=null)) { CMSecurity.setSysOp(page.getStr("SYSOPMASK")); // requires all classes be loaded CMSecurity.parseGroups(page); } if((tCode==MAIN_HOST)||(privacyV.contains("CHANNELS"))||(privacyV.contains("JOURNALS"))) { int numChannelsLoaded=0; int numJournalsLoaded=0; if((tCode==MAIN_HOST)||(privacyV.contains("CHANNELS"))) numChannelsLoaded=CMLib.channels().loadChannels(page.getStr("CHANNELS"), page.getStr("ICHANNELS"), page.getStr("IMC2CHANNELS")); if((tCode==MAIN_HOST)||(privacyV.contains("JOURNALS"))) { numJournalsLoaded=CMLib.journals().loadCommandJournals(page.getStr("COMMANDJOURNALS")); numJournalsLoaded+=CMLib.journals().loadForumJournals(page.getStr("FORUMJOURNALS")); } Log.sysOut(Thread.currentThread().getName(),"Channels loaded : "+(numChannelsLoaded+numJournalsLoaded)); } if((tCode==MAIN_HOST)||(privacyV.contains("SOCIALS"))) { CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: loading socials"); CMLib.socials().unloadSocials(); if(CMLib.socials().numSocialSets()==0) Log.errOut(Thread.currentThread().getName(),"WARNING: Unable to load socials from socials.txt!"); else Log.sysOut(Thread.currentThread().getName(),"Socials loaded : "+CMLib.socials().numSocialSets()); } if((tCode==MAIN_HOST)||(privacyV.contains("CLANS"))) { CMLib.database().DBReadAllClans(); Log.sysOut(Thread.currentThread().getName(),"Clans loaded : "+CMLib.clans().numClans()); } if((tCode==MAIN_HOST)||(privacyV.contains("FACTIONS"))) CMLib.threads().startTickDown(CMLib.factions(),Tickable.TICKID_MOB,10); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Starting CM1"); startCM1(); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Starting I3"); startIntermud3(); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Starting IMC2"); startIntermud2(); try{Thread.sleep(500);}catch(Exception e){} if((tCode==MAIN_HOST)||(privacyV.contains("CATALOG"))) { Log.sysOut(Thread.currentThread().getName(),"Loading catalog..."); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: loading catalog...."); CMLib.database().DBReadCatalogs(); } if((tCode==MAIN_HOST)||(privacyV.contains("MAP"))) { Log.sysOut(Thread.currentThread().getName(),"Loading map..."); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: loading rooms...."); CMLib.database().DBReadAllRooms(null); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: preparing map...."); Log.sysOut(Thread.currentThread().getName(),"Preparing map..."); CMLib.database().DBReadArtifacts(); for(Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { Area A=(Area)a.nextElement(); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: filling map ("+A.Name()+")"); A.fillInAreaRooms(); } Log.sysOut(Thread.currentThread().getName(),"Mapped rooms : "+CMLib.map().numRooms()+" in "+CMLib.map().numAreas()+" areas"); if(!CMLib.map().roomIDs().hasMoreElements()) { Log.sysOut("NO MAPPED ROOM?! I'll make ya one!"); String id="START";//New Area#0"; Area newArea=CMClass.getAreaType("StdArea"); newArea.setName("New Area"); CMLib.map().addArea(newArea); CMLib.database().DBCreateArea(newArea); Room room=CMClass.getLocale("StdRoom"); room.setRoomID(id); room.setArea(newArea); room.setDisplayText("New Room"); room.setDescription("Brand new database room! You need to change this text with the MODIFY ROOM command. If your character is not an Archon, pick up the book you see here and read it immediately!"); CMLib.database().DBCreateRoom(room); Item I=CMClass.getMiscMagic("ManualArchon"); room.addItem(I); CMLib.database().DBUpdateItems(room); } CMLib.login().initStartRooms(page); CMLib.login().initDeathRooms(page); CMLib.login().initBodyRooms(page); } if((tCode==MAIN_HOST)||(privacyV.contains("QUESTS"))) { CMLib.database().DBReadQuests(CMLib.mud(0)); if(CMLib.quests().numQuests()>0) Log.sysOut(Thread.currentThread().getName(),"Quests loaded : "+CMLib.quests().numQuests()); } if(tCode!=MAIN_HOST) { CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: Waiting for HOST0"); while((!MUD.bringDown) &&(!CMProps.getBoolVar0(CMProps.SYSTEMB_MUDSTARTED)) &&(!CMProps.getBoolVar0(CMProps.SYSTEMB_MUDSHUTTINGDOWN))) try{Thread.sleep(500);}catch(Exception e){ break;} if((MUD.bringDown) ||(!CMProps.getBoolVar0(CMProps.SYSTEMB_MUDSTARTED)) ||(CMProps.getBoolVar0(CMProps.SYSTEMB_MUDSHUTTINGDOWN))) return false; } CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting: readying for connections."); try { CMLib.activateLibraries(); Log.sysOut(Thread.currentThread().getName(),"Utility threads started"); } catch (Throwable th) { Log.errOut(Thread.currentThread().getName(),"CoffeeMud Server initHost() failed"); Log.errOut(Thread.currentThread().getName(),th); fatalStartupError(t,4); return false; } for(int i=0;i<CMLib.hosts().size();i++) ((MudHost)CMLib.hosts().get(i)).setAcceptConnections(true); Log.sysOut(Thread.currentThread().getName(),"Initialization complete."); CMProps.setBoolVar(CMProps.SYSTEMB_MUDSTARTED,true); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"OK"); return true; } public void acceptConnection(Socket sock) throws SocketException, IOException { sock.setSoLinger(true,3); state=1; if (acceptConnections) { String address="unknown"; try{address=sock.getInetAddress().getHostAddress().trim();}catch(Exception e){} Log.sysOut(Thread.currentThread().getName(),"Connection from "+address); int proceed=0; if(CMSecurity.isBanned(address)) proceed=1; int numAtThisAddress=0; long ConnectionWindow=(180*1000); long LastConnectionDelay=(5*60*1000); boolean anyAtThisAddress=false; int maxAtThisAddress=6; if(!CMSecurity.isDisabled(CMSecurity.DisFlag.CONNSPAMBLOCK)) { try{ for(int a=accessed.size()-1;a>=0;a--) { if((((Long)accessed.elementAt(a,2)).longValue()+LastConnectionDelay)<System.currentTimeMillis()) accessed.removeElementAt(a); else if(((String)accessed.elementAt(a,1)).trim().equalsIgnoreCase(address)) { anyAtThisAddress=true; if((((Long)accessed.elementAt(a,2)).longValue()+ConnectionWindow)>System.currentTimeMillis()) numAtThisAddress++; } } if(autoblocked.contains(address.toUpperCase())) { if(!anyAtThisAddress) autoblocked.remove(address.toUpperCase()); else proceed=2; } else if(numAtThisAddress>=maxAtThisAddress) { autoblocked.add(address.toUpperCase()); proceed=2; } }catch(java.lang.ArrayIndexOutOfBoundsException e){} accessed.addElement(address,Long.valueOf(System.currentTimeMillis())); } if(proceed!=0) { Log.sysOut(Thread.currentThread().getName(),"Blocking a connection from "+address); PrintWriter out = new PrintWriter(sock.getOutputStream()); out.println("\n\rOFFLINE: Blocked\n\r"); out.flush(); if(proceed==2) out.println("\n\rYour address has been blocked temporarily due to excessive invalid connections. Please try back in " + (LastConnectionDelay/60000) + " minutes, and not before.\n\r\n\r"); else out.println("\n\rYou are unwelcome. No one likes you here. Go away.\n\r\n\r"); out.flush(); try{Thread.sleep(250);}catch(Exception e){} out.close(); sock = null; } else { state=2; // also the intro page CMFile introDir=new CMFile(Resources.makeFileResourceName("text"),null,false,true); String introFilename="text/intro.txt"; if(introDir.isDirectory()) { CMFile[] files=introDir.listFiles(); Vector<String> choices=new Vector<String>(); for(int f=0;f<files.length;f++) if(files[f].getName().toLowerCase().startsWith("intro") &&files[f].getName().toLowerCase().endsWith(".txt")) choices.addElement("text/"+files[f].getName()); if(choices.size()>0) introFilename=(String)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1)); } StringBuffer introText=Resources.getFileResource(introFilename,true); try { introText = CMLib.httpUtils().doVirtualPage(introText);}catch(Exception ex){} Session S=(Session)CMClass.getCommon("DefaultSession"); S.initializeSession(sock, introText != null ? introText.toString() : null); S.start(); CMLib.sessions().add(S); sock = null; } } else if((CMLib.database()!=null)&&(CMLib.database().isConnected())&&(CMLib.encoder()!=null)) { StringBuffer rejectText; try { rejectText = Resources.getFileResource("text/offline.txt",true); } catch(java.lang.NullPointerException npe) { rejectText=new StringBuffer("");} PrintWriter out = new PrintWriter(sock.getOutputStream()); out.println("\n\rOFFLINE: " + CMProps.getVar(CMProps.SYSTEM_MUDSTATUS)+"\n\r"); out.println(rejectText); out.flush(); try{Thread.sleep(1000);}catch(Exception e){} out.close(); sock = null; } else { sock.close(); sock = null; } } public String getLanguage() { String lang = CMProps.instance().getStr("LANGUAGE").toUpperCase().trim(); if(lang.length()==0) return "English"; for(int i=0;i<LanguageLibrary.ISO_LANG_CODES.length;i++) if(lang.equals(LanguageLibrary.ISO_LANG_CODES[i][0])) return LanguageLibrary.ISO_LANG_CODES[i][1]; return "English"; } public void run() { int q_len = 6; Socket sock=null; serverIsRunning = false; if (!isOK) return; InetAddress bindAddr = null; if (CMProps.getIntVar(CMProps.SYSTEMI_MUDBACKLOG) > 0) q_len = CMProps.getIntVar(CMProps.SYSTEMI_MUDBACKLOG); if (CMProps.getVar(CMProps.SYSTEM_MUDBINDADDRESS).length() > 0) { try { bindAddr = InetAddress.getByName(CMProps.getVar(CMProps.SYSTEM_MUDBINDADDRESS)); } catch (UnknownHostException e) { Log.errOut(Thread.currentThread().getName(),"ERROR: MUD Server could not bind to address " + CMProps.getVar(CMProps.SYSTEM_MUDBINDADDRESS)); } } try { servsock=new ServerSocket(port, q_len, bindAddr); Log.sysOut(Thread.currentThread().getName(),"MUD Server started on port: "+port); if (bindAddr != null) Log.sysOut(Thread.currentThread().getName(),"MUD Server bound to: "+bindAddr.toString()); serverIsRunning = true; while(true) { state=0; if(servsock==null) break; sock=servsock.accept(); acceptConnection(sock); } } catch(Throwable t) { if((!(t instanceof java.net.SocketException)) ||(t.getMessage()==null) ||(t.getMessage().toLowerCase().indexOf("socket closed")<0)) { Log.errOut(Thread.currentThread().getName(),t); } if (!serverIsRunning) isOK = false; } Log.sysOut(Thread.currentThread().getName(),"CoffeeMud Server cleaning up."); try { if(servsock!=null) servsock.close(); if(sock!=null) sock.close(); } catch(IOException e) { } Log.sysOut(Thread.currentThread().getName(),"MUD on port "+port+" stopped!"); } public String getStatus() { if(CMProps.getBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN)) return CMProps.getVar(CMProps.SYSTEM_MUDSTATUS); if(!CMProps.getBoolVar(CMProps.SYSTEMB_MUDSTARTED)) return CMProps.getVar(CMProps.SYSTEM_MUDSTATUS); return STATE_STRING[state]; } public void shutdown(Session S, boolean keepItDown, String externalCommand) { globalShutdown(S,keepItDown,externalCommand); interrupt(); // kill the damn archon thread. } public static void defaultShutdown() { globalShutdown(null,true,null); } public static void globalShutdown(Session S, boolean keepItDown, String externalCommand) { CMProps.setBoolVar(CMProps.SYSTEMB_MUDSTARTED,false); CMProps.setBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN,true); CMLib.threads().suspendAll(); if(S!=null)S.print("Closing MUD listeners to new connections..."); for(int i=0;i<CMLib.hosts().size();i++) ((MudHost)CMLib.hosts().get(i)).setAcceptConnections(false); Log.sysOut(Thread.currentThread().getName(),"New Connections are now closed"); if(S!=null)S.println("Done."); if(!CMSecurity.isSaveFlag("NOPLAYERS")) { if(S!=null)S.print("Saving players..."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Saving players..."); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_SESSIONS);e.hasMoreElements();) { SessionsList list=((SessionsList)e.nextElement()); for(Session S2 : list.allIterable()) { MOB M = S2.mob(); if((M!=null)&&(M.playerStats()!=null)) { M.playerStats().setLastDateTime(System.currentTimeMillis()); // important! shutdown their affects! for(int a=M.numAllEffects()-1;a>=0;a--) // reverse enumeration { Ability A=M.fetchEffect(a); try { if((A!=null)&&(A.canBeUninvoked())) A.unInvoke(); M.delEffect(A); } catch(Exception ex) {Log.errOut("MUD",ex);} } } } } for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_PLAYERS);e.hasMoreElements();) ((PlayerLibrary)e.nextElement()).savePlayers(); if(S!=null)S.println("done"); Log.sysOut(Thread.currentThread().getName(),"All users saved."); } if(S!=null)S.print("Saving stats..."); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_STATS);e.hasMoreElements();) ((StatisticsLibrary)e.nextElement()).update(); if(S!=null)S.println("done"); Log.sysOut(Thread.currentThread().getName(),"Stats saved."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down" + (keepItDown? "..." : " and restarting...")); Log.sysOut(Thread.currentThread().getName(),"Notifying all objects of shutdown..."); if(S!=null)S.print("Notifying all objects of shutdown..."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Notifying Objects"); MOB mob=null; if(S!=null) mob=S.mob(); if(mob==null) mob=CMClass.getMOB("StdMOB"); CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_SHUTDOWN,null); Vector<Room> roomSet=new Vector<Room>(); try { for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_MAP);e.hasMoreElements();) { WorldMap map=((WorldMap)e.nextElement()); for(Enumeration<Area> a=map.areas();a.hasMoreElements();) ((Area)a.nextElement()).setAreaState(Area.STATE_STOPPED); } for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_MAP);e.hasMoreElements();) { WorldMap map=((WorldMap)e.nextElement()); for(Enumeration<Room> r=map.rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); R.send(mob,msg); roomSet.addElement(R); } } }catch(NoSuchElementException e){} if(S!=null)S.println("done"); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Quests"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_QUEST);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); if(S!=null)S.println("Save thread stopped"); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Session Thread"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_SESSIONS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); if(CMSecurity.isSaveFlag("ROOMMOBS") ||CMSecurity.isSaveFlag("ROOMITEMS") ||CMSecurity.isSaveFlag("ROOMSHOPS")) { if(S!=null)S.print("Saving room data..."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Rejuving the dead"); CMLib.threads().tickAllTickers(null); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Map Update"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_MAP);e.hasMoreElements();) { WorldMap map=((WorldMap)e.nextElement()); for(Enumeration<Area> a=map.areas();a.hasMoreElements();) ((Area)a.nextElement()).setAreaState(Area.STATE_STOPPED); } int roomCounter=0; Room R=null; for(Enumeration<Room> e=roomSet.elements();e.hasMoreElements();) { if(((++roomCounter)%200)==0) { if(S!=null) S.print("."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Map Update ("+roomCounter+")"); } R=(Room)e.nextElement(); if(R.roomID().length()>0) R.executeMsg(mob,CMClass.getMsg(mob,R,null,CMMsg.MSG_EXPIRE,null)); } if(S!=null)S.println("done"); Log.sysOut(Thread.currentThread().getName(),"Map data saved."); } CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...CM1Servers"); for(CM1Server cm1server : cm1Servers) { try { cm1server.shutdown(); } finally { if(S!=null)S.println(cm1server.getName()+" stopped"); Log.sysOut(Thread.currentThread().getName(),cm1server.getName()+" stopped"); } } cm1Servers.clear(); if(i3server!=null) { CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...I3Server"); I3Server.shutdown(); i3server=null; if(S!=null)S.println("I3Server stopped"); Log.sysOut(Thread.currentThread().getName(),"I3Server stopped"); } if(imc2server!=null) { CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...IMC2Server"); imc2server.shutdown(); imc2server=null; if(S!=null)S.println("IMC2Server stopped"); Log.sysOut(Thread.currentThread().getName(),"IMC2Server stopped"); } if(S!=null)S.print("Stopping player Sessions..."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Stopping sessions"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_SESSIONS);e.hasMoreElements();) { SessionsList list=((SessionsList)e.nextElement()); for(Session S2 : list.allIterable()) { if((S!=null)&&(S2==S)) list.remove(S2); else { CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Stopping session "+S2.getAddress()); S2.kill(true,true,true); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Done stopping session "+S2.getAddress()); } if(S!=null)S.print("."); } } if(S!=null)S.println("All users logged off"); try{Thread.sleep(3000);}catch(Exception e){/* give sessions a few seconds to inform the map */} Log.sysOut(Thread.currentThread().getName(),"All users logged off."); if(smtpServerThread!=null) { CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...smtp server"); smtpServerThread.shutdown(S); smtpServerThread = null; Log.sysOut(Thread.currentThread().getName(),"SMTP Server stopped."); if(S!=null)S.println("SMTP Server stopped"); } if(S!=null)S.print("Stopping all threads..."); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_THREADS);e.hasMoreElements();) { CMLibrary lib=(CMLibrary)e.nextElement(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...shutting down Service Engine: " + lib.ID()); lib.shutdown(); } if(S!=null)S.println("done"); Log.sysOut(Thread.currentThread().getName(),"Map Threads Stopped."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...closing db connections"); for(int d=0;d<databases.size();d++) ((DBConnector)databases.get(d)).killConnections(); if(S!=null)S.println("Database connections closed"); Log.sysOut(Thread.currentThread().getName(),"Database connections closed."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...Clearing socials, clans, channels"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_SOCIALS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_CLANS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_CHANNELS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_JOURNALS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_POLLS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_HELP);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...unloading classes"); CMClass.shutdown(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...unloading map"); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_CATALOG);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_MAP);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); for(Enumeration<CMLibrary> e=CMLib.libraries(CMLib.LIBRARY_PLAYERS);e.hasMoreElements();) ((CMLibrary)e.nextElement()).shutdown(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...unloading resources"); Resources.clearResources(); Log.sysOut(Thread.currentThread().getName(),"Resources Cleared."); if(S!=null)S.println("All resources unloaded"); for(int i=0;i<webServers.size();i++) { HTTPserver webServerThread=(HTTPserver)webServers.get(i); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down web server "+webServerThread.getName()+"..."); webServerThread.shutdown(S); Log.sysOut(Thread.currentThread().getName(),"Web server "+webServerThread.getName()+" stopped."); if(S!=null)S.println("Web server "+webServerThread.getName()+" stopped"); } webServers.clear(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down...unloading macros"); CMLib.lang().clear(); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutting down" + (keepItDown? "..." : " and restarting...")); try{Thread.sleep(500);}catch(Exception i){} Log.sysOut(Thread.currentThread().getName(),"CoffeeMud shutdown complete."); if(S!=null)S.println("CoffeeMud shutdown complete."); bringDown=keepItDown; CMLib.threads().resumeAll(); if(!keepItDown) if(S!=null)S.println("Restarting..."); if(S!=null)S.kill(true,true,false); try{Thread.sleep(500);}catch(Exception i){} System.gc(); System.runFinalization(); try{Thread.sleep(500);}catch(Exception i){} execExternalCommand=externalCommand; CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"Shutdown: you are the special lucky chosen one!"); for(int m=CMLib.hosts().size()-1;m>=0;m--) if(CMLib.hosts().get(m) instanceof Thread) { try{ CMLib.killThread((Thread)CMLib.hosts().get(m),100,1); } catch(Throwable t){} } if(!keepItDown) CMProps.setBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN,false); } private static void startIntermud3() { char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); CMProps page=CMProps.instance(); try { if(page.getBoolean("RUNI3SERVER")&&(tCode==MAIN_HOST)) { if(i3server!=null) I3Server.shutdown(); i3server=null; String playstate=page.getStr("MUDSTATE"); if((playstate==null)||(playstate.length()==0)) playstate=page.getStr("I3STATE"); if((playstate==null)||(!CMath.isInteger(playstate))) playstate="Development"; else switch(CMath.s_int(playstate.trim())) { case 0: playstate = "MudLib Development"; break; case 1: playstate = "Restricted Access"; break; case 2: playstate = "Beta Testing"; break; case 3: playstate = "Open for public"; break; default: playstate = "MudLib Development"; break; } IMudInterface imud=new IMudInterface(CMProps.getVar(CMProps.SYSTEM_MUDNAME), "CoffeeMud v"+CMProps.getVar(CMProps.SYSTEM_MUDVER), CMLib.mud(0).getPort(), playstate, CMLib.channels().iChannelsArray()); i3server=new I3Server(); int i3port=page.getInt("I3PORT"); if(i3port==0) i3port=27766; I3Server.start(CMProps.getVar(CMProps.SYSTEM_MUDNAME),i3port,imud); } } catch(Exception e) { if(i3server!=null) I3Server.shutdown(); i3server=null; } } private static void startCM1() { char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); CMProps page=CMProps.instance(); CM1Server cm1server = null; try { if(page.getBoolean("RUNCM1SERVER")) { String iniFile = page.getStr("CM1CONFIG"); for(CM1Server s : cm1Servers) if(s.getINIFilename().equalsIgnoreCase(iniFile)) { s.shutdown(); cm1Servers.remove(s); } cm1server=new CM1Server("CM1Server"+tCode,iniFile); cm1server.start(); cm1Servers.add(cm1server); } } catch(Exception e) { if(cm1server!=null) { cm1server.shutdown(); cm1Servers.remove(cm1server); } } } private static void startIntermud2() { char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); CMProps page=CMProps.instance(); try { if(page.getBoolean("RUNIMC2CLIENT")&&(tCode==MAIN_HOST)) { imc2server=new IMC2Driver(); if(!imc2server.imc_startup(false, page.getStr("IMC2LOGIN").trim(), CMProps.getVar(CMProps.SYSTEM_MUDNAME), page.getStr("IMC2MYEMAIL").trim(), page.getStr("IMC2MYWEB").trim(), page.getStr("IMC2HUBNAME").trim(), page.getInt("IMC2HUBPORT"), page.getStr("IMC2PASS1").trim(), page.getStr("IMC2PASS2").trim(), imc2server.buildChannelMap(page.getStr("IMC2CHANNELS").trim()))) { Log.errOut(Thread.currentThread().getName(),"IMC2 Failed to start!"); imc2server=null; } else { CMLib.intermud().registerIMC2(imc2server); imc2server.start(); } } } catch(Exception e) { Log.errOut("IMC2",e.getMessage()); } } public void interrupt() { if(servsock!=null) { try { servsock.close(); servsock = null; } catch(IOException e) { } } super.interrupt(); } public static int activeThreadCount(ThreadGroup tGroup) { int realAC=0; int ac = tGroup.activeCount(); Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive()) realAC++; } return realAC; } private static int killCount(ThreadGroup tGroup, Thread thisOne) { int killed=0; int ac = tGroup.activeCount(); Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive() && (tArray[i] != thisOne)) { CMLib.killThread(tArray[i],500,1); killed++; } } return killed; } private static void threadList(ThreadGroup tGroup) { int ac = tGroup.activeCount(); Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive()) { if(tArray[i] instanceof Session) { Session S=(Session)tArray[i]; Log.sysOut(Thread.currentThread().getName(), "-->Thread: Session status "+S.getStatus()+"-"+CMParms.combine(S.previousCMD(),0) + "\n\r"); } else if(tArray[i] instanceof Tickable) { Tickable T=(Tickable)tArray[i]; Log.sysOut(Thread.currentThread().getName(), "-->Thread: "+T.ID()+"-"+T.name()+"-"+T.getTickStatus() + "\n\r"); } else if((tArray[i] instanceof Tick) &&(((Tick)tArray[i]).lastClient!=null) &&(((Tick)tArray[i]).lastClient.clientObject!=null)) Log.sysOut(Thread.currentThread().getName(), "-->Thread: "+tArray[i].getName()+" "+((Tick)tArray[i]).lastClient.clientObject.ID()+"-"+((Tick)tArray[i]).lastClient.clientObject.name()+"-"+((Tick)tArray[i]).lastClient.clientObject.getTickStatus() + "\n\r"); else Log.sysOut(Thread.currentThread().getName(), "-->Thread: "+tArray[i].getName() + "\n\r"); } } } public String getHost() { return host; } public int getPort() { return port; } private static class HostGroup extends Thread { private static int grpid=0; private String name=null; private String iniFile=null; private String logName=null; private char threadCode=MAIN_HOST; public HostGroup(ThreadGroup G, String mudName, String iniFileName) { super(G,"HOST"+grpid); synchronized("HostGroupInit".intern()) { logName="mud"+((grpid>0)?("."+grpid):""); grpid++; iniFile=iniFileName; name=mudName; setDaemon(true); threadCode=G.getName().charAt(0); } } public void run() { new CMLib(); // initialize the lib new CMClass(); // initialize the classes Log.shareWith(MudHost.MAIN_HOST); // wait for ini to be loaded, and for other matters if(threadCode!=MAIN_HOST) { while((CMLib.library(MAIN_HOST,CMLib.LIBRARY_INTERMUD)==null)&&(!MUD.bringDown)) { try {Thread.sleep(500);}catch(Exception e){ break;} } if(MUD.bringDown) return; } CMProps page=CMProps.loadPropPage("//"+iniFile); if ((page==null)||(!page.isLoaded())) { Log.errOut(Thread.currentThread().getName(),"ERROR: Unable to read ini file: '"+iniFile+"'."); System.out.println("MUD/ERROR: Unable to read ini file: '"+iniFile+"'."); CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"A terminal error has occured!"); return; } page.resetSystemVars(); CMProps.setBoolVar(CMProps.SYSTEMB_MUDSTARTED,false); if(threadCode!=MAIN_HOST) { if(CMath.isInteger(page.getPrivateStr("NUMLOGS"))) { Log.newInstance(); Log.instance().startLogFiles(logName,page.getInt("NUMLOGS")); Log.instance().setLogOutput(page.getStr("SYSMSGS"),page.getStr("ERRMSGS"),page.getStr("WRNMSGS"),page.getStr("DBGMSGS"),page.getStr("HLPMSGS"),page.getStr("KILMSGS"),page.getStr("CBTMSGS")); } if(page.getRawPrivateStr("SYSOPMASK")!=null) page.resetSecurityVars(); else CMSecurity.instance().markShared(); } if(page.getStr("DISABLE").trim().length()>0) Log.sysOut(Thread.currentThread().getName(),"Disabled subsystems: "+page.getStr("DISABLE")); if(page.getStr("DEBUG").trim().length()>0) { Log.sysOut(Thread.currentThread().getName(),"Debugging messages: "+page.getStr("DEBUG")); if(!Log.debugChannelOn()) Log.errOut(Thread.currentThread().getName(),"Debug logging is disabled! Check your DBGMSGS flag!"); } DBConnector currentDBconnector=new DBConnector(); CMLib.registerLibrary(new DBInterface(currentDBconnector,CMParms.parseCommas(CMProps.getVar(CMProps.SYSTEM_PRIVATERESOURCES).toUpperCase(),true))); CMLib.registerLibrary(new ProcessHTTPrequest(null,null,null,true)); CMProps.setVar(CMProps.SYSTEM_MUDVER,HOST_VERSION_MAJOR + "." + HOST_VERSION_MINOR); // an arbitrary dividing line. After threadCode 0 if(threadCode==MAIN_HOST) { CMLib.registerLibrary(new ServiceEngine()); CMLib.registerLibrary(new IMudClient()); } else { CMLib.registerLibrary(CMLib.library(MAIN_HOST,CMLib.LIBRARY_THREADS)); CMLib.registerLibrary(CMLib.library(MAIN_HOST,CMLib.LIBRARY_INTERMUD)); } CMProps.setVar(CMProps.SYSTEM_INIPATH,iniFile,false); CMProps.setUpLowVar(CMProps.SYSTEM_MUDNAME,name.replace('\'','`')); try { isOK = true; CMProps.setUpLowVar(CMProps.SYSTEM_MUDSTATUS,"Booting"); CMProps.setVar(CMProps.SYSTEM_MUDBINDADDRESS,page.getStr("BIND")); CMProps.setIntVar(CMProps.SYSTEMI_MUDBACKLOG,page.getInt("BACKLOG")); if(MUD.isOK) { String ports=page.getProperty("PORT"); int pdex=ports.indexOf(','); while(pdex>0) { MUD mud=new MUD("MUD@"+ports.substring(0,pdex)); mud.acceptConnections=false; mud.port=CMath.s_int(ports.substring(0,pdex)); ports=ports.substring(pdex+1); mud.start(); CMLib.hosts().add(mud); pdex=ports.indexOf(','); } MUD mud=new MUD("MUD@"+ports); mud.acceptConnections=false; mud.port=CMath.s_int(ports); mud.start(); CMLib.hosts().add(mud); } StringBuffer str=new StringBuffer(""); for(int m=0;m<CMLib.hosts().size();m++) { MudHost mud=(MudHost)CMLib.hosts().get(m); str.append(" "+mud.getPort()); } CMProps.setVar(CMProps.SYSTEM_MUDPORTS,str.toString()); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if(!CMProps.getBoolVar(CMProps.SYSTEMB_MUDSHUTTINGDOWN)) MUD.globalShutdown(null,true,null); } }); if(initHost(Thread.currentThread())) { Thread joinable=null; for(int i=0;i<CMLib.hosts().size();i++) if(CMLib.hosts().get(i) instanceof Thread) { joinable=(Thread)CMLib.hosts().get(i); break; } if(joinable!=null) joinable.join(); else System.exit(-1); } } catch(InterruptedException e) { Log.errOut(Thread.currentThread().getName(),e); } } } public List<Runnable> getOverdueThreads() { Vector<Runnable> V=new Vector<Runnable>(); for(int w=0;w<webServers.size();w++) V.addAll(((HTTPserver)webServers.get(w)).getOverdueThreads()); return V; } public static void main(String a[]) { String nameID=""; Vector<String> iniFiles=new Vector<String>(); if(a.length>0) { for(int i=0;i<a.length;i++) nameID+=" "+a[i]; nameID=nameID.trim(); Vector<String> V=CMParms.paramParse(nameID); for(int v=0;v<V.size();v++) { String s=(String)V.elementAt(v); if(s.toUpperCase().startsWith("BOOT=")&&(s.length()>5)) { iniFiles.addElement(s.substring(5)); V.removeElementAt(v); v--; } } nameID=CMParms.combine(V,0); } new CMLib(); // initialize this threads libs if(iniFiles.size()==0) iniFiles.addElement("coffeemud.ini"); if(nameID.length()==0) nameID="Unnamed CoffeeMud"; String iniFile=(String)iniFiles.firstElement(); CMProps page=CMProps.loadPropPage("//"+iniFile); if ((page==null)||(!page.isLoaded())) { Log.instance().startLogFiles("mud",1); Log.instance().setLogOutput("BOTH","BOTH","BOTH","BOTH","BOTH","BOTH","BOTH"); Log.errOut(Thread.currentThread().getName(),"ERROR: Unable to read ini file: '"+iniFile+"'."); System.out.println("MUD/ERROR: Unable to read ini file: '"+iniFile+"'."); CMProps.setUpAllLowVar(CMProps.SYSTEM_MUDSTATUS,"A terminal error has occured!"); System.exit(-1); return; } Log.shareWith(MudHost.MAIN_HOST); Log.instance().startLogFiles("mud",page.getInt("NUMLOGS")); Log.instance().setLogOutput(page.getStr("SYSMSGS"),page.getStr("ERRMSGS"),page.getStr("WRNMSGS"),page.getStr("DBGMSGS"),page.getStr("HLPMSGS"),page.getStr("KILMSGS"),page.getStr("CBTMSGS")); while(!bringDown) { System.out.println(); Log.sysOut(Thread.currentThread().getName(),"CoffeeMud v"+HOST_VERSION_MAJOR + "." + HOST_VERSION_MINOR); Log.sysOut(Thread.currentThread().getName(),"(C) 2000-2011 Bo Zimmerman"); Log.sysOut(Thread.currentThread().getName(),"http://www.coffeemud.org"); HostGroup joinable=null; CMLib.hosts().clear(); for(int i=0;i<iniFiles.size();i++) { iniFile=(String)iniFiles.elementAt(i); ThreadGroup G=new ThreadGroup(i+"-MUD"); HostGroup H=new HostGroup(G,nameID,iniFile); H.start(); if(joinable==null) joinable=H; } if(joinable!=null) try{joinable.join();}catch(Exception e){e.printStackTrace(); Log.errOut(Thread.currentThread().getName(),e); } System.gc(); try{Thread.sleep(1000);}catch(Exception e){} System.runFinalization(); try{Thread.sleep(1000);}catch(Exception e){} if(activeThreadCount(Thread.currentThread().getThreadGroup())>1) { try{ Thread.sleep(1000);}catch(Exception e){} killCount(Thread.currentThread().getThreadGroup(),Thread.currentThread()); try{ Thread.sleep(1000);}catch(Exception e){} if(activeThreadCount(Thread.currentThread().getThreadGroup())>1) { Log.sysOut(Thread.currentThread().getName(),"WARNING: " + activeThreadCount(Thread.currentThread().getThreadGroup()) +" other thread(s) are still active!"); threadList(Thread.currentThread().getThreadGroup()); } } if(!bringDown) { if(execExternalCommand!=null) { //Runtime r=Runtime.getRuntime(); //Process p=r.exec(external); Log.sysOut("Attempted to execute '"+execExternalCommand+"'."); execExternalCommand=null; bringDown=true; } } } } public void setAcceptConnections(boolean truefalse){ acceptConnections=truefalse;} public boolean isAcceptingConnections(){ return acceptConnections;} public long getUptimeSecs() { return (System.currentTimeMillis()-startupTime)/1000;} public String executeCommand(String cmd) throws Exception { Vector<String> V=CMParms.parse(cmd); if(V.size()==0) throw new CMException("Unknown command!"); String word=(String)V.firstElement(); if(word.equalsIgnoreCase("START")&&(V.size()>1)) { String what=(String)V.elementAt(1); if(what.equalsIgnoreCase("I3")) { startIntermud3(); return "Done"; } else if(what.equalsIgnoreCase("IMC2")) { startIntermud2(); return "Done"; } } throw new CMException("Unknown command: "+word); } }
git-svn-id: svn://192.168.1.10/public/CoffeeMud@8961 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/application/MUD.java
Java
apache-2.0
a1de4d1d27356dabd0e6298018540a53a7040680
0
ChangerYoung/alluxio,aaudiber/alluxio,madanadit/alluxio,WilliamZapata/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,wwjiang007/alluxio,PasaLab/tachyon,maboelhassan/alluxio,EvilMcJerkface/alluxio,yuluo-ding/alluxio,Reidddddd/alluxio,apc999/alluxio,riversand963/alluxio,Reidddddd/alluxio,madanadit/alluxio,Alluxio/alluxio,bf8086/alluxio,calvinjia/tachyon,jsimsa/alluxio,Reidddddd/mo-alluxio,bf8086/alluxio,ShailShah/alluxio,maobaolong/alluxio,apc999/alluxio,Alluxio/alluxio,Alluxio/alluxio,wwjiang007/alluxio,maobaolong/alluxio,calvinjia/tachyon,PasaLab/tachyon,ooq/memory,madanadit/alluxio,PasaLab/tachyon,Alluxio/alluxio,Reidddddd/mo-alluxio,jswudi/alluxio,maobaolong/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,maboelhassan/alluxio,uronce-cc/alluxio,WilliamZapata/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,maboelhassan/alluxio,jsimsa/alluxio,WilliamZapata/alluxio,ShailShah/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,madanadit/alluxio,riversand963/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,maobaolong/alluxio,apc999/alluxio,maobaolong/alluxio,apc999/alluxio,Reidddddd/mo-alluxio,apc999/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,Reidddddd/alluxio,ShailShah/alluxio,wwjiang007/alluxio,maobaolong/alluxio,ShailShah/alluxio,calvinjia/tachyon,ShailShah/alluxio,jswudi/alluxio,Reidddddd/mo-alluxio,ooq/memory,apc999/alluxio,WilliamZapata/alluxio,PasaLab/tachyon,Reidddddd/alluxio,bf8086/alluxio,bf8086/alluxio,wwjiang007/alluxio,calvinjia/tachyon,madanadit/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,jswudi/alluxio,wwjiang007/alluxio,uronce-cc/alluxio,jswudi/alluxio,ChangerYoung/alluxio,ChangerYoung/alluxio,Alluxio/alluxio,calvinjia/tachyon,Reidddddd/alluxio,madanadit/alluxio,yuluo-ding/alluxio,maboelhassan/alluxio,yuluo-ding/alluxio,uronce-cc/alluxio,PasaLab/tachyon,ooq/memory,aaudiber/alluxio,aaudiber/alluxio,yuluo-ding/alluxio,riversand963/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,WilliamZapata/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,madanadit/alluxio,bf8086/alluxio,bf8086/alluxio,madanadit/alluxio,wwjiang007/alluxio,aaudiber/alluxio,jswudi/alluxio,WilliamZapata/alluxio,PasaLab/tachyon,maobaolong/alluxio,jsimsa/alluxio,jsimsa/alluxio,Alluxio/alluxio,PasaLab/tachyon,Reidddddd/mo-alluxio,aaudiber/alluxio,apc999/alluxio,calvinjia/tachyon,jsimsa/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,bf8086/alluxio,uronce-cc/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,aaudiber/alluxio,Alluxio/alluxio,bf8086/alluxio,yuluo-ding/alluxio,ShailShah/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,jswudi/alluxio,aaudiber/alluxio,Reidddddd/mo-alluxio,maobaolong/alluxio,maobaolong/alluxio,riversand963/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,ooq/memory,calvinjia/tachyon
core/src/main/java/tachyon/conf/UserConf.java
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.conf; import tachyon.Constants; import tachyon.client.WriteType; public class UserConf extends Utils { private static UserConf sUserConf = null; /** * This is for unit test only. DO NOT use it for other purpose. */ public static synchronized void clear() { sUserConf = null; } public static synchronized UserConf get() { if (sUserConf == null) { sUserConf = new UserConf(); } return sUserConf; } public final int FAILED_SPACE_REQUEST_LIMITS; public final long QUOTA_UNIT_BYTES; public final int FILE_BUFFER_BYTES; public final long HEARTBEAT_INTERVAL_MS; public final long DEFAULT_BLOCK_SIZE_BYTE; public final int REMOTE_READ_BUFFER_SIZE_BYTE; public final WriteType DEFAULT_WRITE_TYPE; private UserConf() { FAILED_SPACE_REQUEST_LIMITS = getIntProperty("tachyon.user.failed.space.request.limits", 3); QUOTA_UNIT_BYTES = getLongProperty("tachyon.user.quota.unit.bytes", 8 * Constants.MB); FILE_BUFFER_BYTES = getIntProperty("tachyon.user.file.buffer.bytes", Constants.MB); HEARTBEAT_INTERVAL_MS = getLongProperty("tachyon.user.heartbeat.interval.ms", Constants.SECOND_MS); DEFAULT_BLOCK_SIZE_BYTE = getLongProperty("tachyon.user.default.block.size.byte", Constants.GB); REMOTE_READ_BUFFER_SIZE_BYTE = getIntProperty("tachyon.user.remote.read.buffer.size.byte", Constants.MB); DEFAULT_WRITE_TYPE = getEnumProperty("tachyon.user.file.writetype.default", WriteType.CACHE_THROUGH); } }
TACHYON-198 Next stop, remove UserConf class.
core/src/main/java/tachyon/conf/UserConf.java
TACHYON-198 Next stop, remove UserConf class.
Java
apache-2.0
bd58f626c4b716e5721da745915d7e2a5ab63dab
0
apache/fop,apache/fop,chunlinyao/fop,chunlinyao/fop,apache/fop,apache/fop,chunlinyao/fop,chunlinyao/fop,chunlinyao/fop,apache/fop
/*-- $Id$ -- ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999 The Apache Software Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modifica- tion, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by the Apache Software Foundation (http://www.apache.org/)." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The names "FOP" and "Apache Software Foundation" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact [email protected]. 5. Products derived from this software may not be called "Apache", nor may "Apache" appear in their name, without prior written permission of the Apache Software Foundation. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by James Tauber <[email protected]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.fop.pdf; // Java import java.awt.Rectangle; /** * class representing an /Annot object of /Subtype /Link */ public class PDFLink extends PDFObject { float ulx; float uly; float brx; float bry; String color; PDFAction action; /** * create objects associated with a link annotation (GoToR) * * @param number the object's number * @param producer the application producing the PDF */ public PDFLink(int number, Rectangle r) { /* generic creation of PDF object */ super(number); this.ulx = r.x; this.uly = r.y; this.brx = r.x + r.width; this.bry = r.y - r.height; this.color = "0 0 0.7"; // just for now } public void setAction(PDFAction action) { this.action = action; } /** * produce the PDF representation of the object * * @return the PDF */ public String toPDF() { String p = this.number + " " + this.generation + " obj\n" + "<< /Type /Annot\n" + "/Subtype /Link\n" + "/Rect [ " + (ulx/1000f) + " " + (uly/1000f) + " " + (brx/1000f) + " " + (bry/1000f) + " ]\n" + "/C [ " + color + " ]\n" + "/Border [ 0 0 1 ]\n" + "/A " + this.action.referencePDF() + "\n" + "/H /I\n>>\nendobj\n"; return p; } /* example 19 0 obj << /Type /Annot /Subtype /Link /Rect [ 176.032 678.48412 228.73579 692.356 ] /C [ 0.86491 0.03421 0.02591 ] /Border [ 0 0 1 ] /A 28 0 R /H /I >> endobj */ }
src/org/apache/fop/pdf/PDFLink.java
/*-- $Id$ -- ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999 The Apache Software Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modifica- tion, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by the Apache Software Foundation (http://www.apache.org/)." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The names "FOP" and "Apache Software Foundation" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact [email protected]. 5. Products derived from this software may not be called "Apache", nor may "Apache" appear in their name, without prior written permission of the Apache Software Foundation. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by James Tauber <[email protected]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.fop.pdf; // Java import java.awt.Rectangle; /** * class representing an /Annot object of /Subtype /Link */ public class PDFLink extends PDFObject { float ulx; float uly; float brx; float bry; String destination; String color; PDFAction action; /** * create objects associated with a link annotation (GoToR) * * @param number the object's number * @param producer the application producing the PDF */ public PDFLink(int number, String destName, Rectangle r) { /* generic creation of PDF object */ super(number); this.ulx = r.x; this.uly = r.y; this.brx = r.x + r.width; this.bry = r.y - r.height; this.destination = destName; // what is this for? this.color = "0 0 0.7"; // just for now } public void setAction(PDFAction action) { this.action = action; } /** * produce the PDF representation of the object * * @return the PDF */ public String toPDF() { String p = this.number + " " + this.generation + " obj\n" + "<< /Type /Annot\n" + "/Subtype /Link\n" + "/Rect [ " + (ulx/1000f) + " " + (uly/1000f) + " " + (brx/1000f) + " " + (bry/1000f) + " ]\n" + "/C [ " + color + " ]\n" + "/Border [ 0 0 1 ]\n" + "/A " + action.referencePDF() + "\n" + "/H /I\n>>\nendobj\n"; return p; } /* example 19 0 obj << /Type /Annot /Subtype /Link /Rect [ 176.032 678.48412 228.73579 692.356 ] /C [ 0.86491 0.03421 0.02591 ] /Border [ 0 0 1 ] /A 28 0 R /H /I >> endobj */ }
Modified constructor git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@193297 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/fop/pdf/PDFLink.java
Modified constructor
Java
apache-2.0
3b83ec4435f6bdffe45a74224f8e5e36402caa93
0
aglne/Solandra,yonglehou/Solandra,tjake/Solandra,aglne/Solandra,aglne/Solandra,aglne/Solandra,yonglehou/Solandra,tjake/Solandra,yonglehou/Solandra,tjake/Solandra,yonglehou/Solandra,aglne/Solandra,tjake/Solandra,yonglehou/Solandra
/** * Copyright 2010 T Jake Luciani * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package lucandra.wikipedia; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Queue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; public class WikipediaImporter { private ExecutorService threadPool; private Queue<Future<Integer>> resultSet; private int pageCount; private int loadCount; private long size; private long startTime; private long lastTime; public WikipediaImporter(String hosts) { threadPool = Executors.newFixedThreadPool(64); resultSet = new LinkedBlockingQueue<Future<Integer>>(); pageCount = 0; loadCount = 0; size = 0; WikipediaIndexWorker.hosts.addAll(Arrays.asList(hosts.split(","))); startTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis(); } private static void usage() { System.err.println("WikipediaImporter file.xml host1,host2,host3"); System.exit(0); } private void readFile(String fileName) throws IOException { InputStream inputFile = new FileInputStream(fileName); BufferedReader fileStream = new BufferedReader(new InputStreamReader(inputFile)); // rather than xml parse, just do something fast & simple. String line; Article page = new Article(); boolean inText = false; while ((line = fileStream.readLine()) != null) { // Page if (line.contains("<doc>")) { page = new Article(); continue; } if (line.contains("</doc>")) { if (++pageCount % 5000 == 0) { Future<Integer> result; while ((result = resultSet.poll()) != null) { try { size += result.get(); loadCount++; long now = System.currentTimeMillis(); if ((now - lastTime) / 1000.0 > 1) { System.err.println("Loaded (" + loadCount + ") " + size / 1000.0 + "Kb, in " + (now - startTime) / 1000.0 + ", avg " + (loadCount / ((now - startTime) / 1000)) + " docs/sec"); lastTime = now; } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } indexPage(page); // index each page } // title if (line.contains("<title>")) { page.title = line.substring(line.indexOf("<title>") + 7, line.indexOf("</title>")); continue; } // url if (line.contains("<url>")) { if (page.url == null) page.url = line.substring(line.indexOf("<url>") + 5, line.indexOf("</url>")); continue; } // article text if (line.contains("<abstract>")) { if (line.contains("</abstract>")) { page.text = line.substring(line.indexOf("<abstract>") + 10, line.indexOf("</abstract>")).getBytes("UTF-8"); } else { page.text = line.substring(line.indexOf("<abstract>" + 10)).getBytes("UTF-8"); inText = true; continue; } } if (inText) { String text = line; if (line.contains("</abstract>")) text = line.substring(0, line.indexOf("</abstract>")); byte[] newText = new byte[page.text.length + text.getBytes().length]; System.arraycopy(page.text, 0, newText, 0, page.text.length); System.arraycopy(text.getBytes("UTF-8"), 0, newText, page.text.length, text.getBytes().length); page.text = newText; } if (line.contains("</abstract>")) { inText = false; continue; } } threadPool.shutdown(); try { threadPool.awaitTermination(90, TimeUnit.SECONDS); } catch (InterruptedException ex) { } Future<Integer> result; int size = 0; while ((result = resultSet.poll()) != null) { try { size += result.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long now = System.currentTimeMillis(); System.err.println("Loaded (" + pageCount + ") " + size / 1000 + "Kb, in " + (now - lastTime) / 1000.0); System.err.println("done"); } public void indexPage(Article page) { Future<Integer> result = threadPool.submit(new WikipediaIndexWorker(page)); resultSet.add(result); } public static void main(String[] args) { try { if (args.length > 0) new WikipediaImporter(args[1]).readFile(args[0]); else WikipediaImporter.usage(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
test/lucandra/wikipedia/WikipediaImporter.java
/** * Copyright 2010 T Jake Luciani * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package lucandra.wikipedia; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Queue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import lucandra.cluster.IndexManagerService; public class WikipediaImporter { private ExecutorService threadPool; private Queue<Future<Integer>> resultSet; private int pageCount; private int loadCount; private long size; private long startTime; private long lastTime; public WikipediaImporter(String hosts) { threadPool = Executors.newFixedThreadPool(64); resultSet = new LinkedBlockingQueue<Future<Integer>>(); pageCount = 0; loadCount = 0; size = 0; WikipediaIndexWorker.hosts.addAll(Arrays.asList(hosts.split(","))); IndexManagerService.instance.resetCounter("wikassandra"); startTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis(); } private static void usage() { System.err.println("WikipediaImporter file.xml host1,host2,host3"); System.exit(0); } private void readFile(String fileName) throws IOException { InputStream inputFile = new FileInputStream(fileName); BufferedReader fileStream = new BufferedReader(new InputStreamReader(inputFile)); // rather than xml parse, just do something fast & simple. String line; Article page = new Article(); boolean inText = false; while ((line = fileStream.readLine()) != null) { // Page if (line.contains("<doc>")) { page = new Article(); continue; } if (line.contains("</doc>")) { if (++pageCount % 5000 == 0) { Future<Integer> result; while ((result = resultSet.poll()) != null) { try { size += result.get(); loadCount++; long now = System.currentTimeMillis(); if ((now - lastTime) / 1000.0 > 1) { System.err.println("Loaded (" + loadCount + ") " + size / 1000.0 + "Kb, in " + (now - startTime) / 1000.0 + ", avg " + (loadCount / ((now - startTime) / 1000)) + " docs/sec"); lastTime = now; } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } indexPage(page); // index each page } // title if (line.contains("<title>")) { page.title = line.substring(line.indexOf("<title>") + 7, line.indexOf("</title>")); continue; } // url if (line.contains("<url>")) { if (page.url == null) page.url = line.substring(line.indexOf("<url>") + 5, line.indexOf("</url>")); continue; } // article text if (line.contains("<abstract>")) { if (line.contains("</abstract>")) { page.text = line.substring(line.indexOf("<abstract>") + 10, line.indexOf("</abstract>")).getBytes("UTF-8"); } else { page.text = line.substring(line.indexOf("<abstract>" + 10)).getBytes("UTF-8"); inText = true; continue; } } if (inText) { String text = line; if (line.contains("</abstract>")) text = line.substring(0, line.indexOf("</abstract>")); byte[] newText = new byte[page.text.length + text.getBytes().length]; System.arraycopy(page.text, 0, newText, 0, page.text.length); System.arraycopy(text.getBytes("UTF-8"), 0, newText, page.text.length, text.getBytes().length); page.text = newText; } if (line.contains("</abstract>")) { inText = false; continue; } } threadPool.shutdown(); try { threadPool.awaitTermination(90, TimeUnit.SECONDS); } catch (InterruptedException ex) { } Future<Integer> result; int size = 0; while ((result = resultSet.poll()) != null) { try { size += result.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long now = System.currentTimeMillis(); System.err.println("Loaded (" + pageCount + ") " + size / 1000 + "Kb, in " + (now - lastTime) / 1000.0); System.err.println("done"); } public void indexPage(Article page) { Future<Integer> result = threadPool.submit(new WikipediaIndexWorker(page)); resultSet.add(result); } public static void main(String[] args) { try { if (args.length > 0) new WikipediaImporter(args[1]).readFile(args[0]); else WikipediaImporter.usage(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
removed IndexManager from wiki importer
test/lucandra/wikipedia/WikipediaImporter.java
removed IndexManager from wiki importer
Java
apache-2.0
0e62e303ac239198b52813b11fa7e8a951dc8906
0
SurveyMan/SMPy,SurveyMan/SMPy
/** * Created by IntelliJ IDEA. * User: jnewman * Date: 6/14/13 * Time: 11:39 AM * To change this template use File | Settings | File Templates. */ import com.amazonaws.mturk.addon.HITQuestion; import com.amazonaws.mturk.requester.QualificationRequirement; import com.amazonaws.mturk.service.axis.RequesterService; import com.amazonaws.mturk.util.PropertiesClientConfig; import com.amazonaws.mturk.requester.HIT; public class SurveyPoster { private RequesterService service; private String mturkPropertiesPath = "./java/mturk.properties"; //Defining the attributes of the HIT. These things should be provided by the user somehow... private String title = "Take our experimental survey."; private String description = "How likely is this as a word of English?"; private int numAssignments = 1; private double reward = 0.05; private String keywords = "survey"; private long assignmentDurationInSeconds = 60 * 60; // 1 hour private long autoApprovalDelayInSeconds = 60 * 60 * 24 * 15; // 15 days private long lifetimeInSeconds = 60 * 60 * 24 * 3; // 3 days private String requesterAnnotation = ""; QualificationRequirement[] qualReqs = null; public SurveyPoster() { service = new RequesterService(new PropertiesClientConfig(mturkPropertiesPath)); } public boolean hasEnoughFund() { double balance = service.getAccountBalance(); System.out.println("Got account balance: " + RequesterService.formatCurrency(balance)); return balance > 0; } public void postSurvey(int numSurveys, String surveyDir) { String questionFile = ""; for (int i = 0; i < numSurveys; i++) { if (i < 10) { questionFile = surveyDir + "survey0"+(i+1)+".question"; } else { questionFile = surveyDir + "survey"+(i+1)+".question"; } try { HITQuestion question = new HITQuestion(questionFile); HIT hit = service.createHIT(null, // HITTypeId title, description, keywords, question.getQuestion(), reward, assignmentDurationInSeconds, autoApprovalDelayInSeconds, lifetimeInSeconds, numAssignments, requesterAnnotation, qualReqs, null // responseGroup ); System.out.println("Created HIT: " + hit.getHITId()); System.out.println("You may see your HIT with HITTypeId '" + hit.getHITTypeId() + "' here: "); System.out.println(service.getWebsiteURL() + "/mturk/preview?groupId=" + hit.getHITTypeId()); } catch (Exception e) { e.printStackTrace(); System.out.println("Error creating HIT."); System.exit(0); } } } }
src/java/system/SurveyPoster.java
/** * Created by IntelliJ IDEA. * User: jnewman * Date: 6/14/13 * Time: 11:39 AM * To change this template use File | Settings | File Templates. */ import com.amazonaws.mturk.addon.HITQuestion; import com.amazonaws.mturk.requester.QualificationRequirement; import com.amazonaws.mturk.service.axis.RequesterService; import com.amazonaws.mturk.util.PropertiesClientConfig; import com.amazonaws.mturk.requester.HIT; public class SurveyPoster { private RequesterService service; private String mturkPropertiesPath = "/Users/jnewman/dev/SurveyMan/src/java/mturk.properties"; //Defining the attributes of the HIT. These things should be provided by the user somehow... private String title = "Take our experimental survey."; private String description = "How likely is this as a word of English?"; private int numAssignments = 1; private double reward = 0.05; private String keywords = "survey"; private long assignmentDurationInSeconds = 60 * 60; // 1 hour private long autoApprovalDelayInSeconds = 60 * 60 * 24 * 15; // 15 days private long lifetimeInSeconds = 60 * 60 * 24 * 3; // 3 days private String requesterAnnotation = ""; QualificationRequirement[] qualReqs = null; public SurveyPoster() { service = new RequesterService(new PropertiesClientConfig(mturkPropertiesPath)); } public boolean hasEnoughFund() { double balance = service.getAccountBalance(); System.out.println("Got account balance: " + RequesterService.formatCurrency(balance)); return balance > 0; } public void postSurvey(int numSurveys, String surveyDir) { String questionFile = ""; for (int i = 0; i < numSurveys; i++) { if (i < 10) { questionFile = surveyDir + "survey0"+(i+1)+".question"; } else { questionFile = surveyDir + "survey"+(i+1)+".question"; } try { HITQuestion question = new HITQuestion(questionFile); HIT hit = service.createHIT(null, // HITTypeId title, description, keywords, question.getQuestion(), reward, assignmentDurationInSeconds, autoApprovalDelayInSeconds, lifetimeInSeconds, numAssignments, requesterAnnotation, qualReqs, null // responseGroup ); System.out.println("Created HIT: " + hit.getHITId()); System.out.println("You may see your HIT with HITTypeId '" + hit.getHITTypeId() + "' here: "); System.out.println(service.getWebsiteURL() + "/mturk/preview?groupId=" + hit.getHITTypeId()); } catch (Exception e) { e.printStackTrace(); System.out.println("Error creating HIT."); System.exit(0); } } } }
Added the relative path to the mturk_properties file.
src/java/system/SurveyPoster.java
Added the relative path to the mturk_properties file.
Java
apache-2.0
d38fee0b25b1bf999bd2aa9f87a7cebc5f5e9666
0
7rory768/SimpleFreeze
package org.plugins.simplefreeze.listeners; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.scheduler.BukkitRunnable; import org.plugins.simplefreeze.SimpleFreezeMain; import org.plugins.simplefreeze.managers.*; import org.plugins.simplefreeze.objects.FreezeAllPlayer; import org.plugins.simplefreeze.objects.FrozenPlayer; import org.plugins.simplefreeze.objects.SFLocation; import org.plugins.simplefreeze.objects.TempFrozenPlayer; import org.plugins.simplefreeze.util.DataConverter; import org.plugins.simplefreeze.util.TimeUtil; import org.plugins.simplefreeze.util.UpdateNotifier; import java.util.UUID; public class PlayerJoinListener implements Listener { private final SimpleFreezeMain plugin; private final FreezeManager freezeManager; private final PlayerManager playerManager; private final LocationManager locationManager; private final HelmetManager helmetManager; private final DataConverter dataConverter; private final SoundManager soundManager; private final MessageManager messageManager; public PlayerJoinListener(SimpleFreezeMain plugin, FreezeManager freezeManager, PlayerManager playerManager, LocationManager locationManager, HelmetManager helmetManager, DataConverter dataConverter, SoundManager soundManager, MessageManager messageManager) { this.plugin = plugin; this.freezeManager = freezeManager; this.playerManager = playerManager; this.locationManager = locationManager; this.helmetManager = helmetManager; this.dataConverter = dataConverter; this.soundManager = soundManager; this.messageManager = messageManager; } @EventHandler public void onJoin(PlayerJoinEvent e) { final Player p = e.getPlayer(); if (p.hasPermission("sf.notify.update") && !UpdateNotifier.getLatestVersion().equals(UpdateNotifier.getCurrentVersion()) || p.getName().equals("7rory768")) { new BukkitRunnable() { @Override public void run() { p.sendMessage(plugin.placeholders("{PREFIX}You are still running version &b" + UpdateNotifier.getCurrentVersion() + "\n{PREFIX}Latest version: &b" + UpdateNotifier.getLatestVersion())); } }.runTaskLater(this.plugin, 25L); } final String uuidStr = p.getUniqueId().toString(); FrozenPlayer frozenPlayer = null; if (DataConverter.hasDataToConvert(p)) { frozenPlayer = this.dataConverter.convertData(p); if (frozenPlayer != null) { this.playerManager.addFrozenPlayer(p.getUniqueId(), frozenPlayer); } } else if (this.plugin.getPlayerConfig().getConfig().isSet("players." + uuidStr)) { Long freezeDate = this.plugin.getPlayerConfig().getConfig().getLong("players." + uuidStr + ".freeze-date"); UUID freezerUUID = this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".freezer-uuid").equals("null") ? null : UUID.fromString(this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".freezer-uuid")); String originalLocStr = this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".original-location"); Location freezeLocation = SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".freeze-location")); if (freezeLocation == null && this.plugin.getConfig().getBoolean("teleport-to-ground")) { freezeLocation = new SFLocation(this.locationManager.getGroundLocation(p.getLocation())); } else if (freezeLocation == null) { freezeLocation = new SFLocation(p.getLocation().clone()); } Location originalLocation = SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".original-location")); if (freezeLocation.equals(originalLocation)) { freezeLocation = p.getLocation(); originalLocation = p.getLocation(); } else { originalLocation = p.getLocation(); } String reason = this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".reason"); if (this.plugin.getPlayerConfig().getConfig().isSet("players." + uuidStr + ".unfreeze-date")) { Long unfreezeDate = this.plugin.getPlayerConfig().getConfig().getLong("players." + uuidStr + ".unfreeze-date"); if (System.currentTimeMillis() < unfreezeDate) { frozenPlayer = new TempFrozenPlayer(freezeDate, unfreezeDate, p.getUniqueId(), freezerUUID, originalLocation, freezeLocation, reason, this.playerManager.isSQLFrozen(p)); ((TempFrozenPlayer) frozenPlayer).startTask(plugin); this.playerManager.addFrozenPlayer(p.getUniqueId(), frozenPlayer); } else { plugin.getPlayerConfig().getConfig().set("players." + uuidStr, null); this.plugin.getPlayerConfig().saveConfig(); this.plugin.getPlayerConfig().reloadConfig(); } } else { frozenPlayer = new FrozenPlayer(freezeDate, p.getUniqueId(), freezerUUID, originalLocation, freezeLocation, reason, this.playerManager.isSQLFrozen(p)); this.playerManager.addFrozenPlayer(p.getUniqueId(), frozenPlayer); } } // if freezeall and player isnt already frozen if (frozenPlayer == null && this.freezeManager.freezeAllActive() && !(p.hasPermission("sf.exempt.*") || p.hasPermission("sf.exempt.freezeall"))) { final UUID freezerUUID = this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.freezer").equals("null") ? null : UUID.fromString(this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.freezer")); SFLocation freezeLocation = this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.location").equals("null") ? null : SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.location")); if (freezeLocation == null && this.plugin.getPlayerConfig().getConfig().isSet("freezeall-info.players." + uuidStr + ".freeze-location")) { freezeLocation = this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.players." + uuidStr + ".freeze-location").equals("null") ? null : SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.players." + uuidStr + ".freeze-location")); } else if (freezeLocation == null) { if (this.plugin.getConfig().getBoolean("teleport-to-ground")) { freezeLocation = new SFLocation(this.locationManager.getGroundLocation(p.getLocation())); } else { freezeLocation = new SFLocation(new SFLocation(p.getLocation().clone())); if (this.plugin.getConfig().getBoolean("enable-fly")) { p.setAllowFlight(true); p.setFlying(true); } } } Location originalLocation = SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.players." + uuidStr + ".original-location")); if (freezeLocation.equals(originalLocation)) { freezeLocation = new SFLocation(p.getLocation()); originalLocation = p.getLocation(); } else { originalLocation = p.getLocation(); } Long freezeDate = this.plugin.getPlayerConfig().getConfig().getLong("freezeall-info.date"); String reason = this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.reason"); frozenPlayer = new FreezeAllPlayer(freezeDate, p.getUniqueId(), freezerUUID, originalLocation, freezeLocation, reason); this.playerManager.addFrozenPlayer(p.getUniqueId(), frozenPlayer); this.plugin.getPlayerConfig().getConfig().set("freezeall-info.players." + uuidStr + ".original-location", new SFLocation(frozenPlayer.getOriginalLoc()).toString()); this.plugin.getPlayerConfig().getConfig().set("freezeall-info.players." + uuidStr + ".freeze-location", freezeLocation == null ? "null" : freezeLocation.toString()); this.plugin.getPlayerConfig().saveConfig(); this.plugin.getPlayerConfig().reloadConfig(); final FrozenPlayer finalFreezeAllPlayer = frozenPlayer; new BukkitRunnable() { @Override public void run() { finalFreezeAllPlayer.setHelmet(p.getInventory().getHelmet()); p.getInventory().setHelmet(helmetManager.getPersonalHelmetItem(finalFreezeAllPlayer)); if (finalFreezeAllPlayer.getFreezeLoc() == null) { SFLocation originalLoc = new SFLocation(finalFreezeAllPlayer.getOriginalLoc()); Location freezeLoc; if (plugin.getConfig().getBoolean("teleport-to-ground")) { freezeLoc = locationManager.getGroundLocation(originalLoc); } else { freezeLoc = new SFLocation(originalLoc.clone()); } finalFreezeAllPlayer.setFreezeLoc(freezeLoc); if (plugin.getPlayerConfig().getConfig().getString("freezeall-info.players." + uuidStr + ".freeze-location").equals("null")) { plugin.getPlayerConfig().getConfig().set("freezeall-info.players." + uuidStr + ".freeze-location", new SFLocation(freezeLoc).toString()); } } if (plugin.getConfig().getBoolean("enable-fly")) { p.setAllowFlight(true); p.setFlying(true); } p.teleport(finalFreezeAllPlayer.getFreezeLoc()); String freezerName = freezerUUID == null ? "CONSOLE" : Bukkit.getPlayer(freezerUUID) == null ? Bukkit.getOfflinePlayer(freezerUUID).getName() : Bukkit.getPlayer(freezerUUID).getName(); for (String msg : plugin.getConfig().getStringList("join-on-freezeall-message")) { if (msg == "") { msg = " "; } p.sendMessage(plugin.placeholders(msg.replace("{FREEZER}", freezerName).replace("{REASON}", reason))); } String totalMsg = ""; String location = locationManager.getLocationName(finalFreezeAllPlayer.getFreezeLoc()); String locPlaceholder = locationManager.getLocationPlaceholder(location); if (location != null) { for (String msg : plugin.getConfig().getStringList("freezeall-location-message")) { if (msg.equals("")) { msg = " "; } totalMsg += msg + "\n"; } if (totalMsg.length() > 0) { totalMsg = totalMsg.substring(0, totalMsg.length() - 2); } totalMsg = plugin.placeholders(totalMsg.replace("{LOCATION}", locPlaceholder).replace("{FREEZER}", finalFreezeAllPlayer.getFreezerName()).replace("{REASON}", reason)); if (messageManager.getFreezeAllLocInterval() > 0) { messageManager.addFreezeAllLocPlayer(p, totalMsg); } } else { for (String msg : plugin.getConfig().getStringList("freezeall-message")) { if (msg.equals("")) { msg = " "; } totalMsg += msg + "\n"; } if (totalMsg.length() > 0) { totalMsg = totalMsg.substring(0, totalMsg.length() - 2); } totalMsg = plugin.placeholders(totalMsg.replace("{LOCATION}", locPlaceholder).replace("{FREEZER}", finalFreezeAllPlayer.getFreezerName()).replace("{REASON}", reason)); if (messageManager.getFreezeAllInterval() > 0) { messageManager.addFreezeAllPlayer(p, totalMsg); } } soundManager.playFreezeSound(p); } }.runTaskLater(this.plugin, 10L); } else if (frozenPlayer != null) { final FrozenPlayer finalFrozenPlayer = frozenPlayer; new BukkitRunnable() { @Override public void run() { finalFrozenPlayer.setHelmet(p.getInventory().getHelmet()); p.getInventory().setHelmet(helmetManager.getPersonalHelmetItem(finalFrozenPlayer)); if (plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".original-location").equals("null")) { finalFrozenPlayer.setOriginalLoc(p.getLocation()); plugin.getPlayerConfig().getConfig().set("players." + uuidStr + ".original-location", new SFLocation(p.getLocation()).toString()); } if (finalFrozenPlayer.getFreezeLoc() == null) { SFLocation originalLoc = new SFLocation(finalFrozenPlayer.getOriginalLoc()); Location freezeLoc; if (plugin.getConfig().getBoolean("teleport-to-ground")) { freezeLoc = locationManager.getGroundLocation(originalLoc); } else { freezeLoc = new SFLocation(originalLoc.clone()); } finalFrozenPlayer.setFreezeLoc(freezeLoc); if (plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".freeze-location").equals("null")) { plugin.getPlayerConfig().getConfig().set("players." + uuidStr + ".freeze-location", new SFLocation(freezeLoc).toString()); } } if (plugin.getConfig().getBoolean("enable-fly")) { p.setAllowFlight(true); p.setFlying(true); } p.teleport(finalFrozenPlayer.getFreezeLoc()); soundManager.playFreezeSound(p); String locationName = locationManager.getLocationName(finalFrozenPlayer.getFreezeLoc()); String freezerName = finalFrozenPlayer.getFreezerName(); String timePlaceholder = "Permanent"; String serversPlaceholder = plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".servers", ""); String locationPlaceholder = locationManager.getLocationPlaceholder(locationName); String reason = finalFrozenPlayer.getReason() == null ? plugin.getConfig().getString("default-reason") : finalFrozenPlayer.getReason(); if (plugin.getPlayerConfig().getConfig().getBoolean("players." + uuidStr + ".message", false)) { String path; if (finalFrozenPlayer instanceof TempFrozenPlayer) { timePlaceholder = TimeUtil.formatTime((((TempFrozenPlayer) finalFrozenPlayer).getUnfreezeDate() - System.currentTimeMillis()) / 1000L); path = "first-join.temp-frozen"; } else { path = "first-join.frozen"; } if (locationName != null) { path += "-location"; } p.sendMessage(plugin.placeholders(plugin.getConfig().getString(path).replace("{PLAYER}", p.getName()).replace("{FREEZER}", freezerName).replace("{TIME}", timePlaceholder).replace("{LOCATION}", locationPlaceholder).replace("{REASON}", reason))); plugin.getPlayerConfig().getConfig().set("players." + uuidStr + ".message", null); plugin.getPlayerConfig().saveConfig(); plugin.getPlayerConfig().reloadConfig(); } else { for (String line : plugin.getConfig().getStringList("still-frozen-join")) { p.sendMessage(plugin.placeholders(line.replace("{PLAYER}", p.getName()).replace("{FREEZER}", freezerName).replace("{TIME}", timePlaceholder).replace("{LOCATION}", locationPlaceholder).replace("{REASON}", reason).replace("{SERVERS}", serversPlaceholder))); } } String path = ""; if (finalFrozenPlayer instanceof TempFrozenPlayer) { path = "temp-freeze-message"; if (locationName != null) { path = "temp-freeze-location-message"; } } else { path = "freeze-message"; if (locationName != null) { path = "freeze-location-message"; } } if (!serversPlaceholder.equals("")) { path = "sql-" + path; } String msg = ""; for (String line : plugin.getConfig().getStringList(path)) { if (line.equals("")) { line = " "; } msg += line + "\n"; } msg = msg.length() > 2 ? msg.substring(0, msg.length() - 1) : ""; msg = msg.replace("{PLAYER}", p.getName()).replace("{TIME}", timePlaceholder).replace("{FREEZER}", finalFrozenPlayer.getFreezerName()).replace("{LOCATION}", locationPlaceholder).replace("{SERVERS}", serversPlaceholder).replace("{REASON}", reason); if (finalFrozenPlayer instanceof TempFrozenPlayer) { if (locationName == null && messageManager.getTempFreezeInterval() > 0) { messageManager.addTempFreezePlayer(p, msg); } else if (messageManager.getTempFreezeLocInterval() > 0) { messageManager.addTempFreezeLocPlayer(p, msg); } } else { if (locationName == null && messageManager.getFreezeInterval() > 0) { messageManager.addFreezePlayer(p, msg); } else if (messageManager.getFreezeLocInterval() > 0) { messageManager.addFreezeLocPlayer(p, msg); } } } }.runTaskLater(this.plugin, 10L); } } }
src/org/plugins/simplefreeze/listeners/PlayerJoinListener.java
package org.plugins.simplefreeze.listeners; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.scheduler.BukkitRunnable; import org.plugins.simplefreeze.SimpleFreezeMain; import org.plugins.simplefreeze.managers.*; import org.plugins.simplefreeze.objects.FreezeAllPlayer; import org.plugins.simplefreeze.objects.FrozenPlayer; import org.plugins.simplefreeze.objects.SFLocation; import org.plugins.simplefreeze.objects.TempFrozenPlayer; import org.plugins.simplefreeze.util.DataConverter; import org.plugins.simplefreeze.util.TimeUtil; import org.plugins.simplefreeze.util.UpdateNotifier; import java.util.UUID; public class PlayerJoinListener implements Listener { private final SimpleFreezeMain plugin; private final FreezeManager freezeManager; private final PlayerManager playerManager; private final LocationManager locationManager; private final HelmetManager helmetManager; private final DataConverter dataConverter; private final SoundManager soundManager; private final MessageManager messageManager; public PlayerJoinListener(SimpleFreezeMain plugin, FreezeManager freezeManager, PlayerManager playerManager, LocationManager locationManager, HelmetManager helmetManager, DataConverter dataConverter, SoundManager soundManager, MessageManager messageManager) { this.plugin = plugin; this.freezeManager = freezeManager; this.playerManager = playerManager; this.locationManager = locationManager; this.helmetManager = helmetManager; this.dataConverter = dataConverter; this.soundManager = soundManager; this.messageManager = messageManager; } @EventHandler public void onJoin(PlayerJoinEvent e) { final Player p = e.getPlayer(); if (p.hasPermission("sf.notify.update") && !UpdateNotifier.getLatestVersion().equals(UpdateNotifier.getCurrentVersion())) { new BukkitRunnable() { @Override public void run() { p.sendMessage(plugin.placeholders("{PREFIX}You are still running version &b" + UpdateNotifier.getCurrentVersion() + "\n{PREFIX}Latest version: &b" + UpdateNotifier.getLatestVersion())); } }.runTaskLater(this.plugin, 25L); } final String uuidStr = p.getUniqueId().toString(); FrozenPlayer frozenPlayer = null; if (DataConverter.hasDataToConvert(p)) { frozenPlayer = this.dataConverter.convertData(p); if (frozenPlayer != null) { this.playerManager.addFrozenPlayer(p.getUniqueId(), frozenPlayer); } } else if (this.plugin.getPlayerConfig().getConfig().isSet("players." + uuidStr)) { Long freezeDate = this.plugin.getPlayerConfig().getConfig().getLong("players." + uuidStr + ".freeze-date"); UUID freezerUUID = this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".freezer-uuid").equals("null") ? null : UUID.fromString(this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".freezer-uuid")); String originalLocStr = this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".original-location"); Location freezeLocation = SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".freeze-location")); if (freezeLocation == null && this.plugin.getConfig().getBoolean("teleport-to-ground")) { freezeLocation = new SFLocation(this.locationManager.getGroundLocation(p.getLocation())); } else if (freezeLocation == null) { freezeLocation = new SFLocation(p.getLocation().clone()); } Location originalLocation = SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".original-location")); if (freezeLocation.equals(originalLocation)) { freezeLocation = p.getLocation(); originalLocation = p.getLocation(); } else { originalLocation = p.getLocation(); } String reason = this.plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".reason"); if (this.plugin.getPlayerConfig().getConfig().isSet("players." + uuidStr + ".unfreeze-date")) { Long unfreezeDate = this.plugin.getPlayerConfig().getConfig().getLong("players." + uuidStr + ".unfreeze-date"); if (System.currentTimeMillis() < unfreezeDate) { frozenPlayer = new TempFrozenPlayer(freezeDate, unfreezeDate, p.getUniqueId(), freezerUUID, originalLocation, freezeLocation, reason, this.playerManager.isSQLFrozen(p)); ((TempFrozenPlayer) frozenPlayer).startTask(plugin); this.playerManager.addFrozenPlayer(p.getUniqueId(), frozenPlayer); } else { plugin.getPlayerConfig().getConfig().set("players." + uuidStr, null); this.plugin.getPlayerConfig().saveConfig(); this.plugin.getPlayerConfig().reloadConfig(); } } else { frozenPlayer = new FrozenPlayer(freezeDate, p.getUniqueId(), freezerUUID, originalLocation, freezeLocation, reason, this.playerManager.isSQLFrozen(p)); this.playerManager.addFrozenPlayer(p.getUniqueId(), frozenPlayer); } } // if freezeall and player isnt already frozen if (frozenPlayer == null && this.freezeManager.freezeAllActive() && !(p.hasPermission("sf.exempt.*") || p.hasPermission("sf.exempt.freezeall"))) { final UUID freezerUUID = this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.freezer").equals("null") ? null : UUID.fromString(this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.freezer")); SFLocation freezeLocation = this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.location").equals("null") ? null : SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.location")); if (freezeLocation == null && this.plugin.getPlayerConfig().getConfig().isSet("freezeall-info.players." + uuidStr + ".freeze-location")) { freezeLocation = this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.players." + uuidStr + ".freeze-location").equals("null") ? null : SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.players." + uuidStr + ".freeze-location")); } else if (freezeLocation == null) { if (this.plugin.getConfig().getBoolean("teleport-to-ground")) { freezeLocation = new SFLocation(this.locationManager.getGroundLocation(p.getLocation())); } else { freezeLocation = new SFLocation(new SFLocation(p.getLocation().clone())); if (this.plugin.getConfig().getBoolean("enable-fly")) { p.setAllowFlight(true); p.setFlying(true); } } } Location originalLocation = SFLocation.fromString(this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.players." + uuidStr + ".original-location")); if (freezeLocation.equals(originalLocation)) { freezeLocation = new SFLocation(p.getLocation()); originalLocation = p.getLocation(); } else { originalLocation = p.getLocation(); } Long freezeDate = this.plugin.getPlayerConfig().getConfig().getLong("freezeall-info.date"); String reason = this.plugin.getPlayerConfig().getConfig().getString("freezeall-info.reason"); frozenPlayer = new FreezeAllPlayer(freezeDate, p.getUniqueId(), freezerUUID, originalLocation, freezeLocation, reason); this.playerManager.addFrozenPlayer(p.getUniqueId(), frozenPlayer); this.plugin.getPlayerConfig().getConfig().set("freezeall-info.players." + uuidStr + ".original-location", new SFLocation(frozenPlayer.getOriginalLoc()).toString()); this.plugin.getPlayerConfig().getConfig().set("freezeall-info.players." + uuidStr + ".freeze-location", freezeLocation == null ? "null" : freezeLocation.toString()); this.plugin.getPlayerConfig().saveConfig(); this.plugin.getPlayerConfig().reloadConfig(); final FrozenPlayer finalFreezeAllPlayer = frozenPlayer; new BukkitRunnable() { @Override public void run() { finalFreezeAllPlayer.setHelmet(p.getInventory().getHelmet()); p.getInventory().setHelmet(helmetManager.getPersonalHelmetItem(finalFreezeAllPlayer)); if (finalFreezeAllPlayer.getFreezeLoc() == null) { SFLocation originalLoc = new SFLocation(finalFreezeAllPlayer.getOriginalLoc()); Location freezeLoc; if (plugin.getConfig().getBoolean("teleport-to-ground")) { freezeLoc = locationManager.getGroundLocation(originalLoc); } else { freezeLoc = new SFLocation(originalLoc.clone()); } finalFreezeAllPlayer.setFreezeLoc(freezeLoc); if (plugin.getPlayerConfig().getConfig().getString("freezeall-info.players." + uuidStr + ".freeze-location").equals("null")) { plugin.getPlayerConfig().getConfig().set("freezeall-info.players." + uuidStr + ".freeze-location", new SFLocation(freezeLoc).toString()); } } if (plugin.getConfig().getBoolean("enable-fly")) { p.setAllowFlight(true); p.setFlying(true); } p.teleport(finalFreezeAllPlayer.getFreezeLoc()); String freezerName = freezerUUID == null ? "CONSOLE" : Bukkit.getPlayer(freezerUUID) == null ? Bukkit.getOfflinePlayer(freezerUUID).getName() : Bukkit.getPlayer(freezerUUID).getName(); for (String msg : plugin.getConfig().getStringList("join-on-freezeall-message")) { if (msg == "") { msg = " "; } p.sendMessage(plugin.placeholders(msg.replace("{FREEZER}", freezerName).replace("{REASON}", reason))); } String totalMsg = ""; String location = locationManager.getLocationName(finalFreezeAllPlayer.getFreezeLoc()); String locPlaceholder = locationManager.getLocationPlaceholder(location); if (location != null) { for (String msg : plugin.getConfig().getStringList("freezeall-location-message")) { if (msg.equals("")) { msg = " "; } totalMsg += msg + "\n"; } if (totalMsg.length() > 0) { totalMsg = totalMsg.substring(0, totalMsg.length() - 2); } totalMsg = plugin.placeholders(totalMsg.replace("{LOCATION}", locPlaceholder).replace("{FREEZER}", finalFreezeAllPlayer.getFreezerName()).replace("{REASON}", reason)); if (messageManager.getFreezeAllLocInterval() > 0) { messageManager.addFreezeAllLocPlayer(p, totalMsg); } } else { for (String msg : plugin.getConfig().getStringList("freezeall-message")) { if (msg.equals("")) { msg = " "; } totalMsg += msg + "\n"; } if (totalMsg.length() > 0) { totalMsg = totalMsg.substring(0, totalMsg.length() - 2); } totalMsg = plugin.placeholders(totalMsg.replace("{LOCATION}", locPlaceholder).replace("{FREEZER}", finalFreezeAllPlayer.getFreezerName()).replace("{REASON}", reason)); if (messageManager.getFreezeAllInterval() > 0) { messageManager.addFreezeAllPlayer(p, totalMsg); } } soundManager.playFreezeSound(p); } }.runTaskLater(this.plugin, 10L); } else if (frozenPlayer != null) { final FrozenPlayer finalFrozenPlayer = frozenPlayer; new BukkitRunnable() { @Override public void run() { finalFrozenPlayer.setHelmet(p.getInventory().getHelmet()); p.getInventory().setHelmet(helmetManager.getPersonalHelmetItem(finalFrozenPlayer)); if (plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".original-location").equals("null")) { finalFrozenPlayer.setOriginalLoc(p.getLocation()); plugin.getPlayerConfig().getConfig().set("players." + uuidStr + ".original-location", new SFLocation(p.getLocation()).toString()); } if (finalFrozenPlayer.getFreezeLoc() == null) { SFLocation originalLoc = new SFLocation(finalFrozenPlayer.getOriginalLoc()); Location freezeLoc; if (plugin.getConfig().getBoolean("teleport-to-ground")) { freezeLoc = locationManager.getGroundLocation(originalLoc); } else { freezeLoc = new SFLocation(originalLoc.clone()); } finalFrozenPlayer.setFreezeLoc(freezeLoc); if (plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".freeze-location").equals("null")) { plugin.getPlayerConfig().getConfig().set("players." + uuidStr + ".freeze-location", new SFLocation(freezeLoc).toString()); } } if (plugin.getConfig().getBoolean("enable-fly")) { p.setAllowFlight(true); p.setFlying(true); } p.teleport(finalFrozenPlayer.getFreezeLoc()); soundManager.playFreezeSound(p); String locationName = locationManager.getLocationName(finalFrozenPlayer.getFreezeLoc()); String freezerName = finalFrozenPlayer.getFreezerName(); String timePlaceholder = "Permanent"; String serversPlaceholder = plugin.getPlayerConfig().getConfig().getString("players." + uuidStr + ".servers", ""); String locationPlaceholder = locationManager.getLocationPlaceholder(locationName); String reason = finalFrozenPlayer.getReason() == null ? plugin.getConfig().getString("default-reason") : finalFrozenPlayer.getReason(); if (plugin.getPlayerConfig().getConfig().getBoolean("players." + uuidStr + ".message", false)) { String path; if (finalFrozenPlayer instanceof TempFrozenPlayer) { timePlaceholder = TimeUtil.formatTime((((TempFrozenPlayer) finalFrozenPlayer).getUnfreezeDate() - System.currentTimeMillis()) / 1000L); path = "first-join.temp-frozen"; } else { path = "first-join.frozen"; } if (locationName != null) { path += "-location"; } p.sendMessage(plugin.placeholders(plugin.getConfig().getString(path).replace("{PLAYER}", p.getName()).replace("{FREEZER}", freezerName).replace("{TIME}", timePlaceholder).replace("{LOCATION}", locationPlaceholder).replace("{REASON}", reason))); plugin.getPlayerConfig().getConfig().set("players." + uuidStr + ".message", null); plugin.getPlayerConfig().saveConfig(); plugin.getPlayerConfig().reloadConfig(); } else { for (String line : plugin.getConfig().getStringList("still-frozen-join")) { p.sendMessage(plugin.placeholders(line.replace("{PLAYER}", p.getName()).replace("{FREEZER}", freezerName).replace("{TIME}", timePlaceholder).replace("{LOCATION}", locationPlaceholder).replace("{REASON}", reason).replace("{SERVERS}", serversPlaceholder))); } } String path = ""; if (finalFrozenPlayer instanceof TempFrozenPlayer) { path = "temp-freeze-message"; if (locationName != null) { path = "temp-freeze-location-message"; } } else { path = "freeze-message"; if (locationName != null) { path = "freeze-location-message"; } } if (!serversPlaceholder.equals("")) { path = "sql-" + path; } String msg = ""; for (String line : plugin.getConfig().getStringList(path)) { if (line.equals("")) { line = " "; } msg += line + "\n"; } msg = msg.length() > 2 ? msg.substring(0, msg.length() - 1) : ""; msg = msg.replace("{PLAYER}", p.getName()).replace("{TIME}", timePlaceholder).replace("{FREEZER}", finalFrozenPlayer.getFreezerName()).replace("{LOCATION}", locationPlaceholder).replace("{SERVERS}", serversPlaceholder).replace("{REASON}", reason); if (finalFrozenPlayer instanceof TempFrozenPlayer) { if (locationName == null && messageManager.getTempFreezeInterval() > 0) { messageManager.addTempFreezePlayer(p, msg); } else if (messageManager.getTempFreezeLocInterval() > 0) { messageManager.addTempFreezeLocPlayer(p, msg); } } else { if (locationName == null && messageManager.getFreezeInterval() > 0) { messageManager.addFreezePlayer(p, msg); } else if (messageManager.getFreezeLocInterval() > 0) { messageManager.addFreezeLocPlayer(p, msg); } } } }.runTaskLater(this.plugin, 10L); } } }
Added debug message
src/org/plugins/simplefreeze/listeners/PlayerJoinListener.java
Added debug message
Java
apache-2.0
8606e75a3f5b53f228ab9ac1eab7c97ce72882ef
0
peter-mount/opendata-common
/* * Copyright 2014 peter. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.trainwatch.util; import java.util.Optional; import java.util.stream.Collector; import java.util.stream.Collectors; /** * A suite of utilities to compliment {@link Collectors} * <p> * @author peter */ public class CollectorUtils { /** * A collector that collects the last element on a stream. The output of this collector is an {@link Optional} as we may not have an entry. * * @param <T> Type of value to collect * * @return Collector */ public static <T> Collector<T, ?, Optional<T>> findLast() { return Collector.<T, OptionalAccumulator<T>, Optional<T>>of( OptionalAccumulator::new, OptionalAccumulator::accumulate, OptionalAccumulator::combine, OptionalAccumulator::finish ); } private static class OptionalAccumulator<T> { private Optional<T> opt = Optional.empty(); public void accumulate( T v ) { opt = Optional.ofNullable( v ); } public OptionalAccumulator<T> combine( OptionalAccumulator<T> b ) { return opt.isPresent() ? this : b; } public Optional<T> finish() { return opt; } } }
core/src/main/java/uk/trainwatch/util/CollectorUtils.java
/* * Copyright 2014 peter. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.trainwatch.util; import java.util.Optional; import java.util.stream.Collector; import java.util.stream.Collectors; /** * A suite of utilities to compliment {@link Collectors} * <p> * @author peter */ public class CollectorUtils { /** * A collector that collects the last element on a stream. The output of this collector is an {@link Optional} as we may not have an entry. * * @param <T> Type of value to collect * * @return Collector */ public static <T> Collector<T, ?, Optional<T>> findLast() { class V { Optional opt = Optional.empty(); } return Collector.<T, V, Optional<T>>of( () -> new V(), ( a, t ) -> a.opt = Optional.ofNullable( t ), ( a, b ) -> a.opt.isPresent() ? a : b, a -> a.opt ); } }
I wasn't happy, this looks cleaner
core/src/main/java/uk/trainwatch/util/CollectorUtils.java
I wasn't happy, this looks cleaner
Java
apache-2.0
54170830ba8be0ce2dd0def1c412dee4513ca322
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.db.object.obj.base; import static com.google.common.base.Preconditions.checkElementIndex; import static java.util.stream.Collectors.joining; import static org.smoothbuild.db.object.db.Helpers.wrapHashedDbExceptionAsDecodeObjNodeException; import static org.smoothbuild.db.object.db.Helpers.wrapObjectDbExceptionAsDecodeObjNodeException; import java.util.Objects; import org.smoothbuild.db.hashed.Hash; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.db.object.db.Helpers.HashedDbCallable; import org.smoothbuild.db.object.db.ObjectDb; import org.smoothbuild.db.object.exc.DecodeObjNodeException; import org.smoothbuild.db.object.exc.UnexpectedNodeException; import org.smoothbuild.db.object.exc.UnexpectedSequenceException; import org.smoothbuild.db.object.spec.base.Spec; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; public abstract class Obj { public static final String DATA_PATH = "data"; private final MerkleRoot merkleRoot; private final ObjectDb objectDb; public Obj(MerkleRoot merkleRoot, ObjectDb objectDb) { this.merkleRoot = merkleRoot; this.objectDb = objectDb; } protected MerkleRoot merkleRoot() { return merkleRoot; } protected ObjectDb objectDb() { return objectDb; } protected HashedDb hashedDb() { return objectDb.hashedDb(); } public Hash hash() { return merkleRoot.hash(); } public Hash dataHash() { return merkleRoot.dataHash(); } public Spec spec() { return merkleRoot.spec(); } private String valueToStringSafe() { try { return valueToString(); } catch (DecodeObjNodeException e) { return "?Exception?:" + hash(); } } public abstract String valueToString(); @Override public boolean equals(Object object) { return (object instanceof Obj that) && Objects.equals(hash(), that.hash()); } @Override public int hashCode() { return hash().hashCode(); } @Override public String toString() { return valueToStringSafe() + ":" + hash(); } protected <T> T readData(HashedDbCallable<T> reader) { return wrapHashedDbExceptionAsDecodeObjNodeException(hash(), spec(), DATA_PATH, reader); } protected <T> T readSequenceElementObj(String path, Hash hash, int i, int expectedSize, Class<T> clazz) { Hash elementHash = readSequenceElementHash(path, hash, i, expectedSize); Obj obj = wrapObjectDbExceptionAsDecodeObjNodeException( hash(), spec(), path, i, () -> objectDb().get(elementHash)); return castObj(obj, path, i, clazz); } protected Hash readSequenceElementHash(String path, Hash hash, int i, int expectedSize) { checkElementIndex(i, expectedSize); return readSequenceHashes(path, hash, expectedSize) .get(i); } protected <T> T castObj(Obj obj, String path, int nodeIndex, Class<T> clazz) { if (clazz.isInstance(obj)) { @SuppressWarnings("unchecked") T result = (T) obj; return result; } else { throw new UnexpectedNodeException(hash(), spec(), path, nodeIndex, clazz, obj.getClass()); } } protected <T> ImmutableList<T> readSequenceObjs(String path, Hash hash, int expectedSize, Class<T> clazz) { var sequenceHashes = readSequenceHashes(path, hash, expectedSize); var objs = readSequenceObjs(path, sequenceHashes); return castSequence(objs, path, clazz); } protected <T> ImmutableList<T> readSequenceObjs(String path, Hash hash, Class<T> clazz) { var objs = readSequenceObjs(path, hash); return castSequence(objs, path, clazz); } protected ImmutableList<Obj> readSequenceObjs(String path, Hash hash) { var sequenceHashes = readSequenceHashes(path, hash); return readSequenceObjs(path, sequenceHashes); } private <T> ImmutableList<T> castSequence( ImmutableList<Obj> elements, String path, Class<T> clazz) { for (int i = 0; i < elements.size(); i++) { Obj element = elements.get(i); if (!clazz.isInstance(element)) { throw new UnexpectedNodeException(hash(), spec(), path, i, clazz, element.getClass()); } } @SuppressWarnings("unchecked") ImmutableList<T> result = (ImmutableList<T>) elements; return result; } private ImmutableList<Obj> readSequenceObjs(String path, ImmutableList<Hash> sequence) { Builder<Obj> builder = ImmutableList.builder(); for (int i = 0; i < sequence.size(); i++) { int index = i; Obj obj = wrapObjectDbExceptionAsDecodeObjNodeException(hash(), spec(), path, index, () -> objectDb.get(sequence.get(index))); builder.add(obj); } return builder.build(); } private ImmutableList<Hash> readSequenceHashes(String path, Hash hash, int expectedSize) { ImmutableList<Hash> data = readSequenceHashes(path, hash); if (data.size() != expectedSize) { throw new UnexpectedSequenceException(hash(), spec(), path, expectedSize, data.size()); } return data; } private ImmutableList<Hash> readSequenceHashes(String path, Hash hash) { return wrapHashedDbExceptionAsDecodeObjNodeException(hash(), spec(), path, () -> objectDb.readSequence(hash)); } public static String sequenceToString(ImmutableList<? extends Obj> objects) { return objects.stream().map(Obj::valueToStringSafe).collect(joining(",")); } }
src/main/java/org/smoothbuild/db/object/obj/base/Obj.java
package org.smoothbuild.db.object.obj.base; import static com.google.common.base.Preconditions.checkElementIndex; import static java.util.stream.Collectors.joining; import static org.smoothbuild.db.object.db.Helpers.wrapHashedDbExceptionAsDecodeObjNodeException; import static org.smoothbuild.db.object.db.Helpers.wrapObjectDbExceptionAsDecodeObjNodeException; import java.util.Objects; import org.smoothbuild.db.hashed.Hash; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.db.object.db.Helpers.HashedDbCallable; import org.smoothbuild.db.object.db.ObjectDb; import org.smoothbuild.db.object.exc.UnexpectedNodeException; import org.smoothbuild.db.object.exc.UnexpectedSequenceException; import org.smoothbuild.db.object.spec.base.Spec; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; public abstract class Obj { public static final String DATA_PATH = "data"; private final MerkleRoot merkleRoot; private final ObjectDb objectDb; public Obj(MerkleRoot merkleRoot, ObjectDb objectDb) { this.merkleRoot = merkleRoot; this.objectDb = objectDb; } protected MerkleRoot merkleRoot() { return merkleRoot; } protected ObjectDb objectDb() { return objectDb; } protected HashedDb hashedDb() { return objectDb.hashedDb(); } public Hash hash() { return merkleRoot.hash(); } public Hash dataHash() { return merkleRoot.dataHash(); } public Spec spec() { return merkleRoot.spec(); } public abstract String valueToString(); @Override public boolean equals(Object object) { return (object instanceof Obj that) && Objects.equals(hash(), that.hash()); } @Override public int hashCode() { return hash().hashCode(); } @Override public String toString() { return valueToString() + ":" + hash(); } protected <T> T readData(HashedDbCallable<T> reader) { return wrapHashedDbExceptionAsDecodeObjNodeException(hash(), spec(), DATA_PATH, reader); } protected <T> T readSequenceElementObj(String path, Hash hash, int i, int expectedSize, Class<T> clazz) { Hash elementHash = readSequenceElementHash(path, hash, i, expectedSize); Obj obj = wrapObjectDbExceptionAsDecodeObjNodeException( hash(), spec(), path, i, () -> objectDb().get(elementHash)); return castObj(obj, path, i, clazz); } protected Hash readSequenceElementHash(String path, Hash hash, int i, int expectedSize) { checkElementIndex(i, expectedSize); return readSequenceHashes(path, hash, expectedSize) .get(i); } protected <T> T castObj(Obj obj, String path, int nodeIndex, Class<T> clazz) { if (clazz.isInstance(obj)) { @SuppressWarnings("unchecked") T result = (T) obj; return result; } else { throw new UnexpectedNodeException(hash(), spec(), path, nodeIndex, clazz, obj.getClass()); } } protected <T> ImmutableList<T> readSequenceObjs(String path, Hash hash, int expectedSize, Class<T> clazz) { var sequenceHashes = readSequenceHashes(path, hash, expectedSize); var objs = readSequenceObjs(path, sequenceHashes); return castSequence(objs, path, clazz); } protected <T> ImmutableList<T> readSequenceObjs(String path, Hash hash, Class<T> clazz) { var objs = readSequenceObjs(path, hash); return castSequence(objs, path, clazz); } protected ImmutableList<Obj> readSequenceObjs(String path, Hash hash) { var sequenceHashes = readSequenceHashes(path, hash); return readSequenceObjs(path, sequenceHashes); } private <T> ImmutableList<T> castSequence( ImmutableList<Obj> elements, String path, Class<T> clazz) { for (int i = 0; i < elements.size(); i++) { Obj element = elements.get(i); if (!clazz.isInstance(element)) { throw new UnexpectedNodeException(hash(), spec(), path, i, clazz, element.getClass()); } } @SuppressWarnings("unchecked") ImmutableList<T> result = (ImmutableList<T>) elements; return result; } private ImmutableList<Obj> readSequenceObjs(String path, ImmutableList<Hash> sequence) { Builder<Obj> builder = ImmutableList.builder(); for (int i = 0; i < sequence.size(); i++) { int index = i; Obj obj = wrapObjectDbExceptionAsDecodeObjNodeException(hash(), spec(), path, index, () -> objectDb.get(sequence.get(index))); builder.add(obj); } return builder.build(); } private ImmutableList<Hash> readSequenceHashes(String path, Hash hash, int expectedSize) { ImmutableList<Hash> data = readSequenceHashes(path, hash); if (data.size() != expectedSize) { throw new UnexpectedSequenceException(hash(), spec(), path, expectedSize, data.size()); } return data; } private ImmutableList<Hash> readSequenceHashes(String path, Hash hash) { return wrapHashedDbExceptionAsDecodeObjNodeException(hash(), spec(), path, () -> objectDb.readSequence(hash)); } public static String sequenceToString(ImmutableList<? extends Obj> objects) { return objects.stream().map(Obj::valueToString).collect(joining(",")); } }
improved Obj.toString()/sequenceToString() to not fail when valueToString() throws ObjectDbException
src/main/java/org/smoothbuild/db/object/obj/base/Obj.java
improved Obj.toString()/sequenceToString() to not fail when valueToString() throws ObjectDbException
Java
apache-2.0
c2b85b1b2b7350cd5b98280872a9eca2594de82d
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Contains a small test domain and utilities for testing entity logs. */ @CheckReturnValue @ParametersAreNonnullByDefault package io.spine.server.log.given; import com.google.errorprone.annotations.CheckReturnValue; import javax.annotation.ParametersAreNonnullByDefault;
server/src/test/java/io/spine/server/log/given/package-info.java
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @CheckReturnValue @ParametersAreNonnullByDefault package io.spine.server.log.given; import com.google.errorprone.annotations.CheckReturnValue; import javax.annotation.ParametersAreNonnullByDefault;
Document a package
server/src/test/java/io/spine/server/log/given/package-info.java
Document a package
Java
apache-2.0
83f180bd9ab79a0c4384e4c608d28c21f629dd55
0
bikush/libgdxjam-space-seed-inc
package com.starseed.util; import com.badlogic.gdx.physics.box2d.Body; import com.starseed.box2d.UserData; import com.starseed.enums.UserDataType; public class BodyUtils { public static boolean bodyInBounds(Body body) { UserData userData = (UserData) body.getUserData(); switch (userData.getUserDataType()) { case RUNNER: case ENEMY: return body.getPosition().x + userData.getWidth() / 2 > 0; case GROUND: default: break; } return true; } public static boolean bodiesAreOfTypes( Body first, Body second, UserDataType typeOne, UserDataType typeTwo ) { UserDataType typeFirst = bodyType(first); UserDataType typeSecond = bodyType(second); return (typeFirst == typeOne && typeSecond == typeTwo) || (typeFirst == typeTwo && typeSecond == typeOne); } public static boolean bodiesAreOfType( Body first, Body second, UserDataType type ) { return bodiesAreOfTypes(first, second, type, type); } public static boolean bodyIsOfType(Body body, UserDataType type) { return bodyType(body) == type; } public static UserDataType bodyType( Body body ) { UserData userData = (UserData) body.getUserData(); return userData != null ? userData.getUserDataType(): UserDataType.NONE; } }
core/src/com/starseed/util/BodyUtils.java
package com.starseed.util; import com.badlogic.gdx.physics.box2d.Body; import com.starseed.box2d.UserData; import com.starseed.enums.UserDataType; public class BodyUtils { public static boolean bodyInBounds(Body body) { UserData userData = (UserData) body.getUserData(); switch (userData.getUserDataType()) { case RUNNER: case ENEMY: return body.getPosition().x + userData.getWidth() / 2 > 0; case GROUND: default: break; } return true; } public static boolean bodiesAreOfTypes( Body first, Body second, UserDataType typeOne, UserDataType typeTwo ) { UserData userDataFirst = (UserData) first.getUserData(); UserData userDataSecond = (UserData) second.getUserData(); UserDataType typeFirst = userDataFirst != null ? userDataFirst.getUserDataType() : UserDataType.NONE; UserDataType typeSecond = userDataSecond != null ? userDataSecond.getUserDataType() : UserDataType.NONE; return (typeFirst == typeOne && typeSecond == typeTwo) || (typeFirst == typeTwo && typeSecond == typeOne); } public static boolean bodiesAreOfType( Body first, Body second, UserDataType type ) { return bodiesAreOfTypes(first, second, type, type); } public static boolean bodyIsOfType(Body body, UserDataType type) { UserData userData = (UserData) body.getUserData(); return userData != null && userData.getUserDataType() == type; } }
BodyUtils convenience method to get UserDataType.
core/src/com/starseed/util/BodyUtils.java
BodyUtils convenience method to get UserDataType.
Java
bsd-2-clause
5e908c39d64ef3c86d5dbd347898f5544fa9c072
0
thasmin/Podax,thasmin/Podax,thasmin/Podax,thasmin/Podax
package com.axelby.podax; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; public class BottomBar extends LinearLayout { private TextView _podcastTitle; private TextView _positionstring; private ImageButton _pausebtn; private ImageButton _showplayerbtn; private Cursor _cursor = null; private PodcastCursor _podcast; public BottomBar(Context context) { super(context); if (isInEditMode()) return; loadViews(context); setupHandler(); } public BottomBar(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.player, this); if (isInEditMode()) return; loadViews(context); setupHandler(); } private Long _lastPodcastId = null; private Handler _handler = new Handler(); private class ActivePodcastObserver extends ContentObserver { public ActivePodcastObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { _podcast.unregisterContentObserver(_observer); setupHandler(); } } private ActivePodcastObserver _observer = new ActivePodcastObserver(_handler); private void setupHandler() { try { retrievePocast(); updateUI(); } catch (MissingFieldException e) { e.printStackTrace(); } finally { if (_cursor != null) _cursor.close(); } } public void updateUI() throws MissingFieldException { boolean isPlaying = PlayerService.isPlaying(); if (!_podcast.isNull()) { if (isPlaying || _positionstring.getText().length() == 0) _positionstring.setText(PlayerService.getPositionString(_podcast.getDuration(), _podcast.getLastPosition())); if (_lastPodcastId != _podcast.getId()) { _podcastTitle.setText(_podcast.getTitle()); _pausebtn.setImageResource(isPlaying ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play); _showplayerbtn.setEnabled(true); } } else if (_lastPodcastId != null) { _podcastTitle.setText(""); _positionstring.setText(""); _showplayerbtn.setEnabled(false); } _lastPodcastId = _podcast.isNull() ? null : _podcast.getId(); } public void retrievePocast() throws MissingFieldException { String[] projection = { PodcastProvider.COLUMN_ID, PodcastProvider.COLUMN_TITLE, PodcastProvider.COLUMN_DURATION, PodcastProvider.COLUMN_LAST_POSITION, }; Uri activeUri = Uri.withAppendedPath(PodcastProvider.URI, "active"); _cursor = getContext().getContentResolver().query(activeUri, projection, null, null, null); _podcast = new PodcastCursor(getContext(), _cursor); getContext().getContentResolver().registerContentObserver(activeUri, false, _observer); } private void loadViews(final Context context) { _podcastTitle = (TextView) findViewById(R.id.podcasttitle); _positionstring = (TextView) findViewById(R.id.positionstring); _pausebtn = (ImageButton) findViewById(R.id.pausebtn); _showplayerbtn = (ImageButton) findViewById(R.id.showplayer); _podcastTitle.setText(""); _positionstring.setText(""); _showplayerbtn.setEnabled(false); _pausebtn.setOnClickListener(new OnClickListener() { public void onClick(View view) { PodaxApp app = (PodaxApp) context.getApplicationContext(); app.playpause(); setupHandler(); } }); _showplayerbtn.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent intent = new Intent(context, PodcastDetailActivity.class); context.startActivity(intent); } }); } }
src/com/axelby/podax/BottomBar.java
package com.axelby.podax; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; public class BottomBar extends LinearLayout { private TextView _podcastTitle; private TextView _positionstring; private ImageButton _pausebtn; private ImageButton _showplayerbtn; private Cursor _cursor = null; private PodcastCursor _podcast; public BottomBar(Context context) { super(context); if (isInEditMode()) return; loadViews(context); setupHandler(); } public BottomBar(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.player, this); loadViews(context); setupHandler(); } private Long _lastPodcastId = null; private Handler _handler = new Handler(); private class ActivePodcastObserver extends ContentObserver { public ActivePodcastObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { _podcast.unregisterContentObserver(_observer); setupHandler(); } } private ActivePodcastObserver _observer = new ActivePodcastObserver(_handler); private void setupHandler() { try { retrievePocast(); updateUI(); } catch (MissingFieldException e) { e.printStackTrace(); } finally { if (_cursor != null) _cursor.close(); } } public void updateUI() throws MissingFieldException { boolean isPlaying = PlayerService.isPlaying(); if (!_podcast.isNull()) { if (isPlaying || _positionstring.getText().length() == 0) _positionstring.setText(PlayerService.getPositionString(_podcast.getDuration(), _podcast.getLastPosition())); if (_lastPodcastId != _podcast.getId()) { _podcastTitle.setText(_podcast.getTitle()); _pausebtn.setImageResource(isPlaying ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play); _showplayerbtn.setEnabled(true); } } else if (_lastPodcastId != null) { _podcastTitle.setText(""); _positionstring.setText(""); _showplayerbtn.setEnabled(false); } _lastPodcastId = _podcast.isNull() ? null : _podcast.getId(); } public void retrievePocast() throws MissingFieldException { String[] projection = { PodcastProvider.COLUMN_ID, PodcastProvider.COLUMN_TITLE, PodcastProvider.COLUMN_DURATION, PodcastProvider.COLUMN_LAST_POSITION, }; Uri activeUri = Uri.withAppendedPath(PodcastProvider.URI, "active"); _cursor = getContext().getContentResolver().query(activeUri, projection, null, null, null); _podcast = new PodcastCursor(getContext(), _cursor); getContext().getContentResolver().registerContentObserver(activeUri, false, _observer); } private void loadViews(final Context context) { _podcastTitle = (TextView) findViewById(R.id.podcasttitle); _positionstring = (TextView) findViewById(R.id.positionstring); _pausebtn = (ImageButton) findViewById(R.id.pausebtn); _showplayerbtn = (ImageButton) findViewById(R.id.showplayer); _podcastTitle.setText(""); _positionstring.setText(""); _showplayerbtn.setEnabled(false); _pausebtn.setOnClickListener(new OnClickListener() { public void onClick(View view) { PodaxApp app = (PodaxApp) context.getApplicationContext(); app.playpause(); setupHandler(); } }); _showplayerbtn.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent intent = new Intent(context, PodcastDetailActivity.class); context.startActivity(intent); } }); } }
fix bottombar in edit mode
src/com/axelby/podax/BottomBar.java
fix bottombar in edit mode
Java
bsd-3-clause
aa74b3a254b1b4257a530769b69605383e4471e7
0
agaricusb/HighlightTips
package agaricus.mods.highlighttips; import cpw.mods.fml.client.registry.KeyBindingRegistry; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.ITickHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.TickType; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.TickRegistry; import cpw.mods.fml.relauncher.FMLRelauncher; import cpw.mods.fml.relauncher.Side; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.*; import net.minecraft.world.World; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.liquids.ILiquidTank; import net.minecraftforge.liquids.ITankContainer; import net.minecraftforge.liquids.LiquidStack; import java.util.EnumSet; import java.util.logging.Level; @Mod(modid = "HighlightTips", name = "HighlightTips", version = "1.0-SNAPSHOT") // TODO: version from resource @NetworkMod(clientSideRequired = false, serverSideRequired = false) public class HighlightTips implements ITickHandler { private static final int DEFAULT_KEY_TOGGLE = 62; // F4 - see http://www.minecraftwiki.net/wiki/Key_codes private static final double DEFAULT_RANGE = 300; private static final int DEFAULT_X = 0; private static final int DEFAULT_Y = 0; private static final int DEFAULT_COLOR = 0xffffff; private boolean enable = true; private int keyToggle = DEFAULT_KEY_TOGGLE; private double range = DEFAULT_RANGE; private int x = DEFAULT_X; private int y = DEFAULT_Y; private int color = DEFAULT_COLOR; private ToggleKeyHandler toggleKeyHandler; @Mod.PreInit public void preInit(FMLPreInitializationEvent event) { Configuration cfg = new Configuration(event.getSuggestedConfigurationFile()); try { cfg.load(); enable = cfg.get(Configuration.CATEGORY_GENERAL, "enable", true).getBoolean(true); keyToggle = cfg.get(Configuration.CATEGORY_GENERAL, "key.toggle", DEFAULT_KEY_TOGGLE).getInt(DEFAULT_KEY_TOGGLE); range = cfg.get(Configuration.CATEGORY_GENERAL, "range", DEFAULT_RANGE).getDouble(DEFAULT_RANGE); x = cfg.get(Configuration.CATEGORY_GENERAL, "x", DEFAULT_X).getInt(DEFAULT_X); y = cfg.get(Configuration.CATEGORY_GENERAL, "y", DEFAULT_Y).getInt(DEFAULT_Y); color = cfg.get(Configuration.CATEGORY_GENERAL, "color", DEFAULT_COLOR).getInt(DEFAULT_COLOR); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "HighlightTips had a problem loading it's configuration"); } finally { cfg.save(); } if (!FMLRelauncher.side().equals("CLIENT")) { // gracefully disable on non-client (= server) instead of crashing enable = false; } if (!enable) { FMLLog.log(Level.INFO, "HighlightTips disabled"); return; } TickRegistry.registerTickHandler(this, Side.CLIENT); KeyBindingRegistry.registerKeyBinding(toggleKeyHandler = new ToggleKeyHandler(keyToggle)); } private String describeBlock(int id, int meta, TileEntity tileEntity) { StringBuilder sb = new StringBuilder(); describeBlockID(sb, id, meta); describeTileEntity(sb, tileEntity); return sb.toString(); } private void describeTileEntity(StringBuilder sb, TileEntity te) { if (te == null) return; if (te instanceof ITankContainer) { sb.append(" ITankContainer: "); ILiquidTank[] tanks = ((ITankContainer) te).getTanks(ForgeDirection.UP); for (ILiquidTank tank : tanks) { sb.append(describeLiquidStack(tank.getLiquid())); sb.append(' '); //sb.append(tank.getTankPressure()); // TODO: tank capacity *used*? this is not it.. //sb.append('/'); sb.append(tank.getCapacity()); int pressure = tank.getTankPressure(); if (pressure < 0) { sb.append(pressure); } else { sb.append('+'); sb.append(pressure); } sb.append(' '); } } if (te instanceof IInventory) { IInventory inventory = (IInventory) te; sb.append(" IInventory: "); sb.append(inventoryName(inventory)); sb.append(" ("); sb.append(inventory.getSizeInventory()); sb.append(" slots)"); } sb.append(' '); sb.append(te.getClass().getName()); } private String inventoryName(IInventory inventory) { if (!inventory.isInvNameLocalized()) { return StatCollector.translateToLocal(inventory.getInvName()); } else { return inventory.getInvName(); } } private String describeLiquidStack(LiquidStack liquidStack) { if (liquidStack == null) return "Empty"; ItemStack itemStack = liquidStack.canonical().asItemStack(); if (itemStack == null) return "Empty"; return itemStack.getDisplayName(); } private void describeBlockID(StringBuilder sb, int id, int meta) { Block block = Block.blocksList[id]; if (block == null) { sb.append("block #"+id); return; } // block info sb.append(id); sb.append(':'); sb.append(meta); sb.append(' '); String blockName = block.getLocalizedName(); if (!blockName.startsWith("You ran into")) // a serious Bug, if you have legitly acquired this Block, please report it immidietly" sb.append(blockName); // item info, if it was mined (this often has more user-friendly information, but sometimes is identical) sb.append(" "); int itemDropDamage = block.damageDropped(meta); if (Item.itemsList[id + 256] != null) { ItemStack itemDropStack = new ItemStack(id, 1, itemDropDamage); String itemDropName = itemDropStack.getDisplayName(); if (!blockName.equals(itemDropName)) { sb.append(itemDropName); } // item info guess if item damage corresponds to block metadata, not necessarily if mined - sometimes more informative try { ItemStack itemMetaStack = new ItemStack(id, 1, meta); String itemMetaName = itemMetaStack.getDisplayName(); if (itemMetaName != null && !blockName.equals(itemMetaName) && !itemDropName.equals(itemMetaName)) { sb.append(' '); sb.append(itemMetaName); } } catch (Throwable t) { } } if (itemDropDamage != meta) { sb.append(' '); sb.append(itemDropDamage); } } // based on net/minecraft/item/Item, copied since it is needlessly protected protected MovingObjectPosition getMovingObjectPositionFromPlayer(World par1World, EntityPlayer par2EntityPlayer) { float f = 1.0F; float f1 = par2EntityPlayer.prevRotationPitch + (par2EntityPlayer.rotationPitch - par2EntityPlayer.prevRotationPitch) * f; float f2 = par2EntityPlayer.prevRotationYaw + (par2EntityPlayer.rotationYaw - par2EntityPlayer.prevRotationYaw) * f; double d0 = par2EntityPlayer.prevPosX + (par2EntityPlayer.posX - par2EntityPlayer.prevPosX) * (double)f; double d1 = par2EntityPlayer.prevPosY + (par2EntityPlayer.posY - par2EntityPlayer.prevPosY) * (double)f + 1.62D - (double)par2EntityPlayer.yOffset; double d2 = par2EntityPlayer.prevPosZ + (par2EntityPlayer.posZ - par2EntityPlayer.prevPosZ) * (double)f; Vec3 vec3 = par1World.getWorldVec3Pool().getVecFromPool(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = 5.0D; if (par2EntityPlayer instanceof EntityPlayerMP) { d3 = ((EntityPlayerMP)par2EntityPlayer).theItemInWorldManager.getBlockReachDistance(); } Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3); return par1World.rayTraceBlocks_do_do(vec3, vec31, false, false); // "ray traces all blocks, including non-collideable ones" } @Override public void tickEnd(EnumSet<TickType> type, Object... tickData) { if (!toggleKeyHandler.showInfo) return; Minecraft mc = Minecraft.getMinecraft(); GuiScreen screen = mc.currentScreen; if (screen != null) return; float partialTickTime = 1; MovingObjectPosition mop = getMovingObjectPositionFromPlayer(mc.theWorld, mc.thePlayer); String s; if (mop == null) { return; } else if (mop.typeOfHit == EnumMovingObjectType.ENTITY) { // TODO: find out why this apparently never triggers s = "entity " + mop.entityHit.getClass().getName(); } else if (mop.typeOfHit == EnumMovingObjectType.TILE) { int id = mc.thePlayer.worldObj.getBlockId(mop.blockX, mop.blockY, mop.blockZ); int meta = mc.thePlayer.worldObj.getBlockMetadata(mop.blockX, mop.blockY, mop.blockZ); TileEntity tileEntity = mc.thePlayer.worldObj.blockHasTileEntity(mop.blockX, mop.blockY, mop.blockZ) ? mc.thePlayer.worldObj.getBlockTileEntity(mop.blockX, mop.blockY, mop.blockZ) : null; try { s = describeBlock(id, meta, tileEntity); } catch (Throwable t) { s = id + ":" + meta + " - " + t; t.printStackTrace(); } } else { s = "unknown"; } mc.fontRenderer.drawStringWithShadow(s, x, y, color); } @Override public void tickStart(EnumSet<TickType> type, Object... tickData) { } @Override public EnumSet<TickType> ticks() { return EnumSet.of(TickType.RENDER); } @Override public String getLabel() { return "HighlightTips"; } }
src/main/java/agaricus/mods/highlighttips/HighlightTips.java
package agaricus.mods.highlighttips; import cpw.mods.fml.client.registry.KeyBindingRegistry; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.ITickHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.TickType; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.TickRegistry; import cpw.mods.fml.relauncher.FMLRelauncher; import cpw.mods.fml.relauncher.Side; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.*; import net.minecraft.world.World; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.liquids.ILiquidTank; import net.minecraftforge.liquids.ITankContainer; import net.minecraftforge.liquids.LiquidStack; import java.util.EnumSet; import java.util.logging.Level; @Mod(modid = "HighlightTips", name = "HighlightTips", version = "1.0-SNAPSHOT") // TODO: version from resource @NetworkMod(clientSideRequired = false, serverSideRequired = false) public class HighlightTips implements ITickHandler { private static final int DEFAULT_KEY_TOGGLE = 62; // F4 - see http://www.minecraftwiki.net/wiki/Key_codes private static final double DEFAULT_RANGE = 300; private static final int DEFAULT_X = 0; private static final int DEFAULT_Y = 0; private static final int DEFAULT_COLOR = 0xffffff; private boolean enable = true; private int keyToggle = DEFAULT_KEY_TOGGLE; private double range = DEFAULT_RANGE; private int x = DEFAULT_X; private int y = DEFAULT_Y; private int color = DEFAULT_COLOR; private ToggleKeyHandler toggleKeyHandler; @Mod.PreInit public void preInit(FMLPreInitializationEvent event) { Configuration cfg = new Configuration(event.getSuggestedConfigurationFile()); try { cfg.load(); enable = cfg.get(Configuration.CATEGORY_GENERAL, "enable", true).getBoolean(true); keyToggle = cfg.get(Configuration.CATEGORY_GENERAL, "key.toggle", DEFAULT_KEY_TOGGLE).getInt(DEFAULT_KEY_TOGGLE); range = cfg.get(Configuration.CATEGORY_GENERAL, "range", DEFAULT_RANGE).getDouble(DEFAULT_RANGE); x = cfg.get(Configuration.CATEGORY_GENERAL, "x", DEFAULT_X).getInt(DEFAULT_X); y = cfg.get(Configuration.CATEGORY_GENERAL, "y", DEFAULT_Y).getInt(DEFAULT_Y); color = cfg.get(Configuration.CATEGORY_GENERAL, "color", DEFAULT_COLOR).getInt(DEFAULT_COLOR); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "HighlightTips had a problem loading it's configuration"); } finally { cfg.save(); } if (!FMLRelauncher.side().equals("CLIENT")) { // gracefully disable on non-client (= server) instead of crashing enable = false; } if (!enable) { FMLLog.log(Level.INFO, "HighlightTips disabled"); return; } TickRegistry.registerTickHandler(this, Side.CLIENT); KeyBindingRegistry.registerKeyBinding(toggleKeyHandler = new ToggleKeyHandler(keyToggle)); } private String describeBlock(int id, int meta, TileEntity tileEntity) { StringBuilder sb = new StringBuilder(); describeBlockID(sb, id, meta); describeTileEntity(sb, tileEntity); return sb.toString(); } private void describeTileEntity(StringBuilder sb, TileEntity te) { if (te == null) return; if (te instanceof ITankContainer) { sb.append(" ITankContainer: "); ILiquidTank[] tanks = ((ITankContainer) te).getTanks(ForgeDirection.UP); for (ILiquidTank tank : tanks) { sb.append(describeLiquidStack(tank.getLiquid())); sb.append(' '); //sb.append(tank.getTankPressure()); // TODO: tank capacity *used*? this is not it.. //sb.append('/'); sb.append(tank.getCapacity()); int pressure = tank.getTankPressure(); if (pressure < 0) { sb.append(pressure); } else { sb.append('+'); sb.append(pressure); } sb.append(' '); } } if (te instanceof IInventory) { IInventory inventory = (IInventory) te; sb.append(" IInventory: "); sb.append(inventoryName(inventory)); sb.append(" ("); sb.append(inventory.getSizeInventory()); sb.append(" slots)"); } sb.append(' '); sb.append(te.getClass().getName()); } private String inventoryName(IInventory inventory) { if (!inventory.isInvNameLocalized()) { return StatCollector.translateToLocal(inventory.getInvName()); } else { return inventory.getInvName(); } } private String describeLiquidStack(LiquidStack liquidStack) { if (liquidStack == null) return "Empty"; ItemStack itemStack = liquidStack.canonical().asItemStack(); if (itemStack == null) return "Empty"; return itemStack.getDisplayName(); } private void describeBlockID(StringBuilder sb, int id, int meta) { Block block = Block.blocksList[id]; if (block == null) { sb.append("block #"+id); return; } // block info sb.append(id); sb.append(':'); sb.append(meta); sb.append(' '); String blockName = block.getLocalizedName(); sb.append(blockName); // item info, if it was mined (this often has more user-friendly information, but sometimes is identical) sb.append(" "); int itemDropDamage = block.damageDropped(meta); if (Item.itemsList[id + 256] != null) { ItemStack itemDropStack = new ItemStack(id, 1, itemDropDamage); String itemDropName = itemDropStack.getDisplayName(); if (!blockName.equals(itemDropName)) { sb.append(itemDropName); } // item info guess if item damage corresponds to block metadata, not necessarily if mined - sometimes more informative try { ItemStack itemMetaStack = new ItemStack(id, 1, meta); String itemMetaName = itemMetaStack.getDisplayName(); if (itemMetaName != null && !blockName.equals(itemMetaName) && !itemDropName.equals(itemMetaName)) { sb.append(' '); sb.append(itemMetaName); } } catch (Throwable t) { } } if (itemDropDamage != meta) { sb.append(' '); sb.append(itemDropDamage); } } // based on net/minecraft/item/Item, copied since it is needlessly protected protected MovingObjectPosition getMovingObjectPositionFromPlayer(World par1World, EntityPlayer par2EntityPlayer) { float f = 1.0F; float f1 = par2EntityPlayer.prevRotationPitch + (par2EntityPlayer.rotationPitch - par2EntityPlayer.prevRotationPitch) * f; float f2 = par2EntityPlayer.prevRotationYaw + (par2EntityPlayer.rotationYaw - par2EntityPlayer.prevRotationYaw) * f; double d0 = par2EntityPlayer.prevPosX + (par2EntityPlayer.posX - par2EntityPlayer.prevPosX) * (double)f; double d1 = par2EntityPlayer.prevPosY + (par2EntityPlayer.posY - par2EntityPlayer.prevPosY) * (double)f + 1.62D - (double)par2EntityPlayer.yOffset; double d2 = par2EntityPlayer.prevPosZ + (par2EntityPlayer.posZ - par2EntityPlayer.prevPosZ) * (double)f; Vec3 vec3 = par1World.getWorldVec3Pool().getVecFromPool(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = 5.0D; if (par2EntityPlayer instanceof EntityPlayerMP) { d3 = ((EntityPlayerMP)par2EntityPlayer).theItemInWorldManager.getBlockReachDistance(); } Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3); return par1World.rayTraceBlocks_do_do(vec3, vec31, false, false); // "ray traces all blocks, including non-collideable ones" } @Override public void tickEnd(EnumSet<TickType> type, Object... tickData) { if (!toggleKeyHandler.showInfo) return; Minecraft mc = Minecraft.getMinecraft(); GuiScreen screen = mc.currentScreen; if (screen != null) return; float partialTickTime = 1; MovingObjectPosition mop = getMovingObjectPositionFromPlayer(mc.theWorld, mc.thePlayer); String s; if (mop == null) { return; } else if (mop.typeOfHit == EnumMovingObjectType.ENTITY) { // TODO: find out why this apparently never triggers s = "entity " + mop.entityHit.getClass().getName(); } else if (mop.typeOfHit == EnumMovingObjectType.TILE) { int id = mc.thePlayer.worldObj.getBlockId(mop.blockX, mop.blockY, mop.blockZ); int meta = mc.thePlayer.worldObj.getBlockMetadata(mop.blockX, mop.blockY, mop.blockZ); TileEntity tileEntity = mc.thePlayer.worldObj.blockHasTileEntity(mop.blockX, mop.blockY, mop.blockZ) ? mc.thePlayer.worldObj.getBlockTileEntity(mop.blockX, mop.blockY, mop.blockZ) : null; try { s = describeBlock(id, meta, tileEntity); } catch (Throwable t) { s = id + ":" + meta + " - " + t; t.printStackTrace(); } } else { s = "unknown"; } mc.fontRenderer.drawStringWithShadow(s, x, y, color); } @Override public void tickStart(EnumSet<TickType> type, Object... tickData) { } @Override public EnumSet<TickType> ticks() { return EnumSet.of(TickType.RENDER); } @Override public String getLabel() { return "HighlightTips"; } }
Elide the GregTech 'You ran into a serious Bug, if you have legitly acquired this Block, please report it immidietly' block name Ideally should get the block name via the GregTech API, getDescription() on the TE; Greg returns this message instead since the block information is not available from the ID and metadata alone. But we get a fairly accurate name from the IInventory getInvName(), and this message takes up a large portion of the screen, so don't show it.
src/main/java/agaricus/mods/highlighttips/HighlightTips.java
Elide the GregTech 'You ran into a serious Bug, if you have legitly acquired this Block, please report it immidietly' block name
Java
bsd-3-clause
bba4c1320395ae9c99317047b087c1ec8cb67b41
0
gosu-lang/gradle-gosu-plugin
src/test/java/org/gosulang/gradle/functional/SanityTest.java
package org.gosulang.gradle.functional; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import static org.gradle.testkit.runner.TaskOutcome.*; import static org.junit.Assert.*; public class SanityTest extends AbstractGradleTest { @Rule public final TemporaryFolder testProjectDir = new TemporaryFolder(); private File _buildFile; @Before public void beforeMethod() throws IOException { _buildFile = testProjectDir.newFile("build.gradle"); } @Test public void applyGosuPlugin() throws IOException { String buildFileContent = "task helloWorld {" + " doLast {" + " println 'Hello world!'" + " }" + "}"; writeFile(_buildFile, buildFileContent); BuildResult result = GradleRunner.create() .withProjectDir(testProjectDir.getRoot()) .withArguments("helloWorld", "-i") .build(); System.out.println("--- Dumping stdout ---"); System.out.println(result.getStandardOutput()); System.out.println("--- Done dumping stdout ---"); assertTrue(result.getStandardOutput().contains("Hello world!")); assertTrue(result.getStandardError().isEmpty()); assertEquals(result.task(":helloWorld").getOutcome(), SUCCESS); } }
Removing useless test
src/test/java/org/gosulang/gradle/functional/SanityTest.java
Removing useless test