lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
mit
6a93dd378f8f0ab5fa03f3b1f0d1ce391fc99363
0
trendrr/strest-server,trendrr/strest-server
/** * */ package com.trendrr.strest.contrib.filters; import java.io.UnsupportedEncodingException; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpResponse; import com.trendrr.oss.ListHelper; import com.trendrr.oss.TypeCast; import com.trendrr.strest.ContentTypes; import com.trendrr.strest.StrestException; import com.trendrr.strest.StrestHttpException; import com.trendrr.strest.StrestUtil.HEADERS; import com.trendrr.strest.server.ResponseBuilder; import com.trendrr.strest.server.StrestController; import com.trendrr.strest.server.StrestControllerFilter; /** * * Simple filter to handle jsonp requests. * * * @author Dustin Norlander * @created Apr 12, 2011 * */ public class JsonpFilter implements StrestControllerFilter { protected Log log = LogFactory.getLog(JsonpFilter.class); private static Collection<String> params = ListHelper.toTypedList(String.class, "jsonp,callback", ","); /** * returns the possible names for the jsonp param. * defaults to ['jsonp','callback'] * @return */ protected Collection<String> getParamNames() { return params; } /* (non-Javadoc) * @see com.trendrr.strest.server.StrestControllerFilter#before(com.trendrr.strest.server.StrestController) */ @Override public void before(StrestController controller) throws StrestException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.trendrr.strest.server.StrestControllerFilter#after(com.trendrr.strest.server.StrestController) */ @Override public void after(StrestController controller) throws StrestException { HttpResponse response = controller.getResponse(); if (!ContentTypes.JSON.equals(response.getHeader(HttpHeaders.Names.CONTENT_TYPE))) { return; } String param = null; for (String p : this.getParamNames()) { param = controller.getParams().getString(p); if (param != null) break; } if (param == null) return; try { String jsonp = param +"(" + new String(response.getContent().array(), "utf8") + ");"; ResponseBuilder.instance(response).content(ContentTypes.JAVASCRIPT, jsonp.getBytes("utf8")); } catch (UnsupportedEncodingException e) { throw StrestHttpException.INTERNAL_SERVER_ERROR(e.getMessage()); } } /* (non-Javadoc) * @see com.trendrr.strest.server.StrestControllerFilter#error(com.trendrr.strest.server.StrestController, org.jboss.netty.handler.codec.http.HttpResponse, java.lang.Exception) */ @Override public void error(StrestController controller, HttpResponse response, Exception exception) { // TODO Auto-generated method stub } }
src/com/trendrr/strest/contrib/filters/JsonpFilter.java
/** * */ package com.trendrr.strest.contrib.filters; import java.io.UnsupportedEncodingException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpResponse; import com.trendrr.strest.ContentTypes; import com.trendrr.strest.StrestException; import com.trendrr.strest.StrestHttpException; import com.trendrr.strest.StrestUtil.HEADERS; import com.trendrr.strest.server.ResponseBuilder; import com.trendrr.strest.server.StrestController; import com.trendrr.strest.server.StrestControllerFilter; /** * * Simple filter to handle jsonp requests. * * * @author Dustin Norlander * @created Apr 12, 2011 * */ public class JsonpFilter implements StrestControllerFilter { protected Log log = LogFactory.getLog(JsonpFilter.class); String jsonpParam = "jsonp"; /* (non-Javadoc) * @see com.trendrr.strest.server.StrestControllerFilter#before(com.trendrr.strest.server.StrestController) */ @Override public void before(StrestController controller) throws StrestException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.trendrr.strest.server.StrestControllerFilter#after(com.trendrr.strest.server.StrestController) */ @Override public void after(StrestController controller) throws StrestException { HttpResponse response = controller.getResponse(); if (!ContentTypes.JSON.equals(response.getHeader(HttpHeaders.Names.CONTENT_TYPE))) { return; } String param = controller.getParams().getString(this.jsonpParam); if (param == null) return; try { String jsonp = param +"(" + new String(response.getContent().array(), "utf8") + ");"; ResponseBuilder.instance(response).content(ContentTypes.JAVASCRIPT, jsonp.getBytes("utf8")); } catch (UnsupportedEncodingException e) { throw StrestHttpException.INTERNAL_SERVER_ERROR(e.getMessage()); } } /* (non-Javadoc) * @see com.trendrr.strest.server.StrestControllerFilter#error(com.trendrr.strest.server.StrestController, org.jboss.netty.handler.codec.http.HttpResponse, java.lang.Exception) */ @Override public void error(StrestController controller, HttpResponse response, Exception exception) { // TODO Auto-generated method stub } }
add callback as a possible jsonp param
src/com/trendrr/strest/contrib/filters/JsonpFilter.java
add callback as a possible jsonp param
<ide><path>rc/com/trendrr/strest/contrib/filters/JsonpFilter.java <ide> package com.trendrr.strest.contrib.filters; <ide> <ide> import java.io.UnsupportedEncodingException; <add>import java.util.Collection; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.jboss.netty.handler.codec.http.HttpHeaders; <ide> import org.jboss.netty.handler.codec.http.HttpResponse; <ide> <add>import com.trendrr.oss.ListHelper; <add>import com.trendrr.oss.TypeCast; <ide> import com.trendrr.strest.ContentTypes; <ide> import com.trendrr.strest.StrestException; <ide> import com.trendrr.strest.StrestHttpException; <ide> public class JsonpFilter implements StrestControllerFilter { <ide> <ide> protected Log log = LogFactory.getLog(JsonpFilter.class); <del> <del> String jsonpParam = "jsonp"; <add> <add> private static Collection<String> params = ListHelper.toTypedList(String.class, "jsonp,callback", ","); <add> <add> /** <add> * returns the possible names for the jsonp param. <add> * defaults to ['jsonp','callback'] <add> * @return <add> */ <add> protected Collection<String> getParamNames() { <add> return params; <add> } <ide> <ide> /* (non-Javadoc) <ide> * @see com.trendrr.strest.server.StrestControllerFilter#before(com.trendrr.strest.server.StrestController) <ide> if (!ContentTypes.JSON.equals(response.getHeader(HttpHeaders.Names.CONTENT_TYPE))) { <ide> return; <ide> } <del> String param = controller.getParams().getString(this.jsonpParam); <add> String param = null; <add> for (String p : this.getParamNames()) { <add> param = controller.getParams().getString(p); <add> if (param != null) <add> break; <add> } <ide> if (param == null) <ide> return; <ide> try {
Java
apache-2.0
080e83aedab127410ef62cf4722cb9e4a0354f04
0
UweTrottmann/SeriesGuide,epiphany27/SeriesGuide,hoanganhx86/SeriesGuide,artemnikitin/SeriesGuide,UweTrottmann/SeriesGuide,r00t-user/SeriesGuide,0359xiaodong/SeriesGuide
package com.battlelancer.seriesguide.ui; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.battlelancer.seriesguide.Constants; import com.battlelancer.seriesguide.Constants.SeasonSorting; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.provider.SeriesContract.Episodes; import com.battlelancer.seriesguide.provider.SeriesContract.Seasons; import com.battlelancer.seriesguide.ui.dialogs.SortDialogFragment; import com.battlelancer.seriesguide.util.AnalyticsUtils; import com.battlelancer.seriesguide.util.DBUtils; import android.content.ContentValues; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.Cursor; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v4.widget.SimpleCursorAdapter.ViewBinder; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; public class SeasonsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final int ID_MARK_ALL_WATCHED = 0; private static final int ID_MARK_ALL_UNWATCHED = 1; private static final int LOADER_ID = 1; private Constants.SeasonSorting mSorting; private SimpleCursorAdapter mAdapter; /** * All values have to be integer. */ public interface InitBundle { String SHOW_TVDBID = "show_tvdbid"; } public static SeasonsFragment newInstance(int showId) { SeasonsFragment f = new SeasonsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt(InitBundle.SHOW_TVDBID, showId); f.setArguments(args); return f; } public void fireTrackerEvent(String label) { AnalyticsUtils.getInstance(getActivity()).trackEvent("Seasons", "Click", label, 0); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Seasons"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.list_fragment, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); updatePreferences(); // listen to changes to the sorting preference final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); prefs.registerOnSharedPreferenceChangeListener(mPrefsListener); // populate list fillData(); registerForContextMenu(getListView()); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); updatePreferences(); updateUnwatchedCounts(false); } @Override public void onDestroy() { super.onDestroy(); // stop listening to sort pref changes final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); prefs.unregisterOnSharedPreferenceChangeListener(mPrefsListener); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, ID_MARK_ALL_WATCHED, 0, R.string.mark_all); menu.add(0, ID_MARK_ALL_UNWATCHED, 1, R.string.unmark_all); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case ID_MARK_ALL_WATCHED: markSeasonEpisodes(info.id, true); return true; case ID_MARK_ALL_UNWATCHED: markSeasonEpisodes(info.id, false); return true; } return super.onContextItemSelected(item); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.seasonlist_menu, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { if (Build.VERSION.SDK_INT >= 11) { final CharSequence[] items = getResources().getStringArray(R.array.sesorting); menu.findItem(R.id.menu_sesortby).setTitle( getString(R.string.sort) + ": " + items[mSorting.index()]); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_markall: fireTrackerEvent("Mark all seasons"); markAllEpisodes(true); return true; case R.id.menu_unmarkall: fireTrackerEvent("Unmark all seasons"); markAllEpisodes(false); return true; case R.id.menu_sesortby: fireTrackerEvent("Sort seasons"); showSortDialog(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { Intent intent = new Intent(getActivity(), EpisodesActivity.class); final Cursor item = (Cursor) (getListView().getItemAtPosition(position)); final int seasonNumber = item.getInt(SeasonsQuery.COMBINED); intent.putExtra(EpisodesActivity.InitBundle.SHOW_TVDBID, getShowId()); intent.putExtra(EpisodesActivity.InitBundle.SEASON_TVDBID, (int) id); intent.putExtra(EpisodesActivity.InitBundle.SEASON_NUMBER, seasonNumber); startActivity(intent); getSherlockActivity().overridePendingTransition(R.anim.fragment_slide_left_enter, R.anim.fragment_slide_left_exit); } private void fillData() { String[] from = new String[] { Seasons.COMBINED, Seasons.WATCHCOUNT, Seasons.TOTALCOUNT }; int[] to = new int[] { R.id.TextViewSeasonListTitle, R.id.TextViewSeasonListWatchCount, R.id.season_row_root }; mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.season_row, null, from, to, CursorAdapter.NO_SELECTION); mAdapter.setViewBinder(new ViewBinder() { public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (columnIndex == SeasonsQuery.WATCHCOUNT) { final TextView watchcount = (TextView) view; String episodeCount = ""; final int count = cursor.getInt(SeasonsQuery.WATCHCOUNT); final int unairedCount = cursor.getInt(SeasonsQuery.UNAIREDCOUNT); final int noairdateCount = cursor.getInt(SeasonsQuery.NOAIRDATECOUNT); // add strings for unwatched episodes if (count == 0) { // make sure there are no unchecked episodes that happen // to have no airdate if (noairdateCount == 0) { episodeCount += getString(R.string.season_allwatched); } else { episodeCount += noairdateCount + " "; if (noairdateCount == 1) { episodeCount += getString(R.string.oneotherepisode); } else { episodeCount += getString(R.string.otherepisodes); } } watchcount.setTextColor(Color.GRAY); } else if (count == 1) { episodeCount += count + " " + getString(R.string.season_onenotwatched); watchcount.setTextColor(Color.WHITE); } else { episodeCount += count + " " + getString(R.string.season_watchcount); watchcount.setTextColor(Color.WHITE); } // add strings for unaired episodes if (unairedCount > 0) { episodeCount += " (+" + unairedCount + " " + getString(R.string.season_unaired) + ")"; } watchcount.setText(episodeCount); return true; } if (columnIndex == SeasonsQuery.TOTALCOUNT) { final int count = cursor.getInt(SeasonsQuery.WATCHCOUNT); final int unairedCount = cursor.getInt(SeasonsQuery.UNAIREDCOUNT); final int noairdateCount = cursor.getInt(SeasonsQuery.NOAIRDATECOUNT); final int max = cursor.getInt(SeasonsQuery.TOTALCOUNT); final int progress = max - count - unairedCount - noairdateCount; final ProgressBar bar = (ProgressBar) view.findViewById(R.id.seasonProgressBar); final TextView text = (TextView) view.findViewById(R.id.seasonProgressText); bar.setMax(max); bar.setProgress(progress); text.setText(progress + "/" + max); return true; } if (columnIndex == SeasonsQuery.COMBINED) { final TextView seasonNameTextView = (TextView) view; final String seasonNumber = cursor.getString(SeasonsQuery.COMBINED); final String seasonName; if (seasonNumber.equals("0") || seasonNumber.length() == 0) { seasonName = getString(R.string.specialseason); } else { seasonName = getString(R.string.season) + " " + seasonNumber; } seasonNameTextView.setText(seasonName); return true; } return false; } }); setListAdapter(mAdapter); // now let's get a loader or reconnect to existing one getLoaderManager().initLoader(LOADER_ID, null, this); } private int getShowId() { return getArguments().getInt(InitBundle.SHOW_TVDBID); } /** * Mark all episodes of the given season, updates the status label of the * season. * * @param seasonid * @param state */ private void markSeasonEpisodes(long seasonid, boolean state) { DBUtils.markSeasonEpisodes(getActivity(), String.valueOf(seasonid), state); Thread t = new UpdateUnwatchThread(String.valueOf(getShowId()), String.valueOf(seasonid), true); t.start(); } /** * Mark all episodes of the given show, updates the status labels of the * season. * * @param seasonid * @param state */ private void markAllEpisodes(boolean state) { ContentValues values = new ContentValues(); values.put(Episodes.WATCHED, state); getActivity().getContentResolver().update( Episodes.buildEpisodesOfShowUri(String.valueOf(getShowId())), values, null, null); updateUnwatchedCounts(true); } /** * Update unwatched stats for all seasons of this fragments show. Requeries * the list afterwards. */ protected void updateUnwatchedCounts(boolean updateOverview) { Thread t = new UpdateUnwatchThread(String.valueOf(getShowId()), updateOverview); t.start(); } private class UpdateUnwatchThread extends Thread { private String mSeasonId; private String mShowId; private boolean mUpdateOverview; public UpdateUnwatchThread(String showId, String seasonid, boolean updateOverview) { this(showId, updateOverview); mSeasonId = seasonid; } public UpdateUnwatchThread(String showId, boolean updateOverview) { mShowId = showId; mUpdateOverview = updateOverview; this.setName("UpdateWatchStatsThread"); } public void run() { final FragmentActivity context = getActivity(); if (context == null) { return; } final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (mSeasonId != null) { // update one season DBUtils.updateUnwatchedCount(context, mSeasonId, prefs); } else { // update all seasons of this show final Cursor seasons = context.getContentResolver().query( Seasons.buildSeasonsOfShowUri(mShowId), new String[] { Seasons._ID }, null, null, null); while (seasons.moveToNext()) { String seasonId = seasons.getString(0); DBUtils.updateUnwatchedCount(context, seasonId, prefs); notifyContentProvider(context); } seasons.close(); } notifyContentProvider(context); if (mUpdateOverview) { OverviewFragment overview = (OverviewFragment) context.getSupportFragmentManager() .findFragmentById(R.id.fragment_overview); if (overview != null) { overview.onLoadEpisode(); } } } private void notifyContentProvider(final FragmentActivity context) { context.getContentResolver().notifyChange(Seasons.buildSeasonsOfShowUri(mShowId), null); } } private void updatePreferences() { final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); mSorting = SeasonSorting.fromValue(prefs.getString( SeriesGuidePreferences.KEY_SEASON_SORT_ORDER, SeasonSorting.LATEST_FIRST.value())); } public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { return new CursorLoader(getActivity(), Seasons.buildSeasonsOfShowUri(String .valueOf(getShowId())), SeasonsQuery.PROJECTION, null, null, mSorting.query()); } public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); } public void onLoaderReset(Loader<Cursor> arg0) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } private interface SeasonsQuery { String[] PROJECTION = { BaseColumns._ID, Seasons.COMBINED, Seasons.WATCHCOUNT, Seasons.UNAIREDCOUNT, Seasons.NOAIRDATECOUNT, Seasons.TOTALCOUNT }; // int _ID = 0; int COMBINED = 1; int WATCHCOUNT = 2; int UNAIREDCOUNT = 3; int NOAIRDATECOUNT = 4; int TOTALCOUNT = 5; } private void showSortDialog() { FragmentManager fm = getFragmentManager(); SortDialogFragment sortDialog = SortDialogFragment.newInstance(R.array.sesorting, R.array.sesortingData, mSorting.index(), SeriesGuidePreferences.KEY_SEASON_SORT_ORDER, R.string.pref_seasonsorting); sortDialog.show(fm, "fragment_sort"); } private final OnSharedPreferenceChangeListener mPrefsListener = new OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(SeriesGuidePreferences.KEY_SEASON_SORT_ORDER)) { updateSorting(sharedPreferences); } } }; private void updateSorting(SharedPreferences prefs) { mSorting = SeasonSorting.fromValue(prefs.getString( SeriesGuidePreferences.KEY_SEASON_SORT_ORDER, SeasonSorting.LATEST_FIRST.value())); AnalyticsUtils.getInstance(getActivity()).trackEvent("Seasons", "Sorting", mSorting.name(), 0); // restart loader and update menu description getLoaderManager().restartLoader(LOADER_ID, null, SeasonsFragment.this); getSherlockActivity().invalidateOptionsMenu(); } }
SeriesGuide/src/com/battlelancer/seriesguide/ui/SeasonsFragment.java
package com.battlelancer.seriesguide.ui; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.battlelancer.seriesguide.Constants; import com.battlelancer.seriesguide.Constants.SeasonSorting; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.provider.SeriesContract.Episodes; import com.battlelancer.seriesguide.provider.SeriesContract.Seasons; import com.battlelancer.seriesguide.ui.dialogs.SortDialogFragment; import com.battlelancer.seriesguide.util.AnalyticsUtils; import com.battlelancer.seriesguide.util.DBUtils; import android.content.ContentValues; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.Cursor; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v4.widget.SimpleCursorAdapter.ViewBinder; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; public class SeasonsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final int ID_MARK_ALL_WATCHED = 0; private static final int ID_MARK_ALL_UNWATCHED = 1; private static final int LOADER_ID = 1; private Constants.SeasonSorting mSorting; private SimpleCursorAdapter mAdapter; /** * All values have to be integer. */ public interface InitBundle { String SHOW_TVDBID = "show_tvdbid"; } public static SeasonsFragment newInstance(int showId) { SeasonsFragment f = new SeasonsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt(InitBundle.SHOW_TVDBID, showId); f.setArguments(args); return f; } public void fireTrackerEvent(String label) { AnalyticsUtils.getInstance(getActivity()).trackEvent("Seasons", "Click", label, 0); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Seasons"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.list_fragment, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); updatePreferences(); // listen to changes to the sorting preference final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); prefs.registerOnSharedPreferenceChangeListener(mPrefsListener); // populate list fillData(); registerForContextMenu(getListView()); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); updatePreferences(); updateUnwatchedCounts(false); } @Override public void onDestroy() { super.onDestroy(); // stop listening to sort pref changes final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); prefs.unregisterOnSharedPreferenceChangeListener(mPrefsListener); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, ID_MARK_ALL_WATCHED, 0, R.string.mark_all); menu.add(0, ID_MARK_ALL_UNWATCHED, 1, R.string.unmark_all); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case ID_MARK_ALL_WATCHED: markSeasonEpisodes(info.id, true); return true; case ID_MARK_ALL_UNWATCHED: markSeasonEpisodes(info.id, false); return true; } return super.onContextItemSelected(item); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.seasonlist_menu, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { if (Build.VERSION.SDK_INT >= 11) { final CharSequence[] items = getResources().getStringArray(R.array.sesorting); menu.findItem(R.id.menu_sesortby).setTitle( getString(R.string.sort) + ": " + items[mSorting.index()]); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_markall: fireTrackerEvent("Mark all seasons"); markAllEpisodes(true); return true; case R.id.menu_unmarkall: fireTrackerEvent("Unmark all seasons"); markAllEpisodes(false); return true; case R.id.menu_sesortby: fireTrackerEvent("Sort seasons"); showSortDialog(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { Intent intent = new Intent(getActivity(), EpisodesActivity.class); final Cursor item = (Cursor) (getListView().getItemAtPosition(position)); final int seasonNumber = item.getInt(SeasonsQuery.COMBINED); intent.putExtra(EpisodesActivity.InitBundle.SHOW_TVDBID, getShowId()); intent.putExtra(EpisodesActivity.InitBundle.SEASON_TVDBID, (int) id); intent.putExtra(EpisodesActivity.InitBundle.SEASON_NUMBER, seasonNumber); startActivity(intent); getSherlockActivity().overridePendingTransition(R.anim.fragment_slide_left_enter, R.anim.fragment_slide_left_exit); } private void fillData() { String[] from = new String[] { Seasons.COMBINED, Seasons.WATCHCOUNT, Seasons.TOTALCOUNT }; int[] to = new int[] { R.id.TextViewSeasonListTitle, R.id.TextViewSeasonListWatchCount, R.id.season_row_root }; mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.season_row, null, from, to, CursorAdapter.NO_SELECTION); mAdapter.setViewBinder(new ViewBinder() { public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (columnIndex == SeasonsQuery.WATCHCOUNT) { final TextView watchcount = (TextView) view; String episodeCount = ""; final int count = cursor.getInt(SeasonsQuery.WATCHCOUNT); final int unairedCount = cursor.getInt(SeasonsQuery.UNAIREDCOUNT); final int noairdateCount = cursor.getInt(SeasonsQuery.NOAIRDATECOUNT); // add strings for unwatched episodes if (count == 0) { // make sure there are no unchecked episodes that happen // to have no airdate if (noairdateCount == 0) { episodeCount += getString(R.string.season_allwatched); } else { episodeCount += noairdateCount + " "; if (noairdateCount == 1) { episodeCount += getString(R.string.oneotherepisode); } else { episodeCount += getString(R.string.otherepisodes); } } watchcount.setTextColor(Color.GRAY); } else if (count == 1) { episodeCount += count + " " + getString(R.string.season_onenotwatched); watchcount.setTextColor(Color.WHITE); } else { episodeCount += count + " " + getString(R.string.season_watchcount); watchcount.setTextColor(Color.WHITE); } // add strings for unaired episodes if (unairedCount > 0) { episodeCount += " (+" + unairedCount + " " + getString(R.string.season_unaired) + ")"; } watchcount.setText(episodeCount); return true; } if (columnIndex == SeasonsQuery.TOTALCOUNT) { final int count = cursor.getInt(SeasonsQuery.WATCHCOUNT); final int unairedCount = cursor.getInt(SeasonsQuery.UNAIREDCOUNT); final int noairdateCount = cursor.getInt(SeasonsQuery.NOAIRDATECOUNT); final int max = cursor.getInt(SeasonsQuery.TOTALCOUNT); final int progress = max - count - unairedCount - noairdateCount; final ProgressBar bar = (ProgressBar) view.findViewById(R.id.seasonProgressBar); final TextView text = (TextView) view.findViewById(R.id.seasonProgressText); bar.setMax(max); bar.setProgress(progress); text.setText(progress + "/" + max); return true; } if (columnIndex == SeasonsQuery.COMBINED) { final TextView seasonNameTextView = (TextView) view; final String seasonNumber = cursor.getString(SeasonsQuery.COMBINED); final String seasonName; if (seasonNumber.equals("0") || seasonNumber.length() == 0) { seasonName = getString(R.string.specialseason); } else { seasonName = getString(R.string.season) + " " + seasonNumber; } seasonNameTextView.setText(seasonName); return true; } return false; } }); setListAdapter(mAdapter); // now let's get a loader or reconnect to existing one getLoaderManager().initLoader(LOADER_ID, null, this); } private int getShowId() { return getArguments().getInt(InitBundle.SHOW_TVDBID); } /** * Mark all episodes of the given season, updates the status label of the * season. * * @param seasonid * @param state */ private void markSeasonEpisodes(long seasonid, boolean state) { DBUtils.markSeasonEpisodes(getActivity(), String.valueOf(seasonid), state); Thread t = new UpdateUnwatchThread(String.valueOf(getShowId()), String.valueOf(seasonid), true); t.start(); } /** * Mark all episodes of the given show, updates the status labels of the * season. * * @param seasonid * @param state */ private void markAllEpisodes(boolean state) { ContentValues values = new ContentValues(); values.put(Episodes.WATCHED, state); getActivity().getContentResolver().update( Episodes.buildEpisodesOfShowUri(String.valueOf(getShowId())), values, null, null); updateUnwatchedCounts(true); } /** * Update unwatched stats for all seasons of this fragments show. Requeries * the list afterwards. */ protected void updateUnwatchedCounts(boolean updateOverview) { Thread t = new UpdateUnwatchThread(String.valueOf(getShowId()), updateOverview); t.start(); } private class UpdateUnwatchThread extends Thread { private String mSeasonId; private String mShowId; private boolean mUpdateOverview; public UpdateUnwatchThread(String showId, String seasonid, boolean updateOverview) { this(showId, updateOverview); mSeasonId = seasonid; } public UpdateUnwatchThread(String showId, boolean updateOverview) { mShowId = showId; mUpdateOverview = updateOverview; this.setName("UpdateWatchStatsThread"); } public void run() { final FragmentActivity context = getActivity(); if (context == null) { return; } final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (mSeasonId != null) { // update one season DBUtils.updateUnwatchedCount(context, mSeasonId, prefs); } else { // update all seasons of this show final Cursor seasons = context.getContentResolver().query( Seasons.buildSeasonsOfShowUri(mShowId), new String[] { Seasons._ID }, null, null, null); while (seasons.moveToNext()) { String seasonId = seasons.getString(0); DBUtils.updateUnwatchedCount(context, seasonId, prefs); notifyContentProvider(context); } seasons.close(); } notifyContentProvider(context); if (mUpdateOverview) { OverviewFragment overview = (OverviewFragment) context.getSupportFragmentManager() .findFragmentById(R.id.fragment_overview); if (overview != null) { overview.onLoadEpisode(); } } } private void notifyContentProvider(final FragmentActivity context) { context.getContentResolver().notifyChange(Seasons.buildSeasonsOfShowUri(mShowId), null); } } private void updatePreferences() { final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); if (prefs.getString(SeriesGuidePreferences.KEY_SEASON_SORT_ORDER, "latestfirst").equals( "latestfirst")) { mSorting = Constants.SeasonSorting.LATEST_FIRST; } else { mSorting = Constants.SeasonSorting.OLDEST_FIRST; } } public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { return new CursorLoader(getActivity(), Seasons.buildSeasonsOfShowUri(String .valueOf(getShowId())), SeasonsQuery.PROJECTION, null, null, mSorting.query()); } public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); } public void onLoaderReset(Loader<Cursor> arg0) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } private interface SeasonsQuery { String[] PROJECTION = { BaseColumns._ID, Seasons.COMBINED, Seasons.WATCHCOUNT, Seasons.UNAIREDCOUNT, Seasons.NOAIRDATECOUNT, Seasons.TOTALCOUNT }; // int _ID = 0; int COMBINED = 1; int WATCHCOUNT = 2; int UNAIREDCOUNT = 3; int NOAIRDATECOUNT = 4; int TOTALCOUNT = 5; } private void showSortDialog() { FragmentManager fm = getFragmentManager(); SortDialogFragment sortDialog = SortDialogFragment.newInstance(R.array.sesorting, R.array.sesortingData, mSorting.index(), SeriesGuidePreferences.KEY_SEASON_SORT_ORDER, R.string.pref_seasonsorting); sortDialog.show(fm, "fragment_sort"); } private final OnSharedPreferenceChangeListener mPrefsListener = new OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(SeriesGuidePreferences.KEY_SEASON_SORT_ORDER)) { updateSorting(sharedPreferences); } } }; private void updateSorting(SharedPreferences prefs) { mSorting = SeasonSorting.fromValue(prefs.getString( SeriesGuidePreferences.KEY_SEASON_SORT_ORDER, SeasonSorting.LATEST_FIRST.value())); AnalyticsUtils.getInstance(getActivity()).trackEvent("Seasons", "Sorting", mSorting.name(), 0); // restart loader and update menu description getLoaderManager().restartLoader(LOADER_ID, null, SeasonsFragment.this); getSherlockActivity().invalidateOptionsMenu(); } }
Simplify updating of sorting for SeasonsFragment.
SeriesGuide/src/com/battlelancer/seriesguide/ui/SeasonsFragment.java
Simplify updating of sorting for SeasonsFragment.
<ide><path>eriesGuide/src/com/battlelancer/seriesguide/ui/SeasonsFragment.java <ide> private void updatePreferences() { <ide> final SharedPreferences prefs = PreferenceManager <ide> .getDefaultSharedPreferences(getActivity()); <del> if (prefs.getString(SeriesGuidePreferences.KEY_SEASON_SORT_ORDER, "latestfirst").equals( <del> "latestfirst")) { <del> mSorting = Constants.SeasonSorting.LATEST_FIRST; <del> } else { <del> mSorting = Constants.SeasonSorting.OLDEST_FIRST; <del> } <add> mSorting = SeasonSorting.fromValue(prefs.getString( <add> SeriesGuidePreferences.KEY_SEASON_SORT_ORDER, SeasonSorting.LATEST_FIRST.value())); <ide> } <ide> <ide> public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
JavaScript
mit
f24f30da1c4cb9b43194b9e4774dc51ad5c00521
0
gethuman/pancakes
/** * Author: Jeff Whelpley * Date: 2/6/15 * * Page helper this should be kept in sync with the client side PageHelper */ var utils = require('./utensils'); function PageHelper(routeHelper) { this.routeHelper = routeHelper; this.apps = {}; this.clientRegistrations = []; } /** * Register a function with the page helper * @param appName * @param routeName * @param funcName * @param func */ PageHelper.prototype.register = function register(appName, routeName, funcName, func) { var me = this; // app and route name could be dot notation, so make them camel case appName = utils.getCamelCase(appName); routeName = utils.getCamelCase(routeName); // make sure object is initialized this.apps[appName] = this.apps[appName] || {}; this.apps[appName][routeName] = this.apps[appName][routeName] || {}; var routeHelper = this.routeHelper; // we wrap the input function so we can add the routeHandler to the input options function handler(opts) { opts.routeHelper = routeHelper; return func(opts); } // this is used by the client generator to replicate these functions this.clientRegistrations.push({ appName: appName, routeName: routeName, funcName: funcName, func: func.toString() }); // set handler in the object in case the user calls it dynamically this.apps[appName][routeName][funcName] = handler; // and add a convenience function name for example pageHelper.formatUrlAnswersPost(opts) var name = utils.getCamelCase([funcName, appName, routeName].join('.')); this[name] = handler; // also since many times the route name is unique, pageHelper.formatUrlPost() name = utils.getCamelCase([funcName, routeName].join('.')); this[name] = handler; // finally if just call the function name, let them pass in the appName and routeName // pageHelper.formatUrl(appName, routeName, opts); this[funcName] = function (appName, routeName, opts) { return handler(opts); }; }; // export the class to be instantiated module.exports = PageHelper;
lib/page.helper.js
/** * Author: Jeff Whelpley * Date: 2/6/15 * * Page helper this should be kept in sync with the client side PageHelper */ var utils = require('./utensils'); function PageHelper(routeHelper) { this.routeHelper = routeHelper; this.apps = {}; this.clientRegistrations = []; } /** * Register a function with the page helper * @param appName * @param routeName * @param funcName * @param func */ PageHelper.prototype.register = function register(appName, routeName, funcName, func) { // app and route name could be dot notation, so make them camel case appName = utils.getCamelCase(appName); routeName = utils.getCamelCase(routeName); // make sure object is initialized this.apps[appName] = this.apps[appName] || {}; this.apps[appName][routeName] = this.apps[appName][routeName] || {}; var routeHelper = this.routeHelper; var apps = this.apps; // we wrap the input function so we can add the routeHandler to the input options function handler(opts) { opts.routeHelper = routeHelper; return func(opts); } // this is used by the client generator to replicate these functions this.clientRegistrations.push({ appName: appName, routeName: routeName, funcName: funcName, func: func.toString() }); // set handler in the object in case the user calls it dynamically this.apps[appName][routeName][funcName] = handler; // and add a convenience function name for example pageHelper.formatUrlAnswersPost(opts) var name = utils.getCamelCase([funcName, appName, routeName].join('.')); this[name] = handler; // also since many times the route name is unique, pageHelper.formatUrlPost() name = utils.getCamelCase([funcName, routeName].join('.')); this[name] = handler; // finally if just call the function name, let them pass in the appName and routeName // pageHelper.formatUrl(appName, routeName, opts); this[funcName] = function (appName, routeName, opts) { return apps[appName][routeName][funcName](opts); }; }; // export the class to be instantiated module.exports = PageHelper;
fixing closure issue with page helper
lib/page.helper.js
fixing closure issue with page helper
<ide><path>ib/page.helper.js <ide> * @param func <ide> */ <ide> PageHelper.prototype.register = function register(appName, routeName, funcName, func) { <add> var me = this; <ide> <ide> // app and route name could be dot notation, so make them camel case <ide> appName = utils.getCamelCase(appName); <ide> this.apps[appName][routeName] = this.apps[appName][routeName] || {}; <ide> <ide> var routeHelper = this.routeHelper; <del> var apps = this.apps; <ide> <ide> // we wrap the input function so we can add the routeHandler to the input options <ide> function handler(opts) { <ide> // finally if just call the function name, let them pass in the appName and routeName <ide> // pageHelper.formatUrl(appName, routeName, opts); <ide> this[funcName] = function (appName, routeName, opts) { <del> return apps[appName][routeName][funcName](opts); <add> return handler(opts); <ide> }; <ide> }; <ide>
Java
mit
9d5e31d347aa7362700fa83c49f331d3a6a5dda1
0
TarkanAl-Kazily/2015-Recycle-Rush,Spartronics4915/2015-Recycle-Rush,ClioBatali/2015-Recycle-Rush,NoahLevine/2015-Recycle-Rush
// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc4915.MecanumDrive; import org.usfirst.frc4915.MecanumDrive.RobotMap; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc4915.MecanumDrive.commands.*; import org.usfirst.frc4915.MecanumDrive.subsystems.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command autonomousCommand; public static OI oi; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static DriveTrain driveTrain; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotMap.init(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS driveTrain = new DriveTrain(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS // OI must be constructed after subsystems. If the OI creates Commands //(which it very likely will), subsystems are not guaranteed to be // constructed yet. Thus, their requires() statements may grab null // pointers. Bad news. Don't move it. oi = new OI(); RobotMap.gyro.reset(); // instantiate the command used for the autonomous period // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS autonomousCommand = new AutonomousCommand(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS // Test for sending messages to smart dashboard SendUserMessage.displayMessage(); } /** * This function is called when the disabled button is hit. * You can use it to reset subsystems before shutting down. */ public void disabledInit(){ } public void disabledPeriodic() { Scheduler.getInstance().run(); } public void autonomousInit() { // schedule the autonomous command (example) if (autonomousCommand != null) autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) autonomousCommand.cancel(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
RobotCode/MecanumDrive/src/org/usfirst/frc4915/MecanumDrive/Robot.java
// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc4915.MecanumDrive; import org.usfirst.frc4915.MecanumDrive.RobotMap; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc4915.MecanumDrive.commands.*; import org.usfirst.frc4915.MecanumDrive.subsystems.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command autonomousCommand; public static OI oi; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static DriveTrain driveTrain; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotMap.init(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS driveTrain = new DriveTrain(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS // OI must be constructed after subsystems. If the OI creates Commands //(which it very likely will), subsystems are not guaranteed to be // constructed yet. Thus, their requires() statements may grab null // pointers. Bad news. Don't move it. oi = new OI(); RobotMap.gyro.reset(); // instantiate the command used for the autonomous period // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS autonomousCommand = new AutonomousCommand(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS } /** * This function is called when the disabled button is hit. * You can use it to reset subsystems before shutting down. */ public void disabledInit(){ } public void disabledPeriodic() { Scheduler.getInstance().run(); } public void autonomousInit() { // schedule the autonomous command (example) if (autonomousCommand != null) autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) autonomousCommand.cancel(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
Called SendUserMessage.displayMessage() in Robot.java
RobotCode/MecanumDrive/src/org/usfirst/frc4915/MecanumDrive/Robot.java
Called SendUserMessage.displayMessage() in Robot.java
<ide><path>obotCode/MecanumDrive/src/org/usfirst/frc4915/MecanumDrive/Robot.java <ide> autonomousCommand = new AutonomousCommand(); <ide> <ide> // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS <add> <add> <add> // Test for sending messages to smart dashboard <add> SendUserMessage.displayMessage(); <ide> } <ide> <ide> /**
Java
mit
390fce2d96aad063233059ba8667e0dfc4cc8a83
0
arz-latte/latte-rodeo,arz-latte/latte-rodeo,arz-latte/latte-rodeo
package at.arz.latte.rodeo.release.admin; import java.util.Objects; import javax.inject.Inject; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import at.arz.latte.rodeo.api.ObjectExists; import at.arz.latte.rodeo.api.RodeoCommand; import at.arz.latte.rodeo.infrastructure.RodeoModel; import at.arz.latte.rodeo.release.Release; import at.arz.latte.rodeo.release.ReleaseName; import at.arz.latte.rodeo.release.restapi.FindReleaseByNameQuery; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class CreateRelease implements RodeoCommand<Long> { @NotNull private ReleaseName releaseName; @XmlTransient @Inject private RodeoModel model; CreateRelease() { // tool constructor } public CreateRelease(ReleaseName releaseName) { Objects.requireNonNull(releaseName, "releaseName required"); this.releaseName = releaseName; } @Override public Long execute() { FindReleaseByNameQuery query = new FindReleaseByNameQuery(); query.setReleaseName(getReleaseName()); Release release = model.query(query); if (release != null) { throw new ObjectExists(Release.class, "releaseName", getReleaseName()); } Release r = new Release(releaseName); model.create(r); return r.getId(); } public ReleaseName getReleaseName() { return releaseName; } }
latte-rodeo/src/at/arz/latte/rodeo/release/admin/CreateRelease.java
package at.arz.latte.rodeo.release.admin; import java.util.Objects; import javax.inject.Inject; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import at.arz.latte.rodeo.api.RodeoCommand; import at.arz.latte.rodeo.infrastructure.RodeoModel; import at.arz.latte.rodeo.release.Release; import at.arz.latte.rodeo.release.ReleaseName; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class CreateRelease implements RodeoCommand<Long> { @NotNull private ReleaseName releaseName; @XmlTransient @Inject private RodeoModel model; CreateRelease() { // tool constructor } public CreateRelease(ReleaseName releaseName) { Objects.requireNonNull(releaseName, "releaseName required"); this.releaseName = releaseName; } @Override public Long execute() { Release release = new Release(releaseName); model.create(release); return release.getId(); } public ReleaseName getReleaseName() { return releaseName; } }
add check if release already exist
latte-rodeo/src/at/arz/latte/rodeo/release/admin/CreateRelease.java
add check if release already exist
<ide><path>atte-rodeo/src/at/arz/latte/rodeo/release/admin/CreateRelease.java <ide> import javax.xml.bind.annotation.XmlRootElement; <ide> import javax.xml.bind.annotation.XmlTransient; <ide> <add>import at.arz.latte.rodeo.api.ObjectExists; <ide> import at.arz.latte.rodeo.api.RodeoCommand; <ide> import at.arz.latte.rodeo.infrastructure.RodeoModel; <ide> import at.arz.latte.rodeo.release.Release; <ide> import at.arz.latte.rodeo.release.ReleaseName; <add>import at.arz.latte.rodeo.release.restapi.FindReleaseByNameQuery; <ide> <ide> @XmlRootElement <ide> @XmlAccessorType(XmlAccessType.FIELD) <ide> <ide> @Override <ide> public Long execute() { <del> Release release = new Release(releaseName); <del> model.create(release); <del> return release.getId(); <add> FindReleaseByNameQuery query = new FindReleaseByNameQuery(); <add> query.setReleaseName(getReleaseName()); <add> Release release = model.query(query); <add> if (release != null) { <add> throw new ObjectExists(Release.class, "releaseName", getReleaseName()); <add> } <add> <add> Release r = new Release(releaseName); <add> model.create(r); <add> return r.getId(); <ide> } <ide> <ide> public ReleaseName getReleaseName() {
Java
apache-2.0
f3084d3ce17c56c46b083d5c6f65c3dd03229e72
0
apache/ignite,samaitra/ignite,xtern/ignite,samaitra/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,xtern/ignite,SomeFire/ignite,daradurvs/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,SomeFire/ignite,NSAmelchev/ignite,xtern/ignite,SomeFire/ignite,daradurvs/ignite,apache/ignite,NSAmelchev/ignite,ascherbakoff/ignite,daradurvs/ignite,NSAmelchev/ignite,ascherbakoff/ignite,nizhikov/ignite,samaitra/ignite,xtern/ignite,ascherbakoff/ignite,daradurvs/ignite,nizhikov/ignite,xtern/ignite,NSAmelchev/ignite,chandresh-pancholi/ignite,SomeFire/ignite,samaitra/ignite,SomeFire/ignite,xtern/ignite,nizhikov/ignite,chandresh-pancholi/ignite,apache/ignite,samaitra/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,samaitra/ignite,nizhikov/ignite,samaitra/ignite,chandresh-pancholi/ignite,daradurvs/ignite,SomeFire/ignite,daradurvs/ignite,NSAmelchev/ignite,daradurvs/ignite,SomeFire/ignite,ascherbakoff/ignite,andrey-kuznetsov/ignite,nizhikov/ignite,nizhikov/ignite,SomeFire/ignite,NSAmelchev/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,SomeFire/ignite,xtern/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,chandresh-pancholi/ignite,nizhikov/ignite,NSAmelchev/ignite,samaitra/ignite,andrey-kuznetsov/ignite,apache/ignite,ascherbakoff/ignite,nizhikov/ignite,NSAmelchev/ignite,ascherbakoff/ignite,nizhikov/ignite,samaitra/ignite,chandresh-pancholi/ignite,xtern/ignite,apache/ignite,andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,apache/ignite,apache/ignite,xtern/ignite,chandresh-pancholi/ignite,apache/ignite,SomeFire/ignite,NSAmelchev/ignite,apache/ignite,andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,samaitra/ignite,daradurvs/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite
/* * 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.ignite.internal; import java.io.Externalizable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InvalidObjectException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.ObjectStreamException; import java.io.Serializable; import java.io.UncheckedIOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.reflect.Constructor; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.cache.CacheException; import javax.management.JMException; import org.apache.ignite.DataRegionMetrics; import org.apache.ignite.DataRegionMetricsAdapter; import org.apache.ignite.DataStorageMetrics; import org.apache.ignite.DataStorageMetricsAdapter; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteAtomicLong; import org.apache.ignite.IgniteAtomicReference; import org.apache.ignite.IgniteAtomicSequence; import org.apache.ignite.IgniteAtomicStamped; import org.apache.ignite.IgniteBinary; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteClientDisconnectedException; import org.apache.ignite.IgniteCompute; import org.apache.ignite.IgniteCountDownLatch; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.IgniteEvents; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteFileSystem; import org.apache.ignite.IgniteLock; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteMessaging; import org.apache.ignite.IgniteQueue; import org.apache.ignite.IgniteScheduler; import org.apache.ignite.IgniteSemaphore; import org.apache.ignite.IgniteServices; import org.apache.ignite.IgniteSet; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.IgniteTransactions; import org.apache.ignite.Ignition; import org.apache.ignite.MemoryMetrics; import org.apache.ignite.PersistenceMetrics; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cluster.BaselineNode; import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.cluster.ClusterMetrics; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.configuration.AtomicConfiguration; import org.apache.ignite.configuration.BinaryConfiguration; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.CollectionConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.MemoryConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.binary.BinaryEnumCache; import org.apache.ignite.internal.binary.BinaryMarshaller; import org.apache.ignite.internal.binary.BinaryUtils; import org.apache.ignite.internal.cluster.ClusterGroupAdapter; import org.apache.ignite.internal.cluster.IgniteClusterEx; import org.apache.ignite.internal.managers.GridManager; import org.apache.ignite.internal.managers.IgniteMBeansManager; import org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager; import org.apache.ignite.internal.managers.collision.GridCollisionManager; import org.apache.ignite.internal.managers.communication.GridIoManager; import org.apache.ignite.internal.managers.deployment.GridDeploymentManager; import org.apache.ignite.internal.managers.discovery.DiscoveryLocalJoinData; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager; import org.apache.ignite.internal.managers.encryption.GridEncryptionManager; import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager; import org.apache.ignite.internal.managers.failover.GridFailoverManager; import org.apache.ignite.internal.managers.indexing.GridIndexingManager; import org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager; import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller; import org.apache.ignite.internal.processors.GridProcessor; import org.apache.ignite.internal.processors.GridProcessorAdapter; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.affinity.GridAffinityProcessor; import org.apache.ignite.internal.processors.authentication.IgniteAuthenticationProcessor; import org.apache.ignite.internal.processors.cache.CacheConfigurationOverride; import org.apache.ignite.internal.processors.cache.GridCacheAdapter; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheProcessor; import org.apache.ignite.internal.processors.cache.GridCacheUtilityKey; import org.apache.ignite.internal.processors.cache.IgniteCacheProxy; import org.apache.ignite.internal.processors.cache.IgniteInternalCache; import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl; import org.apache.ignite.internal.processors.cache.mvcc.MvccProcessorImpl; import org.apache.ignite.internal.processors.cache.persistence.DataRegion; import org.apache.ignite.internal.processors.cache.persistence.filename.PdsConsistentIdProcessor; import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor; import org.apache.ignite.internal.processors.closure.GridClosureProcessor; import org.apache.ignite.internal.processors.cluster.ClusterProcessor; import org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState; import org.apache.ignite.internal.processors.cluster.GridClusterStateProcessor; import org.apache.ignite.internal.processors.cluster.IGridClusterStateProcessor; import org.apache.ignite.internal.processors.configuration.distributed.DistributedConfigurationProcessor; import org.apache.ignite.internal.processors.continuous.GridContinuousProcessor; import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor; import org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor; import org.apache.ignite.internal.processors.diagnostic.DiagnosticProcessor; import org.apache.ignite.internal.processors.failure.FailureProcessor; import org.apache.ignite.internal.processors.hadoop.Hadoop; import org.apache.ignite.internal.processors.hadoop.HadoopProcessorAdapter; import org.apache.ignite.internal.processors.job.GridJobProcessor; import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor; import org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor; import org.apache.ignite.internal.processors.metastorage.persistence.DistributedMetaStorageImpl; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistry; import org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.nodevalidation.OsDiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.odbc.ClientListenerProcessor; import org.apache.ignite.internal.processors.platform.PlatformNoopProcessor; import org.apache.ignite.internal.processors.platform.PlatformProcessor; import org.apache.ignite.internal.processors.platform.plugin.PlatformPluginProcessor; import org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor; import org.apache.ignite.internal.processors.pool.PoolProcessor; import org.apache.ignite.internal.processors.port.GridPortProcessor; import org.apache.ignite.internal.processors.port.GridPortRecord; import org.apache.ignite.internal.processors.query.GridQueryProcessor; import org.apache.ignite.internal.processors.resource.GridResourceProcessor; import org.apache.ignite.internal.processors.resource.GridSpringResourceContext; import org.apache.ignite.internal.processors.rest.GridRestProcessor; import org.apache.ignite.internal.processors.security.GridSecurityProcessor; import org.apache.ignite.internal.processors.security.IgniteSecurity; import org.apache.ignite.internal.processors.security.IgniteSecurityProcessor; import org.apache.ignite.internal.processors.security.NoOpIgniteSecurityProcessor; import org.apache.ignite.internal.processors.segmentation.GridSegmentationProcessor; import org.apache.ignite.internal.processors.service.GridServiceProcessor; import org.apache.ignite.internal.processors.service.IgniteServiceProcessor; import org.apache.ignite.internal.processors.session.GridTaskSessionProcessor; import org.apache.ignite.internal.processors.subscription.GridInternalSubscriptionProcessor; import org.apache.ignite.internal.processors.task.GridTaskProcessor; import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor; import org.apache.ignite.internal.suggestions.GridPerformanceSuggestions; import org.apache.ignite.internal.suggestions.JvmConfigurationSuggestions; import org.apache.ignite.internal.suggestions.OsConfigurationSuggestions; import org.apache.ignite.internal.util.StripedExecutor; import org.apache.ignite.internal.util.TimeBag; import org.apache.ignite.internal.util.future.GridCompoundFuture; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.future.IgniteFutureImpl; import org.apache.ignite.internal.util.lang.GridAbsClosure; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.typedef.C1; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.LT; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.SB; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.worker.WorkersRegistry; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.lang.IgniteClosure; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteProductVersion; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.lifecycle.LifecycleBean; import org.apache.ignite.lifecycle.LifecycleEventType; import org.apache.ignite.marshaller.MarshallerExclusions; import org.apache.ignite.marshaller.MarshallerUtils; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.apache.ignite.mxbean.IgniteMXBean; import org.apache.ignite.plugin.IgnitePlugin; import org.apache.ignite.plugin.PluginNotFoundException; import org.apache.ignite.plugin.PluginProvider; import org.apache.ignite.spi.IgniteSpi; import org.apache.ignite.spi.IgniteSpiVersionCheckException; import org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode; import org.apache.ignite.thread.IgniteStripedThreadPoolExecutor; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2; import static org.apache.ignite.IgniteSystemProperties.IGNITE_CONFIG_URL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_DAEMON; import static org.apache.ignite.IgniteSystemProperties.IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED; import static org.apache.ignite.IgniteSystemProperties.IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP; import static org.apache.ignite.IgniteSystemProperties.IGNITE_NO_ASCII; import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID; import static org.apache.ignite.IgniteSystemProperties.IGNITE_REST_START_ON_CLIENT; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK; import static org.apache.ignite.IgniteSystemProperties.IGNITE_STARVATION_CHECK_INTERVAL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SUCCESS_FILE; import static org.apache.ignite.IgniteSystemProperties.getBoolean; import static org.apache.ignite.IgniteSystemProperties.snapshot; import static org.apache.ignite.internal.GridKernalState.DISCONNECTED; import static org.apache.ignite.internal.GridKernalState.STARTED; import static org.apache.ignite.internal.GridKernalState.STARTING; import static org.apache.ignite.internal.GridKernalState.STOPPED; import static org.apache.ignite.internal.GridKernalState.STOPPING; import static org.apache.ignite.internal.IgniteComponentType.COMPRESSION; import static org.apache.ignite.internal.IgniteComponentType.HADOOP_HELPER; import static org.apache.ignite.internal.IgniteComponentType.IGFS; import static org.apache.ignite.internal.IgniteComponentType.IGFS_HELPER; import static org.apache.ignite.internal.IgniteComponentType.SCHEDULE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_DATE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_VER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CLIENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CONSISTENCY_CHECK_SKIPPED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DAEMON; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STORAGE_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STREAMER_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DEPLOYMENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DYNAMIC_CACHE_START_ROLLBACK_SUPPORTED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_FEATURES; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_INSTANCE_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IPS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JIT_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JMX_PORT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_ARGS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_PID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LANG_RUNTIME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LATE_AFFINITY_ASSIGNMENT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_COMPACT_FOOTER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_DFLT_SUID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MEMORY_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_NODE_CONSISTENT_ID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_OFFHEAP_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PEER_CLASSLOADING; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PHY_RAM; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PREFIX; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REBALANCE_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_RESTART_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_PORT_RANGE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SPI_CLASS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_TX_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_USER_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_VALIDATE_CACHE_REQUESTS; import static org.apache.ignite.internal.IgniteVersionUtils.ACK_VER_STR; import static org.apache.ignite.internal.IgniteVersionUtils.BUILD_TSTAMP_STR; import static org.apache.ignite.internal.IgniteVersionUtils.COPYRIGHT; import static org.apache.ignite.internal.IgniteVersionUtils.REV_HASH_STR; import static org.apache.ignite.internal.IgniteVersionUtils.VER; import static org.apache.ignite.internal.IgniteVersionUtils.VER_STR; import static org.apache.ignite.lifecycle.LifecycleEventType.AFTER_NODE_START; import static org.apache.ignite.lifecycle.LifecycleEventType.BEFORE_NODE_START; /** * This class represents an implementation of the main Ignite API {@link Ignite} which is expanded by additional * methods of {@link IgniteEx} for the internal Ignite needs. It also controls the Ignite life cycle, checks * thread pools state for starvation, detects long JVM pauses and prints out the local node metrics. * <p> * Please, refer to the wiki <a href="http://en.wikipedia.org/wiki/Kernal">http://en.wikipedia.org/wiki/Kernal</a> * for the information on the misspelling. * <p> * <h3>Starting</h3> * The main entry point for all the Ignite instances creation is the method - {@link #start(IgniteConfiguration, * ExecutorService, ExecutorService, ExecutorService, ExecutorService,StripedExecutor, ExecutorService, ExecutorService, * ExecutorService, StripedExecutor, ExecutorService, ExecutorService, ExecutorService, IgniteStripedThreadPoolExecutor, * ExecutorService, ExecutorService, Map, GridAbsClosure, WorkersRegistry, Thread.UncaughtExceptionHandler, TimeBag) * start}. * <p> * It starts internal Ignite components (see {@link GridComponent}), for instance: * <ul> * <li>{@link GridManager} - a layer of indirection between kernal and SPI modules.</li> * <li>{@link GridProcessor} - an objects responsible for particular internal process implementation.</li> * <li>{@link IgnitePlugin} - an Ignite addition of user-provided functionality.</li> * </ul> * The {@code start} method also performs additional validation of the provided {@link IgniteConfiguration} and * prints some suggestions such as: * <ul> * <li>Ignite configuration optimizations (e.g. disabling {@link EventType} events).</li> * <li>{@link JvmConfigurationSuggestions} optimizations.</li> * <li>{@link OsConfigurationSuggestions} optimizations.</li> * </ul> * <h3>Stopping</h3> * To stop Ignite instance the {@link #stop(boolean)} method is used. The {@code cancel} argument of this method is used: * <ul> * <li>With {@code true} value. To interrupt all currently acitve {@link GridComponent}s related to the Ignite node. * For instance, {@link ComputeJob} will be interrupted by calling {@link ComputeJob#cancel()} method. Note that just * like with {@link Thread#interrupt()}, it is up to the actual job to exit from execution.</li> * <li>With {@code false} value. To stop the Ignite node gracefully. All jobs currently running will not be interrupted. * The Ignite node will wait for the completion of all {@link GridComponent}s running on it before stopping. * </li> * </ul> */ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable { /** Class serialization version number. */ private static final long serialVersionUID = 0L; /** Ignite web-site that is shown in log messages. */ public static final String SITE = "ignite.apache.org"; /** System line separator. */ private static final String NL = U.nl(); /** * Default interval of checking thread pool state for the starvation. Will be used only if the * {@link IgniteSystemProperties#IGNITE_STARVATION_CHECK_INTERVAL} system property is not set. * <p> * Value is {@code 30 sec}. */ private static final long PERIODIC_STARVATION_CHECK_FREQ = 1000 * 30; /** Object is used to force completion the previous reconnection attempt. See {@link ReconnectState} for details. */ private static final Object STOP_RECONNECT = new Object(); /** The separator is used for coordinator properties formatted as a string. */ public static final String COORDINATOR_PROPERTIES_SEPARATOR = ","; /** * Default timeout in milliseconds for dumping long running operations. Will be used if the * {@link IgniteSystemProperties#IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT} is not set. * <p> * Value is {@code 60 sec}. */ public static final long DFLT_LONG_OPERATIONS_DUMP_TIMEOUT = 60_000L; /** Currently used instance of JVM pause detector thread. See {@link LongJVMPauseDetector} for details. */ private LongJVMPauseDetector longJVMPauseDetector; /** The main kernal context which holds all the {@link GridComponent}s. */ @GridToStringExclude private GridKernalContextImpl ctx; /** Helper which registers and unregisters MBeans. */ @GridToStringExclude private IgniteMBeansManager mBeansMgr; /** Ignite configuration instance. */ private IgniteConfiguration cfg; /** Ignite logger instance which enriches log messages with the node instance name and the node id. */ @GridToStringExclude private GridLoggerProxy log; /** Name of Ignite node. */ private String igniteInstanceName; /** Kernal start timestamp. */ private long startTime = U.currentTimeMillis(); /** Spring context, potentially {@code null}. */ private GridSpringResourceContext rsrcCtx; /** * The instance of scheduled thread pool starvation checker. {@code null} if starvation checks have been * disabled by the value of {@link IgniteSystemProperties#IGNITE_STARVATION_CHECK_INTERVAL} system property. */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask starveTask; /** * The instance of scheduled metrics logger. {@code null} means that the metrics loggin have been disabled * by configuration. See {@link IgniteConfiguration#getMetricsLogFrequency()} for details. */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask metricsLogTask; /** * The instance of scheduled long operation checker. {@code null} means that the operations checker is disabled * by the value of {@link IgniteSystemProperties#IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT} system property. */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask longOpDumpTask; /** {@code true} if an error occurs at Ignite instance stop. */ @GridToStringExclude private boolean errOnStop; /** An instance of the scheduler which provides functionality for scheduling jobs locally. */ @GridToStringExclude private IgniteScheduler scheduler; /** The kernal state guard. See {@link GridKernalGateway} for details. */ @GridToStringExclude private final AtomicReference<GridKernalGateway> gw = new AtomicReference<>(); /** Flag indicates that the ignite instance is scheduled to be stopped. */ @GridToStringExclude private final AtomicBoolean stopGuard = new AtomicBoolean(); /** The state object is used when reconnection occurs. See {@link IgniteKernal#onReconnected(boolean)}. */ private final ReconnectState reconnectState = new ReconnectState(); /** * No-arg constructor is required by externalization. */ public IgniteKernal() { this(null); } /** * @param rsrcCtx Optional Spring application context. */ public IgniteKernal(@Nullable GridSpringResourceContext rsrcCtx) { this.rsrcCtx = rsrcCtx; } /** {@inheritDoc} */ @Override public IgniteClusterEx cluster() { return ctx.cluster().get(); } /** {@inheritDoc} */ @Override public ClusterNode localNode() { return ctx.cluster().get().localNode(); } /** {@inheritDoc} */ @Override public IgniteCompute compute() { return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).compute(); } /** {@inheritDoc} */ @Override public IgniteMessaging message() { return ctx.cluster().get().message(); } /** {@inheritDoc} */ @Override public IgniteEvents events() { return ctx.cluster().get().events(); } /** {@inheritDoc} */ @Override public IgniteServices services() { checkClusterState(); return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService() { return ctx.cluster().get().executorService(); } /** {@inheritDoc} */ @Override public final IgniteCompute compute(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).compute(); } /** {@inheritDoc} */ @Override public final IgniteMessaging message(ClusterGroup prj) { return ((ClusterGroupAdapter)prj).message(); } /** {@inheritDoc} */ @Override public final IgniteEvents events(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).events(); } /** {@inheritDoc} */ @Override public IgniteServices services(ClusterGroup grp) { checkClusterState(); return ((ClusterGroupAdapter)grp).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).executorService(); } /** {@inheritDoc} */ @Override public String name() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getCopyright() { return COPYRIGHT; } /** {@inheritDoc} */ @Override public long getStartTimestamp() { return startTime; } /** {@inheritDoc} */ @Override public String getStartTimestampFormatted() { return DateFormat.getDateTimeInstance().format(new Date(startTime)); } /** {@inheritDoc} */ @Override public boolean isRebalanceEnabled() { return ctx.cache().context().isRebalanceEnabled(); } /** {@inheritDoc} */ @Override public void rebalanceEnabled(boolean rebalanceEnabled) { ctx.cache().context().rebalanceEnabled(rebalanceEnabled); } /** {@inheritDoc} */ @Override public long getUpTime() { return U.currentTimeMillis() - startTime; } /** {@inheritDoc} */ @Override public long getLongJVMPausesCount() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPausesCount() : 0; } /** {@inheritDoc} */ @Override public long getLongJVMPausesTotalDuration() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPausesTotalDuration() : 0; } /** {@inheritDoc} */ @Override public Map<Long, Long> getLongJVMPauseLastEvents() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPauseEvents() : Collections.emptyMap(); } /** {@inheritDoc} */ @Override public String getUpTimeFormatted() { return X.timeSpan2DHMSM(U.currentTimeMillis() - startTime); } /** {@inheritDoc} */ @Override public String getFullVersion() { return VER_STR + '-' + BUILD_TSTAMP_STR; } /** {@inheritDoc} */ @Override public String getCheckpointSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getCheckpointSpi()); } /** {@inheritDoc} */ @Override public String getCurrentCoordinatorFormatted() { ClusterNode node = ctx.discovery().oldestAliveServerNode(AffinityTopologyVersion.NONE); if (node == null) return ""; return new StringBuilder() .append(node.addresses()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.id()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.order()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.hostNames()) .toString(); } /** {@inheritDoc} */ @Override public boolean isNodeInBaseline() { ClusterNode locNode = localNode(); if (locNode.isClient() || locNode.isDaemon()) return false; DiscoveryDataClusterState clusterState = ctx.state().clusterState(); return clusterState.hasBaselineTopology() && CU.baselineNode(locNode, clusterState); } /** {@inheritDoc} */ @Override public String getCommunicationSpiFormatted() { assert cfg != null; return cfg.getCommunicationSpi().toString(); } /** {@inheritDoc} */ @Override public String getDeploymentSpiFormatted() { assert cfg != null; return cfg.getDeploymentSpi().toString(); } /** {@inheritDoc} */ @Override public String getDiscoverySpiFormatted() { assert cfg != null; return cfg.getDiscoverySpi().toString(); } /** {@inheritDoc} */ @Override public String getEventStorageSpiFormatted() { assert cfg != null; return cfg.getEventStorageSpi().toString(); } /** {@inheritDoc} */ @Override public String getCollisionSpiFormatted() { assert cfg != null; return cfg.getCollisionSpi().toString(); } /** {@inheritDoc} */ @Override public String getFailoverSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getFailoverSpi()); } /** {@inheritDoc} */ @Override public String getLoadBalancingSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getLoadBalancingSpi()); } /** {@inheritDoc} */ @Override public String getOsInformation() { return U.osString(); } /** {@inheritDoc} */ @Override public String getJdkInformation() { return U.jdkString(); } /** {@inheritDoc} */ @Override public String getOsUser() { return System.getProperty("user.name"); } /** {@inheritDoc} */ @Override public void printLastErrors() { ctx.exceptionRegistry().printErrors(log); } /** {@inheritDoc} */ @Override public String getVmName() { return ManagementFactory.getRuntimeMXBean().getName(); } /** {@inheritDoc} */ @Override public String getInstanceName() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getExecutorServiceFormatted() { assert cfg != null; return String.valueOf(cfg.getPublicThreadPoolSize()); } /** {@inheritDoc} */ @Override public String getIgniteHome() { assert cfg != null; return cfg.getIgniteHome(); } /** {@inheritDoc} */ @Override public String getGridLoggerFormatted() { assert cfg != null; return cfg.getGridLogger().toString(); } /** {@inheritDoc} */ @Override public String getMBeanServerFormatted() { assert cfg != null; return cfg.getMBeanServer().toString(); } /** {@inheritDoc} */ @Override public UUID getLocalNodeId() { assert cfg != null; return cfg.getNodeId(); } /** {@inheritDoc} */ @Override public List<String> getUserAttributesFormatted() { assert cfg != null; return (List<String>)F.transform(cfg.getUserAttributes().entrySet(), new C1<Map.Entry<String, ?>, String>() { @Override public String apply(Map.Entry<String, ?> e) { return e.getKey() + ", " + e.getValue().toString(); } }); } /** {@inheritDoc} */ @Override public boolean isPeerClassLoadingEnabled() { assert cfg != null; return cfg.isPeerClassLoadingEnabled(); } /** {@inheritDoc} */ @Override public List<String> getLifecycleBeansFormatted() { LifecycleBean[] beans = cfg.getLifecycleBeans(); if (F.isEmpty(beans)) return Collections.emptyList(); else { List<String> res = new ArrayList<>(beans.length); for (LifecycleBean bean : beans) res.add(String.valueOf(bean)); return res; } } /** * @param name New attribute name. * @param val New attribute value. * @throws IgniteCheckedException If duplicated SPI name found. */ private void add(String name, @Nullable Serializable val) throws IgniteCheckedException { assert name != null; if (ctx.addNodeAttribute(name, val) != null) { if (name.endsWith(ATTR_SPI_CLASS)) // User defined duplicated names for the different SPIs. throw new IgniteCheckedException("Failed to set SPI attribute. Duplicated SPI name found: " + name.substring(0, name.length() - ATTR_SPI_CLASS.length())); // Otherwise it's a mistake of setting up duplicated attribute. assert false : "Duplicate attribute: " + name; } } /** * Notifies life-cycle beans of ignite event. * * @param evt Lifecycle event to notify beans with. * @throws IgniteCheckedException If user threw exception during start. */ private void notifyLifecycleBeans(LifecycleEventType evt) throws IgniteCheckedException { if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) if (bean != null) { try { bean.onLifecycleEvent(evt); } catch (Exception e) { throw new IgniteCheckedException(e); } } } } /** * Notifies life-cycle beans of ignite event. * * @param evt Lifecycle event to notify beans with. */ private void notifyLifecycleBeansEx(LifecycleEventType evt) { try { notifyLifecycleBeans(evt); } // Catch generic throwable to secure against user assertions. catch (Throwable e) { U.error(log, "Failed to notify lifecycle bean (safely ignored) [evt=" + evt + (igniteInstanceName == null ? "" : ", igniteInstanceName=" + igniteInstanceName) + ']', e); if (e instanceof Error) throw (Error)e; } } /** * @param clsPathEntry Classpath file to process. * @param clsPathContent StringBuilder to attach path to. */ private void ackClassPathElementRecursive(File clsPathEntry, SB clsPathContent) { if (clsPathEntry.isDirectory()) { String[] list = clsPathEntry.list(); for (String listElement : list) ackClassPathElementRecursive(new File(clsPathEntry, listElement), clsPathContent); } else { String path = clsPathEntry.getAbsolutePath(); if (path.endsWith(".class")) clsPathContent.a(path).a(";"); } } /** * @param clsPathEntry Classpath string to process. * @param clsPathContent StringBuilder to attach path to. */ private void ackClassPathEntry(String clsPathEntry, SB clsPathContent) { File clsPathElementFile = new File(clsPathEntry); if (clsPathElementFile.isDirectory()) ackClassPathElementRecursive(clsPathElementFile, clsPathContent); else { String extension = clsPathEntry.length() >= 4 ? clsPathEntry.substring(clsPathEntry.length() - 4).toLowerCase() : null; if (".jar".equals(extension) || ".zip".equals(extension)) clsPathContent.a(clsPathEntry).a(";"); } } /** * @param clsPathEntry Classpath string to process. * @param clsPathContent StringBuilder to attach path to. */ private void ackClassPathWildCard(String clsPathEntry, SB clsPathContent) { final int lastSeparatorIdx = clsPathEntry.lastIndexOf(File.separator); final int asteriskIdx = clsPathEntry.indexOf('*'); //just to log possibly incorrent entries to err if (asteriskIdx >= 0 && asteriskIdx < lastSeparatorIdx) throw new RuntimeException("Could not parse classpath entry"); final int fileMaskFirstIdx = lastSeparatorIdx + 1; final String fileMask = (fileMaskFirstIdx >= clsPathEntry.length()) ? "*.jar" : clsPathEntry.substring(fileMaskFirstIdx); Path path = Paths.get(lastSeparatorIdx > 0 ? clsPathEntry.substring(0, lastSeparatorIdx) : ".") .toAbsolutePath() .normalize(); if (lastSeparatorIdx == 0) path = path.getRoot(); try { DirectoryStream<Path> files = Files.newDirectoryStream(path, fileMask); for (Path f : files) { String s = f.toString(); if (s.toLowerCase().endsWith(".jar")) clsPathContent.a(f.toString()).a(";"); } } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Prints the list of {@code *.jar} and {@code *.class} files containing in the classpath. */ private void ackClassPathContent() { assert log != null; boolean enabled = IgniteSystemProperties.getBoolean(IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP, true); if (enabled) { String clsPath = System.getProperty("java.class.path", "."); String[] clsPathElements = clsPath.split(File.pathSeparator); U.log(log, "Classpath value: " + clsPath); SB clsPathContent = new SB("List of files containing in classpath: "); for (String clsPathEntry : clsPathElements) { try { if (clsPathEntry.contains("*")) ackClassPathWildCard(clsPathEntry, clsPathContent); else ackClassPathEntry(clsPathEntry, clsPathContent); } catch (Exception e) { U.warn(log, String.format("Could not log class path entry '%s': %s", clsPathEntry, e.getMessage())); } } U.log(log, clsPathContent.toString()); } } /** * @param cfg Ignite configuration to use. * @param utilityCachePool Utility cache pool. * @param execSvc Executor service. * @param svcExecSvc Services executor service. * @param sysExecSvc System executor service. * @param stripedExecSvc Striped executor. * @param p2pExecSvc P2P executor service. * @param mgmtExecSvc Management executor service. * @param igfsExecSvc IGFS executor service. * @param dataStreamExecSvc Data streamer executor service. * @param restExecSvc Reset executor service. * @param affExecSvc Affinity executor service. * @param idxExecSvc Indexing executor service. * @param callbackExecSvc Callback executor service. * @param qryExecSvc Query executor service. * @param schemaExecSvc Schema executor service. * @param customExecSvcs Custom named executors. * @param errHnd Error handler to use for notification about startup problems. * @param workerRegistry Worker registry. * @param hnd Default uncaught exception handler used by thread pools. * @throws IgniteCheckedException Thrown in case of any errors. */ public void start( final IgniteConfiguration cfg, ExecutorService utilityCachePool, final ExecutorService execSvc, final ExecutorService svcExecSvc, final ExecutorService sysExecSvc, final StripedExecutor stripedExecSvc, ExecutorService p2pExecSvc, ExecutorService mgmtExecSvc, ExecutorService igfsExecSvc, StripedExecutor dataStreamExecSvc, ExecutorService restExecSvc, ExecutorService affExecSvc, @Nullable ExecutorService idxExecSvc, IgniteStripedThreadPoolExecutor callbackExecSvc, ExecutorService qryExecSvc, ExecutorService schemaExecSvc, @Nullable final Map<String, ? extends ExecutorService> customExecSvcs, GridAbsClosure errHnd, WorkersRegistry workerRegistry, Thread.UncaughtExceptionHandler hnd, TimeBag startTimer ) throws IgniteCheckedException { gw.compareAndSet(null, new GridKernalGatewayImpl(cfg.getIgniteInstanceName())); GridKernalGateway gw = this.gw.get(); gw.writeLock(); try { switch (gw.getState()) { case STARTED: { U.warn(log, "Grid has already been started (ignored)."); return; } case STARTING: { U.warn(log, "Grid is already in process of being started (ignored)."); return; } case STOPPING: { throw new IgniteCheckedException("Grid is in process of being stopped"); } case STOPPED: { break; } } gw.setState(STARTING); } finally { gw.writeUnlock(); } assert cfg != null; // Make sure we got proper configuration. validateCommon(cfg); igniteInstanceName = cfg.getIgniteInstanceName(); this.cfg = cfg; log = (GridLoggerProxy)cfg.getGridLogger().getLogger( getClass().getName() + (igniteInstanceName != null ? '%' + igniteInstanceName : "")); longJVMPauseDetector = new LongJVMPauseDetector(log); longJVMPauseDetector.start(); RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean(); // Ack various information. ackAsciiLogo(); ackConfigUrl(); ackConfiguration(cfg); ackDaemon(); ackOsInfo(); ackLanguageRuntime(); ackRemoteManagement(); ackLogger(); ackVmArguments(rtBean); ackClassPaths(rtBean); ackSystemProperties(); ackEnvironmentVariables(); ackMemoryConfiguration(); ackCacheConfiguration(); ackP2pConfiguration(); ackRebalanceConfiguration(); ackIPv4StackFlagIsSet(); // Run background network diagnostics. GridDiagnostic.runBackgroundCheck(igniteInstanceName, execSvc, log); // Ack 3-rd party licenses location. if (log.isInfoEnabled() && cfg.getIgniteHome() != null) log.info("3-rd party licenses can be found at: " + cfg.getIgniteHome() + File.separatorChar + "libs" + File.separatorChar + "licenses"); // Check that user attributes are not conflicting // with internally reserved names. for (String name : cfg.getUserAttributes().keySet()) if (name.startsWith(ATTR_PREFIX)) throw new IgniteCheckedException("User attribute has illegal name: '" + name + "'. Note that all names " + "starting with '" + ATTR_PREFIX + "' are reserved for internal use."); // Ack local node user attributes. logNodeUserAttributes(); // Ack configuration. ackSpis(); List<PluginProvider> plugins = cfg.getPluginProviders() != null && cfg.getPluginProviders().length > 0 ? Arrays.asList(cfg.getPluginProviders()) : U.allPluginProviders(); // Spin out SPIs & managers. try { ctx = new GridKernalContextImpl(log, this, cfg, gw, utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, igfsExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, customExecSvcs, plugins, MarshallerUtils.classNameFilter(this.getClass().getClassLoader()), workerRegistry, hnd, longJVMPauseDetector ); startProcessor(new DiagnosticProcessor(ctx)); mBeansMgr = new IgniteMBeansManager(this); cfg.getMarshaller().setContext(ctx.marshallerContext()); GridInternalSubscriptionProcessor subscriptionProc = new GridInternalSubscriptionProcessor(ctx); startProcessor(subscriptionProc); ClusterProcessor clusterProc = new ClusterProcessor(ctx); startProcessor(clusterProc); U.onGridStart(); // Start and configure resource processor first as it contains resources used // by all other managers and processors. GridResourceProcessor rsrcProc = new GridResourceProcessor(ctx); rsrcProc.setSpringContext(rsrcCtx); scheduler = new IgniteSchedulerImpl(ctx); startProcessor(rsrcProc); // Inject resources into lifecycle beans. if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) { if (bean != null) rsrcProc.inject(bean); } } // Lifecycle notification. notifyLifecycleBeans(BEFORE_NODE_START); // Starts lifecycle aware components. U.startLifecycleAware(lifecycleAwares(cfg)); addHelper(IGFS_HELPER.create(F.isEmpty(cfg.getFileSystemConfiguration()))); addHelper(HADOOP_HELPER.createIfInClassPath(ctx, false)); startProcessor(new IgnitePluginProcessor(ctx, cfg, plugins)); startProcessor(new FailureProcessor(ctx)); startProcessor(new PoolProcessor(ctx)); // Closure processor should be started before all others // (except for resource processor), as many components can depend on it. startProcessor(new GridClosureProcessor(ctx)); // Start some other processors (order & place is important). startProcessor(new GridPortProcessor(ctx)); startProcessor(new GridJobMetricsProcessor(ctx)); // Timeout processor needs to be started before managers, // as managers may depend on it. startProcessor(new GridTimeoutProcessor(ctx)); // Start security processors. startProcessor(securityProcessor()); // Start SPI managers. // NOTE: that order matters as there are dependencies between managers. startManager(new GridMetricManager(ctx)); startManager(new GridIoManager(ctx)); startManager(new GridCheckpointManager(ctx)); startManager(new GridEventStorageManager(ctx)); startManager(new GridDeploymentManager(ctx)); startManager(new GridLoadBalancerManager(ctx)); startManager(new GridFailoverManager(ctx)); startManager(new GridCollisionManager(ctx)); startManager(new GridIndexingManager(ctx)); startManager(new GridEncryptionManager(ctx)); ackSecurity(); // Assign discovery manager to context before other processors start so they // are able to register custom event listener. final GridManager discoMgr = new GridDiscoveryManager(ctx); ctx.add(discoMgr, false); // Start processors before discovery manager, so they will // be able to start receiving messages once discovery completes. try { startProcessor(COMPRESSION.createOptional(ctx)); startProcessor(new PdsConsistentIdProcessor(ctx)); startProcessor(new MvccProcessorImpl(ctx)); startProcessor(createComponent(DiscoveryNodeValidationProcessor.class, ctx)); startProcessor(new GridAffinityProcessor(ctx)); startProcessor(createComponent(GridSegmentationProcessor.class, ctx)); startTimer.finishGlobalStage("Start managers"); startProcessor(createComponent(IgniteCacheObjectProcessor.class, ctx)); startTimer.finishGlobalStage("Configure binary metadata"); startProcessor(createComponent(IGridClusterStateProcessor.class, ctx)); startProcessor(new IgniteAuthenticationProcessor(ctx)); startProcessor(new GridCacheProcessor(ctx)); startProcessor(new GridQueryProcessor(ctx)); startProcessor(new ClientListenerProcessor(ctx)); startProcessor(createServiceProcessor()); startProcessor(new GridTaskSessionProcessor(ctx)); startProcessor(new GridJobProcessor(ctx)); startProcessor(new GridTaskProcessor(ctx)); startProcessor((GridProcessor)SCHEDULE.createOptional(ctx)); startProcessor(new GridRestProcessor(ctx)); startProcessor(new DataStreamProcessor(ctx)); startProcessor((GridProcessor)IGFS.create(ctx, F.isEmpty(cfg.getFileSystemConfiguration()))); startProcessor(new GridContinuousProcessor(ctx)); startProcessor(createHadoopComponent()); startProcessor(new DataStructuresProcessor(ctx)); startProcessor(createComponent(PlatformProcessor.class, ctx)); startProcessor(new GridMarshallerMappingProcessor(ctx)); startProcessor(new DistributedMetaStorageImpl(ctx)); startProcessor(new DistributedConfigurationProcessor(ctx)); startTimer.finishGlobalStage("Start processors"); // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) { ctx.add(new GridPluginComponent(provider)); provider.start(ctx.plugins().pluginContextForProvider(provider)); startTimer.finishGlobalStage("Start '"+ provider.name() + "' plugin"); } // Start platform plugins. if (ctx.config().getPlatformConfiguration() != null) startProcessor(new PlatformPluginProcessor(ctx)); ctx.cluster().initDiagnosticListeners(); fillNodeAttributes(clusterProc.updateNotifierEnabled()); ctx.cache().context().database().notifyMetaStorageSubscribersOnReadyForRead(); ((DistributedMetaStorageImpl)ctx.distributedMetastorage()).inMemoryReadyForRead(); startTimer.finishGlobalStage("Init metastore"); ctx.cache().context().database().startMemoryRestore(ctx, startTimer); ctx.recoveryMode(false); startTimer.finishGlobalStage("Finish recovery"); } catch (Throwable e) { U.error( log, "Exception during start processors, node will be stopped and close connections", e); // Stop discovery spi to close tcp socket. ctx.discovery().stop(true); throw e; } gw.writeLock(); try { gw.setState(STARTED); // Start discovery manager last to make sure that grid is fully initialized. startManager(discoMgr); } finally { gw.writeUnlock(); } startTimer.finishGlobalStage("Join topology"); // Check whether UTF-8 is the default character encoding. checkFileEncoding(); // Check whether physical RAM is not exceeded. checkPhysicalRam(); // Suggest configuration optimizations. suggestOptimizations(cfg); // Suggest JVM optimizations. ctx.performance().addAll(JvmConfigurationSuggestions.getSuggestions()); // Suggest Operation System optimizations. ctx.performance().addAll(OsConfigurationSuggestions.getSuggestions()); DiscoveryLocalJoinData joinData = ctx.discovery().localJoin(); IgniteInternalFuture<Boolean> transitionWaitFut = joinData.transitionWaitFuture(); // Notify discovery manager the first to make sure that topology is discovered. // Active flag is not used in managers, so it is safe to pass true. ctx.discovery().onKernalStart(true); // Notify IO manager the second so further components can send and receive messages. // Must notify the IO manager before transition state await to make sure IO connection can be established. ctx.io().onKernalStart(true); boolean active; if (transitionWaitFut != null) { if (log.isInfoEnabled()) { log.info("Join cluster while cluster state transition is in progress, " + "waiting when transition finish."); } active = transitionWaitFut.get(); } else active = joinData.active(); startTimer.finishGlobalStage("Await transition"); boolean recon = false; // Callbacks. for (GridComponent comp : ctx) { // Skip discovery manager. if (comp instanceof GridDiscoveryManager) continue; // Skip IO manager. if (comp instanceof GridIoManager) continue; if (comp instanceof GridPluginComponent) continue; if (!skipDaemon(comp)) { try { comp.onKernalStart(active); } catch (IgniteNeedReconnectException e) { ClusterNode locNode = ctx.discovery().localNode(); assert locNode.isClient(); if (!ctx.discovery().reconnectSupported()) throw new IgniteCheckedException("Client node in forceServerMode " + "is not allowed to reconnect to the cluster and will be stopped."); if (log.isDebugEnabled()) log.debug("Failed to start node components on node start, will wait for reconnect: " + e); recon = true; } } } // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) provider.onIgniteStart(); if (recon) reconnectState.waitFirstReconnect(); ctx.metric().registerThreadPools(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, igfsExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, customExecSvcs); // Register MBeans. mBeansMgr.registerAllMBeans(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, igfsExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, customExecSvcs, ctx.workersRegistry()); // Lifecycle bean notifications. notifyLifecycleBeans(AFTER_NODE_START); } catch (Throwable e) { IgniteSpiVersionCheckException verCheckErr = X.cause(e, IgniteSpiVersionCheckException.class); if (verCheckErr != null) U.error(log, verCheckErr.getMessage()); else if (X.hasCause(e, InterruptedException.class, IgniteInterruptedCheckedException.class)) U.warn(log, "Grid startup routine has been interrupted (will rollback)."); else U.error(log, "Got exception while starting (will rollback startup routine).", e); errHnd.apply(); stop(true); if (e instanceof Error) throw e; else if (e instanceof IgniteCheckedException) throw (IgniteCheckedException)e; else throw new IgniteCheckedException(e); } // Mark start timestamp. startTime = U.currentTimeMillis(); String intervalStr = IgniteSystemProperties.getString(IGNITE_STARVATION_CHECK_INTERVAL); // Start starvation checker if enabled. boolean starveCheck = !isDaemon() && !"0".equals(intervalStr); if (starveCheck) { final long interval = F.isEmpty(intervalStr) ? PERIODIC_STARVATION_CHECK_FREQ : Long.parseLong(intervalStr); starveTask = ctx.timeout().schedule(new Runnable() { /** Last completed task count. */ private long lastCompletedCntPub; /** Last completed task count. */ private long lastCompletedCntSys; @Override public void run() { if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; lastCompletedCntPub = checkPoolStarvation(exec, lastCompletedCntPub, "public"); } if (sysExecSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)sysExecSvc; lastCompletedCntSys = checkPoolStarvation(exec, lastCompletedCntSys, "system"); } if (stripedExecSvc != null) stripedExecSvc.detectStarvation(); } /** * @param exec Thread pool executor to check. * @param lastCompletedCnt Last completed tasks count. * @param pool Pool name for message. * @return Current completed tasks count. */ private long checkPoolStarvation( ThreadPoolExecutor exec, long lastCompletedCnt, String pool ) { long completedCnt = exec.getCompletedTaskCount(); // If all threads are active and no task has completed since last time and there is // at least one waiting request, then it is possible starvation. if (exec.getPoolSize() == exec.getActiveCount() && completedCnt == lastCompletedCnt && !exec.getQueue().isEmpty()) LT.warn( log, "Possible thread pool starvation detected (no task completed in last " + interval + "ms, is " + pool + " thread pool size large enough?)"); return completedCnt; } }, interval, interval); } long metricsLogFreq = cfg.getMetricsLogFrequency(); if (metricsLogFreq > 0) { metricsLogTask = ctx.timeout().schedule(new Runnable() { private final DecimalFormat dblFmt = new DecimalFormat("#.##"); @Override public void run() { ackNodeMetrics(dblFmt, execSvc, sysExecSvc, customExecSvcs); } }, metricsLogFreq, metricsLogFreq); } final long longOpDumpTimeout = IgniteSystemProperties.getLong( IgniteSystemProperties.IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT, DFLT_LONG_OPERATIONS_DUMP_TIMEOUT ); if (longOpDumpTimeout > 0) { longOpDumpTask = ctx.timeout().schedule(new Runnable() { @Override public void run() { GridKernalContext ctx = IgniteKernal.this.ctx; if (ctx != null) ctx.cache().context().exchange().dumpLongRunningOperations(longOpDumpTimeout); } }, longOpDumpTimeout, longOpDumpTimeout); } ctx.performance().add("Disable assertions (remove '-ea' from JVM options)", !U.assertionsEnabled()); ctx.performance().logSuggestions(log, igniteInstanceName); U.quietAndInfo(log, "To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}"); if (!IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_QUIET, true)) ackClassPathContent(); ackStart(rtBean); if (!isDaemon()) ctx.discovery().ackTopology(ctx.discovery().localJoin().joinTopologyVersion().topologyVersion(), EventType.EVT_NODE_JOINED, localNode()); startTimer.finishGlobalStage("Await exchange"); } /** * @return Ignite security processor. See {@link IgniteSecurity} for details. */ private GridProcessor securityProcessor() throws IgniteCheckedException { GridSecurityProcessor prc = createComponent(GridSecurityProcessor.class, ctx); return prc != null && prc.enabled() ? new IgniteSecurityProcessor(ctx, prc) : new NoOpIgniteSecurityProcessor(ctx); } /** * Create description of an executor service for logging. * * @param execSvcName Name of the service. * @param execSvc Service to create a description for. */ private String createExecutorDescription(String execSvcName, ExecutorService execSvc) { int poolActiveThreads = 0; int poolIdleThreads = 0; int poolQSize = 0; if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; int poolSize = exec.getPoolSize(); poolActiveThreads = Math.min(poolSize, exec.getActiveCount()); poolIdleThreads = poolSize - poolActiveThreads; poolQSize = exec.getQueue().size(); } return execSvcName + " [active=" + poolActiveThreads + ", idle=" + poolIdleThreads + ", qSize=" + poolQSize + "]"; } /** * Create Hadoop component. * * @return Non-null Hadoop component: workable or no-op. * @throws IgniteCheckedException If the component is mandatory and cannot be initialized. */ private HadoopProcessorAdapter createHadoopComponent() throws IgniteCheckedException { boolean mandatory = cfg.getHadoopConfiguration() != null; if (mandatory) { if (cfg.isPeerClassLoadingEnabled()) throw new IgniteCheckedException("Hadoop module cannot be used with peer class loading enabled " + "(set IgniteConfiguration.peerClassLoadingEnabled to \"false\")."); HadoopProcessorAdapter res = IgniteComponentType.HADOOP.createIfInClassPath(ctx, true); res.validateEnvironment(); return res; } else { HadoopProcessorAdapter cmp = null; if (!ctx.hadoopHelper().isNoOp() && cfg.isPeerClassLoadingEnabled()) { U.warn(log, "Hadoop module is found in classpath, but will not be started because peer class " + "loading is enabled (set IgniteConfiguration.peerClassLoadingEnabled to \"false\" if you want " + "to use Hadoop module)."); } else { cmp = IgniteComponentType.HADOOP.createIfInClassPath(ctx, false); try { cmp.validateEnvironment(); } catch (IgniteException | IgniteCheckedException e) { U.quietAndWarn(log, "Hadoop module will not start due to exception: " + e.getMessage()); cmp = null; } } if (cmp == null) cmp = IgniteComponentType.HADOOP.create(ctx, true); return cmp; } } /** * Creates service processor depend on {@link IgniteSystemProperties#IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED}. * * @return The service processor. See {@link IgniteServiceProcessor} for details. */ private GridProcessorAdapter createServiceProcessor() { final boolean srvcProcMode = getBoolean(IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, true); if (srvcProcMode) return new IgniteServiceProcessor(ctx); return new GridServiceProcessor(ctx); } /** * Validates common configuration parameters. * * @param cfg Ignite configuration to validate. */ private void validateCommon(IgniteConfiguration cfg) { A.notNull(cfg.getNodeId(), "cfg.getNodeId()"); if (!U.IGNITE_MBEANS_DISABLED) A.notNull(cfg.getMBeanServer(), "cfg.getMBeanServer()"); A.notNull(cfg.getGridLogger(), "cfg.getGridLogger()"); A.notNull(cfg.getMarshaller(), "cfg.getMarshaller()"); A.notNull(cfg.getUserAttributes(), "cfg.getUserAttributes()"); // All SPIs should be non-null. A.notNull(cfg.getCheckpointSpi(), "cfg.getCheckpointSpi()"); A.notNull(cfg.getCommunicationSpi(), "cfg.getCommunicationSpi()"); A.notNull(cfg.getDeploymentSpi(), "cfg.getDeploymentSpi()"); A.notNull(cfg.getDiscoverySpi(), "cfg.getDiscoverySpi()"); A.notNull(cfg.getEventStorageSpi(), "cfg.getEventStorageSpi()"); A.notNull(cfg.getCollisionSpi(), "cfg.getCollisionSpi()"); A.notNull(cfg.getFailoverSpi(), "cfg.getFailoverSpi()"); A.notNull(cfg.getLoadBalancingSpi(), "cfg.getLoadBalancingSpi()"); A.notNull(cfg.getIndexingSpi(), "cfg.getIndexingSpi()"); A.ensure(cfg.getNetworkTimeout() > 0, "cfg.getNetworkTimeout() > 0"); A.ensure(cfg.getNetworkSendRetryDelay() > 0, "cfg.getNetworkSendRetryDelay() > 0"); A.ensure(cfg.getNetworkSendRetryCount() > 0, "cfg.getNetworkSendRetryCount() > 0"); } /** * Check whether UTF-8 is the default character encoding. * Differing character encodings across cluster may lead to erratic behavior. */ private void checkFileEncoding() { String encodingDisplayName = Charset.defaultCharset().displayName(Locale.ENGLISH); if (!"UTF-8".equals(encodingDisplayName)) { U.quietAndWarn(log, "Default character encoding is " + encodingDisplayName + ". Specify UTF-8 character encoding by setting -Dfile.encoding=UTF-8 JVM parameter. " + "Differing character encodings across cluster may lead to erratic behavior."); } } /** * Checks whether physical RAM is not exceeded. */ @SuppressWarnings("ConstantConditions") private void checkPhysicalRam() { long ram = ctx.discovery().localNode().attribute(ATTR_PHY_RAM); if (ram != -1) { String macs = ctx.discovery().localNode().attribute(ATTR_MACS); long totalHeap = 0; long totalOffheap = 0; for (ClusterNode node : ctx.discovery().allNodes()) { if (macs.equals(node.attribute(ATTR_MACS))) { long heap = node.metrics().getHeapMemoryMaximum(); Long offheap = node.<Long>attribute(ATTR_OFFHEAP_SIZE); if (heap != -1) totalHeap += heap; if (offheap != null) totalOffheap += offheap; } } long total = totalHeap + totalOffheap; if (total < 0) total = Long.MAX_VALUE; // 4GB or 20% of available memory is expected to be used by OS and user applications long safeToUse = ram - Math.max(4L << 30, (long)(ram * 0.2)); if (total > safeToUse) { U.quietAndWarn(log, "Nodes started on local machine require more than 80% of physical RAM what can " + "lead to significant slowdown due to swapping (please decrease JVM heap size, data region " + "size or checkpoint buffer size) [required=" + (total >> 20) + "MB, available=" + (ram >> 20) + "MB]"); } } } /** * @param cfg Ignite configuration to check for possible performance issues. */ private void suggestOptimizations(IgniteConfiguration cfg) { GridPerformanceSuggestions perf = ctx.performance(); if (ctx.collision().enabled()) perf.add("Disable collision resolution (remove 'collisionSpi' from configuration)"); if (ctx.checkpoint().enabled()) perf.add("Disable checkpoints (remove 'checkpointSpi' from configuration)"); if (cfg.isMarshalLocalJobs()) perf.add("Disable local jobs marshalling (set 'marshalLocalJobs' to false)"); if (cfg.getIncludeEventTypes() != null && cfg.getIncludeEventTypes().length != 0) perf.add("Disable grid events (remove 'includeEventTypes' from configuration)"); if (BinaryMarshaller.available() && (cfg.getMarshaller() != null && !(cfg.getMarshaller() instanceof BinaryMarshaller))) perf.add("Use default binary marshaller (do not set 'marshaller' explicitly)"); } /** * Creates attributes map and fills it in. * * @param notifyEnabled Update notifier flag. * @throws IgniteCheckedException thrown if was unable to set up attribute. */ private void fillNodeAttributes(boolean notifyEnabled) throws IgniteCheckedException { ctx.addNodeAttribute(ATTR_REBALANCE_POOL_SIZE, configuration().getRebalanceThreadPoolSize()); ctx.addNodeAttribute(ATTR_DATA_STREAMER_POOL_SIZE, configuration().getDataStreamerThreadPoolSize()); final String[] incProps = cfg.getIncludeProperties(); try { // Stick all environment settings into node attributes. for (Map.Entry<String, String> sysEntry : System.getenv().entrySet()) { String name = sysEntry.getKey(); if (incProps == null || U.containsStringArray(incProps, name, true) || U.isVisorNodeStartProperty(name) || U.isVisorRequiredProperty(name)) ctx.addNodeAttribute(name, sysEntry.getValue()); } if (log.isDebugEnabled()) log.debug("Added environment properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add environment properties to node attributes due to " + "security violation: " + e.getMessage()); } try { // Stick all system properties into node's attributes overwriting any // identical names from environment properties. for (Map.Entry<Object, Object> e : snapshot().entrySet()) { String key = (String)e.getKey(); if (incProps == null || U.containsStringArray(incProps, key, true) || U.isVisorRequiredProperty(key)) { Object val = ctx.nodeAttribute(key); if (val != null && !val.equals(e.getValue())) U.warn(log, "System property will override environment variable with the same name: " + key); ctx.addNodeAttribute(key, e.getValue()); } } ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_UPDATE_NOTIFIER_ENABLED, notifyEnabled); if (log.isDebugEnabled()) log.debug("Added system properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add system properties to node attributes due to security " + "violation: " + e.getMessage()); } // Add local network IPs and MACs. String ips = F.concat(U.allLocalIps(), ", "); // Exclude loopbacks. String macs = F.concat(U.allLocalMACs(), ", "); // Only enabled network interfaces. // Ack network context. if (log.isInfoEnabled()) { log.info("Non-loopback local IPs: " + (F.isEmpty(ips) ? "N/A" : ips)); log.info("Enabled local MACs: " + (F.isEmpty(macs) ? "N/A" : macs)); } // Warn about loopback. if (ips.isEmpty() && macs.isEmpty()) U.warn(log, "Ignite is starting on loopback address... Only nodes on the same physical " + "computer can participate in topology."); // Stick in network context into attributes. add(ATTR_IPS, (ips.isEmpty() ? "" : ips)); Map<String, ?> userAttrs = configuration().getUserAttributes(); if (userAttrs != null && userAttrs.get(IgniteNodeAttributes.ATTR_MACS_OVERRIDE) != null) add(ATTR_MACS, (Serializable)userAttrs.get(IgniteNodeAttributes.ATTR_MACS_OVERRIDE)); else add(ATTR_MACS, (macs.isEmpty() ? "" : macs)); // Stick in some system level attributes add(ATTR_JIT_NAME, U.getCompilerMx() == null ? "" : U.getCompilerMx().getName()); add(ATTR_BUILD_VER, VER_STR); add(ATTR_BUILD_DATE, BUILD_TSTAMP_STR); add(ATTR_MARSHALLER, cfg.getMarshaller().getClass().getName()); add(ATTR_MARSHALLER_USE_DFLT_SUID, getBoolean(IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID, OptimizedMarshaller.USE_DFLT_SUID)); add(ATTR_LATE_AFFINITY_ASSIGNMENT, cfg.isLateAffinityAssignment()); if (cfg.getMarshaller() instanceof BinaryMarshaller) { add(ATTR_MARSHALLER_COMPACT_FOOTER, cfg.getBinaryConfiguration() == null ? BinaryConfiguration.DFLT_COMPACT_FOOTER : cfg.getBinaryConfiguration().isCompactFooter()); add(ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2, getBoolean(IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2, BinaryUtils.USE_STR_SERIALIZATION_VER_2)); } add(ATTR_USER_NAME, System.getProperty("user.name")); add(ATTR_IGNITE_INSTANCE_NAME, igniteInstanceName); add(ATTR_PEER_CLASSLOADING, cfg.isPeerClassLoadingEnabled()); add(ATTR_DEPLOYMENT_MODE, cfg.getDeploymentMode()); add(ATTR_LANG_RUNTIME, getLanguage()); add(ATTR_JVM_PID, U.jvmPid()); add(ATTR_CLIENT_MODE, cfg.isClientMode()); add(ATTR_CONSISTENCY_CHECK_SKIPPED, getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK)); add(ATTR_VALIDATE_CACHE_REQUESTS, Boolean.TRUE); if (cfg.getConsistentId() != null) add(ATTR_NODE_CONSISTENT_ID, cfg.getConsistentId()); // Build a string from JVM arguments, because parameters with spaces are split. SB jvmArgs = new SB(512); for (String arg : U.jvmArgs()) { if (arg.startsWith("-")) jvmArgs.a("@@@"); else jvmArgs.a(' '); jvmArgs.a(arg); } // Add it to attributes. add(ATTR_JVM_ARGS, jvmArgs.toString()); // Check daemon system property and override configuration if it's set. if (isDaemon()) add(ATTR_DAEMON, "true"); // In case of the parsing error, JMX remote disabled or port not being set // node attribute won't be set. if (isJmxRemoteEnabled()) { String portStr = System.getProperty("com.sun.management.jmxremote.port"); if (portStr != null) try { add(ATTR_JMX_PORT, Integer.parseInt(portStr)); } catch (NumberFormatException ignore) { // No-op. } } // Whether restart is enabled and stick the attribute. add(ATTR_RESTART_ENABLED, Boolean.toString(isRestartEnabled())); // Save port range, port numbers will be stored by rest processor at runtime. if (cfg.getConnectorConfiguration() != null) add(ATTR_REST_PORT_RANGE, cfg.getConnectorConfiguration().getPortRange()); // Whether rollback of dynamic cache start is supported or not. // This property is added because of backward compatibility. add(ATTR_DYNAMIC_CACHE_START_ROLLBACK_SUPPORTED, Boolean.TRUE); // Save data storage configuration. addDataStorageConfigurationAttributes(); // Save transactions configuration. add(ATTR_TX_CONFIG, cfg.getTransactionConfiguration()); // Supported features. add(ATTR_IGNITE_FEATURES, IgniteFeatures.allFeatures()); // Stick in SPI versions and classes attributes. addSpiAttributes(cfg.getCollisionSpi()); addSpiAttributes(cfg.getDiscoverySpi()); addSpiAttributes(cfg.getFailoverSpi()); addSpiAttributes(cfg.getCommunicationSpi()); addSpiAttributes(cfg.getEventStorageSpi()); addSpiAttributes(cfg.getCheckpointSpi()); addSpiAttributes(cfg.getLoadBalancingSpi()); addSpiAttributes(cfg.getDeploymentSpi()); // Set user attributes for this node. if (cfg.getUserAttributes() != null) { for (Map.Entry<String, ?> e : cfg.getUserAttributes().entrySet()) { if (ctx.hasNodeAttribute(e.getKey())) U.warn(log, "User or internal attribute has the same name as environment or system " + "property and will take precedence: " + e.getKey()); ctx.addNodeAttribute(e.getKey(), e.getValue()); } } ctx.addNodeAttribute(ATTR_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, ctx.service() instanceof IgniteServiceProcessor); } /** * @throws IgniteCheckedException If duplicated SPI name found. */ private void addDataStorageConfigurationAttributes() throws IgniteCheckedException { MemoryConfiguration memCfg = cfg.getMemoryConfiguration(); // Save legacy memory configuration if it's present. if (memCfg != null) { // Page size initialization is suspended, see IgniteCacheDatabaseSharedManager#checkPageSize. // We should copy initialized value from new configuration. memCfg.setPageSize(cfg.getDataStorageConfiguration().getPageSize()); add(ATTR_MEMORY_CONFIG, memCfg); } // Save data storage configuration. add(ATTR_DATA_STORAGE_CONFIG, new JdkMarshaller().marshal(cfg.getDataStorageConfiguration())); } /** * Add SPI version and class attributes into node attributes. * * @param spiList Collection of SPIs to get attributes from. * @throws IgniteCheckedException Thrown if was unable to set up attribute. */ private void addSpiAttributes(IgniteSpi... spiList) throws IgniteCheckedException { for (IgniteSpi spi : spiList) { Class<? extends IgniteSpi> spiCls = spi.getClass(); add(U.spiAttribute(spi, ATTR_SPI_CLASS), spiCls.getName()); } } /** * @param mgr Manager to start. * @throws IgniteCheckedException Throw in case of any errors. */ private void startManager(GridManager mgr) throws IgniteCheckedException { // Add manager to registry before it starts to avoid cases when manager is started // but registry does not have it yet. ctx.add(mgr); try { if (!skipDaemon(mgr)) mgr.start(); } catch (IgniteCheckedException e) { U.error(log, "Failed to start manager: " + mgr, e); throw new IgniteCheckedException("Failed to start manager: " + mgr, e); } } /** * @param proc Processor to start. * @throws IgniteCheckedException Thrown in case of any error. */ private void startProcessor(GridProcessor proc) throws IgniteCheckedException { ctx.add(proc); try { if (!skipDaemon(proc)) proc.start(); } catch (IgniteCheckedException e) { throw new IgniteCheckedException("Failed to start processor: " + proc, e); } } /** * @param helper Helper to attach to kernal context. */ private void addHelper(Object helper) { ctx.addHelper(helper); } /** * Gets "on" or "off" string for given boolean value. * * @param b Boolean value to convert. * @return Result string. */ private String onOff(boolean b) { return b ? "on" : "off"; } /** * @return {@code true} if the REST processor is enabled, {@code false} the otherwise. */ private boolean isRestEnabled() { assert cfg != null; return cfg.getConnectorConfiguration() != null && // By default rest processor doesn't start on client nodes. (!isClientNode() || (isClientNode() && IgniteSystemProperties.getBoolean(IGNITE_REST_START_ON_CLIENT))); } /** * @return {@code True} if node client or daemon otherwise {@code false}. */ private boolean isClientNode() { return cfg.isClientMode() || cfg.isDaemon(); } /** * Acks remote management. */ private void ackRemoteManagement() { assert log != null; if (!log.isInfoEnabled()) return; SB sb = new SB(); sb.a("Remote Management ["); boolean on = isJmxRemoteEnabled(); sb.a("restart: ").a(onOff(isRestartEnabled())).a(", "); sb.a("REST: ").a(onOff(isRestEnabled())).a(", "); sb.a("JMX ("); sb.a("remote: ").a(onOff(on)); if (on) { sb.a(", "); sb.a("port: ").a(System.getProperty("com.sun.management.jmxremote.port", "<n/a>")).a(", "); sb.a("auth: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.authenticate"))).a(", "); // By default SSL is enabled, that's why additional check for null is needed. // See http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html sb.a("ssl: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.ssl") || System.getProperty("com.sun.management.jmxremote.ssl") == null)); } sb.a(")"); sb.a(']'); log.info(sb.toString()); } /** * Acks configuration URL. */ private void ackConfigUrl() { assert log != null; if (log.isInfoEnabled()) log.info("Config URL: " + System.getProperty(IGNITE_CONFIG_URL, "n/a")); } /** * @param cfg Ignite configuration to ack. */ private void ackConfiguration(IgniteConfiguration cfg) { assert log != null; if (log.isInfoEnabled()) log.info(cfg.toString()); } /** * Acks Logger configuration. */ private void ackLogger() { assert log != null; if (log.isInfoEnabled()) log.info("Logger: " + log.getLoggerInfo()); } /** * Acks ASCII-logo. Thanks to http://patorjk.com/software/taag */ private void ackAsciiLogo() { assert log != null; if (System.getProperty(IGNITE_NO_ASCII) == null) { String ver = "ver. " + ACK_VER_STR; // Big thanks to: http://patorjk.com/software/taag // Font name "Small Slant" if (log.isInfoEnabled()) { log.info(NL + NL + ">>> __________ ________________ " + NL + ">>> / _/ ___/ |/ / _/_ __/ __/ " + NL + ">>> _/ // (7 7 // / / / / _/ " + NL + ">>> /___/\\___/_/|_/___/ /_/ /___/ " + NL + ">>> " + NL + ">>> " + ver + NL + ">>> " + COPYRIGHT + NL + ">>> " + NL + ">>> Ignite documentation: " + "http://" + SITE + NL ); } if (log.isQuiet()) { U.quiet(false, " __________ ________________ ", " / _/ ___/ |/ / _/_ __/ __/ ", " _/ // (7 7 // / / / / _/ ", "/___/\\___/_/|_/___/ /_/ /___/ ", "", ver, COPYRIGHT, "", "Ignite documentation: " + "http://" + SITE, "", "Quiet mode."); String fileName = log.fileName(); if (fileName != null) U.quiet(false, " ^-- Logging to file '" + fileName + '\''); U.quiet(false, " ^-- Logging by '" + log.getLoggerInfo() + '\''); U.quiet(false, " ^-- To see **FULL** console log here add -DIGNITE_QUIET=false or \"-v\" to ignite.{sh|bat}", ""); } } } /** * Prints start info. * * @param rtBean Java runtime bean. */ private void ackStart(RuntimeMXBean rtBean) { ClusterNode locNode = localNode(); if (log.isQuiet()) { ackDataRegions(s -> { U.quiet(false, s); return null; }); U.quiet(false, ""); U.quiet(false, "Ignite node started OK (id=" + U.id8(locNode.id()) + (F.isEmpty(igniteInstanceName) ? "" : ", instance name=" + igniteInstanceName) + ')'); } if (log.isInfoEnabled()) { ackDataRegions(s -> { log.info(s); return null; }); String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR; String dash = U.dash(ack.length()); SB sb = new SB(); for (GridPortRecord rec : ctx.ports().records()) sb.a(rec.protocol()).a(":").a(rec.port()).a(" "); String str = NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + ">>> OS name: " + U.osString() + NL + ">>> CPU(s): " + locNode.metrics().getTotalCpus() + NL + ">>> Heap: " + U.heapSize(locNode, 2) + "GB" + NL + ">>> VM name: " + rtBean.getName() + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Local node [" + "ID=" + locNode.id().toString().toUpperCase() + ", order=" + locNode.order() + ", clientMode=" + ctx.clientNode() + "]" + NL + ">>> Local node addresses: " + U.addressesAsString(locNode) + NL + ">>> Local ports: " + sb + NL; log.info(str); } if (!ctx.state().clusterState().active()) { U.quietAndInfo(log, ">>> Ignite cluster is not active (limited functionality available). " + "Use control.(sh|bat) script or IgniteCluster interface to activate."); } } /** * @param clo Message output closure. */ public void ackDataRegions(IgniteClosure<String, Void> clo) { DataStorageConfiguration memCfg = ctx.config().getDataStorageConfiguration(); if (memCfg == null) return; clo.apply("Data Regions Configured:"); clo.apply(dataRegionConfigurationMessage(memCfg.getDefaultDataRegionConfiguration())); DataRegionConfiguration[] dataRegions = memCfg.getDataRegionConfigurations(); if (dataRegions != null) { for (DataRegionConfiguration dataRegion : dataRegions) { String msg = dataRegionConfigurationMessage(dataRegion); if (msg != null) clo.apply(msg); } } } /** * @param regCfg Data region configuration. * @return Data region message. */ private String dataRegionConfigurationMessage(DataRegionConfiguration regCfg) { if (regCfg == null) return null; SB m = new SB(); m.a(" ^-- ").a(regCfg.getName()).a(" ["); m.a("initSize=").a(U.readableSize(regCfg.getInitialSize(), false)); m.a(", maxSize=").a(U.readableSize(regCfg.getMaxSize(), false)); m.a(", persistence=" + regCfg.isPersistenceEnabled()); m.a(", lazyMemoryAllocation=" + regCfg.isLazyMemoryAllocation()).a(']'); return m.toString(); } /** * Logs out OS information. */ private void ackOsInfo() { assert log != null; if (log.isQuiet()) U.quiet(false, "OS: " + U.osString()); if (log.isInfoEnabled()) { log.info("OS: " + U.osString()); log.info("OS user: " + System.getProperty("user.name")); int jvmPid = U.jvmPid(); log.info("PID: " + (jvmPid == -1 ? "N/A" : jvmPid)); } } /** * Logs out language runtime. */ private void ackLanguageRuntime() { assert log != null; if (log.isQuiet()) U.quiet(false, "VM information: " + U.jdkString()); if (log.isInfoEnabled()) { log.info("Language runtime: " + getLanguage()); log.info("VM information: " + U.jdkString()); log.info("VM total memory: " + U.heapSize(2) + "GB"); } } /** * Logs out node metrics. * * @param dblFmt Decimal format. * @param execSvc Executor service. * @param sysExecSvc System executor service. * @param customExecSvcs Custom named executors. */ private void ackNodeMetrics(DecimalFormat dblFmt, ExecutorService execSvc, ExecutorService sysExecSvc, Map<String, ? extends ExecutorService> customExecSvcs ) { if (!log.isInfoEnabled()) return; try { ClusterMetrics m = cluster().localNode().metrics(); final int MByte = 1024 * 1024; double cpuLoadPct = m.getCurrentCpuLoad() * 100; double avgCpuLoadPct = m.getAverageCpuLoad() * 100; double gcPct = m.getCurrentGcCpuLoad() * 100; // Heap params. long heapUsed = m.getHeapMemoryUsed(); long heapMax = m.getHeapMemoryMaximum(); long heapUsedInMBytes = heapUsed / MByte; long heapCommInMBytes = m.getHeapMemoryCommitted() / MByte; double freeHeapPct = heapMax > 0 ? ((double)((heapMax - heapUsed) * 100)) / heapMax : -1; int hosts = 0; int nodes = 0; int cpus = 0; try { ClusterMetrics metrics = cluster().metrics(); Collection<ClusterNode> nodes0 = cluster().nodes(); hosts = U.neighborhood(nodes0).size(); nodes = metrics.getTotalNodes(); cpus = metrics.getTotalCpus(); } catch (IgniteException ignore) { // No-op. } int loadedPages = 0; // Off-heap params. Collection<DataRegion> regions = ctx.cache().context().database().dataRegions(); StringBuilder dataRegionsInfo = new StringBuilder(); StringBuilder pdsRegionsInfo = new StringBuilder(); long offHeapUsedSummary = 0; long offHeapMaxSummary = 0; long offHeapCommSummary = 0; long pdsUsedSummary = 0; boolean persistenceDisabled = true; if (!F.isEmpty(regions)) { for (DataRegion region : regions) { long pagesCnt = region.pageMemory().loadedPages(); long offHeapUsed = region.pageMemory().systemPageSize() * pagesCnt; long offHeapMax = region.config().getMaxSize(); long offHeapComm = region.memoryMetrics().getOffHeapSize(); long offHeapUsedInMBytes = offHeapUsed / MByte; long offHeapCommInMBytes = offHeapComm / MByte; double freeOffHeapPct = offHeapMax > 0 ? ((double)((offHeapMax - offHeapUsed) * 100)) / offHeapMax : -1; offHeapUsedSummary += offHeapUsed; offHeapMaxSummary += offHeapMax; offHeapCommSummary += offHeapComm; loadedPages += pagesCnt; dataRegionsInfo.append(" ^-- ") .append(region.config().getName()).append(" region") .append(" [used=").append(dblFmt.format(offHeapUsedInMBytes)) .append("MB, free=").append(dblFmt.format(freeOffHeapPct)) .append("%, comm=").append(dblFmt.format(offHeapCommInMBytes)).append("MB]") .append(NL); if (region.config().isPersistenceEnabled()) { long pdsUsed = region.memoryMetrics().getTotalAllocatedSize(); long pdsUsedMBytes = pdsUsed / MByte; pdsUsedSummary += pdsUsed; String pdsUsedSize = dblFmt.format(pdsUsedMBytes) + "MB"; pdsRegionsInfo.append(" ^-- ") .append(region.config().getName()).append(" region") .append(" [used=").append(pdsUsedSize).append("]") .append(NL); persistenceDisabled = false; } } } long offHeapUsedInMBytes = offHeapUsedSummary / MByte; long offHeapCommInMBytes = offHeapCommSummary / MByte; long pdsUsedMBytes = pdsUsedSummary / MByte; double freeOffHeapPct = offHeapMaxSummary > 0 ? ((double)((offHeapMaxSummary - offHeapUsedSummary) * 100)) / offHeapMaxSummary : -1; String pdsInfo = persistenceDisabled ? "" : " ^-- Ignite persistence [used=" + dblFmt.format(pdsUsedMBytes) + "MB]" + NL + pdsRegionsInfo; String id = U.id8(localNode().id()); String msg = NL + "Metrics for local node (to disable set 'metricsLogFrequency' to 0)" + NL + " ^-- Node [id=" + id + (name() != null ? ", name=" + name() : "") + ", uptime=" + getUpTimeFormatted() + "]" + NL + " ^-- H/N/C [hosts=" + hosts + ", nodes=" + nodes + ", CPUs=" + cpus + "]" + NL + " ^-- CPU [cur=" + dblFmt.format(cpuLoadPct) + "%, avg=" + dblFmt.format(avgCpuLoadPct) + "%, GC=" + dblFmt.format(gcPct) + "%]" + NL + " ^-- PageMemory [pages=" + loadedPages + "]" + NL + " ^-- Heap [used=" + dblFmt.format(heapUsedInMBytes) + "MB, free=" + dblFmt.format(freeHeapPct) + "%, comm=" + dblFmt.format(heapCommInMBytes) + "MB]" + NL + " ^-- Off-heap [used=" + dblFmt.format(offHeapUsedInMBytes) + "MB, free=" + dblFmt.format(freeOffHeapPct) + "%, comm=" + dblFmt.format(offHeapCommInMBytes) + "MB]" + NL + dataRegionsInfo + pdsInfo + " ^-- Outbound messages queue [size=" + m.getOutboundMessagesQueueSize() + "]" + NL + " ^-- " + createExecutorDescription("Public thread pool", execSvc) + NL + " ^-- " + createExecutorDescription("System thread pool", sysExecSvc); if (customExecSvcs != null) { StringBuilder customSvcsMsg = new StringBuilder(); for (Map.Entry<String, ? extends ExecutorService> entry : customExecSvcs.entrySet()) { customSvcsMsg.append(NL).append(" ^-- ") .append(createExecutorDescription(entry.getKey(), entry.getValue())); } msg += customSvcsMsg; } log.info(msg); ctx.cache().context().database().dumpStatistics(log); } catch (IgniteClientDisconnectedException ignore) { // No-op. } } /** * @return Language runtime. */ private String getLanguage() { boolean scala = false; boolean groovy = false; boolean clojure = false; for (StackTraceElement elem : Thread.currentThread().getStackTrace()) { String s = elem.getClassName().toLowerCase(); if (s.contains("scala")) { scala = true; break; } else if (s.contains("groovy")) { groovy = true; break; } else if (s.contains("clojure")) { clojure = true; break; } } if (scala) { try (InputStream in = getClass().getResourceAsStream("/library.properties")) { Properties props = new Properties(); if (in != null) props.load(in); return "Scala ver. " + props.getProperty("version.number", "<unknown>"); } catch (Exception ignore) { return "Scala ver. <unknown>"; } } // How to get Groovy and Clojure version at runtime?!? return groovy ? "Groovy" : clojure ? "Clojure" : U.jdkName() + " ver. " + U.jdkVersion(); } /** * Stops Ignite instance. * * @param cancel Whether or not to cancel running jobs. */ public void stop(boolean cancel) { // Make sure that thread stopping grid is not interrupted. boolean interrupted = Thread.interrupted(); try { stop0(cancel); } finally { if (interrupted) Thread.currentThread().interrupt(); } } /** * @return {@code True} if node started shutdown sequence. */ public boolean isStopping() { return stopGuard.get(); } /** * @param cancel Whether or not to cancel running jobs. */ private void stop0(boolean cancel) { gw.compareAndSet(null, new GridKernalGatewayImpl(igniteInstanceName)); GridKernalGateway gw = this.gw.get(); if (stopGuard.compareAndSet(false, true)) { // Only one thread is allowed to perform stop sequence. boolean firstStop = false; GridKernalState state = gw.getState(); if (state == STARTED || state == DISCONNECTED) firstStop = true; else if (state == STARTING) U.warn(log, "Attempt to stop starting grid. This operation " + "cannot be guaranteed to be successful."); if (firstStop) { // Notify lifecycle beans. if (log.isDebugEnabled()) log.debug("Notifying lifecycle beans."); notifyLifecycleBeansEx(LifecycleEventType.BEFORE_NODE_STOP); } List<GridComponent> comps = ctx.components(); // Callback component in reverse order while kernal is still functional // if called in the same thread, at least. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onKernalStop(cancel); } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to pre-stop processor: " + comp, e); if (e instanceof Error) throw e; } } if (ctx.hadoopHelper() != null) ctx.hadoopHelper().close(); if (starveTask != null) starveTask.close(); if (metricsLogTask != null) metricsLogTask.close(); if (longOpDumpTask != null) longOpDumpTask.close(); if (longJVMPauseDetector != null) longJVMPauseDetector.stop(); boolean interrupted = false; while (true) { try { if (gw.tryWriteLock(10)) break; } catch (InterruptedException ignored) { // Preserve interrupt status & ignore. // Note that interrupted flag is cleared. interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); try { assert gw.getState() == STARTED || gw.getState() == STARTING || gw.getState() == DISCONNECTED; // No more kernal calls from this point on. gw.setState(STOPPING); ctx.cluster().get().clearNodeMap(); if (log.isDebugEnabled()) log.debug("Grid " + (igniteInstanceName == null ? "" : '\'' + igniteInstanceName + "' ") + "is stopping."); } finally { gw.writeUnlock(); } // Stopping cache operations. GridCacheProcessor cache = ctx.cache(); if (cache != null) cache.blockGateways(); // Unregister MBeans. if (!mBeansMgr.unregisterAllMBeans()) errOnStop = true; // Stop components in reverse order. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) { comp.stop(cancel); if (log.isDebugEnabled()) log.debug("Component stopped: " + comp); } } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to stop component (ignoring): " + comp, e); if (e instanceof Error) throw (Error)e; } } // Stops lifecycle aware components. U.stopLifecycleAware(log, lifecycleAwares(cfg)); // Lifecycle notification. notifyLifecycleBeansEx(LifecycleEventType.AFTER_NODE_STOP); // Clean internal class/classloader caches to avoid stopped contexts held in memory. U.clearClassCache(); MarshallerExclusions.clearCache(); BinaryEnumCache.clear(); gw.writeLock(); try { gw.setState(STOPPED); } finally { gw.writeUnlock(); } // Ack stop. if (log.isQuiet()) { String nodeName = igniteInstanceName == null ? "" : "name=" + igniteInstanceName + ", "; if (!errOnStop) U.quiet(false, "Ignite node stopped OK [" + nodeName + "uptime=" + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + ']'); else U.quiet(true, "Ignite node stopped wih ERRORS [" + nodeName + "uptime=" + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + ']'); } if (log.isInfoEnabled()) if (!errOnStop) { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped OK"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + NL + NL); } else { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped with ERRORS"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + NL + ">>> See log above for detailed error message." + NL + ">>> Note that some errors during stop can prevent grid from" + NL + ">>> maintaining correct topology since this node may have" + NL + ">>> not exited grid properly." + NL + NL); } try { U.onGridStop(); } catch (InterruptedException ignored) { // Preserve interrupt status. Thread.currentThread().interrupt(); } } else { // Proper notification. if (log.isDebugEnabled()) { if (gw.getState() == STOPPED) log.debug("Grid is already stopped. Nothing to do."); else log.debug("Grid is being stopped by another thread. Aborting this stop sequence " + "allowing other thread to finish."); } } } /** * USED ONLY FOR TESTING. * * @param name Cache name. * @param <K> Key type. * @param <V> Value type. * @return Internal cache instance. */ /*@java.test.only*/ public <K, V> GridCacheAdapter<K, V> internalCache(String name) { CU.validateCacheName(name); checkClusterState(); return ctx.cache().internalCache(name); } /** * It's intended for use by internal marshalling implementation only. * * @return Kernal context. */ @Override public GridKernalContext context() { return ctx; } /** * Prints all system properties in debug mode. */ private void ackSystemProperties() { assert log != null; if (log.isDebugEnabled() && S.INCLUDE_SENSITIVE) for (Map.Entry<Object, Object> entry : snapshot().entrySet()) log.debug("System property [" + entry.getKey() + '=' + entry.getValue() + ']'); } /** * Prints all user attributes in info mode. */ private void logNodeUserAttributes() { assert log != null; if (log.isInfoEnabled()) for (Map.Entry<?, ?> attr : cfg.getUserAttributes().entrySet()) log.info("Local node user attribute [" + attr.getKey() + '=' + attr.getValue() + ']'); } /** * Prints all environment variables in debug mode. */ private void ackEnvironmentVariables() { assert log != null; if (log.isDebugEnabled()) for (Map.Entry<?, ?> envVar : System.getenv().entrySet()) log.debug("Environment variable [" + envVar.getKey() + '=' + envVar.getValue() + ']'); } /** * Acks daemon mode status. */ private void ackDaemon() { assert log != null; if (log.isInfoEnabled()) log.info("Daemon mode: " + (isDaemon() ? "on" : "off")); } /** * @return {@code True} is this node is daemon. */ private boolean isDaemon() { assert cfg != null; return cfg.isDaemon() || IgniteSystemProperties.getBoolean(IGNITE_DAEMON); } /** * Whether or not remote JMX management is enabled for this node. Remote JMX management is enabled when the * following system property is set: <ul> <li>{@code com.sun.management.jmxremote}</li> </ul> * * @return {@code True} if remote JMX management is enabled - {@code false} otherwise. */ @Override public boolean isJmxRemoteEnabled() { return System.getProperty("com.sun.management.jmxremote") != null; } /** * Whether or not node restart is enabled. Node restart us supported when this node was started with {@code * bin/ignite.{sh|bat}} script using {@code -r} argument. Node can be programmatically restarted using {@link * Ignition#restart(boolean)}} method. * * @return {@code True} if restart mode is enabled, {@code false} otherwise. * @see Ignition#restart(boolean) */ @Override public boolean isRestartEnabled() { return System.getProperty(IGNITE_SUCCESS_FILE) != null; } /** * Prints all configuration properties in info mode and SPIs in debug mode. */ private void ackSpis() { assert log != null; if (log.isDebugEnabled()) { log.debug("+-------------+"); log.debug("START SPI LIST:"); log.debug("+-------------+"); log.debug("Grid checkpoint SPI : " + Arrays.toString(cfg.getCheckpointSpi())); log.debug("Grid collision SPI : " + cfg.getCollisionSpi()); log.debug("Grid communication SPI : " + cfg.getCommunicationSpi()); log.debug("Grid deployment SPI : " + cfg.getDeploymentSpi()); log.debug("Grid discovery SPI : " + cfg.getDiscoverySpi()); log.debug("Grid event storage SPI : " + cfg.getEventStorageSpi()); log.debug("Grid failover SPI : " + Arrays.toString(cfg.getFailoverSpi())); log.debug("Grid load balancing SPI : " + Arrays.toString(cfg.getLoadBalancingSpi())); } } /** * Acknowledge that the rebalance configuration properties are setted correctly. * * @throws IgniteCheckedException If rebalance configuration validation fail. */ private void ackRebalanceConfiguration() throws IgniteCheckedException { if (cfg.isClientMode()) { if (cfg.getRebalanceThreadPoolSize() != IgniteConfiguration.DFLT_REBALANCE_THREAD_POOL_SIZE) U.warn(log, "Setting the rebalance pool size has no effect on the client mode"); } else { if (cfg.getSystemThreadPoolSize() <= cfg.getRebalanceThreadPoolSize()) throw new IgniteCheckedException("Rebalance thread pool size exceed or equals System thread pool size. " + "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start."); if (cfg.getRebalanceThreadPoolSize() < 1) throw new IgniteCheckedException("Rebalance thread pool size minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start."); if (cfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceBatchesPrefetchCount property before next start."); if (cfg.getRebalanceBatchSize() <= 0) throw new IgniteCheckedException("Rebalance batch size must be greater than zero. " + "Change IgniteConfiguration.rebalanceBatchSize property before next start."); if (cfg.getRebalanceThrottle() < 0) throw new IgniteCheckedException("Rebalance throttle can't have negative value. " + "Change IgniteConfiguration.rebalanceThrottle property before next start."); if (cfg.getRebalanceTimeout() < 0) throw new IgniteCheckedException("Rebalance message timeout can't have negative value. " + "Change IgniteConfiguration.rebalanceTimeout property before next start."); for (CacheConfiguration ccfg : cfg.getCacheConfiguration()) { if (ccfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change CacheConfiguration.rebalanceBatchesPrefetchCount property before next start. " + "[cache=" + ccfg.getName() + "]"); } } } /** * Acknowledge the Ignite configuration related to the data storage. */ private void ackMemoryConfiguration() { DataStorageConfiguration memCfg = cfg.getDataStorageConfiguration(); if (memCfg == null) return; U.log(log, "System cache's DataRegion size is configured to " + (memCfg.getSystemRegionInitialSize() / (1024 * 1024)) + " MB. " + "Use DataStorageConfiguration.systemRegionInitialSize property to change the setting."); } /** * Acknowledge all caches configurations presented in the IgniteConfiguration. */ private void ackCacheConfiguration() { CacheConfiguration[] cacheCfgs = cfg.getCacheConfiguration(); if (cacheCfgs == null || cacheCfgs.length == 0) U.warn(log, "Cache is not configured - in-memory data grid is off."); else { SB sb = new SB(); HashMap<String, ArrayList<String>> memPlcNamesMapping = new HashMap<>(); for (CacheConfiguration c : cacheCfgs) { String cacheName = U.maskName(c.getName()); String memPlcName = c.getDataRegionName(); if (CU.isSystemCache(cacheName)) memPlcName = "sysMemPlc"; else if (memPlcName == null && cfg.getDataStorageConfiguration() != null) memPlcName = cfg.getDataStorageConfiguration().getDefaultDataRegionConfiguration().getName(); if (!memPlcNamesMapping.containsKey(memPlcName)) memPlcNamesMapping.put(memPlcName, new ArrayList<String>()); ArrayList<String> cacheNames = memPlcNamesMapping.get(memPlcName); cacheNames.add(cacheName); } for (Map.Entry<String, ArrayList<String>> e : memPlcNamesMapping.entrySet()) { sb.a("in '").a(e.getKey()).a("' dataRegion: ["); for (String s : e.getValue()) sb.a("'").a(s).a("', "); sb.d(sb.length() - 2, sb.length()).a("], "); } U.log(log, "Configured caches [" + sb.d(sb.length() - 2, sb.length()).toString() + ']'); } } /** * Acknowledge configuration related to the peer class loading. */ private void ackP2pConfiguration() { assert cfg != null; if (cfg.isPeerClassLoadingEnabled()) U.warn( log, "Peer class loading is enabled (disable it in production for performance and " + "deployment consistency reasons)"); } /** * Prints security status. */ private void ackSecurity() { assert log != null; U.quietAndInfo(log, "Security status [authentication=" + onOff(ctx.security().enabled()) + ", tls/ssl=" + onOff(ctx.config().getSslContextFactory() != null) + ']'); } /** * Prints out VM arguments and IGNITE_HOME in info mode. * * @param rtBean Java runtime bean. */ private void ackVmArguments(RuntimeMXBean rtBean) { assert log != null; // Ack IGNITE_HOME and VM arguments. if (log.isInfoEnabled() && S.INCLUDE_SENSITIVE) { log.info("IGNITE_HOME=" + cfg.getIgniteHome()); log.info("VM arguments: " + rtBean.getInputArguments()); } } /** * Prints out class paths in debug mode. * * @param rtBean Java runtime bean. */ private void ackClassPaths(RuntimeMXBean rtBean) { assert log != null; // Ack all class paths. if (log.isDebugEnabled()) { try { log.debug("Boot class path: " + rtBean.getBootClassPath()); log.debug("Class path: " + rtBean.getClassPath()); log.debug("Library path: " + rtBean.getLibraryPath()); } catch (Exception ignore) { // No-op: ignore for Java 9+ and non-standard JVMs. } } } /** * Prints warning if 'java.net.preferIPv4Stack=true' is not set. */ private void ackIPv4StackFlagIsSet() { boolean preferIPv4 = Boolean.valueOf(System.getProperty("java.net.preferIPv4Stack")); if (!preferIPv4) { assert log != null; U.quietAndWarn(log, "Please set system property '-Djava.net.preferIPv4Stack=true' " + "to avoid possible problems in mixed environments."); } } /** * @param cfg Ignite configuration to use. * @return Components provided in configuration which can implement {@link LifecycleAware} interface. */ private Iterable<Object> lifecycleAwares(IgniteConfiguration cfg) { Collection<Object> objs = new ArrayList<>(); if (cfg.getLifecycleBeans() != null) Collections.addAll(objs, cfg.getLifecycleBeans()); if (cfg.getSegmentationResolvers() != null) Collections.addAll(objs, cfg.getSegmentationResolvers()); if (cfg.getConnectorConfiguration() != null) { objs.add(cfg.getConnectorConfiguration().getMessageInterceptor()); objs.add(cfg.getConnectorConfiguration().getSslContextFactory()); } objs.add(cfg.getMarshaller()); objs.add(cfg.getGridLogger()); objs.add(cfg.getMBeanServer()); if (cfg.getCommunicationFailureResolver() != null) objs.add(cfg.getCommunicationFailureResolver()); return objs; } /** {@inheritDoc} */ @Override public IgniteConfiguration configuration() { return cfg; } /** {@inheritDoc} */ @Override public IgniteLogger log() { return cfg.getGridLogger(); } /** {@inheritDoc} */ @Override public boolean removeCheckpoint(String key) { A.notNull(key, "key"); guard(); try { checkClusterState(); return ctx.checkpoint().removeCheckpoint(key); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean pingNode(String nodeId) { A.notNull(nodeId, "nodeId"); return cluster().pingNode(UUID.fromString(nodeId)); } /** {@inheritDoc} */ @Override public void undeployTaskFromGrid(String taskName) throws JMException { A.notNull(taskName, "taskName"); try { compute().undeployTask(taskName); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public String executeTask(String taskName, String arg) throws JMException { try { return compute().execute(taskName, arg); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public boolean pingNodeByAddress(String host) { guard(); try { for (ClusterNode n : cluster().nodes()) if (n.addresses().contains(host)) return ctx.discovery().pingNode(n.id()); return false; } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean eventUserRecordable(int type) { guard(); try { return ctx.event().isUserRecordable(type); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean allEventsUserRecordable(int[] types) { A.notNull(types, "types"); guard(); try { return ctx.event().isAllUserRecordable(types); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteTransactions transactions() { guard(); try { checkClusterState(); return ctx.cache().transactions(); } finally { unguard(); } } /** * @param name Cache name. * @return Ignite internal cache instance related to the given name. */ public <K, V> IgniteInternalCache<K, V> getCache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicCache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> cache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicJCache(name, false, true); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), null, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> createCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, true, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); ctx.cache().createFromTemplate(cacheName).get(); return ctx.cache().publicJCache(cacheName); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg) { return getOrCreateCache0(cacheCfg, false).get1(); } /** {@inheritDoc} */ @Override public <K, V> IgniteBiTuple<IgniteCache<K, V>, Boolean> getOrCreateCache0( CacheConfiguration<K, V> cacheCfg, boolean sql) { A.notNull(cacheCfg, "cacheCfg"); String cacheName = cacheCfg.getName(); CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); Boolean res = false; IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true); if (cache == null) { res = sql ? ctx.cache().dynamicStartSqlCache(cacheCfg).get() : ctx.cache().dynamicStartCache(cacheCfg, cacheName, null, false, true, true).get(); return new IgniteBiTuple<>(ctx.cache().publicJCache(cacheName), res); } else return new IgniteBiTuple<>(cache, res); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> getOrCreateCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, false, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache( CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg ) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> cache = ctx.cache().cache(cacheCfg.getName()); if (cache == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } else { if (cache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } } return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateNewCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(null, cacheName, nearCfg, true, true, true).get(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateNewCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> internalCache = ctx.cache().cache(cacheName); if (internalCache == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } else { if (internalCache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } } IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cache Ignite cache instance to check. * @throws IgniteCheckedException If cache without near cache was already started. */ private void checkNearCacheStarted(IgniteCacheProxy<?, ?> cache) throws IgniteCheckedException { if (!cache.context().isNear()) throw new IgniteCheckedException("Failed to start near cache " + "(a cache with the same name without near cache is already started)"); } /** {@inheritDoc} */ @Override public void destroyCache(String cacheName) { destroyCache0(cacheName, false); } /** {@inheritDoc} */ @Override public boolean destroyCache0(String cacheName, boolean sql) throws CacheException { CU.validateCacheName(cacheName); IgniteInternalFuture<Boolean> stopFut = destroyCacheAsync(cacheName, sql, true); try { return stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** {@inheritDoc} */ @Override public void destroyCaches(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); IgniteInternalFuture stopFut = destroyCachesAsync(cacheNames, true); try { stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** * @param cacheName Cache name. * @param sql If the cache needs to be destroyed only if it was created by SQL {@code CREATE TABLE} command. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future. */ public IgniteInternalFuture<Boolean> destroyCacheAsync(String cacheName, boolean sql, boolean checkThreadTx) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCache(cacheName, sql, checkThreadTx, false, null); } finally { unguard(); } } /** * @param cacheNames Collection of cache names. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future which will be completed when cache is destored. */ public IgniteInternalFuture<?> destroyCachesAsync(Collection<String> cacheNames, boolean checkThreadTx) { CU.validateCacheNames(cacheNames); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCaches(cacheNames, checkThreadTx); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true); if (cache == null) { ctx.cache().getOrCreateFromTemplate(cacheName, true).get(); return ctx.cache().publicJCache(cacheName); } return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cacheName Cache name. * @param templateName Template name. * @param cfgOverride Cache config properties to override. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is deployed. */ public IgniteInternalFuture<?> getOrCreateCacheAsync(String cacheName, String templateName, CacheConfigurationOverride cfgOverride, boolean checkThreadTx) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); if (ctx.cache().cache(cacheName) == null) return ctx.cache().getOrCreateFromTemplate(cacheName, templateName, cfgOverride, checkThreadTx); return new GridFinishedFuture<>(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> void addCacheConfiguration(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().addCacheConfiguration(cacheCfg); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @return Collection of public cache instances. */ public Collection<IgniteCacheProxy<?, ?>> caches() { guard(); try { checkClusterState(); return ctx.cache().publicCaches(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<String> cacheNames() { guard(); try { checkClusterState(); return ctx.cache().publicCacheNames(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K extends GridCacheUtilityKey, V> IgniteInternalCache<K, V> utilityCache() { guard(); try { checkClusterState(); return ctx.cache().utilityCache(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteInternalCache<K, V> cachex(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().cache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteInternalCache<?, ?>> cachesx( IgnitePredicate<? super IgniteInternalCache<?, ?>>[] p) { guard(); try { checkClusterState(); return F.retain(ctx.cache().caches(), true, p); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteDataStreamer<K, V> dataStreamer(String cacheName) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.<K, V>dataStream().dataStreamer(cacheName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteFileSystem fileSystem(String name) { if (name == null) throw new IllegalArgumentException("IGFS name cannot be null"); guard(); try { checkClusterState(); IgniteFileSystem fs = ctx.igfs().igfs(name); if (fs == null) throw new IllegalArgumentException("IGFS is not configured: " + name); return fs; } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteFileSystem igfsx(String name) { if (name == null) throw new IllegalArgumentException("IGFS name cannot be null"); guard(); try { checkClusterState(); return ctx.igfs().igfs(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteFileSystem> fileSystems() { guard(); try { checkClusterState(); return ctx.igfs().igfss(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Hadoop hadoop() { guard(); try { checkClusterState(); return ctx.hadoop().hadoop(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException { guard(); try { checkClusterState(); return (T)ctx.pluginProvider(name).plugin(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteBinary binary() { checkClusterState(); IgniteCacheObjectProcessor objProc = ctx.cacheObjects(); return objProc.binary(); } /** {@inheritDoc} */ @Override public IgniteProductVersion version() { return VER; } /** {@inheritDoc} */ @Override public String latestVersion() { ctx.gateway().readLock(); try { return ctx.cluster().latestVersion(); } finally { ctx.gateway().readUnlock(); } } /** {@inheritDoc} */ @Override public IgniteScheduler scheduler() { return scheduler; } /** {@inheritDoc} */ @Override public void close() throws IgniteException { Ignition.stop(igniteInstanceName, true); } /** {@inheritDoc} */ @Override public <K> Affinity<K> affinity(String cacheName) { CU.validateCacheName(cacheName); checkClusterState(); GridCacheAdapter<K, ?> cache = ctx.cache().internalCache(cacheName); if (cache != null) return cache.affinity(); return ctx.affinity().affinityProxy(cacheName); } /** {@inheritDoc} */ @Override public boolean active() { guard(); try { return context().state().publicApiActiveState(true); } finally { unguard(); } } /** {@inheritDoc} */ @Override public void active(boolean active) { cluster().active(active); } /** */ private Collection<BaselineNode> baselineNodes() { Collection<ClusterNode> srvNodes = cluster().forServers().nodes(); ArrayList baselineNodes = new ArrayList(srvNodes.size()); for (ClusterNode clN : srvNodes) baselineNodes.add(clN); return baselineNodes; } /** {@inheritDoc} */ @Override public void resetLostPartitions(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); guard(); try { ctx.cache().resetCacheState(cacheNames).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<DataRegionMetrics> dataRegionMetrics() { guard(); try { return ctx.cache().context().database().memoryMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public DataRegionMetrics dataRegionMetrics(String memPlcName) { guard(); try { return ctx.cache().context().database().memoryMetrics(memPlcName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public DataStorageMetrics dataStorageMetrics() { guard(); try { return ctx.cache().context().database().persistentStoreMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<MemoryMetrics> memoryMetrics() { return DataRegionMetricsAdapter.collectionOf(dataRegionMetrics()); } /** {@inheritDoc} */ @Nullable @Override public MemoryMetrics memoryMetrics(String memPlcName) { return DataRegionMetricsAdapter.valueOf(dataRegionMetrics(memPlcName)); } /** {@inheritDoc} */ @Override public PersistenceMetrics persistentStoreMetrics() { return DataStorageMetricsAdapter.valueOf(dataStorageMetrics()); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create) { return atomicSequence(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().sequence(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, long initVal, boolean create) { return atomicLong(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicLong(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteAtomicReference<T> atomicReference( String name, @Nullable T initVal, boolean create ) { return atomicReference(name, null, initVal, create); } /** {@inheritDoc} */ @Override public <T> IgniteAtomicReference<T> atomicReference(String name, AtomicConfiguration cfg, @Nullable T initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicReference(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, @Nullable T initVal, @Nullable S initStamp, boolean create) { return atomicStamped(name, null, initVal, initStamp, create); } /** {@inheritDoc} */ @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, AtomicConfiguration cfg, @Nullable T initVal, @Nullable S initStamp, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicStamped(name, cfg, initVal, initStamp, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteCountDownLatch countDownLatch(String name, int cnt, boolean autoDel, boolean create) { guard(); try { checkClusterState(); return ctx.dataStructures().countDownLatch(name, null, cnt, autoDel, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteSemaphore semaphore( String name, int cnt, boolean failoverSafe, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().semaphore(name, null, cnt, failoverSafe, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteLock reentrantLock( String name, boolean failoverSafe, boolean fair, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().reentrantLock(name, null, failoverSafe, fair, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteQueue<T> queue(String name, int cap, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().queue(name, null, cap, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteSet<T> set(String name, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().set(name, null, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** * The {@code ctx.gateway().readLock()} is used underneath. */ private void guard() { assert ctx != null; ctx.gateway().readLock(); } /** * The {@code ctx.gateway().readUnlock()} is used underneath. */ private void unguard() { assert ctx != null; ctx.gateway().readUnlock(); } /** * Validate operation on cluster. Check current cluster state. * * @throws IgniteException If cluster in inActive state. */ private void checkClusterState() throws IgniteException { if (!ctx.state().publicApiActiveState(true)) { throw new IgniteException("Can not perform the operation because the cluster is inactive. Note, that " + "the cluster is considered inactive by default if Ignite Persistent Store is used to let all the nodes " + "join the cluster. To activate the cluster call Ignite.active(true)."); } } /** * Method is responsible for handling the {@link EventType#EVT_CLIENT_NODE_DISCONNECTED} event. Notify all the * GridComponents that the such even has been occurred (e.g. if the local client node disconnected from the cluster * components will be notified with a future which will be completed when the client is reconnected). */ public void onDisconnected() { Throwable err = null; reconnectState.waitPreviousReconnect(); GridFutureAdapter<?> reconnectFut = ctx.gateway().onDisconnected(); if (reconnectFut == null) { assert ctx.gateway().getState() != STARTED : ctx.gateway().getState(); return; } IgniteFutureImpl<?> curFut = (IgniteFutureImpl<?>)ctx.cluster().get().clientReconnectFuture(); IgniteFuture<?> userFut; // In case of previous reconnect did not finish keep reconnect future. if (curFut != null && curFut.internalFuture() == reconnectFut) userFut = curFut; else { userFut = new IgniteFutureImpl<>(reconnectFut); ctx.cluster().get().clientReconnectFuture(userFut); } ctx.disconnected(true); List<GridComponent> comps = ctx.components(); for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onDisconnected(userFut); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } } for (GridCacheContext cctx : ctx.cache().context().cacheContexts()) { cctx.gate().writeLock(); cctx.gate().writeUnlock(); } ctx.gateway().writeLock(); ctx.gateway().writeUnlock(); if (err != null) { reconnectFut.onDone(err); U.error(log, "Failed to reconnect, will stop node", err); close(); } } /** * @param clusterRestarted {@code True} if all cluster nodes restarted while client was disconnected. */ @SuppressWarnings("unchecked") public void onReconnected(final boolean clusterRestarted) { Throwable err = null; try { ctx.disconnected(false); GridCompoundFuture curReconnectFut = reconnectState.curReconnectFut = new GridCompoundFuture<>(); reconnectState.reconnectDone = new GridFutureAdapter<>(); for (GridComponent comp : ctx.components()) { IgniteInternalFuture<?> fut = comp.onReconnected(clusterRestarted); if (fut != null) curReconnectFut.add(fut); } curReconnectFut.add(ctx.cache().context().exchange().reconnectExchangeFuture()); curReconnectFut.markInitialized(); final GridFutureAdapter reconnectDone = reconnectState.reconnectDone; curReconnectFut.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> fut) { try { Object res = fut.get(); if (res == STOP_RECONNECT) return; ctx.gateway().onReconnected(); reconnectState.firstReconnectFut.onDone(); } catch (IgniteCheckedException e) { if (!X.hasCause(e, IgniteNeedReconnectException.class, IgniteClientDisconnectedCheckedException.class, IgniteInterruptedCheckedException.class)) { U.error(log, "Failed to reconnect, will stop node.", e); reconnectState.firstReconnectFut.onDone(e); new Thread(() -> { U.error(log, "Stopping the node after a failed reconnect attempt."); close(); }, "node-stopper").start(); } else { assert ctx.discovery().reconnectSupported(); U.error(log, "Failed to finish reconnect, will retry [locNodeId=" + ctx.localNodeId() + ", err=" + e.getMessage() + ']'); } } finally { reconnectDone.onDone(); } } }); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } if (err != null) { U.error(log, "Failed to reconnect, will stop node", err); if (!X.hasCause(err, NodeStoppingException.class)) close(); } } /** * Creates optional component. * * @param cls Component interface. * @param ctx Kernal context. * @return Created component. * @throws IgniteCheckedException If failed to create component. */ private static <T extends GridComponent> T createComponent(Class<T> cls, GridKernalContext ctx) throws IgniteCheckedException { assert cls.isInterface() : cls; T comp = ctx.plugins().createComponent(cls); if (comp != null) return comp; if (cls.equals(IgniteCacheObjectProcessor.class)) return (T)new CacheObjectBinaryProcessorImpl(ctx); if (cls.equals(DiscoveryNodeValidationProcessor.class)) return (T)new OsDiscoveryNodeValidationProcessor(ctx); if (cls.equals(IGridClusterStateProcessor.class)) return (T)new GridClusterStateProcessor(ctx); if(cls.equals(GridSecurityProcessor.class)) return null; Class<T> implCls = null; try { String clsName; // Handle special case for PlatformProcessor if (cls.equals(PlatformProcessor.class)) clsName = ctx.config().getPlatformConfiguration() == null ? PlatformNoopProcessor.class.getName() : cls.getName() + "Impl"; else clsName = componentClassName(cls); implCls = (Class<T>)Class.forName(clsName); } catch (ClassNotFoundException ignore) { // No-op. } if (implCls == null) throw new IgniteCheckedException("Failed to find component implementation: " + cls.getName()); if (!cls.isAssignableFrom(implCls)) throw new IgniteCheckedException("Component implementation does not implement component interface " + "[component=" + cls.getName() + ", implementation=" + implCls.getName() + ']'); Constructor<T> constructor; try { constructor = implCls.getConstructor(GridKernalContext.class); } catch (NoSuchMethodException e) { throw new IgniteCheckedException("Component does not have expected constructor: " + implCls.getName(), e); } try { return constructor.newInstance(ctx); } catch (ReflectiveOperationException e) { throw new IgniteCheckedException("Failed to create component [component=" + cls.getName() + ", implementation=" + implCls.getName() + ']', e); } } /** * @param cls Component interface. * @return Name of component implementation class for open source edition. */ private static String componentClassName(Class<?> cls) { return cls.getPackage().getName() + ".os." + cls.getSimpleName().replace("Grid", "GridOs"); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igniteInstanceName = U.readString(in); } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igniteInstanceName); } /** * @return IgniteKernal instance. * @throws ObjectStreamException If failed. */ protected Object readResolve() throws ObjectStreamException { try { return IgnitionEx.localIgnite(); } catch (IllegalStateException e) { throw U.withCause(new InvalidObjectException(e.getMessage()), e); } } /** * @param comp Grid component. * @return {@code true} if node running in daemon mode and component marked by {@code SkipDaemon} annotation. */ private boolean skipDaemon(GridComponent comp) { return ctx.isDaemon() && U.hasAnnotation(comp.getClass(), SkipDaemon.class); } /** {@inheritDoc} */ @Override public void dumpDebugInfo() { try { GridKernalContextImpl ctx = this.ctx; GridDiscoveryManager discoMrg = ctx != null ? ctx.discovery() : null; ClusterNode locNode = discoMrg != null ? discoMrg.localNode() : null; if (ctx != null && discoMrg != null && locNode != null) { boolean client = ctx.clientNode(); UUID routerId = locNode instanceof TcpDiscoveryNode ? ((TcpDiscoveryNode)locNode).clientRouterNodeId() : null; U.warn(ctx.cluster().diagnosticLog(), "Dumping debug info for node [id=" + locNode.id() + ", name=" + ctx.igniteInstanceName() + ", order=" + locNode.order() + ", topVer=" + discoMrg.topologyVersion() + ", client=" + client + (client && routerId != null ? ", routerId=" + routerId : "") + ']'); ctx.cache().context().exchange().dumpDebugInfo(null); } else U.warn(log, "Dumping debug info for node, context is not initialized [name=" + igniteInstanceName + ']'); } catch (Exception e) { U.error(log, "Failed to dump debug info for node: " + e, e); } } /** * @param node Node. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(ClusterNode node, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(node, payload, procFromNioThread); } /** * @param nodes Nodes. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(List<ClusterNode> nodes, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(nodes, payload, procFromNioThread); } /** * Class holds client reconnection event handling state. */ private class ReconnectState { /** Future will be completed when the client node connected the first time. */ private final GridFutureAdapter firstReconnectFut = new GridFutureAdapter(); /** * Composed future of all {@link GridComponent#onReconnected(boolean)} callbacks. * The future completes when all Ignite components are finished handle given client reconnect event. */ private GridCompoundFuture<?, Object> curReconnectFut; /** Future completes when reconnection handling is done (doesn't matter successfully or not). */ private GridFutureAdapter<?> reconnectDone; /** * @throws IgniteCheckedException If failed. */ void waitFirstReconnect() throws IgniteCheckedException { firstReconnectFut.get(); } /** * Wait for the previous reconnection handling finished or force completion if not. */ void waitPreviousReconnect() { if (curReconnectFut != null && !curReconnectFut.isDone()) { assert reconnectDone != null; curReconnectFut.onDone(STOP_RECONNECT); try { reconnectDone.get(); } catch (IgniteCheckedException ignore) { // No-op. } } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ReconnectState.class, this); } } /** {@inheritDoc} */ @Override public void runIoTest( long warmup, long duration, int threads, long maxLatency, int rangesCnt, int payLoadSize, boolean procFromNioThread ) { ctx.io().runIoTest(warmup, duration, threads, maxLatency, rangesCnt, payLoadSize, procFromNioThread, new ArrayList(ctx.cluster().get().forServers().forRemotes().nodes())); } /** {@inheritDoc} */ @Override public void clearNodeLocalMap() { ctx.cluster().get().clearNodeMap(); } /** {@inheritDoc} */ @Override public void resetMetrics(String registry) { assert registry != null; MetricRegistry mreg = ctx.metric().registry(registry); if (mreg != null) mreg.reset(); else if (log.isInfoEnabled()) log.info("\"" + registry + "\" not found."); } /** {@inheritDoc} */ @Override public boolean readOnlyMode() { return ctx.state().publicApiReadOnlyMode(); } /** {@inheritDoc} */ @Override public void readOnlyMode(boolean readOnly) { ctx.state().changeGlobalState(readOnly); } /** {@inheritDoc} */ @Override public long getReadOnlyModeDuration() { if (ctx.state().publicApiReadOnlyMode()) return U.currentTimeMillis() - ctx.state().readOnlyModeStateChangeTime(); else return 0; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(IgniteKernal.class, this); } }
modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.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.ignite.internal; import java.io.Externalizable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InvalidObjectException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.ObjectStreamException; import java.io.Serializable; import java.io.UncheckedIOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.reflect.Constructor; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.cache.CacheException; import javax.management.JMException; import org.apache.ignite.DataRegionMetrics; import org.apache.ignite.DataRegionMetricsAdapter; import org.apache.ignite.DataStorageMetrics; import org.apache.ignite.DataStorageMetricsAdapter; import org.apache.ignite.IgniteAtomicLong; import org.apache.ignite.IgniteAtomicReference; import org.apache.ignite.IgniteAtomicSequence; import org.apache.ignite.IgniteAtomicStamped; import org.apache.ignite.IgniteBinary; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteClientDisconnectedException; import org.apache.ignite.IgniteCompute; import org.apache.ignite.IgniteCountDownLatch; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.IgniteEvents; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteFileSystem; import org.apache.ignite.IgniteLock; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteMessaging; import org.apache.ignite.IgniteQueue; import org.apache.ignite.IgniteScheduler; import org.apache.ignite.IgniteSemaphore; import org.apache.ignite.IgniteServices; import org.apache.ignite.IgniteSet; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.IgniteTransactions; import org.apache.ignite.Ignition; import org.apache.ignite.MemoryMetrics; import org.apache.ignite.PersistenceMetrics; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cluster.BaselineNode; import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.cluster.ClusterMetrics; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.AtomicConfiguration; import org.apache.ignite.configuration.BinaryConfiguration; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.CollectionConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.MemoryConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.binary.BinaryEnumCache; import org.apache.ignite.internal.binary.BinaryMarshaller; import org.apache.ignite.internal.binary.BinaryUtils; import org.apache.ignite.internal.cluster.ClusterGroupAdapter; import org.apache.ignite.internal.cluster.IgniteClusterEx; import org.apache.ignite.internal.managers.GridManager; import org.apache.ignite.internal.managers.IgniteMBeansManager; import org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager; import org.apache.ignite.internal.managers.collision.GridCollisionManager; import org.apache.ignite.internal.managers.communication.GridIoManager; import org.apache.ignite.internal.managers.deployment.GridDeploymentManager; import org.apache.ignite.internal.managers.discovery.DiscoveryLocalJoinData; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager; import org.apache.ignite.internal.managers.encryption.GridEncryptionManager; import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager; import org.apache.ignite.internal.managers.failover.GridFailoverManager; import org.apache.ignite.internal.managers.indexing.GridIndexingManager; import org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager; import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller; import org.apache.ignite.internal.processors.GridProcessor; import org.apache.ignite.internal.processors.GridProcessorAdapter; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.affinity.GridAffinityProcessor; import org.apache.ignite.internal.processors.authentication.IgniteAuthenticationProcessor; import org.apache.ignite.internal.processors.cache.CacheConfigurationOverride; import org.apache.ignite.internal.processors.cache.GridCacheAdapter; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheProcessor; import org.apache.ignite.internal.processors.cache.GridCacheUtilityKey; import org.apache.ignite.internal.processors.cache.IgniteCacheProxy; import org.apache.ignite.internal.processors.cache.IgniteInternalCache; import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl; import org.apache.ignite.internal.processors.cache.mvcc.MvccProcessorImpl; import org.apache.ignite.internal.processors.cache.persistence.DataRegion; import org.apache.ignite.internal.processors.cache.persistence.filename.PdsConsistentIdProcessor; import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor; import org.apache.ignite.internal.processors.closure.GridClosureProcessor; import org.apache.ignite.internal.processors.cluster.ClusterProcessor; import org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState; import org.apache.ignite.internal.processors.cluster.GridClusterStateProcessor; import org.apache.ignite.internal.processors.cluster.IGridClusterStateProcessor; import org.apache.ignite.internal.processors.configuration.distributed.DistributedConfigurationProcessor; import org.apache.ignite.internal.processors.continuous.GridContinuousProcessor; import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor; import org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor; import org.apache.ignite.internal.processors.diagnostic.DiagnosticProcessor; import org.apache.ignite.internal.processors.failure.FailureProcessor; import org.apache.ignite.internal.processors.hadoop.Hadoop; import org.apache.ignite.internal.processors.hadoop.HadoopProcessorAdapter; import org.apache.ignite.internal.processors.job.GridJobProcessor; import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor; import org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor; import org.apache.ignite.internal.processors.metastorage.persistence.DistributedMetaStorageImpl; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistry; import org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.nodevalidation.OsDiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.odbc.ClientListenerProcessor; import org.apache.ignite.internal.processors.platform.PlatformNoopProcessor; import org.apache.ignite.internal.processors.platform.PlatformProcessor; import org.apache.ignite.internal.processors.platform.plugin.PlatformPluginProcessor; import org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor; import org.apache.ignite.internal.processors.pool.PoolProcessor; import org.apache.ignite.internal.processors.port.GridPortProcessor; import org.apache.ignite.internal.processors.port.GridPortRecord; import org.apache.ignite.internal.processors.query.GridQueryProcessor; import org.apache.ignite.internal.processors.resource.GridResourceProcessor; import org.apache.ignite.internal.processors.resource.GridSpringResourceContext; import org.apache.ignite.internal.processors.rest.GridRestProcessor; import org.apache.ignite.internal.processors.security.GridSecurityProcessor; import org.apache.ignite.internal.processors.security.IgniteSecurityProcessor; import org.apache.ignite.internal.processors.security.NoOpIgniteSecurityProcessor; import org.apache.ignite.internal.processors.segmentation.GridSegmentationProcessor; import org.apache.ignite.internal.processors.service.GridServiceProcessor; import org.apache.ignite.internal.processors.service.IgniteServiceProcessor; import org.apache.ignite.internal.processors.session.GridTaskSessionProcessor; import org.apache.ignite.internal.processors.subscription.GridInternalSubscriptionProcessor; import org.apache.ignite.internal.processors.task.GridTaskProcessor; import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor; import org.apache.ignite.internal.suggestions.GridPerformanceSuggestions; import org.apache.ignite.internal.suggestions.JvmConfigurationSuggestions; import org.apache.ignite.internal.suggestions.OsConfigurationSuggestions; import org.apache.ignite.internal.util.StripedExecutor; import org.apache.ignite.internal.util.TimeBag; import org.apache.ignite.internal.util.future.GridCompoundFuture; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.future.IgniteFutureImpl; import org.apache.ignite.internal.util.lang.GridAbsClosure; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.typedef.C1; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.LT; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.SB; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.worker.WorkersRegistry; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.lang.IgniteClosure; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteProductVersion; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.lifecycle.LifecycleBean; import org.apache.ignite.lifecycle.LifecycleEventType; import org.apache.ignite.marshaller.MarshallerExclusions; import org.apache.ignite.marshaller.MarshallerUtils; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.apache.ignite.mxbean.IgniteMXBean; import org.apache.ignite.plugin.IgnitePlugin; import org.apache.ignite.plugin.PluginNotFoundException; import org.apache.ignite.plugin.PluginProvider; import org.apache.ignite.spi.IgniteSpi; import org.apache.ignite.spi.IgniteSpiVersionCheckException; import org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode; import org.apache.ignite.thread.IgniteStripedThreadPoolExecutor; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2; import static org.apache.ignite.IgniteSystemProperties.IGNITE_CONFIG_URL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_DAEMON; import static org.apache.ignite.IgniteSystemProperties.IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED; import static org.apache.ignite.IgniteSystemProperties.IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP; import static org.apache.ignite.IgniteSystemProperties.IGNITE_NO_ASCII; import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID; import static org.apache.ignite.IgniteSystemProperties.IGNITE_REST_START_ON_CLIENT; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK; import static org.apache.ignite.IgniteSystemProperties.IGNITE_STARVATION_CHECK_INTERVAL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SUCCESS_FILE; import static org.apache.ignite.IgniteSystemProperties.getBoolean; import static org.apache.ignite.IgniteSystemProperties.snapshot; import static org.apache.ignite.internal.GridKernalState.DISCONNECTED; import static org.apache.ignite.internal.GridKernalState.STARTED; import static org.apache.ignite.internal.GridKernalState.STARTING; import static org.apache.ignite.internal.GridKernalState.STOPPED; import static org.apache.ignite.internal.GridKernalState.STOPPING; import static org.apache.ignite.internal.IgniteComponentType.COMPRESSION; import static org.apache.ignite.internal.IgniteComponentType.HADOOP_HELPER; import static org.apache.ignite.internal.IgniteComponentType.IGFS; import static org.apache.ignite.internal.IgniteComponentType.IGFS_HELPER; import static org.apache.ignite.internal.IgniteComponentType.SCHEDULE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_DATE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_VER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CLIENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CONSISTENCY_CHECK_SKIPPED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DAEMON; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STORAGE_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STREAMER_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DEPLOYMENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DYNAMIC_CACHE_START_ROLLBACK_SUPPORTED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_FEATURES; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_INSTANCE_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IPS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JIT_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JMX_PORT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_ARGS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_PID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LANG_RUNTIME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LATE_AFFINITY_ASSIGNMENT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_COMPACT_FOOTER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_DFLT_SUID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MEMORY_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_NODE_CONSISTENT_ID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_OFFHEAP_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PEER_CLASSLOADING; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PHY_RAM; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PREFIX; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REBALANCE_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_RESTART_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_PORT_RANGE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SPI_CLASS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_TX_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_USER_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_VALIDATE_CACHE_REQUESTS; import static org.apache.ignite.internal.IgniteVersionUtils.ACK_VER_STR; import static org.apache.ignite.internal.IgniteVersionUtils.BUILD_TSTAMP_STR; import static org.apache.ignite.internal.IgniteVersionUtils.COPYRIGHT; import static org.apache.ignite.internal.IgniteVersionUtils.REV_HASH_STR; import static org.apache.ignite.internal.IgniteVersionUtils.VER; import static org.apache.ignite.internal.IgniteVersionUtils.VER_STR; import static org.apache.ignite.lifecycle.LifecycleEventType.AFTER_NODE_START; import static org.apache.ignite.lifecycle.LifecycleEventType.BEFORE_NODE_START; /** * Ignite kernal. * <p/> * See <a href="http://en.wikipedia.org/wiki/Kernal">http://en.wikipedia.org/wiki/Kernal</a> for information on the * misspelling. */ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable { /** */ private static final long serialVersionUID = 0L; /** Ignite site that is shown in log messages. */ public static final String SITE = "ignite.apache.org"; /** System line separator. */ private static final String NL = U.nl(); /** Periodic starvation check interval. */ private static final long PERIODIC_STARVATION_CHECK_FREQ = 1000 * 30; /** Force complete reconnect future. */ private static final Object STOP_RECONNECT = new Object(); /** Separator for formatted coordinator properties. */ public static final String COORDINATOR_PROPERTIES_SEPARATOR = ","; /** Default long operations dump timeout. */ public static final long DFLT_LONG_OPERATIONS_DUMP_TIMEOUT = 60_000L; /** Long jvm pause detector. */ private LongJVMPauseDetector longJVMPauseDetector; /** */ @GridToStringExclude private GridKernalContextImpl ctx; /** Helper that registers MBeans */ @GridToStringExclude private IgniteMBeansManager mBeansMgr; /** Configuration. */ private IgniteConfiguration cfg; /** */ @GridToStringExclude private GridLoggerProxy log; /** */ private String igniteInstanceName; /** Kernal start timestamp. */ private long startTime = U.currentTimeMillis(); /** Spring context, potentially {@code null}. */ private GridSpringResourceContext rsrcCtx; /** */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask starveTask; /** */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask metricsLogTask; /** */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask longOpDumpTask; /** Indicate error on grid stop. */ @GridToStringExclude private boolean errOnStop; /** Scheduler. */ @GridToStringExclude private IgniteScheduler scheduler; /** Kernal gateway. */ @GridToStringExclude private final AtomicReference<GridKernalGateway> gw = new AtomicReference<>(); /** Stop guard. */ @GridToStringExclude private final AtomicBoolean stopGuard = new AtomicBoolean(); /** */ private final ReconnectState reconnectState = new ReconnectState(); /** * No-arg constructor is required by externalization. */ public IgniteKernal() { this(null); } /** * @param rsrcCtx Optional Spring application context. */ public IgniteKernal(@Nullable GridSpringResourceContext rsrcCtx) { this.rsrcCtx = rsrcCtx; } /** {@inheritDoc} */ @Override public IgniteClusterEx cluster() { return ctx.cluster().get(); } /** {@inheritDoc} */ @Override public ClusterNode localNode() { return ctx.cluster().get().localNode(); } /** {@inheritDoc} */ @Override public IgniteCompute compute() { return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).compute(); } /** {@inheritDoc} */ @Override public IgniteMessaging message() { return ctx.cluster().get().message(); } /** {@inheritDoc} */ @Override public IgniteEvents events() { return ctx.cluster().get().events(); } /** {@inheritDoc} */ @Override public IgniteServices services() { checkClusterState(); return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService() { return ctx.cluster().get().executorService(); } /** {@inheritDoc} */ @Override public final IgniteCompute compute(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).compute(); } /** {@inheritDoc} */ @Override public final IgniteMessaging message(ClusterGroup prj) { return ((ClusterGroupAdapter)prj).message(); } /** {@inheritDoc} */ @Override public final IgniteEvents events(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).events(); } /** {@inheritDoc} */ @Override public IgniteServices services(ClusterGroup grp) { checkClusterState(); return ((ClusterGroupAdapter)grp).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).executorService(); } /** {@inheritDoc} */ @Override public String name() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getCopyright() { return COPYRIGHT; } /** {@inheritDoc} */ @Override public long getStartTimestamp() { return startTime; } /** {@inheritDoc} */ @Override public String getStartTimestampFormatted() { return DateFormat.getDateTimeInstance().format(new Date(startTime)); } /** {@inheritDoc} */ @Override public boolean isRebalanceEnabled() { return ctx.cache().context().isRebalanceEnabled(); } /** {@inheritDoc} */ @Override public void rebalanceEnabled(boolean rebalanceEnabled) { ctx.cache().context().rebalanceEnabled(rebalanceEnabled); } /** {@inheritDoc} */ @Override public long getUpTime() { return U.currentTimeMillis() - startTime; } /** {@inheritDoc} */ @Override public long getLongJVMPausesCount() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPausesCount() : 0; } /** {@inheritDoc} */ @Override public long getLongJVMPausesTotalDuration() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPausesTotalDuration() : 0; } /** {@inheritDoc} */ @Override public Map<Long, Long> getLongJVMPauseLastEvents() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPauseEvents() : Collections.emptyMap(); } /** {@inheritDoc} */ @Override public String getUpTimeFormatted() { return X.timeSpan2DHMSM(U.currentTimeMillis() - startTime); } /** {@inheritDoc} */ @Override public String getFullVersion() { return VER_STR + '-' + BUILD_TSTAMP_STR; } /** {@inheritDoc} */ @Override public String getCheckpointSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getCheckpointSpi()); } /** {@inheritDoc} */ @Override public String getCurrentCoordinatorFormatted() { ClusterNode node = ctx.discovery().oldestAliveServerNode(AffinityTopologyVersion.NONE); if (node == null) return ""; return new StringBuilder() .append(node.addresses()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.id()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.order()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.hostNames()) .toString(); } /** {@inheritDoc} */ @Override public boolean isNodeInBaseline() { ClusterNode locNode = localNode(); if (locNode.isClient() || locNode.isDaemon()) return false; DiscoveryDataClusterState clusterState = ctx.state().clusterState(); return clusterState.hasBaselineTopology() && CU.baselineNode(locNode, clusterState); } /** {@inheritDoc} */ @Override public String getCommunicationSpiFormatted() { assert cfg != null; return cfg.getCommunicationSpi().toString(); } /** {@inheritDoc} */ @Override public String getDeploymentSpiFormatted() { assert cfg != null; return cfg.getDeploymentSpi().toString(); } /** {@inheritDoc} */ @Override public String getDiscoverySpiFormatted() { assert cfg != null; return cfg.getDiscoverySpi().toString(); } /** {@inheritDoc} */ @Override public String getEventStorageSpiFormatted() { assert cfg != null; return cfg.getEventStorageSpi().toString(); } /** {@inheritDoc} */ @Override public String getCollisionSpiFormatted() { assert cfg != null; return cfg.getCollisionSpi().toString(); } /** {@inheritDoc} */ @Override public String getFailoverSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getFailoverSpi()); } /** {@inheritDoc} */ @Override public String getLoadBalancingSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getLoadBalancingSpi()); } /** {@inheritDoc} */ @Override public String getOsInformation() { return U.osString(); } /** {@inheritDoc} */ @Override public String getJdkInformation() { return U.jdkString(); } /** {@inheritDoc} */ @Override public String getOsUser() { return System.getProperty("user.name"); } /** {@inheritDoc} */ @Override public void printLastErrors() { ctx.exceptionRegistry().printErrors(log); } /** {@inheritDoc} */ @Override public String getVmName() { return ManagementFactory.getRuntimeMXBean().getName(); } /** {@inheritDoc} */ @Override public String getInstanceName() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getExecutorServiceFormatted() { assert cfg != null; return String.valueOf(cfg.getPublicThreadPoolSize()); } /** {@inheritDoc} */ @Override public String getIgniteHome() { assert cfg != null; return cfg.getIgniteHome(); } /** {@inheritDoc} */ @Override public String getGridLoggerFormatted() { assert cfg != null; return cfg.getGridLogger().toString(); } /** {@inheritDoc} */ @Override public String getMBeanServerFormatted() { assert cfg != null; return cfg.getMBeanServer().toString(); } /** {@inheritDoc} */ @Override public UUID getLocalNodeId() { assert cfg != null; return cfg.getNodeId(); } /** {@inheritDoc} */ @Override public List<String> getUserAttributesFormatted() { assert cfg != null; return (List<String>)F.transform(cfg.getUserAttributes().entrySet(), new C1<Map.Entry<String, ?>, String>() { @Override public String apply(Map.Entry<String, ?> e) { return e.getKey() + ", " + e.getValue().toString(); } }); } /** {@inheritDoc} */ @Override public boolean isPeerClassLoadingEnabled() { assert cfg != null; return cfg.isPeerClassLoadingEnabled(); } /** {@inheritDoc} */ @Override public List<String> getLifecycleBeansFormatted() { LifecycleBean[] beans = cfg.getLifecycleBeans(); if (F.isEmpty(beans)) return Collections.emptyList(); else { List<String> res = new ArrayList<>(beans.length); for (LifecycleBean bean : beans) res.add(String.valueOf(bean)); return res; } } /** * @param name New attribute name. * @param val New attribute value. * @throws IgniteCheckedException If duplicated SPI name found. */ private void add(String name, @Nullable Serializable val) throws IgniteCheckedException { assert name != null; if (ctx.addNodeAttribute(name, val) != null) { if (name.endsWith(ATTR_SPI_CLASS)) // User defined duplicated names for the different SPIs. throw new IgniteCheckedException("Failed to set SPI attribute. Duplicated SPI name found: " + name.substring(0, name.length() - ATTR_SPI_CLASS.length())); // Otherwise it's a mistake of setting up duplicated attribute. assert false : "Duplicate attribute: " + name; } } /** * Notifies life-cycle beans of grid event. * * @param evt Grid event. * @throws IgniteCheckedException If user threw exception during start. */ private void notifyLifecycleBeans(LifecycleEventType evt) throws IgniteCheckedException { if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) if (bean != null) { try { bean.onLifecycleEvent(evt); } catch (Exception e) { throw new IgniteCheckedException(e); } } } } /** * Notifies life-cycle beans of grid event. * * @param evt Grid event. */ private void notifyLifecycleBeansEx(LifecycleEventType evt) { try { notifyLifecycleBeans(evt); } // Catch generic throwable to secure against user assertions. catch (Throwable e) { U.error(log, "Failed to notify lifecycle bean (safely ignored) [evt=" + evt + (igniteInstanceName == null ? "" : ", igniteInstanceName=" + igniteInstanceName) + ']', e); if (e instanceof Error) throw (Error)e; } } /** */ private void ackClassPathElementRecursive(File clsPathEntry, SB clsPathContent) { if (clsPathEntry.isDirectory()) { String[] list = clsPathEntry.list(); for (String listElement : list) ackClassPathElementRecursive(new File(clsPathEntry, listElement), clsPathContent); } else { String path = clsPathEntry.getAbsolutePath(); if (path.endsWith(".class")) clsPathContent.a(path).a(";"); } } /** */ private void ackClassPathEntry(String clsPathEntry, SB clsPathContent) { File clsPathElementFile = new File(clsPathEntry); if (clsPathElementFile.isDirectory()) ackClassPathElementRecursive(clsPathElementFile, clsPathContent); else { String extension = clsPathEntry.length() >= 4 ? clsPathEntry.substring(clsPathEntry.length() - 4).toLowerCase() : null; if (".jar".equals(extension) || ".zip".equals(extension)) clsPathContent.a(clsPathEntry).a(";"); } } /** */ private void ackClassPathWildCard(String clsPathEntry, SB clsPathContent) { final int lastSeparatorIdx = clsPathEntry.lastIndexOf(File.separator); final int asteriskIdx = clsPathEntry.indexOf('*'); //just to log possibly incorrent entries to err if (asteriskIdx >= 0 && asteriskIdx < lastSeparatorIdx) throw new RuntimeException("Could not parse classpath entry"); final int fileMaskFirstIdx = lastSeparatorIdx + 1; final String fileMask = (fileMaskFirstIdx >= clsPathEntry.length()) ? "*.jar" : clsPathEntry.substring(fileMaskFirstIdx); Path path = Paths.get(lastSeparatorIdx > 0 ? clsPathEntry.substring(0, lastSeparatorIdx) : ".") .toAbsolutePath() .normalize(); if (lastSeparatorIdx == 0) path = path.getRoot(); try { DirectoryStream<Path> files = Files.newDirectoryStream(path, fileMask); for (Path f : files) { String s = f.toString(); if (s.toLowerCase().endsWith(".jar")) clsPathContent.a(f.toString()).a(";"); } } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Prints the list of *.jar and *.class files containing in classpath. */ private void ackClassPathContent() { assert log != null; boolean enabled = IgniteSystemProperties.getBoolean(IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP, true); if (enabled) { String clsPath = System.getProperty("java.class.path", "."); String[] clsPathElements = clsPath.split(File.pathSeparator); U.log(log, "Classpath value: " + clsPath); SB clsPathContent = new SB("List of files containing in classpath: "); for (String clsPathEntry : clsPathElements) { try { if (clsPathEntry.contains("*")) ackClassPathWildCard(clsPathEntry, clsPathContent); else ackClassPathEntry(clsPathEntry, clsPathContent); } catch (Exception e) { U.warn(log, String.format("Could not log class path entry '%s': %s", clsPathEntry, e.getMessage())); } } U.log(log, clsPathContent.toString()); } } /** * @param cfg Configuration to use. * @param utilityCachePool Utility cache pool. * @param execSvc Executor service. * @param sysExecSvc System executor service. * @param stripedExecSvc Striped executor. * @param p2pExecSvc P2P executor service. * @param mgmtExecSvc Management executor service. * @param igfsExecSvc IGFS executor service. * @param dataStreamExecSvc data stream executor service. * @param restExecSvc Reset executor service. * @param affExecSvc Affinity executor service. * @param idxExecSvc Indexing executor service. * @param callbackExecSvc Callback executor service. * @param qryExecSvc Query executor service. * @param schemaExecSvc Schema executor service. * @param customExecSvcs Custom named executors. * @param errHnd Error handler to use for notification about startup problems. * @param workerRegistry Worker registry. * @param hnd Default uncaught exception handler used by thread pools. * @throws IgniteCheckedException Thrown in case of any errors. */ public void start( final IgniteConfiguration cfg, ExecutorService utilityCachePool, final ExecutorService execSvc, final ExecutorService svcExecSvc, final ExecutorService sysExecSvc, final StripedExecutor stripedExecSvc, ExecutorService p2pExecSvc, ExecutorService mgmtExecSvc, ExecutorService igfsExecSvc, StripedExecutor dataStreamExecSvc, ExecutorService restExecSvc, ExecutorService affExecSvc, @Nullable ExecutorService idxExecSvc, IgniteStripedThreadPoolExecutor callbackExecSvc, ExecutorService qryExecSvc, ExecutorService schemaExecSvc, @Nullable final Map<String, ? extends ExecutorService> customExecSvcs, GridAbsClosure errHnd, WorkersRegistry workerRegistry, Thread.UncaughtExceptionHandler hnd, TimeBag startTimer ) throws IgniteCheckedException { gw.compareAndSet(null, new GridKernalGatewayImpl(cfg.getIgniteInstanceName())); GridKernalGateway gw = this.gw.get(); gw.writeLock(); try { switch (gw.getState()) { case STARTED: { U.warn(log, "Grid has already been started (ignored)."); return; } case STARTING: { U.warn(log, "Grid is already in process of being started (ignored)."); return; } case STOPPING: { throw new IgniteCheckedException("Grid is in process of being stopped"); } case STOPPED: { break; } } gw.setState(STARTING); } finally { gw.writeUnlock(); } assert cfg != null; // Make sure we got proper configuration. validateCommon(cfg); igniteInstanceName = cfg.getIgniteInstanceName(); this.cfg = cfg; log = (GridLoggerProxy)cfg.getGridLogger().getLogger( getClass().getName() + (igniteInstanceName != null ? '%' + igniteInstanceName : "")); longJVMPauseDetector = new LongJVMPauseDetector(log); longJVMPauseDetector.start(); RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean(); // Ack various information. ackAsciiLogo(); ackConfigUrl(); ackConfiguration(cfg); ackDaemon(); ackOsInfo(); ackLanguageRuntime(); ackRemoteManagement(); ackLogger(); ackVmArguments(rtBean); ackClassPaths(rtBean); ackSystemProperties(); ackEnvironmentVariables(); ackMemoryConfiguration(); ackCacheConfiguration(); ackP2pConfiguration(); ackRebalanceConfiguration(); ackIPv4StackFlagIsSet(); // Run background network diagnostics. GridDiagnostic.runBackgroundCheck(igniteInstanceName, execSvc, log); // Ack 3-rd party licenses location. if (log.isInfoEnabled() && cfg.getIgniteHome() != null) log.info("3-rd party licenses can be found at: " + cfg.getIgniteHome() + File.separatorChar + "libs" + File.separatorChar + "licenses"); // Check that user attributes are not conflicting // with internally reserved names. for (String name : cfg.getUserAttributes().keySet()) if (name.startsWith(ATTR_PREFIX)) throw new IgniteCheckedException("User attribute has illegal name: '" + name + "'. Note that all names " + "starting with '" + ATTR_PREFIX + "' are reserved for internal use."); // Ack local node user attributes. logNodeUserAttributes(); // Ack configuration. ackSpis(); List<PluginProvider> plugins = cfg.getPluginProviders() != null && cfg.getPluginProviders().length > 0 ? Arrays.asList(cfg.getPluginProviders()) : U.allPluginProviders(); // Spin out SPIs & managers. try { ctx = new GridKernalContextImpl(log, this, cfg, gw, utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, igfsExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, customExecSvcs, plugins, MarshallerUtils.classNameFilter(this.getClass().getClassLoader()), workerRegistry, hnd, longJVMPauseDetector ); startProcessor(new DiagnosticProcessor(ctx)); mBeansMgr = new IgniteMBeansManager(this); cfg.getMarshaller().setContext(ctx.marshallerContext()); GridInternalSubscriptionProcessor subscriptionProc = new GridInternalSubscriptionProcessor(ctx); startProcessor(subscriptionProc); ClusterProcessor clusterProc = new ClusterProcessor(ctx); startProcessor(clusterProc); U.onGridStart(); // Start and configure resource processor first as it contains resources used // by all other managers and processors. GridResourceProcessor rsrcProc = new GridResourceProcessor(ctx); rsrcProc.setSpringContext(rsrcCtx); scheduler = new IgniteSchedulerImpl(ctx); startProcessor(rsrcProc); // Inject resources into lifecycle beans. if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) { if (bean != null) rsrcProc.inject(bean); } } // Lifecycle notification. notifyLifecycleBeans(BEFORE_NODE_START); // Starts lifecycle aware components. U.startLifecycleAware(lifecycleAwares(cfg)); addHelper(IGFS_HELPER.create(F.isEmpty(cfg.getFileSystemConfiguration()))); addHelper(HADOOP_HELPER.createIfInClassPath(ctx, false)); startProcessor(new IgnitePluginProcessor(ctx, cfg, plugins)); startProcessor(new FailureProcessor(ctx)); startProcessor(new PoolProcessor(ctx)); // Closure processor should be started before all others // (except for resource processor), as many components can depend on it. startProcessor(new GridClosureProcessor(ctx)); // Start some other processors (order & place is important). startProcessor(new GridPortProcessor(ctx)); startProcessor(new GridJobMetricsProcessor(ctx)); // Timeout processor needs to be started before managers, // as managers may depend on it. startProcessor(new GridTimeoutProcessor(ctx)); // Start security processors. startProcessor(securityProcessor()); // Start SPI managers. // NOTE: that order matters as there are dependencies between managers. startManager(new GridMetricManager(ctx)); startManager(new GridIoManager(ctx)); startManager(new GridCheckpointManager(ctx)); startManager(new GridEventStorageManager(ctx)); startManager(new GridDeploymentManager(ctx)); startManager(new GridLoadBalancerManager(ctx)); startManager(new GridFailoverManager(ctx)); startManager(new GridCollisionManager(ctx)); startManager(new GridIndexingManager(ctx)); startManager(new GridEncryptionManager(ctx)); ackSecurity(); // Assign discovery manager to context before other processors start so they // are able to register custom event listener. final GridManager discoMgr = new GridDiscoveryManager(ctx); ctx.add(discoMgr, false); // Start processors before discovery manager, so they will // be able to start receiving messages once discovery completes. try { startProcessor(COMPRESSION.createOptional(ctx)); startProcessor(new PdsConsistentIdProcessor(ctx)); startProcessor(new MvccProcessorImpl(ctx)); startProcessor(createComponent(DiscoveryNodeValidationProcessor.class, ctx)); startProcessor(new GridAffinityProcessor(ctx)); startProcessor(createComponent(GridSegmentationProcessor.class, ctx)); startTimer.finishGlobalStage("Start managers"); startProcessor(createComponent(IgniteCacheObjectProcessor.class, ctx)); startTimer.finishGlobalStage("Configure binary metadata"); startProcessor(createComponent(IGridClusterStateProcessor.class, ctx)); startProcessor(new IgniteAuthenticationProcessor(ctx)); startProcessor(new GridCacheProcessor(ctx)); startProcessor(new GridQueryProcessor(ctx)); startProcessor(new ClientListenerProcessor(ctx)); startProcessor(createServiceProcessor()); startProcessor(new GridTaskSessionProcessor(ctx)); startProcessor(new GridJobProcessor(ctx)); startProcessor(new GridTaskProcessor(ctx)); startProcessor((GridProcessor)SCHEDULE.createOptional(ctx)); startProcessor(new GridRestProcessor(ctx)); startProcessor(new DataStreamProcessor(ctx)); startProcessor((GridProcessor)IGFS.create(ctx, F.isEmpty(cfg.getFileSystemConfiguration()))); startProcessor(new GridContinuousProcessor(ctx)); startProcessor(createHadoopComponent()); startProcessor(new DataStructuresProcessor(ctx)); startProcessor(createComponent(PlatformProcessor.class, ctx)); startProcessor(new GridMarshallerMappingProcessor(ctx)); startProcessor(new DistributedMetaStorageImpl(ctx)); startProcessor(new DistributedConfigurationProcessor(ctx)); startTimer.finishGlobalStage("Start processors"); // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) { ctx.add(new GridPluginComponent(provider)); provider.start(ctx.plugins().pluginContextForProvider(provider)); startTimer.finishGlobalStage("Start '"+ provider.name() + "' plugin"); } // Start platform plugins. if (ctx.config().getPlatformConfiguration() != null) startProcessor(new PlatformPluginProcessor(ctx)); ctx.cluster().initDiagnosticListeners(); fillNodeAttributes(clusterProc.updateNotifierEnabled()); ctx.cache().context().database().notifyMetaStorageSubscribersOnReadyForRead(); ((DistributedMetaStorageImpl)ctx.distributedMetastorage()).inMemoryReadyForRead(); startTimer.finishGlobalStage("Init metastore"); ctx.cache().context().database().startMemoryRestore(ctx, startTimer); ctx.recoveryMode(false); startTimer.finishGlobalStage("Finish recovery"); } catch (Throwable e) { U.error( log, "Exception during start processors, node will be stopped and close connections", e); // Stop discovery spi to close tcp socket. ctx.discovery().stop(true); throw e; } gw.writeLock(); try { gw.setState(STARTED); // Start discovery manager last to make sure that grid is fully initialized. startManager(discoMgr); } finally { gw.writeUnlock(); } startTimer.finishGlobalStage("Join topology"); // Check whether UTF-8 is the default character encoding. checkFileEncoding(); // Check whether physical RAM is not exceeded. checkPhysicalRam(); // Suggest configuration optimizations. suggestOptimizations(cfg); // Suggest JVM optimizations. ctx.performance().addAll(JvmConfigurationSuggestions.getSuggestions()); // Suggest Operation System optimizations. ctx.performance().addAll(OsConfigurationSuggestions.getSuggestions()); DiscoveryLocalJoinData joinData = ctx.discovery().localJoin(); IgniteInternalFuture<Boolean> transitionWaitFut = joinData.transitionWaitFuture(); // Notify discovery manager the first to make sure that topology is discovered. // Active flag is not used in managers, so it is safe to pass true. ctx.discovery().onKernalStart(true); // Notify IO manager the second so further components can send and receive messages. // Must notify the IO manager before transition state await to make sure IO connection can be established. ctx.io().onKernalStart(true); boolean active; if (transitionWaitFut != null) { if (log.isInfoEnabled()) { log.info("Join cluster while cluster state transition is in progress, " + "waiting when transition finish."); } active = transitionWaitFut.get(); } else active = joinData.active(); startTimer.finishGlobalStage("Await transition"); boolean recon = false; // Callbacks. for (GridComponent comp : ctx) { // Skip discovery manager. if (comp instanceof GridDiscoveryManager) continue; // Skip IO manager. if (comp instanceof GridIoManager) continue; if (comp instanceof GridPluginComponent) continue; if (!skipDaemon(comp)) { try { comp.onKernalStart(active); } catch (IgniteNeedReconnectException e) { ClusterNode locNode = ctx.discovery().localNode(); assert locNode.isClient(); if (!ctx.discovery().reconnectSupported()) throw new IgniteCheckedException("Client node in forceServerMode " + "is not allowed to reconnect to the cluster and will be stopped."); if (log.isDebugEnabled()) log.debug("Failed to start node components on node start, will wait for reconnect: " + e); recon = true; } } } // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) provider.onIgniteStart(); if (recon) reconnectState.waitFirstReconnect(); ctx.metric().registerThreadPools(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, igfsExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, customExecSvcs); // Register MBeans. mBeansMgr.registerAllMBeans(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, igfsExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, customExecSvcs, ctx.workersRegistry()); // Lifecycle bean notifications. notifyLifecycleBeans(AFTER_NODE_START); } catch (Throwable e) { IgniteSpiVersionCheckException verCheckErr = X.cause(e, IgniteSpiVersionCheckException.class); if (verCheckErr != null) U.error(log, verCheckErr.getMessage()); else if (X.hasCause(e, InterruptedException.class, IgniteInterruptedCheckedException.class)) U.warn(log, "Grid startup routine has been interrupted (will rollback)."); else U.error(log, "Got exception while starting (will rollback startup routine).", e); errHnd.apply(); stop(true); if (e instanceof Error) throw e; else if (e instanceof IgniteCheckedException) throw (IgniteCheckedException)e; else throw new IgniteCheckedException(e); } // Mark start timestamp. startTime = U.currentTimeMillis(); String intervalStr = IgniteSystemProperties.getString(IGNITE_STARVATION_CHECK_INTERVAL); // Start starvation checker if enabled. boolean starveCheck = !isDaemon() && !"0".equals(intervalStr); if (starveCheck) { final long interval = F.isEmpty(intervalStr) ? PERIODIC_STARVATION_CHECK_FREQ : Long.parseLong(intervalStr); starveTask = ctx.timeout().schedule(new Runnable() { /** Last completed task count. */ private long lastCompletedCntPub; /** Last completed task count. */ private long lastCompletedCntSys; @Override public void run() { if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; lastCompletedCntPub = checkPoolStarvation(exec, lastCompletedCntPub, "public"); } if (sysExecSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)sysExecSvc; lastCompletedCntSys = checkPoolStarvation(exec, lastCompletedCntSys, "system"); } if (stripedExecSvc != null) stripedExecSvc.detectStarvation(); } /** * @param exec Thread pool executor to check. * @param lastCompletedCnt Last completed tasks count. * @param pool Pool name for message. * @return Current completed tasks count. */ private long checkPoolStarvation( ThreadPoolExecutor exec, long lastCompletedCnt, String pool ) { long completedCnt = exec.getCompletedTaskCount(); // If all threads are active and no task has completed since last time and there is // at least one waiting request, then it is possible starvation. if (exec.getPoolSize() == exec.getActiveCount() && completedCnt == lastCompletedCnt && !exec.getQueue().isEmpty()) LT.warn( log, "Possible thread pool starvation detected (no task completed in last " + interval + "ms, is " + pool + " thread pool size large enough?)"); return completedCnt; } }, interval, interval); } long metricsLogFreq = cfg.getMetricsLogFrequency(); if (metricsLogFreq > 0) { metricsLogTask = ctx.timeout().schedule(new Runnable() { private final DecimalFormat dblFmt = new DecimalFormat("#.##"); @Override public void run() { ackNodeMetrics(dblFmt, execSvc, sysExecSvc, customExecSvcs); } }, metricsLogFreq, metricsLogFreq); } final long longOpDumpTimeout = IgniteSystemProperties.getLong( IgniteSystemProperties.IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT, DFLT_LONG_OPERATIONS_DUMP_TIMEOUT ); if (longOpDumpTimeout > 0) { longOpDumpTask = ctx.timeout().schedule(new Runnable() { @Override public void run() { GridKernalContext ctx = IgniteKernal.this.ctx; if (ctx != null) ctx.cache().context().exchange().dumpLongRunningOperations(longOpDumpTimeout); } }, longOpDumpTimeout, longOpDumpTimeout); } ctx.performance().add("Disable assertions (remove '-ea' from JVM options)", !U.assertionsEnabled()); ctx.performance().logSuggestions(log, igniteInstanceName); U.quietAndInfo(log, "To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}"); if (!IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_QUIET, true)) ackClassPathContent(); ackStart(rtBean); if (!isDaemon()) ctx.discovery().ackTopology(ctx.discovery().localJoin().joinTopologyVersion().topologyVersion(), EventType.EVT_NODE_JOINED, localNode()); startTimer.finishGlobalStage("Await exchange"); } /** * @return IgniteSecurity. */ private GridProcessor securityProcessor() throws IgniteCheckedException { GridSecurityProcessor prc = createComponent(GridSecurityProcessor.class, ctx); return prc != null && prc.enabled() ? new IgniteSecurityProcessor(ctx, prc) : new NoOpIgniteSecurityProcessor(ctx); } /** * Create description of an executor service for logging. * * @param execSvcName name of the service * @param execSvc service to create a description for */ private String createExecutorDescription(String execSvcName, ExecutorService execSvc) { int poolActiveThreads = 0; int poolIdleThreads = 0; int poolQSize = 0; if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; int poolSize = exec.getPoolSize(); poolActiveThreads = Math.min(poolSize, exec.getActiveCount()); poolIdleThreads = poolSize - poolActiveThreads; poolQSize = exec.getQueue().size(); } return execSvcName + " [active=" + poolActiveThreads + ", idle=" + poolIdleThreads + ", qSize=" + poolQSize + "]"; } /** * Create Hadoop component. * * @return Non-null Hadoop component: workable or no-op. * @throws IgniteCheckedException If the component is mandatory and cannot be initialized. */ private HadoopProcessorAdapter createHadoopComponent() throws IgniteCheckedException { boolean mandatory = cfg.getHadoopConfiguration() != null; if (mandatory) { if (cfg.isPeerClassLoadingEnabled()) throw new IgniteCheckedException("Hadoop module cannot be used with peer class loading enabled " + "(set IgniteConfiguration.peerClassLoadingEnabled to \"false\")."); HadoopProcessorAdapter res = IgniteComponentType.HADOOP.createIfInClassPath(ctx, true); res.validateEnvironment(); return res; } else { HadoopProcessorAdapter cmp = null; if (!ctx.hadoopHelper().isNoOp() && cfg.isPeerClassLoadingEnabled()) { U.warn(log, "Hadoop module is found in classpath, but will not be started because peer class " + "loading is enabled (set IgniteConfiguration.peerClassLoadingEnabled to \"false\" if you want " + "to use Hadoop module)."); } else { cmp = IgniteComponentType.HADOOP.createIfInClassPath(ctx, false); try { cmp.validateEnvironment(); } catch (IgniteException | IgniteCheckedException e) { U.quietAndWarn(log, "Hadoop module will not start due to exception: " + e.getMessage()); cmp = null; } } if (cmp == null) cmp = IgniteComponentType.HADOOP.create(ctx, true); return cmp; } } /** * Creates service processor depend on {@link IgniteSystemProperties#IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED}. * * @return Service processor. */ private GridProcessorAdapter createServiceProcessor() { final boolean srvcProcMode = getBoolean(IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, true); if (srvcProcMode) return new IgniteServiceProcessor(ctx); return new GridServiceProcessor(ctx); } /** * Validates common configuration parameters. * * @param cfg Configuration. */ private void validateCommon(IgniteConfiguration cfg) { A.notNull(cfg.getNodeId(), "cfg.getNodeId()"); if (!U.IGNITE_MBEANS_DISABLED) A.notNull(cfg.getMBeanServer(), "cfg.getMBeanServer()"); A.notNull(cfg.getGridLogger(), "cfg.getGridLogger()"); A.notNull(cfg.getMarshaller(), "cfg.getMarshaller()"); A.notNull(cfg.getUserAttributes(), "cfg.getUserAttributes()"); // All SPIs should be non-null. A.notNull(cfg.getCheckpointSpi(), "cfg.getCheckpointSpi()"); A.notNull(cfg.getCommunicationSpi(), "cfg.getCommunicationSpi()"); A.notNull(cfg.getDeploymentSpi(), "cfg.getDeploymentSpi()"); A.notNull(cfg.getDiscoverySpi(), "cfg.getDiscoverySpi()"); A.notNull(cfg.getEventStorageSpi(), "cfg.getEventStorageSpi()"); A.notNull(cfg.getCollisionSpi(), "cfg.getCollisionSpi()"); A.notNull(cfg.getFailoverSpi(), "cfg.getFailoverSpi()"); A.notNull(cfg.getLoadBalancingSpi(), "cfg.getLoadBalancingSpi()"); A.notNull(cfg.getIndexingSpi(), "cfg.getIndexingSpi()"); A.ensure(cfg.getNetworkTimeout() > 0, "cfg.getNetworkTimeout() > 0"); A.ensure(cfg.getNetworkSendRetryDelay() > 0, "cfg.getNetworkSendRetryDelay() > 0"); A.ensure(cfg.getNetworkSendRetryCount() > 0, "cfg.getNetworkSendRetryCount() > 0"); } /** * Check whether UTF-8 is the default character encoding. * Differing character encodings across cluster may lead to erratic behavior. */ private void checkFileEncoding() { String encodingDisplayName = Charset.defaultCharset().displayName(Locale.ENGLISH); if (!"UTF-8".equals(encodingDisplayName)) { U.quietAndWarn(log, "Default character encoding is " + encodingDisplayName + ". Specify UTF-8 character encoding by setting -Dfile.encoding=UTF-8 JVM parameter. " + "Differing character encodings across cluster may lead to erratic behavior."); } } /** * Checks whether physical RAM is not exceeded. */ @SuppressWarnings("ConstantConditions") private void checkPhysicalRam() { long ram = ctx.discovery().localNode().attribute(ATTR_PHY_RAM); if (ram != -1) { String macs = ctx.discovery().localNode().attribute(ATTR_MACS); long totalHeap = 0; long totalOffheap = 0; for (ClusterNode node : ctx.discovery().allNodes()) { if (macs.equals(node.attribute(ATTR_MACS))) { long heap = node.metrics().getHeapMemoryMaximum(); Long offheap = node.<Long>attribute(ATTR_OFFHEAP_SIZE); if (heap != -1) totalHeap += heap; if (offheap != null) totalOffheap += offheap; } } long total = totalHeap + totalOffheap; if (total < 0) total = Long.MAX_VALUE; // 4GB or 20% of available memory is expected to be used by OS and user applications long safeToUse = ram - Math.max(4L << 30, (long)(ram * 0.2)); if (total > safeToUse) { U.quietAndWarn(log, "Nodes started on local machine require more than 80% of physical RAM what can " + "lead to significant slowdown due to swapping (please decrease JVM heap size, data region " + "size or checkpoint buffer size) [required=" + (total >> 20) + "MB, available=" + (ram >> 20) + "MB]"); } } } /** * @param cfg Configuration to check for possible performance issues. */ private void suggestOptimizations(IgniteConfiguration cfg) { GridPerformanceSuggestions perf = ctx.performance(); if (ctx.collision().enabled()) perf.add("Disable collision resolution (remove 'collisionSpi' from configuration)"); if (ctx.checkpoint().enabled()) perf.add("Disable checkpoints (remove 'checkpointSpi' from configuration)"); if (cfg.isMarshalLocalJobs()) perf.add("Disable local jobs marshalling (set 'marshalLocalJobs' to false)"); if (cfg.getIncludeEventTypes() != null && cfg.getIncludeEventTypes().length != 0) perf.add("Disable grid events (remove 'includeEventTypes' from configuration)"); if (BinaryMarshaller.available() && (cfg.getMarshaller() != null && !(cfg.getMarshaller() instanceof BinaryMarshaller))) perf.add("Use default binary marshaller (do not set 'marshaller' explicitly)"); } /** * Creates attributes map and fills it in. * * @param notifyEnabled Update notifier flag. * @throws IgniteCheckedException thrown if was unable to set up attribute. */ private void fillNodeAttributes(boolean notifyEnabled) throws IgniteCheckedException { ctx.addNodeAttribute(ATTR_REBALANCE_POOL_SIZE, configuration().getRebalanceThreadPoolSize()); ctx.addNodeAttribute(ATTR_DATA_STREAMER_POOL_SIZE, configuration().getDataStreamerThreadPoolSize()); final String[] incProps = cfg.getIncludeProperties(); try { // Stick all environment settings into node attributes. for (Map.Entry<String, String> sysEntry : System.getenv().entrySet()) { String name = sysEntry.getKey(); if (incProps == null || U.containsStringArray(incProps, name, true) || U.isVisorNodeStartProperty(name) || U.isVisorRequiredProperty(name)) ctx.addNodeAttribute(name, sysEntry.getValue()); } if (log.isDebugEnabled()) log.debug("Added environment properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add environment properties to node attributes due to " + "security violation: " + e.getMessage()); } try { // Stick all system properties into node's attributes overwriting any // identical names from environment properties. for (Map.Entry<Object, Object> e : snapshot().entrySet()) { String key = (String)e.getKey(); if (incProps == null || U.containsStringArray(incProps, key, true) || U.isVisorRequiredProperty(key)) { Object val = ctx.nodeAttribute(key); if (val != null && !val.equals(e.getValue())) U.warn(log, "System property will override environment variable with the same name: " + key); ctx.addNodeAttribute(key, e.getValue()); } } ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_UPDATE_NOTIFIER_ENABLED, notifyEnabled); if (log.isDebugEnabled()) log.debug("Added system properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add system properties to node attributes due to security " + "violation: " + e.getMessage()); } // Add local network IPs and MACs. String ips = F.concat(U.allLocalIps(), ", "); // Exclude loopbacks. String macs = F.concat(U.allLocalMACs(), ", "); // Only enabled network interfaces. // Ack network context. if (log.isInfoEnabled()) { log.info("Non-loopback local IPs: " + (F.isEmpty(ips) ? "N/A" : ips)); log.info("Enabled local MACs: " + (F.isEmpty(macs) ? "N/A" : macs)); } // Warn about loopback. if (ips.isEmpty() && macs.isEmpty()) U.warn(log, "Ignite is starting on loopback address... Only nodes on the same physical " + "computer can participate in topology."); // Stick in network context into attributes. add(ATTR_IPS, (ips.isEmpty() ? "" : ips)); Map<String, ?> userAttrs = configuration().getUserAttributes(); if (userAttrs != null && userAttrs.get(IgniteNodeAttributes.ATTR_MACS_OVERRIDE) != null) add(ATTR_MACS, (Serializable)userAttrs.get(IgniteNodeAttributes.ATTR_MACS_OVERRIDE)); else add(ATTR_MACS, (macs.isEmpty() ? "" : macs)); // Stick in some system level attributes add(ATTR_JIT_NAME, U.getCompilerMx() == null ? "" : U.getCompilerMx().getName()); add(ATTR_BUILD_VER, VER_STR); add(ATTR_BUILD_DATE, BUILD_TSTAMP_STR); add(ATTR_MARSHALLER, cfg.getMarshaller().getClass().getName()); add(ATTR_MARSHALLER_USE_DFLT_SUID, getBoolean(IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID, OptimizedMarshaller.USE_DFLT_SUID)); add(ATTR_LATE_AFFINITY_ASSIGNMENT, cfg.isLateAffinityAssignment()); if (cfg.getMarshaller() instanceof BinaryMarshaller) { add(ATTR_MARSHALLER_COMPACT_FOOTER, cfg.getBinaryConfiguration() == null ? BinaryConfiguration.DFLT_COMPACT_FOOTER : cfg.getBinaryConfiguration().isCompactFooter()); add(ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2, getBoolean(IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2, BinaryUtils.USE_STR_SERIALIZATION_VER_2)); } add(ATTR_USER_NAME, System.getProperty("user.name")); add(ATTR_IGNITE_INSTANCE_NAME, igniteInstanceName); add(ATTR_PEER_CLASSLOADING, cfg.isPeerClassLoadingEnabled()); add(ATTR_DEPLOYMENT_MODE, cfg.getDeploymentMode()); add(ATTR_LANG_RUNTIME, getLanguage()); add(ATTR_JVM_PID, U.jvmPid()); add(ATTR_CLIENT_MODE, cfg.isClientMode()); add(ATTR_CONSISTENCY_CHECK_SKIPPED, getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK)); add(ATTR_VALIDATE_CACHE_REQUESTS, Boolean.TRUE); if (cfg.getConsistentId() != null) add(ATTR_NODE_CONSISTENT_ID, cfg.getConsistentId()); // Build a string from JVM arguments, because parameters with spaces are split. SB jvmArgs = new SB(512); for (String arg : U.jvmArgs()) { if (arg.startsWith("-")) jvmArgs.a("@@@"); else jvmArgs.a(' '); jvmArgs.a(arg); } // Add it to attributes. add(ATTR_JVM_ARGS, jvmArgs.toString()); // Check daemon system property and override configuration if it's set. if (isDaemon()) add(ATTR_DAEMON, "true"); // In case of the parsing error, JMX remote disabled or port not being set // node attribute won't be set. if (isJmxRemoteEnabled()) { String portStr = System.getProperty("com.sun.management.jmxremote.port"); if (portStr != null) try { add(ATTR_JMX_PORT, Integer.parseInt(portStr)); } catch (NumberFormatException ignore) { // No-op. } } // Whether restart is enabled and stick the attribute. add(ATTR_RESTART_ENABLED, Boolean.toString(isRestartEnabled())); // Save port range, port numbers will be stored by rest processor at runtime. if (cfg.getConnectorConfiguration() != null) add(ATTR_REST_PORT_RANGE, cfg.getConnectorConfiguration().getPortRange()); // Whether rollback of dynamic cache start is supported or not. // This property is added because of backward compatibility. add(ATTR_DYNAMIC_CACHE_START_ROLLBACK_SUPPORTED, Boolean.TRUE); // Save data storage configuration. addDataStorageConfigurationAttributes(); // Save transactions configuration. add(ATTR_TX_CONFIG, cfg.getTransactionConfiguration()); // Supported features. add(ATTR_IGNITE_FEATURES, IgniteFeatures.allFeatures()); // Stick in SPI versions and classes attributes. addSpiAttributes(cfg.getCollisionSpi()); addSpiAttributes(cfg.getDiscoverySpi()); addSpiAttributes(cfg.getFailoverSpi()); addSpiAttributes(cfg.getCommunicationSpi()); addSpiAttributes(cfg.getEventStorageSpi()); addSpiAttributes(cfg.getCheckpointSpi()); addSpiAttributes(cfg.getLoadBalancingSpi()); addSpiAttributes(cfg.getDeploymentSpi()); // Set user attributes for this node. if (cfg.getUserAttributes() != null) { for (Map.Entry<String, ?> e : cfg.getUserAttributes().entrySet()) { if (ctx.hasNodeAttribute(e.getKey())) U.warn(log, "User or internal attribute has the same name as environment or system " + "property and will take precedence: " + e.getKey()); ctx.addNodeAttribute(e.getKey(), e.getValue()); } } ctx.addNodeAttribute(ATTR_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, ctx.service() instanceof IgniteServiceProcessor); } /** * */ private void addDataStorageConfigurationAttributes() throws IgniteCheckedException { MemoryConfiguration memCfg = cfg.getMemoryConfiguration(); // Save legacy memory configuration if it's present. if (memCfg != null) { // Page size initialization is suspended, see IgniteCacheDatabaseSharedManager#checkPageSize. // We should copy initialized value from new configuration. memCfg.setPageSize(cfg.getDataStorageConfiguration().getPageSize()); add(ATTR_MEMORY_CONFIG, memCfg); } // Save data storage configuration. add(ATTR_DATA_STORAGE_CONFIG, new JdkMarshaller().marshal(cfg.getDataStorageConfiguration())); } /** * Add SPI version and class attributes into node attributes. * * @param spiList Collection of SPIs to get attributes from. * @throws IgniteCheckedException Thrown if was unable to set up attribute. */ private void addSpiAttributes(IgniteSpi... spiList) throws IgniteCheckedException { for (IgniteSpi spi : spiList) { Class<? extends IgniteSpi> spiCls = spi.getClass(); add(U.spiAttribute(spi, ATTR_SPI_CLASS), spiCls.getName()); } } /** * @param mgr Manager to start. * @throws IgniteCheckedException Throw in case of any errors. */ private void startManager(GridManager mgr) throws IgniteCheckedException { // Add manager to registry before it starts to avoid cases when manager is started // but registry does not have it yet. ctx.add(mgr); try { if (!skipDaemon(mgr)) mgr.start(); } catch (IgniteCheckedException e) { U.error(log, "Failed to start manager: " + mgr, e); throw new IgniteCheckedException("Failed to start manager: " + mgr, e); } } /** * @param proc Processor to start. * @throws IgniteCheckedException Thrown in case of any error. */ private void startProcessor(GridProcessor proc) throws IgniteCheckedException { ctx.add(proc); try { if (!skipDaemon(proc)) proc.start(); } catch (IgniteCheckedException e) { throw new IgniteCheckedException("Failed to start processor: " + proc, e); } } /** * Add helper. * * @param helper Helper. */ private void addHelper(Object helper) { ctx.addHelper(helper); } /** * Gets "on" or "off" string for given boolean value. * * @param b Boolean value to convert. * @return Result string. */ private String onOff(boolean b) { return b ? "on" : "off"; } /** * @return Whether or not REST is enabled. */ private boolean isRestEnabled() { assert cfg != null; return cfg.getConnectorConfiguration() != null && // By default rest processor doesn't start on client nodes. (!isClientNode() || (isClientNode() && IgniteSystemProperties.getBoolean(IGNITE_REST_START_ON_CLIENT))); } /** * @return {@code True} if node client or daemon otherwise {@code false}. */ private boolean isClientNode() { return cfg.isClientMode() || cfg.isDaemon(); } /** * Acks remote management. */ private void ackRemoteManagement() { assert log != null; if (!log.isInfoEnabled()) return; SB sb = new SB(); sb.a("Remote Management ["); boolean on = isJmxRemoteEnabled(); sb.a("restart: ").a(onOff(isRestartEnabled())).a(", "); sb.a("REST: ").a(onOff(isRestEnabled())).a(", "); sb.a("JMX ("); sb.a("remote: ").a(onOff(on)); if (on) { sb.a(", "); sb.a("port: ").a(System.getProperty("com.sun.management.jmxremote.port", "<n/a>")).a(", "); sb.a("auth: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.authenticate"))).a(", "); // By default SSL is enabled, that's why additional check for null is needed. // See http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html sb.a("ssl: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.ssl") || System.getProperty("com.sun.management.jmxremote.ssl") == null)); } sb.a(")"); sb.a(']'); log.info(sb.toString()); } /** * Acks configuration URL. */ private void ackConfigUrl() { assert log != null; if (log.isInfoEnabled()) log.info("Config URL: " + System.getProperty(IGNITE_CONFIG_URL, "n/a")); } /** * Acks configuration. */ private void ackConfiguration(IgniteConfiguration cfg) { assert log != null; if (log.isInfoEnabled()) log.info(cfg.toString()); } /** * Acks Logger configuration. */ private void ackLogger() { assert log != null; if (log.isInfoEnabled()) log.info("Logger: " + log.getLoggerInfo()); } /** * Acks ASCII-logo. Thanks to http://patorjk.com/software/taag */ private void ackAsciiLogo() { assert log != null; if (System.getProperty(IGNITE_NO_ASCII) == null) { String ver = "ver. " + ACK_VER_STR; // Big thanks to: http://patorjk.com/software/taag // Font name "Small Slant" if (log.isInfoEnabled()) { log.info(NL + NL + ">>> __________ ________________ " + NL + ">>> / _/ ___/ |/ / _/_ __/ __/ " + NL + ">>> _/ // (7 7 // / / / / _/ " + NL + ">>> /___/\\___/_/|_/___/ /_/ /___/ " + NL + ">>> " + NL + ">>> " + ver + NL + ">>> " + COPYRIGHT + NL + ">>> " + NL + ">>> Ignite documentation: " + "http://" + SITE + NL ); } if (log.isQuiet()) { U.quiet(false, " __________ ________________ ", " / _/ ___/ |/ / _/_ __/ __/ ", " _/ // (7 7 // / / / / _/ ", "/___/\\___/_/|_/___/ /_/ /___/ ", "", ver, COPYRIGHT, "", "Ignite documentation: " + "http://" + SITE, "", "Quiet mode."); String fileName = log.fileName(); if (fileName != null) U.quiet(false, " ^-- Logging to file '" + fileName + '\''); U.quiet(false, " ^-- Logging by '" + log.getLoggerInfo() + '\''); U.quiet(false, " ^-- To see **FULL** console log here add -DIGNITE_QUIET=false or \"-v\" to ignite.{sh|bat}", ""); } } } /** * Prints start info. * * @param rtBean Java runtime bean. */ private void ackStart(RuntimeMXBean rtBean) { ClusterNode locNode = localNode(); if (log.isQuiet()) { ackDataRegions(s -> { U.quiet(false, s); return null; }); U.quiet(false, ""); U.quiet(false, "Ignite node started OK (id=" + U.id8(locNode.id()) + (F.isEmpty(igniteInstanceName) ? "" : ", instance name=" + igniteInstanceName) + ')'); } if (log.isInfoEnabled()) { ackDataRegions(s -> { log.info(s); return null; }); String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR; String dash = U.dash(ack.length()); SB sb = new SB(); for (GridPortRecord rec : ctx.ports().records()) sb.a(rec.protocol()).a(":").a(rec.port()).a(" "); String str = NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + ">>> OS name: " + U.osString() + NL + ">>> CPU(s): " + locNode.metrics().getTotalCpus() + NL + ">>> Heap: " + U.heapSize(locNode, 2) + "GB" + NL + ">>> VM name: " + rtBean.getName() + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Local node [" + "ID=" + locNode.id().toString().toUpperCase() + ", order=" + locNode.order() + ", clientMode=" + ctx.clientNode() + "]" + NL + ">>> Local node addresses: " + U.addressesAsString(locNode) + NL + ">>> Local ports: " + sb + NL; log.info(str); } if (!ctx.state().clusterState().active()) { U.quietAndInfo(log, ">>> Ignite cluster is not active (limited functionality available). " + "Use control.(sh|bat) script or IgniteCluster interface to activate."); } } /** * @param clo Message output closure. */ public void ackDataRegions(IgniteClosure<String, Void> clo) { DataStorageConfiguration memCfg = ctx.config().getDataStorageConfiguration(); if (memCfg == null) return; clo.apply("Data Regions Configured:"); clo.apply(dataRegionConfigurationMessage(memCfg.getDefaultDataRegionConfiguration())); DataRegionConfiguration[] dataRegions = memCfg.getDataRegionConfigurations(); if (dataRegions != null) { for (DataRegionConfiguration dataRegion : dataRegions) { String msg = dataRegionConfigurationMessage(dataRegion); if (msg != null) clo.apply(msg); } } } /** * @param regCfg Data region configuration. * @return Data region message. */ private String dataRegionConfigurationMessage(DataRegionConfiguration regCfg) { if (regCfg == null) return null; SB m = new SB(); m.a(" ^-- ").a(regCfg.getName()).a(" ["); m.a("initSize=").a(U.readableSize(regCfg.getInitialSize(), false)); m.a(", maxSize=").a(U.readableSize(regCfg.getMaxSize(), false)); m.a(", persistence=" + regCfg.isPersistenceEnabled()); m.a(", lazyMemoryAllocation=" + regCfg.isLazyMemoryAllocation()).a(']'); return m.toString(); } /** * Logs out OS information. */ private void ackOsInfo() { assert log != null; if (log.isQuiet()) U.quiet(false, "OS: " + U.osString()); if (log.isInfoEnabled()) { log.info("OS: " + U.osString()); log.info("OS user: " + System.getProperty("user.name")); int jvmPid = U.jvmPid(); log.info("PID: " + (jvmPid == -1 ? "N/A" : jvmPid)); } } /** * Logs out language runtime. */ private void ackLanguageRuntime() { assert log != null; if (log.isQuiet()) U.quiet(false, "VM information: " + U.jdkString()); if (log.isInfoEnabled()) { log.info("Language runtime: " + getLanguage()); log.info("VM information: " + U.jdkString()); log.info("VM total memory: " + U.heapSize(2) + "GB"); } } /** * Logs out node metrics. * * @param dblFmt Decimal format. * @param execSvc Executor service. * @param sysExecSvc System executor service. * @param customExecSvcs Custom named executors. */ private void ackNodeMetrics(DecimalFormat dblFmt, ExecutorService execSvc, ExecutorService sysExecSvc, Map<String, ? extends ExecutorService> customExecSvcs ) { if (!log.isInfoEnabled()) return; try { ClusterMetrics m = cluster().localNode().metrics(); final int MByte = 1024 * 1024; double cpuLoadPct = m.getCurrentCpuLoad() * 100; double avgCpuLoadPct = m.getAverageCpuLoad() * 100; double gcPct = m.getCurrentGcCpuLoad() * 100; // Heap params. long heapUsed = m.getHeapMemoryUsed(); long heapMax = m.getHeapMemoryMaximum(); long heapUsedInMBytes = heapUsed / MByte; long heapCommInMBytes = m.getHeapMemoryCommitted() / MByte; double freeHeapPct = heapMax > 0 ? ((double)((heapMax - heapUsed) * 100)) / heapMax : -1; int hosts = 0; int nodes = 0; int cpus = 0; try { ClusterMetrics metrics = cluster().metrics(); Collection<ClusterNode> nodes0 = cluster().nodes(); hosts = U.neighborhood(nodes0).size(); nodes = metrics.getTotalNodes(); cpus = metrics.getTotalCpus(); } catch (IgniteException ignore) { // No-op. } int loadedPages = 0; // Off-heap params. Collection<DataRegion> regions = ctx.cache().context().database().dataRegions(); StringBuilder dataRegionsInfo = new StringBuilder(); StringBuilder pdsRegionsInfo = new StringBuilder(); long offHeapUsedSummary = 0; long offHeapMaxSummary = 0; long offHeapCommSummary = 0; long pdsUsedSummary = 0; boolean persistenceDisabled = true; if (!F.isEmpty(regions)) { for (DataRegion region : regions) { long pagesCnt = region.pageMemory().loadedPages(); long offHeapUsed = region.pageMemory().systemPageSize() * pagesCnt; long offHeapMax = region.config().getMaxSize(); long offHeapComm = region.memoryMetrics().getOffHeapSize(); long offHeapUsedInMBytes = offHeapUsed / MByte; long offHeapCommInMBytes = offHeapComm / MByte; double freeOffHeapPct = offHeapMax > 0 ? ((double)((offHeapMax - offHeapUsed) * 100)) / offHeapMax : -1; offHeapUsedSummary += offHeapUsed; offHeapMaxSummary += offHeapMax; offHeapCommSummary += offHeapComm; loadedPages += pagesCnt; dataRegionsInfo.append(" ^-- ") .append(region.config().getName()).append(" region") .append(" [used=").append(dblFmt.format(offHeapUsedInMBytes)) .append("MB, free=").append(dblFmt.format(freeOffHeapPct)) .append("%, comm=").append(dblFmt.format(offHeapCommInMBytes)).append("MB]") .append(NL); if (region.config().isPersistenceEnabled()) { long pdsUsed = region.memoryMetrics().getTotalAllocatedSize(); long pdsUsedMBytes = pdsUsed / MByte; pdsUsedSummary += pdsUsed; String pdsUsedSize = dblFmt.format(pdsUsedMBytes) + "MB"; pdsRegionsInfo.append(" ^-- ") .append(region.config().getName()).append(" region") .append(" [used=").append(pdsUsedSize).append("]") .append(NL); persistenceDisabled = false; } } } long offHeapUsedInMBytes = offHeapUsedSummary / MByte; long offHeapCommInMBytes = offHeapCommSummary / MByte; long pdsUsedMBytes = pdsUsedSummary / MByte; double freeOffHeapPct = offHeapMaxSummary > 0 ? ((double)((offHeapMaxSummary - offHeapUsedSummary) * 100)) / offHeapMaxSummary : -1; String pdsInfo = persistenceDisabled ? "" : " ^-- Ignite persistence [used=" + dblFmt.format(pdsUsedMBytes) + "MB]" + NL + pdsRegionsInfo; String id = U.id8(localNode().id()); String msg = NL + "Metrics for local node (to disable set 'metricsLogFrequency' to 0)" + NL + " ^-- Node [id=" + id + (name() != null ? ", name=" + name() : "") + ", uptime=" + getUpTimeFormatted() + "]" + NL + " ^-- H/N/C [hosts=" + hosts + ", nodes=" + nodes + ", CPUs=" + cpus + "]" + NL + " ^-- CPU [cur=" + dblFmt.format(cpuLoadPct) + "%, avg=" + dblFmt.format(avgCpuLoadPct) + "%, GC=" + dblFmt.format(gcPct) + "%]" + NL + " ^-- PageMemory [pages=" + loadedPages + "]" + NL + " ^-- Heap [used=" + dblFmt.format(heapUsedInMBytes) + "MB, free=" + dblFmt.format(freeHeapPct) + "%, comm=" + dblFmt.format(heapCommInMBytes) + "MB]" + NL + " ^-- Off-heap [used=" + dblFmt.format(offHeapUsedInMBytes) + "MB, free=" + dblFmt.format(freeOffHeapPct) + "%, comm=" + dblFmt.format(offHeapCommInMBytes) + "MB]" + NL + dataRegionsInfo + pdsInfo + " ^-- Outbound messages queue [size=" + m.getOutboundMessagesQueueSize() + "]" + NL + " ^-- " + createExecutorDescription("Public thread pool", execSvc) + NL + " ^-- " + createExecutorDescription("System thread pool", sysExecSvc); if (customExecSvcs != null) { StringBuilder customSvcsMsg = new StringBuilder(); for (Map.Entry<String, ? extends ExecutorService> entry : customExecSvcs.entrySet()) { customSvcsMsg.append(NL).append(" ^-- ") .append(createExecutorDescription(entry.getKey(), entry.getValue())); } msg += customSvcsMsg; } log.info(msg); ctx.cache().context().database().dumpStatistics(log); } catch (IgniteClientDisconnectedException ignore) { // No-op. } } /** * @return Language runtime. */ private String getLanguage() { boolean scala = false; boolean groovy = false; boolean clojure = false; for (StackTraceElement elem : Thread.currentThread().getStackTrace()) { String s = elem.getClassName().toLowerCase(); if (s.contains("scala")) { scala = true; break; } else if (s.contains("groovy")) { groovy = true; break; } else if (s.contains("clojure")) { clojure = true; break; } } if (scala) { try (InputStream in = getClass().getResourceAsStream("/library.properties")) { Properties props = new Properties(); if (in != null) props.load(in); return "Scala ver. " + props.getProperty("version.number", "<unknown>"); } catch (Exception ignore) { return "Scala ver. <unknown>"; } } // How to get Groovy and Clojure version at runtime?!? return groovy ? "Groovy" : clojure ? "Clojure" : U.jdkName() + " ver. " + U.jdkVersion(); } /** * Stops grid instance. * * @param cancel Whether or not to cancel running jobs. */ public void stop(boolean cancel) { // Make sure that thread stopping grid is not interrupted. boolean interrupted = Thread.interrupted(); try { stop0(cancel); } finally { if (interrupted) Thread.currentThread().interrupt(); } } /** * @return {@code True} if node started shutdown sequence. */ public boolean isStopping() { return stopGuard.get(); } /** * @param cancel Whether or not to cancel running jobs. */ private void stop0(boolean cancel) { gw.compareAndSet(null, new GridKernalGatewayImpl(igniteInstanceName)); GridKernalGateway gw = this.gw.get(); if (stopGuard.compareAndSet(false, true)) { // Only one thread is allowed to perform stop sequence. boolean firstStop = false; GridKernalState state = gw.getState(); if (state == STARTED || state == DISCONNECTED) firstStop = true; else if (state == STARTING) U.warn(log, "Attempt to stop starting grid. This operation " + "cannot be guaranteed to be successful."); if (firstStop) { // Notify lifecycle beans. if (log.isDebugEnabled()) log.debug("Notifying lifecycle beans."); notifyLifecycleBeansEx(LifecycleEventType.BEFORE_NODE_STOP); } List<GridComponent> comps = ctx.components(); // Callback component in reverse order while kernal is still functional // if called in the same thread, at least. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onKernalStop(cancel); } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to pre-stop processor: " + comp, e); if (e instanceof Error) throw e; } } if (ctx.hadoopHelper() != null) ctx.hadoopHelper().close(); if (starveTask != null) starveTask.close(); if (metricsLogTask != null) metricsLogTask.close(); if (longOpDumpTask != null) longOpDumpTask.close(); if (longJVMPauseDetector != null) longJVMPauseDetector.stop(); boolean interrupted = false; while (true) { try { if (gw.tryWriteLock(10)) break; } catch (InterruptedException ignored) { // Preserve interrupt status & ignore. // Note that interrupted flag is cleared. interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); try { assert gw.getState() == STARTED || gw.getState() == STARTING || gw.getState() == DISCONNECTED; // No more kernal calls from this point on. gw.setState(STOPPING); ctx.cluster().get().clearNodeMap(); if (log.isDebugEnabled()) log.debug("Grid " + (igniteInstanceName == null ? "" : '\'' + igniteInstanceName + "' ") + "is stopping."); } finally { gw.writeUnlock(); } // Stopping cache operations. GridCacheProcessor cache = ctx.cache(); if (cache != null) cache.blockGateways(); // Unregister MBeans. if (!mBeansMgr.unregisterAllMBeans()) errOnStop = true; // Stop components in reverse order. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) { comp.stop(cancel); if (log.isDebugEnabled()) log.debug("Component stopped: " + comp); } } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to stop component (ignoring): " + comp, e); if (e instanceof Error) throw (Error)e; } } // Stops lifecycle aware components. U.stopLifecycleAware(log, lifecycleAwares(cfg)); // Lifecycle notification. notifyLifecycleBeansEx(LifecycleEventType.AFTER_NODE_STOP); // Clean internal class/classloader caches to avoid stopped contexts held in memory. U.clearClassCache(); MarshallerExclusions.clearCache(); BinaryEnumCache.clear(); gw.writeLock(); try { gw.setState(STOPPED); } finally { gw.writeUnlock(); } // Ack stop. if (log.isQuiet()) { String nodeName = igniteInstanceName == null ? "" : "name=" + igniteInstanceName + ", "; if (!errOnStop) U.quiet(false, "Ignite node stopped OK [" + nodeName + "uptime=" + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + ']'); else U.quiet(true, "Ignite node stopped wih ERRORS [" + nodeName + "uptime=" + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + ']'); } if (log.isInfoEnabled()) if (!errOnStop) { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped OK"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + NL + NL); } else { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped with ERRORS"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + NL + ">>> See log above for detailed error message." + NL + ">>> Note that some errors during stop can prevent grid from" + NL + ">>> maintaining correct topology since this node may have" + NL + ">>> not exited grid properly." + NL + NL); } try { U.onGridStop(); } catch (InterruptedException ignored) { // Preserve interrupt status. Thread.currentThread().interrupt(); } } else { // Proper notification. if (log.isDebugEnabled()) { if (gw.getState() == STOPPED) log.debug("Grid is already stopped. Nothing to do."); else log.debug("Grid is being stopped by another thread. Aborting this stop sequence " + "allowing other thread to finish."); } } } /** * USED ONLY FOR TESTING. * * @param name Cache name. * @param <K> Key type. * @param <V> Value type. * @return Internal cache instance. */ /*@java.test.only*/ public <K, V> GridCacheAdapter<K, V> internalCache(String name) { CU.validateCacheName(name); checkClusterState(); return ctx.cache().internalCache(name); } /** * It's intended for use by internal marshalling implementation only. * * @return Kernal context. */ @Override public GridKernalContext context() { return ctx; } /** * Prints all system properties in debug mode. */ private void ackSystemProperties() { assert log != null; if (log.isDebugEnabled() && S.INCLUDE_SENSITIVE) for (Map.Entry<Object, Object> entry : snapshot().entrySet()) log.debug("System property [" + entry.getKey() + '=' + entry.getValue() + ']'); } /** * Prints all user attributes in info mode. */ private void logNodeUserAttributes() { assert log != null; if (log.isInfoEnabled()) for (Map.Entry<?, ?> attr : cfg.getUserAttributes().entrySet()) log.info("Local node user attribute [" + attr.getKey() + '=' + attr.getValue() + ']'); } /** * Prints all environment variables in debug mode. */ private void ackEnvironmentVariables() { assert log != null; if (log.isDebugEnabled()) for (Map.Entry<?, ?> envVar : System.getenv().entrySet()) log.debug("Environment variable [" + envVar.getKey() + '=' + envVar.getValue() + ']'); } /** * Acks daemon mode status. */ private void ackDaemon() { assert log != null; if (log.isInfoEnabled()) log.info("Daemon mode: " + (isDaemon() ? "on" : "off")); } /** * @return {@code True} is this node is daemon. */ private boolean isDaemon() { assert cfg != null; return cfg.isDaemon() || IgniteSystemProperties.getBoolean(IGNITE_DAEMON); } /** * Whether or not remote JMX management is enabled for this node. Remote JMX management is enabled when the * following system property is set: <ul> <li>{@code com.sun.management.jmxremote}</li> </ul> * * @return {@code True} if remote JMX management is enabled - {@code false} otherwise. */ @Override public boolean isJmxRemoteEnabled() { return System.getProperty("com.sun.management.jmxremote") != null; } /** * Whether or not node restart is enabled. Node restart us supported when this node was started with {@code * bin/ignite.{sh|bat}} script using {@code -r} argument. Node can be programmatically restarted using {@link * Ignition#restart(boolean)}} method. * * @return {@code True} if restart mode is enabled, {@code false} otherwise. * @see Ignition#restart(boolean) */ @Override public boolean isRestartEnabled() { return System.getProperty(IGNITE_SUCCESS_FILE) != null; } /** * Prints all configuration properties in info mode and SPIs in debug mode. */ private void ackSpis() { assert log != null; if (log.isDebugEnabled()) { log.debug("+-------------+"); log.debug("START SPI LIST:"); log.debug("+-------------+"); log.debug("Grid checkpoint SPI : " + Arrays.toString(cfg.getCheckpointSpi())); log.debug("Grid collision SPI : " + cfg.getCollisionSpi()); log.debug("Grid communication SPI : " + cfg.getCommunicationSpi()); log.debug("Grid deployment SPI : " + cfg.getDeploymentSpi()); log.debug("Grid discovery SPI : " + cfg.getDiscoverySpi()); log.debug("Grid event storage SPI : " + cfg.getEventStorageSpi()); log.debug("Grid failover SPI : " + Arrays.toString(cfg.getFailoverSpi())); log.debug("Grid load balancing SPI : " + Arrays.toString(cfg.getLoadBalancingSpi())); } } /** * */ private void ackRebalanceConfiguration() throws IgniteCheckedException { if (cfg.isClientMode()) { if (cfg.getRebalanceThreadPoolSize() != IgniteConfiguration.DFLT_REBALANCE_THREAD_POOL_SIZE) U.warn(log, "Setting the rebalance pool size has no effect on the client mode"); } else { if (cfg.getSystemThreadPoolSize() <= cfg.getRebalanceThreadPoolSize()) throw new IgniteCheckedException("Rebalance thread pool size exceed or equals System thread pool size. " + "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start."); if (cfg.getRebalanceThreadPoolSize() < 1) throw new IgniteCheckedException("Rebalance thread pool size minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start."); if (cfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceBatchesPrefetchCount property before next start."); if (cfg.getRebalanceBatchSize() <= 0) throw new IgniteCheckedException("Rebalance batch size must be greater than zero. " + "Change IgniteConfiguration.rebalanceBatchSize property before next start."); if (cfg.getRebalanceThrottle() < 0) throw new IgniteCheckedException("Rebalance throttle can't have negative value. " + "Change IgniteConfiguration.rebalanceThrottle property before next start."); if (cfg.getRebalanceTimeout() < 0) throw new IgniteCheckedException("Rebalance message timeout can't have negative value. " + "Change IgniteConfiguration.rebalanceTimeout property before next start."); for (CacheConfiguration ccfg : cfg.getCacheConfiguration()) { if (ccfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change CacheConfiguration.rebalanceBatchesPrefetchCount property before next start. " + "[cache=" + ccfg.getName() + "]"); } } } /** * */ private void ackMemoryConfiguration() { DataStorageConfiguration memCfg = cfg.getDataStorageConfiguration(); if (memCfg == null) return; U.log(log, "System cache's DataRegion size is configured to " + (memCfg.getSystemRegionInitialSize() / (1024 * 1024)) + " MB. " + "Use DataStorageConfiguration.systemRegionInitialSize property to change the setting."); } /** * */ private void ackCacheConfiguration() { CacheConfiguration[] cacheCfgs = cfg.getCacheConfiguration(); if (cacheCfgs == null || cacheCfgs.length == 0) U.warn(log, "Cache is not configured - in-memory data grid is off."); else { SB sb = new SB(); HashMap<String, ArrayList<String>> memPlcNamesMapping = new HashMap<>(); for (CacheConfiguration c : cacheCfgs) { String cacheName = U.maskName(c.getName()); String memPlcName = c.getDataRegionName(); if (CU.isSystemCache(cacheName)) memPlcName = "sysMemPlc"; else if (memPlcName == null && cfg.getDataStorageConfiguration() != null) memPlcName = cfg.getDataStorageConfiguration().getDefaultDataRegionConfiguration().getName(); if (!memPlcNamesMapping.containsKey(memPlcName)) memPlcNamesMapping.put(memPlcName, new ArrayList<String>()); ArrayList<String> cacheNames = memPlcNamesMapping.get(memPlcName); cacheNames.add(cacheName); } for (Map.Entry<String, ArrayList<String>> e : memPlcNamesMapping.entrySet()) { sb.a("in '").a(e.getKey()).a("' dataRegion: ["); for (String s : e.getValue()) sb.a("'").a(s).a("', "); sb.d(sb.length() - 2, sb.length()).a("], "); } U.log(log, "Configured caches [" + sb.d(sb.length() - 2, sb.length()).toString() + ']'); } } /** * */ private void ackP2pConfiguration() { assert cfg != null; if (cfg.isPeerClassLoadingEnabled()) U.warn( log, "Peer class loading is enabled (disable it in production for performance and " + "deployment consistency reasons)"); } /** * Prints security status. */ private void ackSecurity() { assert log != null; U.quietAndInfo(log, "Security status [authentication=" + onOff(ctx.security().enabled()) + ", tls/ssl=" + onOff(ctx.config().getSslContextFactory() != null) + ']'); } /** * Prints out VM arguments and IGNITE_HOME in info mode. * * @param rtBean Java runtime bean. */ private void ackVmArguments(RuntimeMXBean rtBean) { assert log != null; // Ack IGNITE_HOME and VM arguments. if (log.isInfoEnabled() && S.INCLUDE_SENSITIVE) { log.info("IGNITE_HOME=" + cfg.getIgniteHome()); log.info("VM arguments: " + rtBean.getInputArguments()); } } /** * Prints out class paths in debug mode. * * @param rtBean Java runtime bean. */ private void ackClassPaths(RuntimeMXBean rtBean) { assert log != null; // Ack all class paths. if (log.isDebugEnabled()) { try { log.debug("Boot class path: " + rtBean.getBootClassPath()); log.debug("Class path: " + rtBean.getClassPath()); log.debug("Library path: " + rtBean.getLibraryPath()); } catch (Exception ignore) { // No-op: ignore for Java 9+ and non-standard JVMs. } } } /** * Prints warning if 'java.net.preferIPv4Stack=true' is not set. */ private void ackIPv4StackFlagIsSet() { boolean preferIPv4 = Boolean.valueOf(System.getProperty("java.net.preferIPv4Stack")); if (!preferIPv4) { assert log != null; U.quietAndWarn(log, "Please set system property '-Djava.net.preferIPv4Stack=true' " + "to avoid possible problems in mixed environments."); } } /** * @param cfg Grid configuration. * @return Components provided in configuration which can implement {@link LifecycleAware} interface. */ private Iterable<Object> lifecycleAwares(IgniteConfiguration cfg) { Collection<Object> objs = new ArrayList<>(); if (cfg.getLifecycleBeans() != null) Collections.addAll(objs, cfg.getLifecycleBeans()); if (cfg.getSegmentationResolvers() != null) Collections.addAll(objs, cfg.getSegmentationResolvers()); if (cfg.getConnectorConfiguration() != null) { objs.add(cfg.getConnectorConfiguration().getMessageInterceptor()); objs.add(cfg.getConnectorConfiguration().getSslContextFactory()); } objs.add(cfg.getMarshaller()); objs.add(cfg.getGridLogger()); objs.add(cfg.getMBeanServer()); if (cfg.getCommunicationFailureResolver() != null) objs.add(cfg.getCommunicationFailureResolver()); return objs; } /** {@inheritDoc} */ @Override public IgniteConfiguration configuration() { return cfg; } /** {@inheritDoc} */ @Override public IgniteLogger log() { return cfg.getGridLogger(); } /** {@inheritDoc} */ @Override public boolean removeCheckpoint(String key) { A.notNull(key, "key"); guard(); try { checkClusterState(); return ctx.checkpoint().removeCheckpoint(key); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean pingNode(String nodeId) { A.notNull(nodeId, "nodeId"); return cluster().pingNode(UUID.fromString(nodeId)); } /** {@inheritDoc} */ @Override public void undeployTaskFromGrid(String taskName) throws JMException { A.notNull(taskName, "taskName"); try { compute().undeployTask(taskName); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public String executeTask(String taskName, String arg) throws JMException { try { return compute().execute(taskName, arg); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public boolean pingNodeByAddress(String host) { guard(); try { for (ClusterNode n : cluster().nodes()) if (n.addresses().contains(host)) return ctx.discovery().pingNode(n.id()); return false; } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean eventUserRecordable(int type) { guard(); try { return ctx.event().isUserRecordable(type); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean allEventsUserRecordable(int[] types) { A.notNull(types, "types"); guard(); try { return ctx.event().isAllUserRecordable(types); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteTransactions transactions() { guard(); try { checkClusterState(); return ctx.cache().transactions(); } finally { unguard(); } } /** * @param name Cache name. * @return Cache. */ public <K, V> IgniteInternalCache<K, V> getCache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicCache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> cache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicJCache(name, false, true); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), null, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> createCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, true, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); ctx.cache().createFromTemplate(cacheName).get(); return ctx.cache().publicJCache(cacheName); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg) { return getOrCreateCache0(cacheCfg, false).get1(); } /** {@inheritDoc} */ @Override public <K, V> IgniteBiTuple<IgniteCache<K, V>, Boolean> getOrCreateCache0( CacheConfiguration<K, V> cacheCfg, boolean sql) { A.notNull(cacheCfg, "cacheCfg"); String cacheName = cacheCfg.getName(); CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); Boolean res = false; IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true); if (cache == null) { res = sql ? ctx.cache().dynamicStartSqlCache(cacheCfg).get() : ctx.cache().dynamicStartCache(cacheCfg, cacheName, null, false, true, true).get(); return new IgniteBiTuple<>(ctx.cache().publicJCache(cacheName), res); } else return new IgniteBiTuple<>(cache, res); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> getOrCreateCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, false, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache( CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg ) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> cache = ctx.cache().cache(cacheCfg.getName()); if (cache == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } else { if (cache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } } return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateNewCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(null, cacheName, nearCfg, true, true, true).get(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateNewCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> internalCache = ctx.cache().cache(cacheName); if (internalCache == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } else { if (internalCache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } } IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cache Cache. * @throws IgniteCheckedException If cache without near cache was already started. */ private void checkNearCacheStarted(IgniteCacheProxy<?, ?> cache) throws IgniteCheckedException { if (!cache.context().isNear()) throw new IgniteCheckedException("Failed to start near cache " + "(a cache with the same name without near cache is already started)"); } /** {@inheritDoc} */ @Override public void destroyCache(String cacheName) { destroyCache0(cacheName, false); } /** {@inheritDoc} */ @Override public boolean destroyCache0(String cacheName, boolean sql) throws CacheException { CU.validateCacheName(cacheName); IgniteInternalFuture<Boolean> stopFut = destroyCacheAsync(cacheName, sql, true); try { return stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** {@inheritDoc} */ @Override public void destroyCaches(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); IgniteInternalFuture stopFut = destroyCachesAsync(cacheNames, true); try { stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** * @param cacheName Cache name. * @param sql If the cache needs to be destroyed only if it was created by SQL {@code CREATE TABLE} command. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future. */ public IgniteInternalFuture<Boolean> destroyCacheAsync(String cacheName, boolean sql, boolean checkThreadTx) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCache(cacheName, sql, checkThreadTx, false, null); } finally { unguard(); } } /** * @param cacheNames Collection of cache names. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future. */ public IgniteInternalFuture<?> destroyCachesAsync(Collection<String> cacheNames, boolean checkThreadTx) { CU.validateCacheNames(cacheNames); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCaches(cacheNames, checkThreadTx); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true); if (cache == null) { ctx.cache().getOrCreateFromTemplate(cacheName, true).get(); return ctx.cache().publicJCache(cacheName); } return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cacheName Cache name. * @param templateName Template name. * @param cfgOverride Cache config properties to override. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is deployed. */ public IgniteInternalFuture<?> getOrCreateCacheAsync(String cacheName, String templateName, CacheConfigurationOverride cfgOverride, boolean checkThreadTx) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); if (ctx.cache().cache(cacheName) == null) return ctx.cache().getOrCreateFromTemplate(cacheName, templateName, cfgOverride, checkThreadTx); return new GridFinishedFuture<>(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> void addCacheConfiguration(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().addCacheConfiguration(cacheCfg); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @return Public caches. */ public Collection<IgniteCacheProxy<?, ?>> caches() { guard(); try { checkClusterState(); return ctx.cache().publicCaches(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<String> cacheNames() { guard(); try { checkClusterState(); return ctx.cache().publicCacheNames(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K extends GridCacheUtilityKey, V> IgniteInternalCache<K, V> utilityCache() { guard(); try { checkClusterState(); return ctx.cache().utilityCache(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteInternalCache<K, V> cachex(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().cache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteInternalCache<?, ?>> cachesx( IgnitePredicate<? super IgniteInternalCache<?, ?>>[] p) { guard(); try { checkClusterState(); return F.retain(ctx.cache().caches(), true, p); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteDataStreamer<K, V> dataStreamer(String cacheName) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.<K, V>dataStream().dataStreamer(cacheName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteFileSystem fileSystem(String name) { if (name == null) throw new IllegalArgumentException("IGFS name cannot be null"); guard(); try { checkClusterState(); IgniteFileSystem fs = ctx.igfs().igfs(name); if (fs == null) throw new IllegalArgumentException("IGFS is not configured: " + name); return fs; } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteFileSystem igfsx(String name) { if (name == null) throw new IllegalArgumentException("IGFS name cannot be null"); guard(); try { checkClusterState(); return ctx.igfs().igfs(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteFileSystem> fileSystems() { guard(); try { checkClusterState(); return ctx.igfs().igfss(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Hadoop hadoop() { guard(); try { checkClusterState(); return ctx.hadoop().hadoop(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException { guard(); try { checkClusterState(); return (T)ctx.pluginProvider(name).plugin(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteBinary binary() { checkClusterState(); IgniteCacheObjectProcessor objProc = ctx.cacheObjects(); return objProc.binary(); } /** {@inheritDoc} */ @Override public IgniteProductVersion version() { return VER; } /** {@inheritDoc} */ @Override public String latestVersion() { ctx.gateway().readLock(); try { return ctx.cluster().latestVersion(); } finally { ctx.gateway().readUnlock(); } } /** {@inheritDoc} */ @Override public IgniteScheduler scheduler() { return scheduler; } /** {@inheritDoc} */ @Override public void close() throws IgniteException { Ignition.stop(igniteInstanceName, true); } /** {@inheritDoc} */ @Override public <K> Affinity<K> affinity(String cacheName) { CU.validateCacheName(cacheName); checkClusterState(); GridCacheAdapter<K, ?> cache = ctx.cache().internalCache(cacheName); if (cache != null) return cache.affinity(); return ctx.affinity().affinityProxy(cacheName); } /** {@inheritDoc} */ @Override public boolean active() { guard(); try { return context().state().publicApiActiveState(true); } finally { unguard(); } } /** {@inheritDoc} */ @Override public void active(boolean active) { cluster().active(active); } /** */ private Collection<BaselineNode> baselineNodes() { Collection<ClusterNode> srvNodes = cluster().forServers().nodes(); ArrayList baselineNodes = new ArrayList(srvNodes.size()); for (ClusterNode clN : srvNodes) baselineNodes.add(clN); return baselineNodes; } /** {@inheritDoc} */ @Override public void resetLostPartitions(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); guard(); try { ctx.cache().resetCacheState(cacheNames).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<DataRegionMetrics> dataRegionMetrics() { guard(); try { return ctx.cache().context().database().memoryMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public DataRegionMetrics dataRegionMetrics(String memPlcName) { guard(); try { return ctx.cache().context().database().memoryMetrics(memPlcName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public DataStorageMetrics dataStorageMetrics() { guard(); try { return ctx.cache().context().database().persistentStoreMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<MemoryMetrics> memoryMetrics() { return DataRegionMetricsAdapter.collectionOf(dataRegionMetrics()); } /** {@inheritDoc} */ @Nullable @Override public MemoryMetrics memoryMetrics(String memPlcName) { return DataRegionMetricsAdapter.valueOf(dataRegionMetrics(memPlcName)); } /** {@inheritDoc} */ @Override public PersistenceMetrics persistentStoreMetrics() { return DataStorageMetricsAdapter.valueOf(dataStorageMetrics()); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create) { return atomicSequence(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().sequence(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, long initVal, boolean create) { return atomicLong(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicLong(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteAtomicReference<T> atomicReference( String name, @Nullable T initVal, boolean create ) { return atomicReference(name, null, initVal, create); } /** {@inheritDoc} */ @Override public <T> IgniteAtomicReference<T> atomicReference(String name, AtomicConfiguration cfg, @Nullable T initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicReference(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, @Nullable T initVal, @Nullable S initStamp, boolean create) { return atomicStamped(name, null, initVal, initStamp, create); } /** {@inheritDoc} */ @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, AtomicConfiguration cfg, @Nullable T initVal, @Nullable S initStamp, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicStamped(name, cfg, initVal, initStamp, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteCountDownLatch countDownLatch(String name, int cnt, boolean autoDel, boolean create) { guard(); try { checkClusterState(); return ctx.dataStructures().countDownLatch(name, null, cnt, autoDel, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteSemaphore semaphore( String name, int cnt, boolean failoverSafe, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().semaphore(name, null, cnt, failoverSafe, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteLock reentrantLock( String name, boolean failoverSafe, boolean fair, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().reentrantLock(name, null, failoverSafe, fair, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteQueue<T> queue(String name, int cap, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().queue(name, null, cap, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteSet<T> set(String name, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().set(name, null, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** * <tt>ctx.gateway().readLock()</tt> */ private void guard() { assert ctx != null; ctx.gateway().readLock(); } /** * <tt>ctx.gateway().readUnlock()</tt> */ private void unguard() { assert ctx != null; ctx.gateway().readUnlock(); } /** * Validate operation on cluster. Check current cluster state. * * @throws IgniteException if cluster in inActive state */ private void checkClusterState() throws IgniteException { if (!ctx.state().publicApiActiveState(true)) { throw new IgniteException("Can not perform the operation because the cluster is inactive. Note, that " + "the cluster is considered inactive by default if Ignite Persistent Store is used to let all the nodes " + "join the cluster. To activate the cluster call Ignite.active(true)."); } } /** * */ public void onDisconnected() { Throwable err = null; reconnectState.waitPreviousReconnect(); GridFutureAdapter<?> reconnectFut = ctx.gateway().onDisconnected(); if (reconnectFut == null) { assert ctx.gateway().getState() != STARTED : ctx.gateway().getState(); return; } IgniteFutureImpl<?> curFut = (IgniteFutureImpl<?>)ctx.cluster().get().clientReconnectFuture(); IgniteFuture<?> userFut; // In case of previous reconnect did not finish keep reconnect future. if (curFut != null && curFut.internalFuture() == reconnectFut) userFut = curFut; else { userFut = new IgniteFutureImpl<>(reconnectFut); ctx.cluster().get().clientReconnectFuture(userFut); } ctx.disconnected(true); List<GridComponent> comps = ctx.components(); for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onDisconnected(userFut); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } } for (GridCacheContext cctx : ctx.cache().context().cacheContexts()) { cctx.gate().writeLock(); cctx.gate().writeUnlock(); } ctx.gateway().writeLock(); ctx.gateway().writeUnlock(); if (err != null) { reconnectFut.onDone(err); U.error(log, "Failed to reconnect, will stop node", err); close(); } } /** * @param clusterRestarted {@code True} if all cluster nodes restarted while client was disconnected. */ @SuppressWarnings("unchecked") public void onReconnected(final boolean clusterRestarted) { Throwable err = null; try { ctx.disconnected(false); GridCompoundFuture curReconnectFut = reconnectState.curReconnectFut = new GridCompoundFuture<>(); reconnectState.reconnectDone = new GridFutureAdapter<>(); for (GridComponent comp : ctx.components()) { IgniteInternalFuture<?> fut = comp.onReconnected(clusterRestarted); if (fut != null) curReconnectFut.add(fut); } curReconnectFut.add(ctx.cache().context().exchange().reconnectExchangeFuture()); curReconnectFut.markInitialized(); final GridFutureAdapter reconnectDone = reconnectState.reconnectDone; curReconnectFut.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> fut) { try { Object res = fut.get(); if (res == STOP_RECONNECT) return; ctx.gateway().onReconnected(); reconnectState.firstReconnectFut.onDone(); } catch (IgniteCheckedException e) { if (!X.hasCause(e, IgniteNeedReconnectException.class, IgniteClientDisconnectedCheckedException.class, IgniteInterruptedCheckedException.class)) { U.error(log, "Failed to reconnect, will stop node.", e); reconnectState.firstReconnectFut.onDone(e); new Thread(() -> { U.error(log, "Stopping the node after a failed reconnect attempt."); close(); }, "node-stopper").start(); } else { assert ctx.discovery().reconnectSupported(); U.error(log, "Failed to finish reconnect, will retry [locNodeId=" + ctx.localNodeId() + ", err=" + e.getMessage() + ']'); } } finally { reconnectDone.onDone(); } } }); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } if (err != null) { U.error(log, "Failed to reconnect, will stop node", err); if (!X.hasCause(err, NodeStoppingException.class)) close(); } } /** * Creates optional component. * * @param cls Component interface. * @param ctx Kernal context. * @return Created component. * @throws IgniteCheckedException If failed to create component. */ private static <T extends GridComponent> T createComponent(Class<T> cls, GridKernalContext ctx) throws IgniteCheckedException { assert cls.isInterface() : cls; T comp = ctx.plugins().createComponent(cls); if (comp != null) return comp; if (cls.equals(IgniteCacheObjectProcessor.class)) return (T)new CacheObjectBinaryProcessorImpl(ctx); if (cls.equals(DiscoveryNodeValidationProcessor.class)) return (T)new OsDiscoveryNodeValidationProcessor(ctx); if (cls.equals(IGridClusterStateProcessor.class)) return (T)new GridClusterStateProcessor(ctx); if(cls.equals(GridSecurityProcessor.class)) return null; Class<T> implCls = null; try { String clsName; // Handle special case for PlatformProcessor if (cls.equals(PlatformProcessor.class)) clsName = ctx.config().getPlatformConfiguration() == null ? PlatformNoopProcessor.class.getName() : cls.getName() + "Impl"; else clsName = componentClassName(cls); implCls = (Class<T>)Class.forName(clsName); } catch (ClassNotFoundException ignore) { // No-op. } if (implCls == null) throw new IgniteCheckedException("Failed to find component implementation: " + cls.getName()); if (!cls.isAssignableFrom(implCls)) throw new IgniteCheckedException("Component implementation does not implement component interface " + "[component=" + cls.getName() + ", implementation=" + implCls.getName() + ']'); Constructor<T> constructor; try { constructor = implCls.getConstructor(GridKernalContext.class); } catch (NoSuchMethodException e) { throw new IgniteCheckedException("Component does not have expected constructor: " + implCls.getName(), e); } try { return constructor.newInstance(ctx); } catch (ReflectiveOperationException e) { throw new IgniteCheckedException("Failed to create component [component=" + cls.getName() + ", implementation=" + implCls.getName() + ']', e); } } /** * @param cls Component interface. * @return Name of component implementation class for open source edition. */ private static String componentClassName(Class<?> cls) { return cls.getPackage().getName() + ".os." + cls.getSimpleName().replace("Grid", "GridOs"); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igniteInstanceName = U.readString(in); } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igniteInstanceName); } /** * @return IgniteKernal instance. * @throws ObjectStreamException If failed. */ protected Object readResolve() throws ObjectStreamException { try { return IgnitionEx.localIgnite(); } catch (IllegalStateException e) { throw U.withCause(new InvalidObjectException(e.getMessage()), e); } } /** * @param comp Grid component. * @return {@code true} if node running in daemon mode and component marked by {@code SkipDaemon} annotation. */ private boolean skipDaemon(GridComponent comp) { return ctx.isDaemon() && U.hasAnnotation(comp.getClass(), SkipDaemon.class); } /** {@inheritDoc} */ @Override public void dumpDebugInfo() { try { GridKernalContextImpl ctx = this.ctx; GridDiscoveryManager discoMrg = ctx != null ? ctx.discovery() : null; ClusterNode locNode = discoMrg != null ? discoMrg.localNode() : null; if (ctx != null && discoMrg != null && locNode != null) { boolean client = ctx.clientNode(); UUID routerId = locNode instanceof TcpDiscoveryNode ? ((TcpDiscoveryNode)locNode).clientRouterNodeId() : null; U.warn(ctx.cluster().diagnosticLog(), "Dumping debug info for node [id=" + locNode.id() + ", name=" + ctx.igniteInstanceName() + ", order=" + locNode.order() + ", topVer=" + discoMrg.topologyVersion() + ", client=" + client + (client && routerId != null ? ", routerId=" + routerId : "") + ']'); ctx.cache().context().exchange().dumpDebugInfo(null); } else U.warn(log, "Dumping debug info for node, context is not initialized [name=" + igniteInstanceName + ']'); } catch (Exception e) { U.error(log, "Failed to dump debug info for node: " + e, e); } } /** * @param node Node. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(ClusterNode node, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(node, payload, procFromNioThread); } /** * @param nodes Nodes. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(List<ClusterNode> nodes, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(nodes, payload, procFromNioThread); } /** * */ private class ReconnectState { /** */ private final GridFutureAdapter firstReconnectFut = new GridFutureAdapter(); /** */ private GridCompoundFuture<?, Object> curReconnectFut; /** */ private GridFutureAdapter<?> reconnectDone; /** * @throws IgniteCheckedException If failed. */ void waitFirstReconnect() throws IgniteCheckedException { firstReconnectFut.get(); } /** * */ void waitPreviousReconnect() { if (curReconnectFut != null && !curReconnectFut.isDone()) { assert reconnectDone != null; curReconnectFut.onDone(STOP_RECONNECT); try { reconnectDone.get(); } catch (IgniteCheckedException ignote) { // No-op. } } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ReconnectState.class, this); } } /** {@inheritDoc} */ @Override public void runIoTest( long warmup, long duration, int threads, long maxLatency, int rangesCnt, int payLoadSize, boolean procFromNioThread ) { ctx.io().runIoTest(warmup, duration, threads, maxLatency, rangesCnt, payLoadSize, procFromNioThread, new ArrayList(ctx.cluster().get().forServers().forRemotes().nodes())); } /** {@inheritDoc} */ @Override public void clearNodeLocalMap() { ctx.cluster().get().clearNodeMap(); } /** {@inheritDoc} */ @Override public void resetMetrics(String registry) { assert registry != null; MetricRegistry mreg = ctx.metric().registry(registry); if (mreg != null) mreg.reset(); else if (log.isInfoEnabled()) log.info("\"" + registry + "\" not found."); } /** {@inheritDoc} */ @Override public boolean readOnlyMode() { return ctx.state().publicApiReadOnlyMode(); } /** {@inheritDoc} */ @Override public void readOnlyMode(boolean readOnly) { ctx.state().changeGlobalState(readOnly); } /** {@inheritDoc} */ @Override public long getReadOnlyModeDuration() { if (ctx.state().publicApiReadOnlyMode()) return U.currentTimeMillis() - ctx.state().readOnlyModeStateChangeTime(); else return 0; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(IgniteKernal.class, this); } }
IGNITE-12051 Update javadoc for the IgniteKernal class - Fixes #6760. Signed-off-by: ipavlukhin <[email protected]>
modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
IGNITE-12051 Update javadoc for the IgniteKernal class - Fixes #6760.
<ide><path>odules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java <ide> import org.apache.ignite.DataRegionMetricsAdapter; <ide> import org.apache.ignite.DataStorageMetrics; <ide> import org.apache.ignite.DataStorageMetricsAdapter; <add>import org.apache.ignite.Ignite; <ide> import org.apache.ignite.IgniteAtomicLong; <ide> import org.apache.ignite.IgniteAtomicReference; <ide> import org.apache.ignite.IgniteAtomicSequence; <ide> import org.apache.ignite.cluster.ClusterGroup; <ide> import org.apache.ignite.cluster.ClusterMetrics; <ide> import org.apache.ignite.cluster.ClusterNode; <add>import org.apache.ignite.compute.ComputeJob; <ide> import org.apache.ignite.configuration.AtomicConfiguration; <ide> import org.apache.ignite.configuration.BinaryConfiguration; <ide> import org.apache.ignite.configuration.CacheConfiguration; <ide> import org.apache.ignite.internal.processors.resource.GridSpringResourceContext; <ide> import org.apache.ignite.internal.processors.rest.GridRestProcessor; <ide> import org.apache.ignite.internal.processors.security.GridSecurityProcessor; <add>import org.apache.ignite.internal.processors.security.IgniteSecurity; <ide> import org.apache.ignite.internal.processors.security.IgniteSecurityProcessor; <ide> import org.apache.ignite.internal.processors.security.NoOpIgniteSecurityProcessor; <ide> import org.apache.ignite.internal.processors.segmentation.GridSegmentationProcessor; <ide> import static org.apache.ignite.lifecycle.LifecycleEventType.BEFORE_NODE_START; <ide> <ide> /** <del> * Ignite kernal. <del> * <p/> <del> * See <a href="http://en.wikipedia.org/wiki/Kernal">http://en.wikipedia.org/wiki/Kernal</a> for information on the <del> * misspelling. <add> * This class represents an implementation of the main Ignite API {@link Ignite} which is expanded by additional <add> * methods of {@link IgniteEx} for the internal Ignite needs. It also controls the Ignite life cycle, checks <add> * thread pools state for starvation, detects long JVM pauses and prints out the local node metrics. <add> * <p> <add> * Please, refer to the wiki <a href="http://en.wikipedia.org/wiki/Kernal">http://en.wikipedia.org/wiki/Kernal</a> <add> * for the information on the misspelling. <add> * <p> <add> * <h3>Starting</h3> <add> * The main entry point for all the Ignite instances creation is the method - {@link #start(IgniteConfiguration, <add> * ExecutorService, ExecutorService, ExecutorService, ExecutorService,StripedExecutor, ExecutorService, ExecutorService, <add> * ExecutorService, StripedExecutor, ExecutorService, ExecutorService, ExecutorService, IgniteStripedThreadPoolExecutor, <add> * ExecutorService, ExecutorService, Map, GridAbsClosure, WorkersRegistry, Thread.UncaughtExceptionHandler, TimeBag) <add> * start}. <add> * <p> <add> * It starts internal Ignite components (see {@link GridComponent}), for instance: <add> * <ul> <add> * <li>{@link GridManager} - a layer of indirection between kernal and SPI modules.</li> <add> * <li>{@link GridProcessor} - an objects responsible for particular internal process implementation.</li> <add> * <li>{@link IgnitePlugin} - an Ignite addition of user-provided functionality.</li> <add> * </ul> <add> * The {@code start} method also performs additional validation of the provided {@link IgniteConfiguration} and <add> * prints some suggestions such as: <add> * <ul> <add> * <li>Ignite configuration optimizations (e.g. disabling {@link EventType} events).</li> <add> * <li>{@link JvmConfigurationSuggestions} optimizations.</li> <add> * <li>{@link OsConfigurationSuggestions} optimizations.</li> <add> * </ul> <add> * <h3>Stopping</h3> <add> * To stop Ignite instance the {@link #stop(boolean)} method is used. The {@code cancel} argument of this method is used: <add> * <ul> <add> * <li>With {@code true} value. To interrupt all currently acitve {@link GridComponent}s related to the Ignite node. <add> * For instance, {@link ComputeJob} will be interrupted by calling {@link ComputeJob#cancel()} method. Note that just <add> * like with {@link Thread#interrupt()}, it is up to the actual job to exit from execution.</li> <add> * <li>With {@code false} value. To stop the Ignite node gracefully. All jobs currently running will not be interrupted. <add> * The Ignite node will wait for the completion of all {@link GridComponent}s running on it before stopping. <add> * </li> <add> * </ul> <ide> */ <ide> public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable { <del> /** */ <add> /** Class serialization version number. */ <ide> private static final long serialVersionUID = 0L; <ide> <del> /** Ignite site that is shown in log messages. */ <add> /** Ignite web-site that is shown in log messages. */ <ide> public static final String SITE = "ignite.apache.org"; <ide> <ide> /** System line separator. */ <ide> private static final String NL = U.nl(); <ide> <del> /** Periodic starvation check interval. */ <add> /** <add> * Default interval of checking thread pool state for the starvation. Will be used only if the <add> * {@link IgniteSystemProperties#IGNITE_STARVATION_CHECK_INTERVAL} system property is not set. <add> * <p> <add> * Value is {@code 30 sec}. <add> */ <ide> private static final long PERIODIC_STARVATION_CHECK_FREQ = 1000 * 30; <ide> <del> /** Force complete reconnect future. */ <add> /** Object is used to force completion the previous reconnection attempt. See {@link ReconnectState} for details. */ <ide> private static final Object STOP_RECONNECT = new Object(); <ide> <del> /** Separator for formatted coordinator properties. */ <add> /** The separator is used for coordinator properties formatted as a string. */ <ide> public static final String COORDINATOR_PROPERTIES_SEPARATOR = ","; <ide> <del> /** Default long operations dump timeout. */ <add> /** <add> * Default timeout in milliseconds for dumping long running operations. Will be used if the <add> * {@link IgniteSystemProperties#IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT} is not set. <add> * <p> <add> * Value is {@code 60 sec}. <add> */ <ide> public static final long DFLT_LONG_OPERATIONS_DUMP_TIMEOUT = 60_000L; <ide> <del> /** Long jvm pause detector. */ <add> /** Currently used instance of JVM pause detector thread. See {@link LongJVMPauseDetector} for details. */ <ide> private LongJVMPauseDetector longJVMPauseDetector; <ide> <del> /** */ <add> /** The main kernal context which holds all the {@link GridComponent}s. */ <ide> @GridToStringExclude <ide> private GridKernalContextImpl ctx; <ide> <del> /** Helper that registers MBeans */ <add> /** Helper which registers and unregisters MBeans. */ <ide> @GridToStringExclude <ide> private IgniteMBeansManager mBeansMgr; <ide> <del> /** Configuration. */ <add> /** Ignite configuration instance. */ <ide> private IgniteConfiguration cfg; <ide> <del> /** */ <add> /** Ignite logger instance which enriches log messages with the node instance name and the node id. */ <ide> @GridToStringExclude <ide> private GridLoggerProxy log; <ide> <del> /** */ <add> /** Name of Ignite node. */ <ide> private String igniteInstanceName; <ide> <ide> /** Kernal start timestamp. */ <ide> /** Spring context, potentially {@code null}. */ <ide> private GridSpringResourceContext rsrcCtx; <ide> <del> /** */ <add> /** <add> * The instance of scheduled thread pool starvation checker. {@code null} if starvation checks have been <add> * disabled by the value of {@link IgniteSystemProperties#IGNITE_STARVATION_CHECK_INTERVAL} system property. <add> */ <ide> @GridToStringExclude <ide> private GridTimeoutProcessor.CancelableTask starveTask; <ide> <del> /** */ <add> /** <add> * The instance of scheduled metrics logger. {@code null} means that the metrics loggin have been disabled <add> * by configuration. See {@link IgniteConfiguration#getMetricsLogFrequency()} for details. <add> */ <ide> @GridToStringExclude <ide> private GridTimeoutProcessor.CancelableTask metricsLogTask; <ide> <del> /** */ <add> /** <add> * The instance of scheduled long operation checker. {@code null} means that the operations checker is disabled <add> * by the value of {@link IgniteSystemProperties#IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT} system property. <add> */ <ide> @GridToStringExclude <ide> private GridTimeoutProcessor.CancelableTask longOpDumpTask; <ide> <del> /** Indicate error on grid stop. */ <add> /** {@code true} if an error occurs at Ignite instance stop. */ <ide> @GridToStringExclude <ide> private boolean errOnStop; <ide> <del> /** Scheduler. */ <add> /** An instance of the scheduler which provides functionality for scheduling jobs locally. */ <ide> @GridToStringExclude <ide> private IgniteScheduler scheduler; <ide> <del> /** Kernal gateway. */ <add> /** The kernal state guard. See {@link GridKernalGateway} for details. */ <ide> @GridToStringExclude <ide> private final AtomicReference<GridKernalGateway> gw = new AtomicReference<>(); <ide> <del> /** Stop guard. */ <add> /** Flag indicates that the ignite instance is scheduled to be stopped. */ <ide> @GridToStringExclude <ide> private final AtomicBoolean stopGuard = new AtomicBoolean(); <ide> <del> /** */ <add> /** The state object is used when reconnection occurs. See {@link IgniteKernal#onReconnected(boolean)}. */ <ide> private final ReconnectState reconnectState = new ReconnectState(); <ide> <ide> /** <ide> } <ide> <ide> /** <del> * Notifies life-cycle beans of grid event. <add> * Notifies life-cycle beans of ignite event. <ide> * <del> * @param evt Grid event. <add> * @param evt Lifecycle event to notify beans with. <ide> * @throws IgniteCheckedException If user threw exception during start. <ide> */ <ide> private void notifyLifecycleBeans(LifecycleEventType evt) throws IgniteCheckedException { <ide> } <ide> <ide> /** <del> * Notifies life-cycle beans of grid event. <add> * Notifies life-cycle beans of ignite event. <ide> * <del> * @param evt Grid event. <add> * @param evt Lifecycle event to notify beans with. <ide> */ <ide> private void notifyLifecycleBeansEx(LifecycleEventType evt) { <ide> try { <ide> } <ide> } <ide> <del> /** */ <add> /** <add> * @param clsPathEntry Classpath file to process. <add> * @param clsPathContent StringBuilder to attach path to. <add> */ <ide> private void ackClassPathElementRecursive(File clsPathEntry, SB clsPathContent) { <ide> if (clsPathEntry.isDirectory()) { <ide> String[] list = clsPathEntry.list(); <ide> } <ide> } <ide> <del> /** */ <add> /** <add> * @param clsPathEntry Classpath string to process. <add> * @param clsPathContent StringBuilder to attach path to. <add> */ <ide> private void ackClassPathEntry(String clsPathEntry, SB clsPathContent) { <ide> File clsPathElementFile = new File(clsPathEntry); <ide> <ide> } <ide> } <ide> <del> /** */ <add> /** <add> * @param clsPathEntry Classpath string to process. <add> * @param clsPathContent StringBuilder to attach path to. <add> */ <ide> private void ackClassPathWildCard(String clsPathEntry, SB clsPathContent) { <ide> final int lastSeparatorIdx = clsPathEntry.lastIndexOf(File.separator); <ide> <ide> } <ide> <ide> /** <del> * Prints the list of *.jar and *.class files containing in classpath. <add> * Prints the list of {@code *.jar} and {@code *.class} files containing in the classpath. <ide> */ <ide> private void ackClassPathContent() { <ide> assert log != null; <ide> } <ide> <ide> /** <del> * @param cfg Configuration to use. <add> * @param cfg Ignite configuration to use. <ide> * @param utilityCachePool Utility cache pool. <ide> * @param execSvc Executor service. <add> * @param svcExecSvc Services executor service. <ide> * @param sysExecSvc System executor service. <ide> * @param stripedExecSvc Striped executor. <ide> * @param p2pExecSvc P2P executor service. <ide> * @param mgmtExecSvc Management executor service. <ide> * @param igfsExecSvc IGFS executor service. <del> * @param dataStreamExecSvc data stream executor service. <add> * @param dataStreamExecSvc Data streamer executor service. <ide> * @param restExecSvc Reset executor service. <ide> * @param affExecSvc Affinity executor service. <ide> * @param idxExecSvc Indexing executor service. <ide> } <ide> <ide> /** <del> * @return IgniteSecurity. <add> * @return Ignite security processor. See {@link IgniteSecurity} for details. <ide> */ <ide> private GridProcessor securityProcessor() throws IgniteCheckedException { <ide> GridSecurityProcessor prc = createComponent(GridSecurityProcessor.class, ctx); <ide> /** <ide> * Create description of an executor service for logging. <ide> * <del> * @param execSvcName name of the service <del> * @param execSvc service to create a description for <add> * @param execSvcName Name of the service. <add> * @param execSvc Service to create a description for. <ide> */ <ide> private String createExecutorDescription(String execSvcName, ExecutorService execSvc) { <ide> int poolActiveThreads = 0; <ide> /** <ide> * Creates service processor depend on {@link IgniteSystemProperties#IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED}. <ide> * <del> * @return Service processor. <add> * @return The service processor. See {@link IgniteServiceProcessor} for details. <ide> */ <ide> private GridProcessorAdapter createServiceProcessor() { <ide> final boolean srvcProcMode = getBoolean(IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, true); <ide> /** <ide> * Validates common configuration parameters. <ide> * <del> * @param cfg Configuration. <add> * @param cfg Ignite configuration to validate. <ide> */ <ide> private void validateCommon(IgniteConfiguration cfg) { <ide> A.notNull(cfg.getNodeId(), "cfg.getNodeId()"); <ide> } <ide> <ide> /** <del> * @param cfg Configuration to check for possible performance issues. <add> * @param cfg Ignite configuration to check for possible performance issues. <ide> */ <ide> private void suggestOptimizations(IgniteConfiguration cfg) { <ide> GridPerformanceSuggestions perf = ctx.performance(); <ide> } <ide> <ide> /** <del> * <add> * @throws IgniteCheckedException If duplicated SPI name found. <ide> */ <ide> private void addDataStorageConfigurationAttributes() throws IgniteCheckedException { <ide> MemoryConfiguration memCfg = cfg.getMemoryConfiguration(); <ide> } <ide> <ide> /** <del> * Add helper. <del> * <del> * @param helper Helper. <add> * @param helper Helper to attach to kernal context. <ide> */ <ide> private void addHelper(Object helper) { <ide> ctx.addHelper(helper); <ide> } <ide> <ide> /** <del> * @return Whether or not REST is enabled. <add> * @return {@code true} if the REST processor is enabled, {@code false} the otherwise. <ide> */ <ide> private boolean isRestEnabled() { <ide> assert cfg != null; <ide> } <ide> <ide> /** <del> * Acks configuration. <add> * @param cfg Ignite configuration to ack. <ide> */ <ide> private void ackConfiguration(IgniteConfiguration cfg) { <ide> assert log != null; <ide> } <ide> <ide> /** <del> * Stops grid instance. <add> * Stops Ignite instance. <ide> * <ide> * @param cancel Whether or not to cancel running jobs. <ide> */ <ide> } <ide> <ide> /** <add> * Acknowledge that the rebalance configuration properties are setted correctly. <ide> * <add> * @throws IgniteCheckedException If rebalance configuration validation fail. <ide> */ <ide> private void ackRebalanceConfiguration() throws IgniteCheckedException { <ide> if (cfg.isClientMode()) { <ide> } <ide> <ide> /** <del> * <add> * Acknowledge the Ignite configuration related to the data storage. <ide> */ <ide> private void ackMemoryConfiguration() { <ide> DataStorageConfiguration memCfg = cfg.getDataStorageConfiguration(); <ide> } <ide> <ide> /** <del> * <add> * Acknowledge all caches configurations presented in the IgniteConfiguration. <ide> */ <ide> private void ackCacheConfiguration() { <ide> CacheConfiguration[] cacheCfgs = cfg.getCacheConfiguration(); <ide> } <ide> <ide> /** <del> * <add> * Acknowledge configuration related to the peer class loading. <ide> */ <ide> private void ackP2pConfiguration() { <ide> assert cfg != null; <ide> } <ide> <ide> /** <del> * @param cfg Grid configuration. <add> * @param cfg Ignite configuration to use. <ide> * @return Components provided in configuration which can implement {@link LifecycleAware} interface. <ide> */ <ide> private Iterable<Object> lifecycleAwares(IgniteConfiguration cfg) { <ide> <ide> /** <ide> * @param name Cache name. <del> * @return Cache. <add> * @return Ignite internal cache instance related to the given name. <ide> */ <ide> public <K, V> IgniteInternalCache<K, V> getCache(String name) { <ide> CU.validateCacheName(name); <ide> } <ide> <ide> /** <del> * @param cache Cache. <add> * @param cache Ignite cache instance to check. <ide> * @throws IgniteCheckedException If cache without near cache was already started. <ide> */ <ide> private void checkNearCacheStarted(IgniteCacheProxy<?, ?> cache) throws IgniteCheckedException { <ide> /** <ide> * @param cacheNames Collection of cache names. <ide> * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. <del> * @return Ignite future. <add> * @return Ignite future which will be completed when cache is destored. <ide> */ <ide> public IgniteInternalFuture<?> destroyCachesAsync(Collection<String> cacheNames, boolean checkThreadTx) { <ide> CU.validateCacheNames(cacheNames); <ide> } <ide> <ide> /** <del> * @return Public caches. <add> * @return Collection of public cache instances. <ide> */ <ide> public Collection<IgniteCacheProxy<?, ?>> caches() { <ide> guard(); <ide> } <ide> <ide> /** <del> * <tt>ctx.gateway().readLock()</tt> <add> * The {@code ctx.gateway().readLock()} is used underneath. <ide> */ <ide> private void guard() { <ide> assert ctx != null; <ide> } <ide> <ide> /** <del> * <tt>ctx.gateway().readUnlock()</tt> <add> * The {@code ctx.gateway().readUnlock()} is used underneath. <ide> */ <ide> private void unguard() { <ide> assert ctx != null; <ide> /** <ide> * Validate operation on cluster. Check current cluster state. <ide> * <del> * @throws IgniteException if cluster in inActive state <add> * @throws IgniteException If cluster in inActive state. <ide> */ <ide> private void checkClusterState() throws IgniteException { <ide> if (!ctx.state().publicApiActiveState(true)) { <ide> } <ide> <ide> /** <del> * <add> * Method is responsible for handling the {@link EventType#EVT_CLIENT_NODE_DISCONNECTED} event. Notify all the <add> * GridComponents that the such even has been occurred (e.g. if the local client node disconnected from the cluster <add> * components will be notified with a future which will be completed when the client is reconnected). <ide> */ <ide> public void onDisconnected() { <ide> Throwable err = null; <ide> } <ide> <ide> /** <del> * <add> * Class holds client reconnection event handling state. <ide> */ <ide> private class ReconnectState { <del> /** */ <add> /** Future will be completed when the client node connected the first time. */ <ide> private final GridFutureAdapter firstReconnectFut = new GridFutureAdapter(); <ide> <del> /** */ <add> /** <add> * Composed future of all {@link GridComponent#onReconnected(boolean)} callbacks. <add> * The future completes when all Ignite components are finished handle given client reconnect event. <add> */ <ide> private GridCompoundFuture<?, Object> curReconnectFut; <ide> <del> /** */ <add> /** Future completes when reconnection handling is done (doesn't matter successfully or not). */ <ide> private GridFutureAdapter<?> reconnectDone; <ide> <ide> /** <ide> } <ide> <ide> /** <del> * <add> * Wait for the previous reconnection handling finished or force completion if not. <ide> */ <ide> void waitPreviousReconnect() { <ide> if (curReconnectFut != null && !curReconnectFut.isDone()) { <ide> try { <ide> reconnectDone.get(); <ide> } <del> catch (IgniteCheckedException ignote) { <add> catch (IgniteCheckedException ignore) { <ide> // No-op. <ide> } <ide> }
JavaScript
mit
331f6a217c2b33aaa44b1171c376fdefd25b3c78
0
ticketmaster-api/ticketmaster-api.github.io,romil93/ticketmaster-api.github.io,ticketmaster-api/ticketmaster-api.github.io,ticketmaster-api/ticketmaster-api.github.io,romil93/ticketmaster-api.github.io,romil93/ticketmaster-api.github.io,ticketmaster-api/ticketmaster-api.github.io,ticketmaster-api/ticketmaster-api.github.io,romil93/ticketmaster-api.github.io,ticketmaster-api-staging/ticketmaster-api-staging.github.io,ticketmaster-api-staging/ticketmaster-api-staging.github.io
$(document).ready(function() { var getInnerText = function (element) { var html = element.find("code")[0].outerHTML; var proxyItem = document.createElement("div"); proxyItem.innerHTML = html; return proxyItem.textContent; }; var createButton = function(className){ var btn = document.createElement("div"); btn.className = className; return btn; }; var startScreenView = function(){ var content = this.dataset !== undefined ? this.dataset.clipboardText : this.getAttribute("data-clipboard-text"); window.sessionStorage.setItem("content", content); var title = $(this).parent().parent().parent().parent().find('h2') .clone(true) .find('a') .remove() .end() .html(); var content = $(this).parent().parent() .clone(true) .find('.active-lang') .remove() .end() .find('.copy-btn') .addClass('copy-btn-fs') .removeClass('copy-btn') .end() .find('.screen-btn') .attr('data-original-title', 'Exit Full Screen') .end() .find('.tooltip') .remove() .end() .html(); $(".fs-modal #modal-title").html(title); $(".fs-modal .modal-body").html(content); $(".fs-modal .modal-body").delegate(".reqres a", "click", function(event) { event.preventDefault(); $(this).parent().children().removeClass("active"); $(this).addClass("active"); $(this).parents().closest(".modal-body").children().removeClass("active"); $(this).parents().closest(".modal-body").children().eq($(this).index() + 1).addClass("active"); var reqresNo = $(this).parent().parent().attr('class').substr(7); $(".left-wrapper .reqres." + reqresNo + " a").eq($(this).index()).click(); }); }; var startRowView = function(){ var content = this.dataset !== undefined ? this.dataset.contentText : this.getAttribute("data-content-text"); window.sessionStorage.setItem("content", content); var win = window.open(window.location.protocol + "//" + window.location.host + "/products-and-docs/raw-view/", '_blank'); win.focus(); }; var makeCopy = function () { this.classList.add("copied") window.setTimeout(function(){ document.getElementsByClassName("copied")[0].classList.remove("copied"); }, 2000); }; $(".reqres").each(function(index) { $(this).addClass("n" + index); tab1 = $(this).next(); tab2 = $(this).next().next(); var screenbtn1 = createButton("screen-btn"); if(screenbtn1.dataset !== undefined){ screenbtn1.dataset.clipboardText = getInnerText(tab1); } else{ screenbtn1.setAttribute("data-clipboard-text", getInnerText(tab1)); } screenbtn1.addEventListener("click",startScreenView); tab1.prepend(screenbtn1); screenbtn1.setAttribute("data-toggle", "modal"); screenbtn1.setAttribute("data-target", ".modal-langs"); screenbtn1.setAttribute("rel", "tooltip"); screenbtn1.setAttribute("data-placement", "top"); screenbtn1.setAttribute("data-original-title", "View Full Screen"); var rawbtn1 = createButton("raw-btn"); if(rawbtn1.dataset !== undefined){ rawbtn1.dataset.contentText = getInnerText(tab1); } else{ rawbtn1.setAttribute("data-content-text", getInnerText(tab1)); } rawbtn1.addEventListener("click",startRowView); tab1.prepend(rawbtn1); rawbtn1.setAttribute("rel", "tooltip"); rawbtn1.setAttribute("data-placement", "top"); rawbtn1.setAttribute("data-original-title", "View Raw"); var btn1 = createButton("copy-btn"); btn1.dataset.clipboardText = getInnerText(tab1); btn1.addEventListener("click", makeCopy); tab1.prepend(btn1); btn1.setAttribute("rel", "tooltip"); btn1.setAttribute("data-placement", "top"); btn1.setAttribute("data-original-title", "Copy to Clipboard"); var screenbtn2 = createButton("screen-btn"); if(screenbtn2.dataset !== undefined){ screenbtn2.dataset.clipboardText = getInnerText(tab2); } else{ screenbtn2.setAttribute("data-clipboard-text", getInnerText(tab2)); } screenbtn2.addEventListener("click",startScreenView); tab2.prepend(screenbtn2); screenbtn2.setAttribute("data-toggle", "modal"); screenbtn2.setAttribute("data-target", ".modal-langs"); screenbtn2.setAttribute("rel", "tooltip"); screenbtn2.setAttribute("data-placement", "top"); screenbtn2.setAttribute("data-original-title", "View Full Screen"); var rawbtn2 = createButton("raw-btn"); if(rawbtn2.dataset !== undefined){ rawbtn2.dataset.contentText = getInnerText(tab2); } else{ rawbtn2.setAttribute("data-content-text", getInnerText(tab2)); } rawbtn2.addEventListener("click", startRowView); tab2.prepend(rawbtn2); rawbtn2.setAttribute("rel", "tooltip"); rawbtn2.setAttribute("data-placement", "top"); rawbtn2.setAttribute("data-original-title", "View Raw"); var btn2 = createButton("copy-btn"); btn2.dataset.clipboardText = getInnerText(tab2); btn2.addEventListener("click", makeCopy); tab2.prepend(btn2); btn2.setAttribute("rel", "tooltip"); btn2.setAttribute("data-placement", "top"); btn2.setAttribute("data-original-title", "Copy to Clipboard"); $('<div class="reqres-wrapper"></div>').insertBefore($(this)); $(this).prev().append($(this)).append(tab1).append(tab2); $(this).parent().find('a').eq(0).addClass("active"); $(this).next().addClass("r-tab").next().addClass("r-tab"); $(this).next().addClass("active"); }); $(".reqres a").click(function(event) { event.preventDefault(); $(this).parent().find(".active").removeClass("active"); $(this).parent().parent().parent().find(".r-tab.active").removeClass("active"); $(this).parent().parent().parent().find(".r-tab").eq($(this).index()).addClass("active"); $(this).addClass("active"); }); $(function () { $('body').tooltip({ selector: '[rel="tooltip"]' }); /* $('[rel="tooltip"]').tooltip({ animation: true }); */ }) });
scripts/components/request-response.js
$(document).ready(function() { var getInnerText = function (element) { var html = element.find("code")[0].outerHTML; var proxyItem = document.createElement("div"); proxyItem.innerHTML = html; return proxyItem.textContent; }; var createButton = function(className){ var btn = document.createElement("div"); btn.className = className; return btn; }; var startScreenView = function(){ var content = this.dataset !== undefined ? this.dataset.clipboardText : this.getAttribute("data-clipboard-text"); window.sessionStorage.setItem("content", content); var title = $(this).parent().parent().parent().parent().find('h2') .clone(true) .find('a') .remove() .end() .html(); var content = $(this).parent().parent() .clone(true) .find('.active-lang') .remove() .end() .find('.copy-btn') .addClass('copy-btn-fs') .removeClass('copy-btn') .end() .find('.screen-btn') .attr('data-original-title', 'Exit Full Screen') .end() .find('.tooltip') .remove() .end() .html(); $(".fs-modal #modal-title").html(title); $(".fs-modal .modal-body").html(content); $(".fs-modal .modal-body").delegate(".reqres a", "click", function() { $(this).parent().children().removeClass("active"); $(this).addClass("active"); $(this).parents().closest(".modal-body").children().removeClass("active"); $(this).parents().closest(".modal-body").children().eq($(this).index() + 1).addClass("active"); var reqresNo = $(this).parent().parent().attr('class').substr(7); $(".left-wrapper .reqres." + reqresNo + " a").eq($(this).index()).click(); }); }; var startRowView = function(){ var content = this.dataset !== undefined ? this.dataset.contentText : this.getAttribute("data-content-text"); window.sessionStorage.setItem("content", content); var win = window.open(window.location.protocol + "//" + window.location.host + "/products-and-docs/raw-view/", '_blank'); win.focus(); }; var makeCopy = function () { this.classList.add("copied") window.setTimeout(function(){ document.getElementsByClassName("copied")[0].classList.remove("copied"); }, 2000); }; $(".reqres").each(function(index) { $(this).addClass("n" + index); tab1 = $(this).next(); tab2 = $(this).next().next(); var screenbtn1 = createButton("screen-btn"); if(screenbtn1.dataset !== undefined){ screenbtn1.dataset.clipboardText = getInnerText(tab1); } else{ screenbtn1.setAttribute("data-clipboard-text", getInnerText(tab1)); } screenbtn1.addEventListener("click",startScreenView); tab1.prepend(screenbtn1); screenbtn1.setAttribute("data-toggle", "modal"); screenbtn1.setAttribute("data-target", ".modal-langs"); screenbtn1.setAttribute("rel", "tooltip"); screenbtn1.setAttribute("data-placement", "top"); screenbtn1.setAttribute("data-original-title", "View Full Screen"); var rawbtn1 = createButton("raw-btn"); if(rawbtn1.dataset !== undefined){ rawbtn1.dataset.contentText = getInnerText(tab1); } else{ rawbtn1.setAttribute("data-content-text", getInnerText(tab1)); } rawbtn1.addEventListener("click",startRowView); tab1.prepend(rawbtn1); rawbtn1.setAttribute("rel", "tooltip"); rawbtn1.setAttribute("data-placement", "top"); rawbtn1.setAttribute("data-original-title", "View Raw"); var btn1 = createButton("copy-btn"); btn1.dataset.clipboardText = getInnerText(tab1); btn1.addEventListener("click", makeCopy); tab1.prepend(btn1); btn1.setAttribute("rel", "tooltip"); btn1.setAttribute("data-placement", "top"); btn1.setAttribute("data-original-title", "Copy to Clipboard"); var screenbtn2 = createButton("screen-btn"); if(screenbtn2.dataset !== undefined){ screenbtn2.dataset.clipboardText = getInnerText(tab2); } else{ screenbtn2.setAttribute("data-clipboard-text", getInnerText(tab2)); } screenbtn2.addEventListener("click",startScreenView); tab2.prepend(screenbtn2); screenbtn2.setAttribute("data-toggle", "modal"); screenbtn2.setAttribute("data-target", ".modal-langs"); screenbtn2.setAttribute("rel", "tooltip"); screenbtn2.setAttribute("data-placement", "top"); screenbtn2.setAttribute("data-original-title", "View Full Screen"); var rawbtn2 = createButton("raw-btn"); if(rawbtn2.dataset !== undefined){ rawbtn2.dataset.contentText = getInnerText(tab2); } else{ rawbtn2.setAttribute("data-content-text", getInnerText(tab2)); } rawbtn2.addEventListener("click", startRowView); tab2.prepend(rawbtn2); rawbtn2.setAttribute("rel", "tooltip"); rawbtn2.setAttribute("data-placement", "top"); rawbtn2.setAttribute("data-original-title", "View Raw"); var btn2 = createButton("copy-btn"); btn2.dataset.clipboardText = getInnerText(tab2); btn2.addEventListener("click", makeCopy); tab2.prepend(btn2); btn2.setAttribute("rel", "tooltip"); btn2.setAttribute("data-placement", "top"); btn2.setAttribute("data-original-title", "Copy to Clipboard"); $('<div class="reqres-wrapper"></div>').insertBefore($(this)); $(this).prev().append($(this)).append(tab1).append(tab2); $(this).parent().find('a').eq(0).addClass("active"); $(this).next().addClass("r-tab").next().addClass("r-tab"); $(this).next().addClass("active"); }); $(".reqres a").click(function(event) { $(this).parent().find(".active").removeClass("active"); $(this).parent().parent().parent().find(".r-tab.active").removeClass("active"); $(this).parent().parent().parent().find(".r-tab").eq($(this).index()).addClass("active"); $(this).addClass("active"); }); $(function () { $('body').tooltip({ selector: '[rel="tooltip"]' }); /* $('[rel="tooltip"]').tooltip({ animation: true }); */ }) });
Changelog
scripts/components/request-response.js
Changelog
<ide><path>cripts/components/request-response.js <ide> $(".fs-modal #modal-title").html(title); <ide> $(".fs-modal .modal-body").html(content); <ide> <del> $(".fs-modal .modal-body").delegate(".reqres a", "click", function() { <add> $(".fs-modal .modal-body").delegate(".reqres a", "click", function(event) { <add> event.preventDefault(); <ide> $(this).parent().children().removeClass("active"); <ide> $(this).addClass("active"); <ide> $(this).parents().closest(".modal-body").children().removeClass("active"); <ide> }); <ide> <ide> $(".reqres a").click(function(event) { <add> event.preventDefault(); <ide> $(this).parent().find(".active").removeClass("active"); <ide> $(this).parent().parent().parent().find(".r-tab.active").removeClass("active"); <ide> $(this).parent().parent().parent().find(".r-tab").eq($(this).index()).addClass("active");
Java
apache-2.0
29e3909c5bb767d711ee64be92107592a68df036
0
myrrix/myrrix-recommender,myrrix/myrrix-recommender
/* * Copyright Myrrix Ltd * * 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 net.myrrix.client; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.zip.GZIPOutputStream; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.io.CharStreams; import com.google.common.io.Closeables; import org.apache.mahout.cf.taste.common.NoSuchItemException; import org.apache.mahout.cf.taste.common.NoSuchUserException; import org.apache.mahout.cf.taste.common.Refreshable; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.impl.common.FastIDSet; import org.apache.mahout.cf.taste.impl.recommender.GenericRecommendedItem; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.recommender.IDRescorer; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.Rescorer; import org.apache.mahout.common.LongPair; import org.apache.mahout.common.Pair; import org.apache.mahout.common.RandomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.myrrix.common.io.IOUtils; import net.myrrix.common.LangUtils; import net.myrrix.common.MyrrixRecommender; import net.myrrix.common.NotReadyException; /** * <p>An implementation of {@link MyrrixRecommender} which accesses a remote Serving Layer instance * over HTTP or HTTPS. This is like a local "handle" on the remote recommender.</p> * * <p>It is useful to note here, again, that the API methods {@link #setPreference(long, long)} * and {@link #removePreference(long, long)}, retained from Apache Mahout, have a somewhat different meaning * than in Mahout. They add to an association strength, rather than replace it. See the javadoc.</p> * * <p>There are a few advanced, system-wide parameters that can be set to affect how the client works. * These should not normally be used:</p> * * <ul> * <li>{@code client.connection.close}: Causes the client to request no HTTP keep-alive. This can avoid * running out of local sockets on the client side during load testing, but should not otherwise be set.</li> * <li>{@code client.https.ignoreHost}: When using HTTPS, ignore the host specified in the certificate. This * can make development easier, but must not be used in production.</li> * </ul> * * @author Sean Owen */ public final class ClientRecommender implements MyrrixRecommender { private static final Logger log = LoggerFactory.getLogger(ClientRecommender.class); private static final Splitter COMMA = Splitter.on(','); private static final String IGNORE_HOSTNAME_KEY = "client.https.ignoreHost"; private static final String CONNECTION_CLOSE_KEY = "client.connection.close"; private final MyrrixClientConfiguration config; private final boolean needAuthentication; private final boolean closeConnection; private final boolean ignoreHTTPSHost; private final List<List<Pair<String,Integer>>> partitions; private final Random random; /** * Instantiates a new recommender client with the given configuration * * @param config configuration to use with this client * @throws IOException if the HTTP client encounters an error during configuration */ public ClientRecommender(MyrrixClientConfiguration config) throws IOException { Preconditions.checkNotNull(config); this.config = config; final String userName = config.getUserName(); final String password = config.getPassword(); needAuthentication = userName != null && password != null; if (needAuthentication) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray()); } }); } if (config.getKeystoreFile() != null) { log.warn("A keystore file has been specified. " + "This should only be done to accept self-signed certificates in development."); HttpsURLConnection.setDefaultSSLSocketFactory(buildSSLSocketFactory()); } closeConnection = Boolean.valueOf(System.getProperty(CONNECTION_CLOSE_KEY)); ignoreHTTPSHost = Boolean.valueOf(System.getProperty(IGNORE_HOSTNAME_KEY)); partitions = config.getPartitions(); random = RandomUtils.getRandom(); } private SSLSocketFactory buildSSLSocketFactory() throws IOException { final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ @Override public boolean verify(String hostname, SSLSession sslSession) { return ignoreHTTPSHost || "localhost".equals(hostname) || "127.0.0.1".equals(hostname) || defaultVerifier.verify(hostname, sslSession); } }); try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); File trustStoreFile = config.getKeystoreFile(); String password = config.getKeystorePassword(); Preconditions.checkNotNull(password); InputStream in = new FileInputStream(trustStoreFile); try { keyStore.load(in, password.toCharArray()); } finally { Closeables.closeQuietly(in); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, tmf.getTrustManagers(), null); return ctx.getSocketFactory(); } catch (NoSuchAlgorithmException nsae) { // can't happen? throw new IllegalStateException(nsae); } catch (KeyStoreException kse) { throw new IOException(kse); } catch (KeyManagementException kme) { throw new IOException(kme); } catch (CertificateException ce) { throw new IOException(ce); } } /** * @param path URL to access * @param method HTTP method to use * @param partitionID ID value that determines partition, or {@code null} if no partition is needed * @return a {@link HttpURLConnection} to the Serving Layer with default configuration in place */ private HttpURLConnection makeConnection(String path, String method, Long partitionID) throws IOException { String protocol = config.isSecure() ? "https" : "http"; Pair<String,Integer> replica = choosePartitionAndReplica(partitionID); URL url; try { url = new URL(protocol, replica.getFirst(), replica.getSecond(), path); } catch (MalformedURLException mue) { // can't happen throw new IllegalStateException(mue); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept", "text/csv"); if (closeConnection) { connection.setRequestProperty("Connection", "close"); } return connection; } private Pair<String,Integer> choosePartitionAndReplica(Long id) { List<Pair<String,Integer>> replicas; int numPartitions = partitions.size(); if (numPartitions == 1) { replicas = partitions.get(0); } else { if (id == null) { // No need to partition, use one at random replicas = partitions.get(random.nextInt(numPartitions)); } else { replicas = partitions.get(partition(id)); } } int numReplicas = replicas.size(); return numReplicas == 1 ? replicas.get(0) : replicas.get(random.nextInt(numReplicas)); } private int partition(long id) { return LangUtils.mod(id, partitions.size()); } /** * Calls {@link #setPreference(long, long, float)} with value 1.0. */ @Override public void setPreference(long userID, long itemID) throws TasteException { setPreference(userID, itemID, 1.0f); } @Override public void setPreference(long userID, long itemID, float value) throws TasteException { doSetOrRemove(userID, itemID, value, true); } @Override public void removePreference(long userID, long itemID) throws TasteException { doSetOrRemove(userID, itemID, 1.0f, false); // 1.0 is a dummy value that gets ignored } private void doSetOrRemove(long userID, long itemID, float value, boolean set) throws TasteException { boolean sendValue = value != 1.0f; try { String method = set ? "POST" : "DELETE"; HttpURLConnection connection = makeConnection("/pref/" + userID + '/' + itemID, method, userID); connection.setDoOutput(sendValue); try { if (sendValue) { byte[] bytes = Float.toString(value).getBytes(Charsets.UTF_8); connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8"); connection.setRequestProperty("Content-Length", Integer.toString(bytes.length)); OutputStream out = connection.getOutputStream(); out.write(bytes); Closeables.closeQuietly(out); } // Should not be able to return Not Available status if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } /** * @param userID user ID whose preference is to be estimated * @param itemID item ID to estimate preference for * @return an estimate of the strength of the association between the user and item. These values are the * same as will be returned from {@link #recommend(long, int)}. They are opaque values and have no interpretation * other than that larger means stronger. The values are typically in the range [0,1] but are not guaranteed * to be so. * @throws NoSuchUserException if the user is not known in the model * @throws NoSuchItemException if the item is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs */ @Override public float estimatePreference(long userID, long itemID) throws TasteException { float[] results = estimatePreferences(userID, itemID); return results[0]; } @Override public float[] estimatePreferences(long userID, long... itemIDs) throws TasteException { StringBuilder urlPath = new StringBuilder(); urlPath.append("/estimate/"); urlPath.append(userID); for (long itemID : itemIDs) { urlPath.append('/').append(itemID); } try { HttpURLConnection connection = makeConnection(urlPath.toString(), "GET", userID); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(userID + "/" + Arrays.toString(itemIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8)); try { float[] result = new float[itemIDs.length]; for (int i = 0; i < itemIDs.length; i++) { result[i] = LangUtils.parseFloat(reader.readLine()); } return result; } finally { Closeables.closeQuietly(reader); } } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } /** * Like {@link #recommend(long, int, boolean, IDRescorer)}, and sets {@code considerKnownItems} to {@code false} * and {@code rescorer} to {@code null}. */ @Override public List<RecommendedItem> recommend(long userID, int howMany) throws TasteException { return recommend(userID, howMany, false, null); } /** * <p>Note that {@link IDRescorer} is not supported in the client now and must be null.</p> * * @param userID user for which recommendations are to be computed * @param howMany desired number of recommendations * @param considerKnownItems if true, items that the user is already associated to are candidates * for recommendation. Normally this is {@code false}. * @param rescorer must be null * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least * @throws NoSuchUserException if the user is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs * @throws UnsupportedOperationException if rescorer is not null */ @Override public List<RecommendedItem> recommend(long userID, int howMany, boolean considerKnownItems, IDRescorer rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } StringBuilder urlPath = new StringBuilder(); urlPath.append("/recommend/"); urlPath.append(userID); urlPath.append("?howMany=").append(howMany); if (considerKnownItems) { urlPath.append("&considerKnownItems=true"); } try { HttpURLConnection connection = makeConnection(urlPath.toString(), "GET", userID); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchUserException(userID); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeItems(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } private static List<RecommendedItem> consumeItems(HttpURLConnection connection) throws IOException { List<RecommendedItem> result = Lists.newArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8)); try { String line; while ((line = reader.readLine()) != null) { Iterator<String> tokens = COMMA.split(line).iterator(); long itemID = Long.parseLong(tokens.next()); float value = LangUtils.parseFloat(tokens.next()); result.add(new GenericRecommendedItem(itemID, value)); } } finally { Closeables.closeQuietly(reader); } return result; } /** * <p>Note that {@link IDRescorer} is not supported in the client now and must be null.</p> * * @param userIDs users for which recommendations are to be computed * @param howMany desired number of recommendations * @param considerKnownItems if true, items that the user is already associated to are candidates * for recommendation. Normally this is {@code false}. * @param rescorer must be null * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least * @throws NoSuchUserException if the user is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs * @throws UnsupportedOperationException if rescorer is not null */ @Override public List<RecommendedItem> recommendToMany(long[] userIDs, int howMany, boolean considerKnownItems, IDRescorer rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } StringBuilder urlPath = new StringBuilder(); urlPath.append("/recommendToMany"); for (long userID : userIDs) { urlPath.append('/').append(userID); } urlPath.append("?howMany=").append(howMany); Integer requiredPartition = null; for (long userID : userIDs) { if (requiredPartition == null) { requiredPartition = partition(userID); } else { if (requiredPartition != partition(userID)) { throw new IllegalArgumentException("Not all user IDs are on the same partition"); } } } try { HttpURLConnection connection = makeConnection(urlPath.toString(), "GET", userIDs[0]); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchUserException(Arrays.toString(userIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeItems(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } @Override public List<RecommendedItem> recommendToAnonymous(long[] itemIDs, int howMany) throws TasteException { return anonymousOrSimilar(itemIDs, howMany, "/recommendToAnonymous"); } /** * Computes items most similar to an item or items. The returned items have the highest average similarity * to the given items. * * @param itemIDs items for which most similar items are required * @param howMany maximum number of similar items to return; fewer may be returned * @return {@link RecommendedItem}s representing the top recommendations for the user, ordered by quality, * descending. The score associated to it is an opaque value. Larger means more similar, but no further * interpretation may necessarily be applied. * @throws NoSuchItemException if any of the items is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs */ @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany) throws TasteException { return anonymousOrSimilar(itemIDs, howMany, "/similarity"); } private List<RecommendedItem> anonymousOrSimilar(long[] itemIDs, int howMany, String path) throws TasteException { StringBuilder urlPath = new StringBuilder(); urlPath.append(path); for (long itemID : itemIDs) { urlPath.append('/').append(itemID); } urlPath.append("?howMany=").append(howMany); try { HttpURLConnection connection = makeConnection(urlPath.toString(), "GET", null); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(Arrays.toString(itemIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeItems(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } /** * One-argument version of {@link #mostSimilarItems(long[], int)}. */ @Override public List<RecommendedItem> mostSimilarItems(long itemID, int howMany) throws TasteException { return mostSimilarItems(new long[] { itemID }, howMany); } /** * <p>Lists the items that were most influential in recommending a given item to a given user. Exactly how this * is determined is left to the implementation, but, generally this will return items that the user prefers * and that are similar to the given item.</p> * * <p>These values by which the results are ordered are opaque values and have no interpretation * other than that larger means stronger.</p> * * @param userID ID of user who was recommended the item * @param itemID ID of item that was recommended * @param howMany maximum number of items to return * @return {@link List} of {@link RecommendedItem}, ordered from most influential in recommended the given * item to least * @throws NoSuchUserException if the user is not known in the model * @throws NoSuchItemException if the item is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs */ @Override public List<RecommendedItem> recommendedBecause(long userID, long itemID, int howMany) throws TasteException { try { HttpURLConnection connection = makeConnection("/because/" + userID + '/' + itemID + "?howMany=" + howMany, "GET", userID); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(userID + '/' + itemID); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeItems(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } @Override public void ingest(File file) throws TasteException { Reader reader = null; try { reader = new InputStreamReader(IOUtils.openMaybeDecompressing(file), Charsets.UTF_8); ingest(reader); } catch (IOException ioe) { throw new TasteException(ioe); } finally { Closeables.closeQuietly(reader); } } @Override public void ingest(Reader reader) throws TasteException { try { HttpURLConnection connection = makeConnection("/ingest", "POST", null); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8"); connection.setRequestProperty("Content-Encoding", "gzip"); if (needAuthentication) { log.info("Authentication is enabled, so ingest data must be buffered in memory"); } else { connection.setChunkedStreamingMode(0); // Use default buffer size } // Must buffer in memory if using authentication since it won't handle the authorization challenge // otherwise -- client will have to buffer all in memory try { Writer out = new OutputStreamWriter(new GZIPOutputStream(connection.getOutputStream()), Charsets.UTF_8); try { CharStreams.copy(reader, out); } finally { out.close(); // Want to know of output stream close failed -- maybe failed to write } // Should not be able to return Not Available status if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } /** * Requests that the Serving Layer recompute its models. This is a request, and may or may not result * in an update. * * @param alreadyRefreshed should be null */ @Override public void refresh(Collection<Refreshable> alreadyRefreshed) { try { HttpURLConnection connection = makeConnection("/refresh", "POST", null); try { if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { log.warn("Unable to refresh; continuing"); } } finally { connection.disconnect(); } } catch (IOException ioe) { log.warn("Unable to refresh; continuing"); } } /** * Not available. The client does not directly use any {@link DataModel}. * * @throws UnsupportedOperationException * @deprecated do not call */ @Deprecated @Override public DataModel getDataModel() { throw new UnsupportedOperationException(); } /** * {@link Rescorer}s are not available at this time in the model. * * @return {@link #recommend(long, int)} if rescorer is null * @throws UnsupportedOperationException otherwise * @deprecated use {@link #recommend(long, int)} instead */ @Deprecated @Override public List<RecommendedItem> recommend(long userID, int howMany, IDRescorer rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } return recommend(userID, howMany); } /** * {@link Rescorer}s are not available at this time in the model. * * @return {@link #mostSimilarItems(long, int)} if rescorer is null * @throws UnsupportedOperationException otherwise * @deprecated use {@link #mostSimilarItems(long, int)} instead */ @Deprecated @Override public List<RecommendedItem> mostSimilarItems(long itemID, int howMany, Rescorer<LongPair> rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } return mostSimilarItems(itemID, howMany); } /** * {@link Rescorer}s are not available at this time in the model. * * @return {@link #mostSimilarItems(long[], int)} if rescorer is null * @throws UnsupportedOperationException otherwise * @deprecated use {@link #mostSimilarItems(long[], int)} instead */ @Deprecated @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany, Rescorer<LongPair> rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } return mostSimilarItems(itemIDs, howMany); } /** * {@code excludeItemIfNotSimilarToAll} is not applicable in this implementation. * * @return {@link #mostSimilarItems(long[], int)} if excludeItemIfNotSimilarToAll is false * @throws UnsupportedOperationException otherwise * @deprecated use {@link #mostSimilarItems(long[], int)} instead */ @Deprecated @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany, boolean excludeItemIfNotSimilarToAll) throws TasteException { if (excludeItemIfNotSimilarToAll) { throw new UnsupportedOperationException(); } return mostSimilarItems(itemIDs, howMany); } /** * {@link Rescorer}s are not available at this time in the model. * {@code excludeItemIfNotSimilarToAll} is not applicable in this implementation. * * @return {@link #mostSimilarItems(long[], int)} if excludeItemIfNotSimilarToAll is false and rescorer is null * @throws UnsupportedOperationException otherwise * @deprecated use {@link #mostSimilarItems(long[], int)} instead */ @Deprecated @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany, Rescorer<LongPair> rescorer, boolean excludeItemIfNotSimilarToAll) throws TasteException { if (excludeItemIfNotSimilarToAll || rescorer != null) { throw new UnsupportedOperationException(); } return mostSimilarItems(itemIDs, howMany); } @Override public boolean isReady() throws TasteException { try { HttpURLConnection connection = makeConnection("/ready", "HEAD", null); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return true; case HttpURLConnection.HTTP_UNAVAILABLE: return false; default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } @Override public void await() throws TasteException { while (!isReady()) { try { Thread.sleep(1000L); } catch (InterruptedException e) { // continue } } } @Override public FastIDSet getAllUserIDs() throws TasteException { try { FastIDSet result = new FastIDSet(); int numPartitions = partitions.size(); for (int i = 0; i < numPartitions; i++) { getAllUserIDsFromPartition(i, result); } return result; } catch (IOException ioe) { throw new TasteException(ioe); } } private void getAllUserIDsFromPartition(int partition, FastIDSet result) throws IOException, TasteException { HttpURLConnection connection = makeConnection("/user/allIDs", "GET", (long) partition); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } consumeIDs(connection, result); } finally { connection.disconnect(); } } @Override public FastIDSet getAllItemIDs() throws TasteException { try { HttpURLConnection connection = makeConnection("/item/allIDs", "GET", null); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeIDs(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } private static FastIDSet consumeIDs(HttpURLConnection connection) throws IOException { FastIDSet result = new FastIDSet(); consumeIDs(connection, result); return result; } private static void consumeIDs(HttpURLConnection connection, FastIDSet result) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8)); try { String line; while ((line = reader.readLine()) != null) { result.add(Long.parseLong(line)); } } finally { Closeables.closeQuietly(reader); } } }
client/src/net/myrrix/client/ClientRecommender.java
/* * Copyright Myrrix Ltd * * 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 net.myrrix.client; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.zip.GZIPOutputStream; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.io.CharStreams; import com.google.common.io.Closeables; import org.apache.mahout.cf.taste.common.NoSuchItemException; import org.apache.mahout.cf.taste.common.NoSuchUserException; import org.apache.mahout.cf.taste.common.Refreshable; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.impl.common.FastIDSet; import org.apache.mahout.cf.taste.impl.recommender.GenericRecommendedItem; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.recommender.IDRescorer; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.Rescorer; import org.apache.mahout.common.LongPair; import org.apache.mahout.common.Pair; import org.apache.mahout.common.RandomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.myrrix.common.io.IOUtils; import net.myrrix.common.LangUtils; import net.myrrix.common.MyrrixRecommender; import net.myrrix.common.NotReadyException; /** * <p>An implementation of {@link MyrrixRecommender} which accesses a remote Serving Layer instance * over HTTP or HTTPS. This is like a local "handle" on the remote recommender.</p> * * <p>It is useful to note here, again, that the API methods {@link #setPreference(long, long)} * and {@link #removePreference(long, long)}, retained from Apache Mahout, have a somewhat different meaning * than in Mahout. They add to an association strength, rather than replace it. See the javadoc.</p> * * <p>There are a few advanced, system-wide parameters that can be set to affect how the client works. * These should not normally be used:</p> * * <ul> * <li>{@code client.connection.close}: Causes the client to request no HTTP keep-alive. This can avoid * running out of local sockets on the client side during load testing, but should not otherwise be set.</li> * </ul> * * @author Sean Owen */ public final class ClientRecommender implements MyrrixRecommender { private static final Logger log = LoggerFactory.getLogger(ClientRecommender.class); private static final Splitter COMMA = Splitter.on(','); private final MyrrixClientConfiguration config; private final boolean needAuthentication; private final boolean closeConnection; private final List<List<Pair<String,Integer>>> partitions; private final Random random; /** * Instantiates a new recommender client with the given configuration * * @param config configuration to use with this client * @throws IOException if the HTTP client encounters an error during configuration */ public ClientRecommender(MyrrixClientConfiguration config) throws IOException { Preconditions.checkNotNull(config); this.config = config; final String userName = config.getUserName(); final String password = config.getPassword(); needAuthentication = userName != null && password != null; if (needAuthentication) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray()); } }); } if (config.getKeystoreFile() != null) { log.warn("A keystore file has been specified. " + "This should only be done to accept self-signed certificates in development."); HttpsURLConnection.setDefaultSSLSocketFactory(buildSSLSocketFactory()); } closeConnection = Boolean.valueOf(System.getProperty("client.connection.close")); partitions = config.getPartitions(); random = RandomUtils.getRandom(); } private SSLSocketFactory buildSSLSocketFactory() throws IOException { final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ @Override public boolean verify(String hostname, SSLSession sslSession) { return "localhost".equals(hostname) || "127.0.0.1".equals(hostname) || defaultVerifier.verify(hostname, sslSession); } }); try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); File trustStoreFile = config.getKeystoreFile(); String password = config.getKeystorePassword(); Preconditions.checkNotNull(password); InputStream in = new FileInputStream(trustStoreFile); try { keyStore.load(in, password.toCharArray()); } finally { Closeables.closeQuietly(in); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, tmf.getTrustManagers(), null); return ctx.getSocketFactory(); } catch (NoSuchAlgorithmException nsae) { // can't happen? throw new IllegalStateException(nsae); } catch (KeyStoreException kse) { throw new IOException(kse); } catch (KeyManagementException kme) { throw new IOException(kme); } catch (CertificateException ce) { throw new IOException(ce); } } /** * @param path URL to access * @param method HTTP method to use * @param partitionID ID value that determines partition, or {@code null} if no partition is needed * @return a {@link HttpURLConnection} to the Serving Layer with default configuration in place */ private HttpURLConnection makeConnection(String path, String method, Long partitionID) throws IOException { String protocol = config.isSecure() ? "https" : "http"; Pair<String,Integer> replica = choosePartitionAndReplica(partitionID); URL url; try { url = new URL(protocol, replica.getFirst(), replica.getSecond(), path); } catch (MalformedURLException mue) { // can't happen throw new IllegalStateException(mue); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept", "text/csv"); if (closeConnection) { connection.setRequestProperty("Connection", "close"); } return connection; } private Pair<String,Integer> choosePartitionAndReplica(Long id) { List<Pair<String,Integer>> replicas; int numPartitions = partitions.size(); if (numPartitions == 1) { replicas = partitions.get(0); } else { if (id == null) { // No need to partition, use one at random replicas = partitions.get(random.nextInt(numPartitions)); } else { replicas = partitions.get(partition(id)); } } int numReplicas = replicas.size(); return numReplicas == 1 ? replicas.get(0) : replicas.get(random.nextInt(numReplicas)); } private int partition(long id) { return LangUtils.mod(id, partitions.size()); } /** * Calls {@link #setPreference(long, long, float)} with value 1.0. */ @Override public void setPreference(long userID, long itemID) throws TasteException { setPreference(userID, itemID, 1.0f); } @Override public void setPreference(long userID, long itemID, float value) throws TasteException { doSetOrRemove(userID, itemID, value, true); } @Override public void removePreference(long userID, long itemID) throws TasteException { doSetOrRemove(userID, itemID, 1.0f, false); // 1.0 is a dummy value that gets ignored } private void doSetOrRemove(long userID, long itemID, float value, boolean set) throws TasteException { boolean sendValue = value != 1.0f; try { String method = set ? "POST" : "DELETE"; HttpURLConnection connection = makeConnection("/pref/" + userID + '/' + itemID, method, userID); connection.setDoOutput(sendValue); try { if (sendValue) { byte[] bytes = Float.toString(value).getBytes(Charsets.UTF_8); connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8"); connection.setRequestProperty("Content-Length", Integer.toString(bytes.length)); OutputStream out = connection.getOutputStream(); out.write(bytes); Closeables.closeQuietly(out); } // Should not be able to return Not Available status if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } /** * @param userID user ID whose preference is to be estimated * @param itemID item ID to estimate preference for * @return an estimate of the strength of the association between the user and item. These values are the * same as will be returned from {@link #recommend(long, int)}. They are opaque values and have no interpretation * other than that larger means stronger. The values are typically in the range [0,1] but are not guaranteed * to be so. * @throws NoSuchUserException if the user is not known in the model * @throws NoSuchItemException if the item is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs */ @Override public float estimatePreference(long userID, long itemID) throws TasteException { float[] results = estimatePreferences(userID, itemID); return results[0]; } @Override public float[] estimatePreferences(long userID, long... itemIDs) throws TasteException { StringBuilder urlPath = new StringBuilder(); urlPath.append("/estimate/"); urlPath.append(userID); for (long itemID : itemIDs) { urlPath.append('/').append(itemID); } try { HttpURLConnection connection = makeConnection(urlPath.toString(), "GET", userID); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(userID + "/" + Arrays.toString(itemIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8)); try { float[] result = new float[itemIDs.length]; for (int i = 0; i < itemIDs.length; i++) { result[i] = LangUtils.parseFloat(reader.readLine()); } return result; } finally { Closeables.closeQuietly(reader); } } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } /** * Like {@link #recommend(long, int, boolean, IDRescorer)}, and sets {@code considerKnownItems} to {@code false} * and {@code rescorer} to {@code null}. */ @Override public List<RecommendedItem> recommend(long userID, int howMany) throws TasteException { return recommend(userID, howMany, false, null); } /** * <p>Note that {@link IDRescorer} is not supported in the client now and must be null.</p> * * @param userID user for which recommendations are to be computed * @param howMany desired number of recommendations * @param considerKnownItems if true, items that the user is already associated to are candidates * for recommendation. Normally this is {@code false}. * @param rescorer must be null * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least * @throws NoSuchUserException if the user is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs * @throws UnsupportedOperationException if rescorer is not null */ @Override public List<RecommendedItem> recommend(long userID, int howMany, boolean considerKnownItems, IDRescorer rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } StringBuilder urlPath = new StringBuilder(); urlPath.append("/recommend/"); urlPath.append(userID); urlPath.append("?howMany=").append(howMany); if (considerKnownItems) { urlPath.append("&considerKnownItems=true"); } try { HttpURLConnection connection = makeConnection(urlPath.toString(), "GET", userID); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchUserException(userID); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeItems(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } private static List<RecommendedItem> consumeItems(HttpURLConnection connection) throws IOException { List<RecommendedItem> result = Lists.newArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8)); try { String line; while ((line = reader.readLine()) != null) { Iterator<String> tokens = COMMA.split(line).iterator(); long itemID = Long.parseLong(tokens.next()); float value = LangUtils.parseFloat(tokens.next()); result.add(new GenericRecommendedItem(itemID, value)); } } finally { Closeables.closeQuietly(reader); } return result; } /** * <p>Note that {@link IDRescorer} is not supported in the client now and must be null.</p> * * @param userIDs users for which recommendations are to be computed * @param howMany desired number of recommendations * @param considerKnownItems if true, items that the user is already associated to are candidates * for recommendation. Normally this is {@code false}. * @param rescorer must be null * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least * @throws NoSuchUserException if the user is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs * @throws UnsupportedOperationException if rescorer is not null */ @Override public List<RecommendedItem> recommendToMany(long[] userIDs, int howMany, boolean considerKnownItems, IDRescorer rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } StringBuilder urlPath = new StringBuilder(); urlPath.append("/recommendToMany"); for (long userID : userIDs) { urlPath.append('/').append(userID); } urlPath.append("?howMany=").append(howMany); Integer requiredPartition = null; for (long userID : userIDs) { if (requiredPartition == null) { requiredPartition = partition(userID); } else { if (requiredPartition != partition(userID)) { throw new IllegalArgumentException("Not all user IDs are on the same partition"); } } } try { HttpURLConnection connection = makeConnection(urlPath.toString(), "GET", userIDs[0]); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchUserException(Arrays.toString(userIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeItems(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } @Override public List<RecommendedItem> recommendToAnonymous(long[] itemIDs, int howMany) throws TasteException { return anonymousOrSimilar(itemIDs, howMany, "/recommendToAnonymous"); } /** * Computes items most similar to an item or items. The returned items have the highest average similarity * to the given items. * * @param itemIDs items for which most similar items are required * @param howMany maximum number of similar items to return; fewer may be returned * @return {@link RecommendedItem}s representing the top recommendations for the user, ordered by quality, * descending. The score associated to it is an opaque value. Larger means more similar, but no further * interpretation may necessarily be applied. * @throws NoSuchItemException if any of the items is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs */ @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany) throws TasteException { return anonymousOrSimilar(itemIDs, howMany, "/similarity"); } private List<RecommendedItem> anonymousOrSimilar(long[] itemIDs, int howMany, String path) throws TasteException { StringBuilder urlPath = new StringBuilder(); urlPath.append(path); for (long itemID : itemIDs) { urlPath.append('/').append(itemID); } urlPath.append("?howMany=").append(howMany); try { HttpURLConnection connection = makeConnection(urlPath.toString(), "GET", null); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(Arrays.toString(itemIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeItems(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } /** * One-argument version of {@link #mostSimilarItems(long[], int)}. */ @Override public List<RecommendedItem> mostSimilarItems(long itemID, int howMany) throws TasteException { return mostSimilarItems(new long[] { itemID }, howMany); } /** * <p>Lists the items that were most influential in recommending a given item to a given user. Exactly how this * is determined is left to the implementation, but, generally this will return items that the user prefers * and that are similar to the given item.</p> * * <p>These values by which the results are ordered are opaque values and have no interpretation * other than that larger means stronger.</p> * * @param userID ID of user who was recommended the item * @param itemID ID of item that was recommended * @param howMany maximum number of items to return * @return {@link List} of {@link RecommendedItem}, ordered from most influential in recommended the given * item to least * @throws NoSuchUserException if the user is not known in the model * @throws NoSuchItemException if the item is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs */ @Override public List<RecommendedItem> recommendedBecause(long userID, long itemID, int howMany) throws TasteException { try { HttpURLConnection connection = makeConnection("/because/" + userID + '/' + itemID + "?howMany=" + howMany, "GET", userID); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(userID + '/' + itemID); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeItems(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } @Override public void ingest(File file) throws TasteException { Reader reader = null; try { reader = new InputStreamReader(IOUtils.openMaybeDecompressing(file), Charsets.UTF_8); ingest(reader); } catch (IOException ioe) { throw new TasteException(ioe); } finally { Closeables.closeQuietly(reader); } } @Override public void ingest(Reader reader) throws TasteException { try { HttpURLConnection connection = makeConnection("/ingest", "POST", null); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8"); connection.setRequestProperty("Content-Encoding", "gzip"); if (!needAuthentication) { connection.setChunkedStreamingMode(0); // Use default buffer size } // Must buffer in memory if using authentication since it won't handle the authorization challenge // otherwise -- client will have to buffer all in memory try { Writer out = new OutputStreamWriter(new GZIPOutputStream(connection.getOutputStream()), Charsets.UTF_8); try { CharStreams.copy(reader, out); } finally { out.close(); // Want to know of output stream close failed -- maybe failed to write } // Should not be able to return Not Available status if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } /** * Requests that the Serving Layer recompute its models. This is a request, and may or may not result * in an update. * * @param alreadyRefreshed should be null */ @Override public void refresh(Collection<Refreshable> alreadyRefreshed) { try { HttpURLConnection connection = makeConnection("/refresh", "POST", null); try { if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { log.warn("Unable to refresh; continuing"); } } finally { connection.disconnect(); } } catch (IOException ioe) { log.warn("Unable to refresh; continuing"); } } /** * Not available. The client does not directly use any {@link DataModel}. * * @throws UnsupportedOperationException * @deprecated do not call */ @Deprecated @Override public DataModel getDataModel() { throw new UnsupportedOperationException(); } /** * {@link Rescorer}s are not available at this time in the model. * * @return {@link #recommend(long, int)} if rescorer is null * @throws UnsupportedOperationException otherwise * @deprecated use {@link #recommend(long, int)} instead */ @Deprecated @Override public List<RecommendedItem> recommend(long userID, int howMany, IDRescorer rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } return recommend(userID, howMany); } /** * {@link Rescorer}s are not available at this time in the model. * * @return {@link #mostSimilarItems(long, int)} if rescorer is null * @throws UnsupportedOperationException otherwise * @deprecated use {@link #mostSimilarItems(long, int)} instead */ @Deprecated @Override public List<RecommendedItem> mostSimilarItems(long itemID, int howMany, Rescorer<LongPair> rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } return mostSimilarItems(itemID, howMany); } /** * {@link Rescorer}s are not available at this time in the model. * * @return {@link #mostSimilarItems(long[], int)} if rescorer is null * @throws UnsupportedOperationException otherwise * @deprecated use {@link #mostSimilarItems(long[], int)} instead */ @Deprecated @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany, Rescorer<LongPair> rescorer) throws TasteException { if (rescorer != null) { throw new UnsupportedOperationException(); } return mostSimilarItems(itemIDs, howMany); } /** * {@code excludeItemIfNotSimilarToAll} is not applicable in this implementation. * * @return {@link #mostSimilarItems(long[], int)} if excludeItemIfNotSimilarToAll is false * @throws UnsupportedOperationException otherwise * @deprecated use {@link #mostSimilarItems(long[], int)} instead */ @Deprecated @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany, boolean excludeItemIfNotSimilarToAll) throws TasteException { if (excludeItemIfNotSimilarToAll) { throw new UnsupportedOperationException(); } return mostSimilarItems(itemIDs, howMany); } /** * {@link Rescorer}s are not available at this time in the model. * {@code excludeItemIfNotSimilarToAll} is not applicable in this implementation. * * @return {@link #mostSimilarItems(long[], int)} if excludeItemIfNotSimilarToAll is false and rescorer is null * @throws UnsupportedOperationException otherwise * @deprecated use {@link #mostSimilarItems(long[], int)} instead */ @Deprecated @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany, Rescorer<LongPair> rescorer, boolean excludeItemIfNotSimilarToAll) throws TasteException { if (excludeItemIfNotSimilarToAll || rescorer != null) { throw new UnsupportedOperationException(); } return mostSimilarItems(itemIDs, howMany); } @Override public boolean isReady() throws TasteException { try { HttpURLConnection connection = makeConnection("/ready", "HEAD", null); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return true; case HttpURLConnection.HTTP_UNAVAILABLE: return false; default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } @Override public void await() throws TasteException { while (!isReady()) { try { Thread.sleep(1000L); } catch (InterruptedException e) { // continue } } } @Override public FastIDSet getAllUserIDs() throws TasteException { try { FastIDSet result = new FastIDSet(); int numPartitions = partitions.size(); for (int i = 0; i < numPartitions; i++) { getAllUserIDsFromPartition(i, result); } return result; } catch (IOException ioe) { throw new TasteException(ioe); } } private void getAllUserIDsFromPartition(int partition, FastIDSet result) throws IOException, TasteException { HttpURLConnection connection = makeConnection("/user/allIDs", "GET", (long) partition); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } consumeIDs(connection, result); } finally { connection.disconnect(); } } @Override public FastIDSet getAllItemIDs() throws TasteException { try { HttpURLConnection connection = makeConnection("/item/allIDs", "GET", null); try { switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return consumeIDs(connection); } finally { connection.disconnect(); } } catch (IOException ioe) { throw new TasteException(ioe); } } private static FastIDSet consumeIDs(HttpURLConnection connection) throws IOException { FastIDSet result = new FastIDSet(); consumeIDs(connection, result); return result; } private static void consumeIDs(HttpURLConnection connection, FastIDSet result) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8)); try { String line; while ((line = reader.readLine()) != null) { result.add(Long.parseLong(line)); } } finally { Closeables.closeQuietly(reader); } } }
Add option to ignore HTTPS cert server for testing git-svn-id: f7ac9ee3e7208fd97c9a3deb5e52ce295d20494a@180 0d189622-dca1-7e23-9e30-e8815eb7bd2f
client/src/net/myrrix/client/ClientRecommender.java
Add option to ignore HTTPS cert server for testing
<ide><path>lient/src/net/myrrix/client/ClientRecommender.java <ide> * <ul> <ide> * <li>{@code client.connection.close}: Causes the client to request no HTTP keep-alive. This can avoid <ide> * running out of local sockets on the client side during load testing, but should not otherwise be set.</li> <add> * <li>{@code client.https.ignoreHost}: When using HTTPS, ignore the host specified in the certificate. This <add> * can make development easier, but must not be used in production.</li> <ide> * </ul> <ide> * <ide> * @author Sean Owen <ide> private static final Logger log = LoggerFactory.getLogger(ClientRecommender.class); <ide> <ide> private static final Splitter COMMA = Splitter.on(','); <add> private static final String IGNORE_HOSTNAME_KEY = "client.https.ignoreHost"; <add> private static final String CONNECTION_CLOSE_KEY = "client.connection.close"; <ide> <ide> private final MyrrixClientConfiguration config; <ide> private final boolean needAuthentication; <ide> private final boolean closeConnection; <add> private final boolean ignoreHTTPSHost; <ide> private final List<List<Pair<String,Integer>>> partitions; <ide> private final Random random; <ide> <ide> HttpsURLConnection.setDefaultSSLSocketFactory(buildSSLSocketFactory()); <ide> } <ide> <del> closeConnection = Boolean.valueOf(System.getProperty("client.connection.close")); <add> closeConnection = Boolean.valueOf(System.getProperty(CONNECTION_CLOSE_KEY)); <add> ignoreHTTPSHost = Boolean.valueOf(System.getProperty(IGNORE_HOSTNAME_KEY)); <ide> <ide> partitions = config.getPartitions(); <ide> random = RandomUtils.getRandom(); <ide> new HostnameVerifier(){ <ide> @Override <ide> public boolean verify(String hostname, SSLSession sslSession) { <del> return "localhost".equals(hostname) <add> return ignoreHTTPSHost <add> || "localhost".equals(hostname) <ide> || "127.0.0.1".equals(hostname) <ide> || defaultVerifier.verify(hostname, sslSession); <ide> } <ide> connection.setDoOutput(true); <ide> connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8"); <ide> connection.setRequestProperty("Content-Encoding", "gzip"); <del> if (!needAuthentication) { <add> if (needAuthentication) { <add> log.info("Authentication is enabled, so ingest data must be buffered in memory"); <add> } else { <ide> connection.setChunkedStreamingMode(0); // Use default buffer size <ide> } <ide> // Must buffer in memory if using authentication since it won't handle the authorization challenge
Java
apache-2.0
3958f0ae7d51c6669d3596ea706e02ded3fd381c
0
benbenw/jmeter,apache/jmeter,ham1/jmeter,etnetera/jmeter,ham1/jmeter,etnetera/jmeter,benbenw/jmeter,etnetera/jmeter,apache/jmeter,apache/jmeter,apache/jmeter,ham1/jmeter,ham1/jmeter,apache/jmeter,etnetera/jmeter,ham1/jmeter,etnetera/jmeter,benbenw/jmeter,benbenw/jmeter
/* * 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.jmeter.gui.action; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.tree.TreePath; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.apache.jmeter.gui.GuiPackage; import org.apache.jmeter.gui.Replaceable; import org.apache.jmeter.gui.Searchable; import org.apache.jmeter.gui.tree.JMeterTreeModel; import org.apache.jmeter.gui.tree.JMeterTreeNode; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.documentation.VisibleForTesting; import org.apache.jorphan.gui.ComponentUtil; import org.apache.jorphan.gui.JLabeledTextField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Dialog to search in tree of element */ public class SearchTreeDialog extends JDialog implements ActionListener { // NOSONAR private static final long serialVersionUID = -4436834972710248247L; private static final Logger logger = LoggerFactory.getLogger(SearchTreeDialog.class); private static final Font FONT_DEFAULT = UIManager.getDefaults().getFont("TextField.font"); private static final Font FONT_SMALL = new Font("SansSerif", Font.PLAIN, (int) Math.round(FONT_DEFAULT.getSize() * 0.8)); private JButton searchButton; private JButton nextButton; private JButton previousButton; private JButton searchAndExpandButton; private JButton replaceButton; private JButton replaceAllButton; private JButton replaceAndFindButton; private JButton cancelButton; private JLabeledTextField searchTF; private JLabeledTextField replaceTF; private JLabel statusLabel; private JCheckBox isRegexpCB; private JCheckBox isCaseSensitiveCB; private transient Triple<String, Boolean, Boolean> lastSearchConditions = null; private List<JMeterTreeNode> lastSearchResult = new ArrayList<>(); private int currentSearchIndex; @VisibleForTesting public SearchTreeDialog() { super(); } public SearchTreeDialog(JFrame parent) { super(parent, JMeterUtils.getResString("search_tree_title"), false); //$NON-NLS-1$ init(); } @Override protected JRootPane createRootPane() { JRootPane rootPane = new JRootPane(); // Hide Window on ESC Action escapeAction = new AbstractAction("ESCAPE") { private static final long serialVersionUID = -6543764044868772971L; @Override public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; // Do search on Enter Action enterAction = new AbstractAction("ENTER") { private static final long serialVersionUID = -3661361497864527363L; @Override public void actionPerformed(ActionEvent actionEvent) { doSearch(actionEvent); } }; ActionMap actionMap = rootPane.getActionMap(); actionMap.put(escapeAction.getValue(Action.NAME), escapeAction); actionMap.put(enterAction.getValue(Action.NAME), enterAction); InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStrokes.ESC, escapeAction.getValue(Action.NAME)); inputMap.put(KeyStrokes.ENTER, enterAction.getValue(Action.NAME)); return rootPane; } private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final) this.getContentPane().setLayout(new BorderLayout(10,10)); searchTF = new JLabeledTextField(JMeterUtils.getResString("search_text_field"), 20); //$NON-NLS-1$ searchTF.setAlignmentY(TOP_ALIGNMENT); if (lastSearchConditions != null) { searchTF.setText(lastSearchConditions.getLeft()); isCaseSensitiveCB.setSelected(lastSearchConditions.getMiddle()); isRegexpCB.setSelected(lastSearchConditions.getRight()); } replaceTF = new JLabeledTextField(JMeterUtils.getResString("search_text_replace"), 20); //$NON-NLS-1$ replaceTF.setAlignmentX(TOP_ALIGNMENT); statusLabel = new JLabel(" "); statusLabel.setPreferredSize(new Dimension(100, 20)); statusLabel.setMinimumSize(new Dimension(100, 20)); isRegexpCB = new JCheckBox(JMeterUtils.getResString("search_text_chkbox_regexp"), false); //$NON-NLS-1$ isCaseSensitiveCB = new JCheckBox(JMeterUtils.getResString("search_text_chkbox_case"), true); //$NON-NLS-1$ isRegexpCB.setFont(FONT_SMALL); isCaseSensitiveCB.setFont(FONT_SMALL); JPanel searchCriterionPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); searchCriterionPanel.setBorder(BorderFactory.createTitledBorder(JMeterUtils.getResString("search_matching"))); //$NON-NLS-1$ searchCriterionPanel.add(isCaseSensitiveCB); searchCriterionPanel.add(isRegexpCB); JPanel searchPanel = new JPanel(); searchPanel.setLayout(new GridLayout(4, 1)); searchPanel.setBorder(BorderFactory.createEmptyBorder(7, 3, 3, 3)); searchPanel.add(searchTF); searchPanel.add(replaceTF); searchPanel.add(statusLabel); searchPanel.add(searchCriterionPanel); JPanel buttonsPanel = new JPanel(new GridLayout(9, 1)); searchButton = createButton("search_search_all"); //$NON-NLS-1$ searchButton.addActionListener(this); nextButton = createButton("search_next"); //$NON-NLS-1$ nextButton.addActionListener(this); previousButton = createButton("search_previous"); //$NON-NLS-1$ previousButton.addActionListener(this); searchAndExpandButton = createButton("search_search_all_expand"); //$NON-NLS-1$ searchAndExpandButton.addActionListener(this); replaceButton = createButton("search_replace"); //$NON-NLS-1$ replaceButton.addActionListener(this); replaceAllButton = createButton("search_replace_all"); //$NON-NLS-1$ replaceAllButton.addActionListener(this); replaceAndFindButton = createButton("search_replace_and_find"); //$NON-NLS-1$ replaceAndFindButton.addActionListener(this); cancelButton = createButton("cancel"); //$NON-NLS-1$ cancelButton.addActionListener(this); buttonsPanel.add(nextButton); buttonsPanel.add(previousButton); buttonsPanel.add(searchButton); buttonsPanel.add(searchAndExpandButton); buttonsPanel.add(Box.createVerticalStrut(30)); buttonsPanel.add(replaceButton); buttonsPanel.add(replaceAllButton); buttonsPanel.add(replaceAndFindButton); buttonsPanel.add(cancelButton); JPanel searchAndReplacePanel = new JPanel(); searchAndReplacePanel.setLayout(new BorderLayout()); searchAndReplacePanel.add(searchPanel, BorderLayout.CENTER); searchAndReplacePanel.add(buttonsPanel, BorderLayout.EAST); this.getContentPane().add(searchAndReplacePanel); searchTF.requestFocusInWindow(); this.pack(); ComponentUtil.centerComponentInWindow(this); } private JButton createButton(String messageKey) { return new JButton(JMeterUtils.getResString(messageKey)); } /** * Do search * @param e {@link ActionEvent} */ @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); statusLabel.setText(""); if (source == cancelButton) { searchTF.requestFocusInWindow(); this.setVisible(false); } else if (source == searchButton || source == searchAndExpandButton) { doSearch(e); } else if (source == nextButton || source == previousButton) { doNavigateToSearchResult(source == nextButton); } else if (source == replaceAllButton){ doReplaceAll(e); } else if (!lastSearchResult.isEmpty() && source == replaceButton){ doReplace(); } else if (source == replaceAndFindButton){ if(!lastSearchResult.isEmpty()) { doReplace(); } doNavigateToSearchResult(true); } } /** * */ private void doReplace() { GuiPackage.getInstance().updateCurrentNode(); int nbReplacements = 0; if(currentSearchIndex >= 0) { JMeterTreeNode currentNode = lastSearchResult.get(currentSearchIndex); if(currentNode != null) { String wordToSearch = searchTF.getText(); String wordToReplace = replaceTF.getText(); String regex = isRegexpCB.isSelected() ? wordToSearch : Pattern.quote(wordToSearch); boolean caseSensitiveReplacement = isCaseSensitiveCB.isSelected(); Pair<Integer, JMeterTreeNode> pair = doReplacementInCurrentNode(currentNode, regex, wordToReplace, caseSensitiveReplacement); if(pair != null) { nbReplacements = pair.getLeft(); GuiPackage.getInstance().updateCurrentGui(); GuiPackage.getInstance().getMainFrame().repaint(); } } } statusLabel.setText(MessageFormat.format("Replaced {0} occurrences", nbReplacements)); } private JMeterTreeNode doNavigateToSearchResult(boolean isNext) { boolean doSearchAgain = lastSearchConditions == null || !Triple.of(searchTF.getText(), isCaseSensitiveCB.isSelected(), isRegexpCB.isSelected()) .equals(lastSearchConditions); if(doSearchAgain) { String wordToSearch = searchTF.getText(); if (StringUtils.isEmpty(wordToSearch)) { this.lastSearchConditions = null; return null; } else { this.lastSearchConditions = Triple.of(wordToSearch, isCaseSensitiveCB.isSelected(), isRegexpCB.isSelected()); } Searcher searcher = createSearcher(wordToSearch); searchInTree(GuiPackage.getInstance(), searcher, wordToSearch); } if(!lastSearchResult.isEmpty()) { if(isNext) { currentSearchIndex = ++currentSearchIndex % lastSearchResult.size(); } else { currentSearchIndex = currentSearchIndex > 0 ? --currentSearchIndex : lastSearchResult.size()-1; } JMeterTreeNode selectedNode = lastSearchResult.get(currentSearchIndex); TreePath selection = new TreePath(selectedNode.getPath()); GuiPackage.getInstance().getMainFrame().getTree().setSelectionPath(selection); GuiPackage.getInstance().getMainFrame().getTree().scrollPathToVisible(selection); return selectedNode; } return null; } /** * @param e {@link ActionEvent} */ private void doSearch(ActionEvent e) { boolean expand = e.getSource()==searchAndExpandButton; String wordToSearch = searchTF.getText(); if (StringUtils.isEmpty(wordToSearch)) { this.lastSearchConditions = null; return; } else { this.lastSearchConditions = Triple.of(wordToSearch, isCaseSensitiveCB.isSelected(), isRegexpCB.isSelected()); } // reset previous result ActionRouter.getInstance().doActionNow(new ActionEvent(e.getSource(), e.getID(), ActionNames.SEARCH_RESET)); // do search Searcher searcher = createSearcher(wordToSearch); GuiPackage guiPackage = GuiPackage.getInstance(); guiPackage.beginUndoTransaction(); int numberOfMatches = 0; try { Pair<Integer, Set<JMeterTreeNode>> result = searchInTree(guiPackage, searcher, wordToSearch); numberOfMatches = result.getLeft(); markConcernedNodes(expand, result.getRight()); } finally { guiPackage.endUndoTransaction(); } GuiPackage.getInstance().getMainFrame().repaint(); searchTF.requestFocusInWindow(); statusLabel.setText( MessageFormat.format( JMeterUtils.getResString("search_tree_matches"), numberOfMatches)); } /** * @param wordToSearch * @return */ private Searcher createSearcher(String wordToSearch) { if (isRegexpCB.isSelected()) { return new RegexpSearcher(isCaseSensitiveCB.isSelected(), wordToSearch); } else { return new RawTextSearcher(isCaseSensitiveCB.isSelected(), wordToSearch); } } private Pair<Integer, Set<JMeterTreeNode>> searchInTree(GuiPackage guiPackage, Searcher searcher, String wordToSearch) { int numberOfMatches = 0; JMeterTreeModel jMeterTreeModel = guiPackage.getTreeModel(); Set<JMeterTreeNode> nodes = new LinkedHashSet<>(); for (JMeterTreeNode jMeterTreeNode : jMeterTreeModel.getNodesOfType(Searchable.class)) { try { Searchable searchable = (Searchable) jMeterTreeNode.getUserObject(); List<String> searchableTokens = searchable.getSearchableTokens(); boolean result = searcher.search(searchableTokens); if (result) { numberOfMatches++; nodes.add(jMeterTreeNode); } } catch (Exception ex) { logger.error("Error occurred searching for word:{} in node:{}", wordToSearch, jMeterTreeNode.getName(), ex); } } this.currentSearchIndex = -1; this.lastSearchResult.clear(); this.lastSearchResult.addAll(nodes); return Pair.of(numberOfMatches, nodes); } /** * @param expand true if we want to expand * @param nodes Set of {@link JMeterTreeNode} to mark */ private void markConcernedNodes(boolean expand, Set<JMeterTreeNode> nodes) { GuiPackage guiInstance = GuiPackage.getInstance(); JTree jTree = guiInstance.getMainFrame().getTree(); for (JMeterTreeNode jMeterTreeNode : nodes) { jMeterTreeNode.setMarkedBySearch(true); if (expand) { if(jMeterTreeNode.isLeaf()) { jTree.expandPath(new TreePath(((JMeterTreeNode)jMeterTreeNode.getParent()).getPath())); } else { jTree.expandPath(new TreePath(jMeterTreeNode.getPath())); } } } } /** * Replace all occurrences in nodes that contain {@link Replaceable} Test Elements * @param e {@link ActionEvent} */ private void doReplaceAll(ActionEvent e) { boolean expand = e.getSource()==searchAndExpandButton; String wordToSearch = searchTF.getText(); String wordToReplace = replaceTF.getText(); if (StringUtils.isEmpty(wordToReplace)) { return; } // Save any change to current node GuiPackage.getInstance().updateCurrentNode(); // reset previous result ActionRouter.getInstance().doActionNow(new ActionEvent(e.getSource(), e.getID(), ActionNames.SEARCH_RESET)); Searcher searcher = createSearcher(wordToSearch); String regex = isRegexpCB.isSelected() ? wordToSearch : Pattern.quote(wordToSearch); GuiPackage guiPackage = GuiPackage.getInstance(); boolean caseSensitiveReplacement = isCaseSensitiveCB.isSelected(); int totalReplaced = 0; Pair<Integer, Set<JMeterTreeNode>> result = searchInTree(guiPackage, searcher, wordToSearch); Set<JMeterTreeNode> matchingNodes = result.getRight(); Set<JMeterTreeNode> replacedNodes = new HashSet<>(); for (JMeterTreeNode jMeterTreeNode : matchingNodes) { Pair<Integer, JMeterTreeNode> pair = doReplacementInCurrentNode(jMeterTreeNode, regex, wordToReplace, caseSensitiveReplacement); if(pair != null) { totalReplaced += pair.getLeft(); replacedNodes.add(pair.getRight()); } } statusLabel.setText(MessageFormat.format("Replaced {0} occurrences", totalReplaced)); markConcernedNodes(expand, replacedNodes); // Update GUI as current node may be concerned by changes if (totalReplaced > 0) { GuiPackage.getInstance().refreshCurrentGui(); } GuiPackage.getInstance().getMainFrame().repaint(); searchTF.requestFocusInWindow(); } /** * Replace in jMeterTreeNode regex by replaceBy * @param jMeterTreeNode Current {@link JMeterTreeNode} * @param regex Text to search (can be regex) * @param replaceBy Replacement text * @param caseSensitiveReplacement boolean if search is case sensitive * @return null if no replacement occurred or Pair of (number of replacement, current tree node) */ private Pair<Integer, JMeterTreeNode> doReplacementInCurrentNode(JMeterTreeNode jMeterTreeNode, String regex, String replaceBy, boolean caseSensitiveReplacement) { try { if (jMeterTreeNode.getUserObject() instanceof Replaceable) { Replaceable replaceable = (Replaceable) jMeterTreeNode.getUserObject(); int numberOfReplacements = replaceable.replace(regex, replaceBy, caseSensitiveReplacement); if (numberOfReplacements > 0) { if (logger.isInfoEnabled()) { logger.info("Replaced {} in element:{}", numberOfReplacements, ((TestElement) jMeterTreeNode.getUserObject()).getName()); } return Pair.of(numberOfReplacements, jMeterTreeNode); } } } catch (Exception ex) { logger.error("Error occurred replacing data in node:{}", jMeterTreeNode.getName(), ex); } return null; } /* (non-Javadoc) * @see java.awt.Dialog#setVisible(boolean) */ @Override public void setVisible(boolean b) { super.setVisible(b); searchTF.requestFocusInWindow(); } }
src/core/org/apache/jmeter/gui/action/SearchTreeDialog.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.jmeter.gui.action; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.tree.TreePath; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.apache.jmeter.gui.GuiPackage; import org.apache.jmeter.gui.Replaceable; import org.apache.jmeter.gui.Searchable; import org.apache.jmeter.gui.tree.JMeterTreeModel; import org.apache.jmeter.gui.tree.JMeterTreeNode; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.gui.ComponentUtil; import org.apache.jorphan.gui.JLabeledTextField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Dialog to search in tree of element */ public class SearchTreeDialog extends JDialog implements ActionListener { // NOSONAR private static final long serialVersionUID = -4436834972710248247L; private static final Logger logger = LoggerFactory.getLogger(SearchTreeDialog.class); private static final Font FONT_DEFAULT = UIManager.getDefaults().getFont("TextField.font"); private static final Font FONT_SMALL = new Font("SansSerif", Font.PLAIN, (int) Math.round(FONT_DEFAULT.getSize() * 0.8)); private JButton searchButton; private JButton nextButton; private JButton previousButton; private JButton searchAndExpandButton; private JButton replaceButton; private JButton replaceAllButton; private JButton replaceAndFindButton; private JButton cancelButton; private JLabeledTextField searchTF; private JLabeledTextField replaceTF; private JLabel statusLabel; private JCheckBox isRegexpCB; private JCheckBox isCaseSensitiveCB; private transient Triple<String, Boolean, Boolean> lastSearchConditions = null; private List<JMeterTreeNode> lastSearchResult = new ArrayList<>(); private int currentSearchIndex; public SearchTreeDialog(JFrame parent) { super(parent, JMeterUtils.getResString("search_tree_title"), false); //$NON-NLS-1$ init(); } @Override protected JRootPane createRootPane() { JRootPane rootPane = new JRootPane(); // Hide Window on ESC Action escapeAction = new AbstractAction("ESCAPE") { private static final long serialVersionUID = -6543764044868772971L; @Override public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; // Do search on Enter Action enterAction = new AbstractAction("ENTER") { private static final long serialVersionUID = -3661361497864527363L; @Override public void actionPerformed(ActionEvent actionEvent) { doSearch(actionEvent); } }; ActionMap actionMap = rootPane.getActionMap(); actionMap.put(escapeAction.getValue(Action.NAME), escapeAction); actionMap.put(enterAction.getValue(Action.NAME), enterAction); InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStrokes.ESC, escapeAction.getValue(Action.NAME)); inputMap.put(KeyStrokes.ENTER, enterAction.getValue(Action.NAME)); return rootPane; } private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final) this.getContentPane().setLayout(new BorderLayout(10,10)); searchTF = new JLabeledTextField(JMeterUtils.getResString("search_text_field"), 20); //$NON-NLS-1$ searchTF.setAlignmentY(TOP_ALIGNMENT); if (lastSearchConditions != null) { searchTF.setText(lastSearchConditions.getLeft()); isCaseSensitiveCB.setSelected(lastSearchConditions.getMiddle()); isRegexpCB.setSelected(lastSearchConditions.getRight()); } replaceTF = new JLabeledTextField(JMeterUtils.getResString("search_text_replace"), 20); //$NON-NLS-1$ replaceTF.setAlignmentX(TOP_ALIGNMENT); statusLabel = new JLabel(" "); statusLabel.setPreferredSize(new Dimension(100, 20)); statusLabel.setMinimumSize(new Dimension(100, 20)); isRegexpCB = new JCheckBox(JMeterUtils.getResString("search_text_chkbox_regexp"), false); //$NON-NLS-1$ isCaseSensitiveCB = new JCheckBox(JMeterUtils.getResString("search_text_chkbox_case"), true); //$NON-NLS-1$ isRegexpCB.setFont(FONT_SMALL); isCaseSensitiveCB.setFont(FONT_SMALL); JPanel searchCriterionPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); searchCriterionPanel.setBorder(BorderFactory.createTitledBorder(JMeterUtils.getResString("search_matching"))); //$NON-NLS-1$ searchCriterionPanel.add(isCaseSensitiveCB); searchCriterionPanel.add(isRegexpCB); JPanel searchPanel = new JPanel(); searchPanel.setLayout(new GridLayout(4, 1)); searchPanel.setBorder(BorderFactory.createEmptyBorder(7, 3, 3, 3)); searchPanel.add(searchTF); searchPanel.add(replaceTF); searchPanel.add(statusLabel); searchPanel.add(searchCriterionPanel); JPanel buttonsPanel = new JPanel(new GridLayout(9, 1)); searchButton = createButton("search_search_all"); //$NON-NLS-1$ searchButton.addActionListener(this); nextButton = createButton("search_next"); //$NON-NLS-1$ nextButton.addActionListener(this); previousButton = createButton("search_previous"); //$NON-NLS-1$ previousButton.addActionListener(this); searchAndExpandButton = createButton("search_search_all_expand"); //$NON-NLS-1$ searchAndExpandButton.addActionListener(this); replaceButton = createButton("search_replace"); //$NON-NLS-1$ replaceButton.addActionListener(this); replaceAllButton = createButton("search_replace_all"); //$NON-NLS-1$ replaceAllButton.addActionListener(this); replaceAndFindButton = createButton("search_replace_and_find"); //$NON-NLS-1$ replaceAndFindButton.addActionListener(this); cancelButton = createButton("cancel"); //$NON-NLS-1$ cancelButton.addActionListener(this); buttonsPanel.add(nextButton); buttonsPanel.add(previousButton); buttonsPanel.add(searchButton); buttonsPanel.add(searchAndExpandButton); buttonsPanel.add(Box.createVerticalStrut(30)); buttonsPanel.add(replaceButton); buttonsPanel.add(replaceAllButton); buttonsPanel.add(replaceAndFindButton); buttonsPanel.add(cancelButton); JPanel searchAndReplacePanel = new JPanel(); searchAndReplacePanel.setLayout(new BorderLayout()); searchAndReplacePanel.add(searchPanel, BorderLayout.CENTER); searchAndReplacePanel.add(buttonsPanel, BorderLayout.EAST); this.getContentPane().add(searchAndReplacePanel); searchTF.requestFocusInWindow(); this.pack(); ComponentUtil.centerComponentInWindow(this); } private JButton createButton(String messageKey) { return new JButton(JMeterUtils.getResString(messageKey)); } /** * Do search * @param e {@link ActionEvent} */ @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); statusLabel.setText(""); if (source == cancelButton) { searchTF.requestFocusInWindow(); this.setVisible(false); } else if (source == searchButton || source == searchAndExpandButton) { doSearch(e); } else if (source == nextButton || source == previousButton) { doNavigateToSearchResult(source == nextButton); } else if (source == replaceAllButton){ doReplaceAll(e); } else if (!lastSearchResult.isEmpty() && source == replaceButton){ doReplace(); } else if (source == replaceAndFindButton){ if(!lastSearchResult.isEmpty()) { doReplace(); } doNavigateToSearchResult(true); } } /** * */ private void doReplace() { GuiPackage.getInstance().updateCurrentNode(); int nbReplacements = 0; if(currentSearchIndex >= 0) { JMeterTreeNode currentNode = lastSearchResult.get(currentSearchIndex); if(currentNode != null) { String wordToSearch = searchTF.getText(); String wordToReplace = replaceTF.getText(); String regex = isRegexpCB.isSelected() ? wordToSearch : Pattern.quote(wordToSearch); boolean caseSensitiveReplacement = isCaseSensitiveCB.isSelected(); Pair<Integer, JMeterTreeNode> pair = doReplacementInCurrentNode(currentNode, regex, wordToReplace, caseSensitiveReplacement); if(pair != null) { nbReplacements = pair.getLeft(); GuiPackage.getInstance().updateCurrentGui(); GuiPackage.getInstance().getMainFrame().repaint(); } } } statusLabel.setText(MessageFormat.format("Replaced {0} occurrences", nbReplacements)); } private JMeterTreeNode doNavigateToSearchResult(boolean isNext) { boolean doSearchAgain = lastSearchConditions == null || !Triple.of(searchTF.getText(), isCaseSensitiveCB.isSelected(), isRegexpCB.isSelected()) .equals(lastSearchConditions); if(doSearchAgain) { String wordToSearch = searchTF.getText(); if (StringUtils.isEmpty(wordToSearch)) { this.lastSearchConditions = null; return null; } else { this.lastSearchConditions = Triple.of(wordToSearch, isCaseSensitiveCB.isSelected(), isRegexpCB.isSelected()); } Searcher searcher = createSearcher(wordToSearch); searchInTree(GuiPackage.getInstance(), searcher, wordToSearch); } if(!lastSearchResult.isEmpty()) { if(isNext) { currentSearchIndex = ++currentSearchIndex % lastSearchResult.size(); } else { currentSearchIndex = currentSearchIndex > 0 ? --currentSearchIndex : lastSearchResult.size()-1; } JMeterTreeNode selectedNode = lastSearchResult.get(currentSearchIndex); TreePath selection = new TreePath(selectedNode.getPath()); GuiPackage.getInstance().getMainFrame().getTree().setSelectionPath(selection); GuiPackage.getInstance().getMainFrame().getTree().scrollPathToVisible(selection); return selectedNode; } return null; } /** * @param e {@link ActionEvent} */ private void doSearch(ActionEvent e) { boolean expand = e.getSource()==searchAndExpandButton; String wordToSearch = searchTF.getText(); if (StringUtils.isEmpty(wordToSearch)) { this.lastSearchConditions = null; return; } else { this.lastSearchConditions = Triple.of(wordToSearch, isCaseSensitiveCB.isSelected(), isRegexpCB.isSelected()); } // reset previous result ActionRouter.getInstance().doActionNow(new ActionEvent(e.getSource(), e.getID(), ActionNames.SEARCH_RESET)); // do search Searcher searcher = createSearcher(wordToSearch); GuiPackage guiPackage = GuiPackage.getInstance(); guiPackage.beginUndoTransaction(); int numberOfMatches = 0; try { Pair<Integer, Set<JMeterTreeNode>> result = searchInTree(guiPackage, searcher, wordToSearch); numberOfMatches = result.getLeft(); markConcernedNodes(expand, result.getRight()); } finally { guiPackage.endUndoTransaction(); } GuiPackage.getInstance().getMainFrame().repaint(); searchTF.requestFocusInWindow(); statusLabel.setText( MessageFormat.format( JMeterUtils.getResString("search_tree_matches"), numberOfMatches)); } /** * @param wordToSearch * @return */ private Searcher createSearcher(String wordToSearch) { if (isRegexpCB.isSelected()) { return new RegexpSearcher(isCaseSensitiveCB.isSelected(), wordToSearch); } else { return new RawTextSearcher(isCaseSensitiveCB.isSelected(), wordToSearch); } } private Pair<Integer, Set<JMeterTreeNode>> searchInTree(GuiPackage guiPackage, Searcher searcher, String wordToSearch) { int numberOfMatches = 0; JMeterTreeModel jMeterTreeModel = guiPackage.getTreeModel(); Set<JMeterTreeNode> nodes = new LinkedHashSet<>(); for (JMeterTreeNode jMeterTreeNode : jMeterTreeModel.getNodesOfType(Searchable.class)) { try { Searchable searchable = (Searchable) jMeterTreeNode.getUserObject(); List<String> searchableTokens = searchable.getSearchableTokens(); boolean result = searcher.search(searchableTokens); if (result) { numberOfMatches++; nodes.add(jMeterTreeNode); } } catch (Exception ex) { logger.error("Error occurred searching for word:{} in node:{}", wordToSearch, jMeterTreeNode.getName(), ex); } } this.currentSearchIndex = -1; this.lastSearchResult.clear(); this.lastSearchResult.addAll(nodes); return Pair.of(numberOfMatches, nodes); } /** * @param expand true if we want to expand * @param nodes Set of {@link JMeterTreeNode} to mark */ private void markConcernedNodes(boolean expand, Set<JMeterTreeNode> nodes) { GuiPackage guiInstance = GuiPackage.getInstance(); JTree jTree = guiInstance.getMainFrame().getTree(); for (JMeterTreeNode jMeterTreeNode : nodes) { jMeterTreeNode.setMarkedBySearch(true); if (expand) { if(jMeterTreeNode.isLeaf()) { jTree.expandPath(new TreePath(((JMeterTreeNode)jMeterTreeNode.getParent()).getPath())); } else { jTree.expandPath(new TreePath(jMeterTreeNode.getPath())); } } } } /** * Replace all occurrences in nodes that contain {@link Replaceable} Test Elements * @param e {@link ActionEvent} */ private void doReplaceAll(ActionEvent e) { boolean expand = e.getSource()==searchAndExpandButton; String wordToSearch = searchTF.getText(); String wordToReplace = replaceTF.getText(); if (StringUtils.isEmpty(wordToReplace)) { return; } // Save any change to current node GuiPackage.getInstance().updateCurrentNode(); // reset previous result ActionRouter.getInstance().doActionNow(new ActionEvent(e.getSource(), e.getID(), ActionNames.SEARCH_RESET)); Searcher searcher = createSearcher(wordToSearch); String regex = isRegexpCB.isSelected() ? wordToSearch : Pattern.quote(wordToSearch); GuiPackage guiPackage = GuiPackage.getInstance(); boolean caseSensitiveReplacement = isCaseSensitiveCB.isSelected(); int totalReplaced = 0; Pair<Integer, Set<JMeterTreeNode>> result = searchInTree(guiPackage, searcher, wordToSearch); Set<JMeterTreeNode> matchingNodes = result.getRight(); Set<JMeterTreeNode> replacedNodes = new HashSet<>(); for (JMeterTreeNode jMeterTreeNode : matchingNodes) { Pair<Integer, JMeterTreeNode> pair = doReplacementInCurrentNode(jMeterTreeNode, regex, wordToReplace, caseSensitiveReplacement); if(pair != null) { totalReplaced += pair.getLeft(); replacedNodes.add(pair.getRight()); } } statusLabel.setText(MessageFormat.format("Replaced {0} occurrences", totalReplaced)); markConcernedNodes(expand, replacedNodes); // Update GUI as current node may be concerned by changes if (totalReplaced > 0) { GuiPackage.getInstance().refreshCurrentGui(); } GuiPackage.getInstance().getMainFrame().repaint(); searchTF.requestFocusInWindow(); } /** * Replace in jMeterTreeNode regex by replaceBy * @param jMeterTreeNode Current {@link JMeterTreeNode} * @param regex Text to search (can be regex) * @param replaceBy Replacement text * @param caseSensitiveReplacement boolean if search is case sensitive * @return null if no replacement occurred or Pair of (number of replacement, current tree node) */ private Pair<Integer, JMeterTreeNode> doReplacementInCurrentNode(JMeterTreeNode jMeterTreeNode, String regex, String replaceBy, boolean caseSensitiveReplacement) { try { if (jMeterTreeNode.getUserObject() instanceof Replaceable) { Replaceable replaceable = (Replaceable) jMeterTreeNode.getUserObject(); int numberOfReplacements = replaceable.replace(regex, replaceBy, caseSensitiveReplacement); if (numberOfReplacements > 0) { if (logger.isInfoEnabled()) { logger.info("Replaced {} in element:{}", numberOfReplacements, ((TestElement) jMeterTreeNode.getUserObject()).getName()); } return Pair.of(numberOfReplacements, jMeterTreeNode); } } } catch (Exception ex) { logger.error("Error occurred replacing data in node:{}", jMeterTreeNode.getName(), ex); } return null; } /* (non-Javadoc) * @see java.awt.Dialog#setVisible(boolean) */ @Override public void setVisible(boolean b) { super.setVisible(b); searchTF.requestFocusInWindow(); } }
Bug 63203 - Unit Tests : Replace use of @Deprecated by @VisibleForTesting for methods/constructors/classes made public for Unit Testing only Bugzilla Id: 63203 git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1854263 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: 269c8e9f6e6d35caa631fd7cab82a921a1cb60e8
src/core/org/apache/jmeter/gui/action/SearchTreeDialog.java
Bug 63203 - Unit Tests : Replace use of @Deprecated by @VisibleForTesting for methods/constructors/classes made public for Unit Testing only Bugzilla Id: 63203
<ide><path>rc/core/org/apache/jmeter/gui/action/SearchTreeDialog.java <ide> import org.apache.jmeter.gui.tree.JMeterTreeNode; <ide> import org.apache.jmeter.testelement.TestElement; <ide> import org.apache.jmeter.util.JMeterUtils; <add>import org.apache.jorphan.documentation.VisibleForTesting; <ide> import org.apache.jorphan.gui.ComponentUtil; <ide> import org.apache.jorphan.gui.JLabeledTextField; <ide> import org.slf4j.Logger; <ide> private List<JMeterTreeNode> lastSearchResult = new ArrayList<>(); <ide> private int currentSearchIndex; <ide> <add> @VisibleForTesting <add> public SearchTreeDialog() { <add> super(); <add> } <add> <ide> public SearchTreeDialog(JFrame parent) { <ide> super(parent, JMeterUtils.getResString("search_tree_title"), false); //$NON-NLS-1$ <ide> init();
Java
lgpl-2.1
a1b3c5ca9e75e602314ef9579bd03bc728cd791c
0
4ment/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc,4ment/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,4ment/beast-mcmc,maxbiostat/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc
/* * BeagleSequenceSimulatorParser.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST 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 * of the License, or (at your option) any later version. * * BEAST 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 BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.app.beagle.tools.parsers; import dr.app.beagle.tools.BeagleSequenceSimulator; import dr.app.beagle.tools.Partition; import dr.evolution.alignment.Alignment; import dr.evolution.alignment.SimpleAlignment; import dr.evolution.datatype.Codons; import dr.evolution.datatype.Nucleotides; import dr.xml.*; import java.util.ArrayList; import java.util.logging.Logger; /** * @author Filip Bielejec * @version $Id$ */ public class BeagleSequenceSimulatorParser extends AbstractXMLObjectParser { public static final String BEAGLE_SEQUENCE_SIMULATOR = "beagleSequenceSimulator"; public static final String PARALLEL = "parallel"; public static final String OUTPUT_ANCESTRAL_SEQUENCES = "outputAncestralSequences"; public static final String OUTPUT = "output"; public String getParserName() { return BEAGLE_SEQUENCE_SIMULATOR; } @Override public String getParserDescription() { return "Beagle sequence simulator"; } @Override public Class<Alignment> getReturnType() { return Alignment.class; } @Override public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[]{ AttributeRule.newBooleanRule(PARALLEL, true, "Whether to use multiple Beagle instances for simulation, default is false (sequential execution)."), new StringAttributeRule(OUTPUT, "Possible output formats", SimpleAlignment.OutputType.values(), //TODO: this should ignore upper/lower cas false), new ElementRule(Partition.class, 1, Integer.MAX_VALUE) }; }// END: getSyntaxRules @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { String msg = ""; boolean parallel = false; boolean outputAncestralSequences = false; if (xo.hasAttribute(PARALLEL)) { parallel = xo.getBooleanAttribute(PARALLEL); } if (xo.hasAttribute(OUTPUT_ANCESTRAL_SEQUENCES)) { outputAncestralSequences = xo.getBooleanAttribute(OUTPUT_ANCESTRAL_SEQUENCES); } SimpleAlignment.OutputType output = SimpleAlignment.OutputType.FASTA; if (xo.hasAttribute(OUTPUT)) { output = SimpleAlignment.OutputType.parseFromString( xo.getStringAttribute(OUTPUT)); } int siteCount = 0; int to = 0; for (int i = 0; i < xo.getChildCount(); i++) { Partition partition = (Partition) xo.getChild(i); to = partition.to + 1; if (to > siteCount) { siteCount = to; } }// END: partitions loop ArrayList<Partition> partitionsList = new ArrayList<Partition>(); for (int i = 0; i < xo.getChildCount(); i++) { Partition partition = (Partition) xo.getChild(i); if (partition.from > siteCount) { throw new XMLParseException( "Illegal 'from' attribute in " + PartitionParser.PARTITION + " element"); } if (partition.to > siteCount) { throw new XMLParseException( "Illegal 'to' attribute in " + PartitionParser.PARTITION + " element"); } if (partition.to == -1) { partition.to = siteCount - 1; } if (partition.getRootSequence() != null) { // TODO: what about 'every'? int partitionSiteCount = (partition.to - partition.from) +1; if (partition.getRootSequence().getLength() != 3 * partitionSiteCount && partition.getFreqModel().getDataType() instanceof Codons) { throw new RuntimeException("Root codon sequence " + "for partition "+ (i+1) +" has " + partition.getRootSequence().getLength() + " characters " + "expecting " + 3 * partitionSiteCount + " characters"); } else if (partition.getRootSequence().getLength() != partitionSiteCount && partition.getFreqModel().getDataType() instanceof Nucleotides) { throw new RuntimeException("Root nuleotide sequence "+ "for partition "+ (i+1) +" has " + partition.getRootSequence().getLength() + " characters " + "expecting " + partitionSiteCount + " characters"); }// END: dataType check // System.exit(-1); }// END: ancestralSequence check partitionsList.add(partition); }// END: partitions loop msg += "\n\t" + partitionsList.size() + " partitions:"; msg += "\n\t\t" + siteCount + ((siteCount > 1) ? " replications " : " replication"); if (msg.length() > 0) { Logger.getLogger("dr.app.beagle.tools").info("\nUsing Beagle Sequence Simulator: " + msg + "\n"); } BeagleSequenceSimulator s = new BeagleSequenceSimulator(partitionsList); SimpleAlignment alignment = s.simulate(parallel, outputAncestralSequences); alignment.setOutputType(output); return alignment; }// END: parseXMLObject }// END: class
src/dr/app/beagle/tools/parsers/BeagleSequenceSimulatorParser.java
/* * BeagleSequenceSimulatorParser.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST 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 * of the License, or (at your option) any later version. * * BEAST 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 BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.app.beagle.tools.parsers; import dr.app.beagle.tools.BeagleSequenceSimulator; import dr.app.beagle.tools.Partition; import dr.evolution.alignment.Alignment; import dr.evolution.alignment.SimpleAlignment; import dr.evolution.datatype.Codons; import dr.evolution.datatype.Nucleotides; import dr.xml.*; import java.util.ArrayList; import java.util.logging.Logger; /** * @author Filip Bielejec * @version $Id$ */ public class BeagleSequenceSimulatorParser extends AbstractXMLObjectParser { public static final String BEAGLE_SEQUENCE_SIMULATOR = "beagleSequenceSimulator"; public static final String PARALLEL = "parallel"; public static final String OUTPUT_ANCESTRAL_SEQUENCES = "outputAncestralSequences"; public static final String OUTPUT = "output"; public String getParserName() { return BEAGLE_SEQUENCE_SIMULATOR; } @Override public String getParserDescription() { return "Beagle sequence simulator"; } @Override public Class<Alignment> getReturnType() { return Alignment.class; } @Override public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[]{ AttributeRule.newBooleanRule(PARALLEL, true, "Whether to use multiple Beagle instances for simulation, default is false (sequential execution)."), new StringAttributeRule(OUTPUT, "Possible output formats", SimpleAlignment.OutputType.values(), //TODO: this should ignore upper/lower cas false), new ElementRule(Partition.class, 1, Integer.MAX_VALUE) }; }// END: getSyntaxRules @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { String msg = ""; boolean parallel = false; boolean outputAncestralSequences = false; if (xo.hasAttribute(PARALLEL)) { parallel = xo.getBooleanAttribute(PARALLEL); } if (xo.hasAttribute(OUTPUT_ANCESTRAL_SEQUENCES)) { outputAncestralSequences = xo.getBooleanAttribute(OUTPUT_ANCESTRAL_SEQUENCES); } SimpleAlignment.OutputType output = SimpleAlignment.OutputType.FASTA; if (xo.hasAttribute(OUTPUT)) { output = SimpleAlignment.OutputType.parseFromString( xo.getStringAttribute(OUTPUT)); } int siteCount = 0; int to = 0; for (int i = 0; i < xo.getChildCount(); i++) { Partition partition = (Partition) xo.getChild(i); to = partition.to + 1; if (to > siteCount) { siteCount = to; } }// END: partitions loop ArrayList<Partition> partitionsList = new ArrayList<Partition>(); for (int i = 0; i < xo.getChildCount(); i++) { Partition partition = (Partition) xo.getChild(i); if (partition.from > siteCount) { throw new XMLParseException( "Illegal 'from' attribute in " + PartitionParser.PARTITION + " element"); } if (partition.to > siteCount) { throw new XMLParseException( "Illegal 'to' attribute in " + PartitionParser.PARTITION + " element"); } if (partition.to == -1) { partition.to = siteCount - 1; } if (partition.getRootSequence() != null) { // TODO: what about 'every'? int partitionSiteCount = (partition.to - partition.from) +1; // System.out.println("SCRAAAAAM:" + partitionSiteCount); if (partition.getRootSequence().getLength() != 3 * partitionSiteCount && partition.getFreqModel().getDataType() instanceof Codons) { throw new RuntimeException("Root codon sequence " + "for partition "+ (i+1) +" has " + partition.getRootSequence().getLength() + " characters " + "expecting " + 3 * partitionSiteCount + " characters"); } else if (partition.getRootSequence().getLength() != partitionSiteCount && partition.getFreqModel().getDataType() instanceof Nucleotides) { throw new RuntimeException("Root nuleotide sequence "+ "for partition "+ (i+1) +" has " + partition.getRootSequence().getLength() + " characters " + "expecting " + partitionSiteCount + " characters"); }// END: dataType check // System.exit(-1); }// END: ancestralSequence check partitionsList.add(partition); }// END: partitions loop msg += "\n\t" + siteCount + ((siteCount > 1) ? " replications " : " replication"); if (msg.length() > 0) { Logger.getLogger("dr.app.beagle.tools").info("Using Beagle Sequence Simulator: " + msg); } BeagleSequenceSimulator s = new BeagleSequenceSimulator(partitionsList); SimpleAlignment alignment = s.simulate(parallel, outputAncestralSequences); alignment.setOutputType(output); return alignment; }// END: parseXMLObject }// END: class
Additional output to screen for sequence simulation.
src/dr/app/beagle/tools/parsers/BeagleSequenceSimulatorParser.java
Additional output to screen for sequence simulation.
<ide><path>rc/dr/app/beagle/tools/parsers/BeagleSequenceSimulatorParser.java <ide> // TODO: what about 'every'? <ide> <ide> int partitionSiteCount = (partition.to - partition.from) +1; <del> <del>// System.out.println("SCRAAAAAM:" + partitionSiteCount); <del> <add> <ide> if (partition.getRootSequence().getLength() != 3 * partitionSiteCount && partition.getFreqModel().getDataType() instanceof Codons) { <ide> <ide> throw new RuntimeException("Root codon sequence " + "for partition "+ (i+1) +" has " <ide> partitionsList.add(partition); <ide> }// END: partitions loop <ide> <del> msg += "\n\t" + siteCount + ((siteCount > 1) ? " replications " : " replication"); <add> msg += "\n\t" + partitionsList.size() + " partitions:"; <add> msg += "\n\t\t" + siteCount + ((siteCount > 1) ? " replications " : " replication"); <ide> if (msg.length() > 0) { <del> Logger.getLogger("dr.app.beagle.tools").info("Using Beagle Sequence Simulator: " + msg); <add> Logger.getLogger("dr.app.beagle.tools").info("\nUsing Beagle Sequence Simulator: " + msg + "\n"); <ide> } <ide> <ide> BeagleSequenceSimulator s = new BeagleSequenceSimulator(partitionsList);
JavaScript
mit
b020cb1ee61c3483d0fa2a3714f514c89beff250
0
tangrams/tangram,tangrams/tangram
import Scene from '../src/scene'; import * as URLs from '../src/utils/urls'; /* Special web worker treatment: - Custom worker build to use the Babel runtime (since there seem to be issues w/multiple instances of the polyfill getting instantiated on each test run otherwise). - Stub the worker so that we only load it once, to avoid flooding connections (was causing disconnnect errors). */ let worker_url = '/tangram.test.js'; function loadWorkerContent(url) { let xhr = new XMLHttpRequest(), response; xhr.onreadystatechange = () => { if (xhr.readyState === 4 && xhr.status === 200) { response = xhr.responseText; } }; xhr.onerror = (error) => { throw error; }; xhr.open('GET', url, false); xhr.send(); return response; } let workerBody = loadWorkerContent(worker_url); sinon.stub(Scene.prototype, 'getWorkerUrl').returns( URL.createObjectURL(new Blob([workerBody], { type: 'application/javascript' })) ); sinon.stub(URLs, 'revokeObjectURL').returns(null); let container = document.createElement('div'); container.style.width = '250px'; container.style.height = '250px'; document.body.appendChild(container); window.makeScene = function (options) { options = options || {}; options.disableRenderLoop = options.disableRenderLoop || true; options.workerUrl = options.workerUrl || worker_url; options.container = options.container || container; options.logLevel = options.logLevel || 'info'; return new Scene( options.config || 'http://localhost:9876/base/test/fixtures/sample-scene.yaml', options ); };
test/helpers.js
import Scene from '../src/scene'; /* Special web worker treatment: - Custom worker build to use the Babel runtime (since there seem to be issues w/multiple instances of the polyfill getting instantiated on each test run otherwise). - Stub the worker so that we only load it once, to avoid flooding connections (was causing disconnnect errors). */ let worker_url = '/tangram.test.js'; function loadWorkerContent(url) { let xhr = new XMLHttpRequest(), response; xhr.onreadystatechange = () => { if (xhr.readyState === 4 && xhr.status === 200) { response = xhr.responseText; } }; xhr.onerror = (error) => { throw error; }; xhr.open('GET', url, false); xhr.send(); return response; } let workerBody = loadWorkerContent(worker_url); sinon.stub(Scene.prototype, 'getWorkerUrl').returns( URL.createObjectURL(new Blob([workerBody], { type: 'application/javascript' })) ); let container = document.createElement('div'); container.style.width = '250px'; container.style.height = '250px'; document.body.appendChild(container); window.makeScene = function (options) { options = options || {}; options.disableRenderLoop = options.disableRenderLoop || true; options.workerUrl = options.workerUrl || worker_url; options.container = options.container || container; options.logLevel = options.logLevel || 'info'; return new Scene( options.config || 'http://localhost:9876/base/test/fixtures/sample-scene.yaml', options ); };
tests: don't revoke object URLs TODO: find a better solution, this is a quick fix for "The operation is insecure" errors in karma/sauce
test/helpers.js
tests: don't revoke object URLs TODO: find a better solution, this is a quick fix for "The operation is insecure" errors in karma/sauce
<ide><path>est/helpers.js <ide> import Scene from '../src/scene'; <add>import * as URLs from '../src/utils/urls'; <ide> <ide> /* <ide> Special web worker treatment: <ide> URL.createObjectURL(new Blob([workerBody], { type: 'application/javascript' })) <ide> ); <ide> <add>sinon.stub(URLs, 'revokeObjectURL').returns(null); <add> <ide> let container = document.createElement('div'); <ide> container.style.width = '250px'; <ide> container.style.height = '250px';
Java
mit
247bb8ee6c65d74f040d915674984ebed97b0bc7
0
open-keychain/spongycastle,Skywalker-11/spongycastle,Skywalker-11/spongycastle,open-keychain/spongycastle,Skywalker-11/spongycastle,open-keychain/spongycastle,bcgit/bc-java,bcgit/bc-java,bcgit/bc-java
package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; /** * The KeyPurposeId object. * <pre> * KeyPurposeId ::= OBJECT IDENTIFIER * * id-kp ::= OBJECT IDENTIFIER { iso(1) identified-organization(3) * dod(6) internet(1) security(5) mechanisms(5) pkix(7) 3} * * </pre> * To create a new KeyPurposeId where none of the below suit, use * <pre> * ASN1ObjectIdentifier newKeyPurposeIdOID = new ASN1ObjectIdentifier("1.3.6.1..."); * * KeyPurposeId newKeyPurposeId = KeyPurposeId.getInstance(newKeyPurposeIdOID); * </pre> */ public class KeyPurposeId extends ASN1Object { private static final ASN1ObjectIdentifier id_kp = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.3"); /** * { 2 5 29 37 0 } */ public static final KeyPurposeId anyExtendedKeyUsage = new KeyPurposeId(Extension.extendedKeyUsage.branch("0")); /** * { id-kp 1 } */ public static final KeyPurposeId id_kp_serverAuth = new KeyPurposeId(id_kp.branch("1")); /** * { id-kp 2 } */ public static final KeyPurposeId id_kp_clientAuth = new KeyPurposeId(id_kp.branch("2")); /** * { id-kp 3 } */ public static final KeyPurposeId id_kp_codeSigning = new KeyPurposeId(id_kp.branch("3")); /** * { id-kp 4 } */ public static final KeyPurposeId id_kp_emailProtection = new KeyPurposeId(id_kp.branch("4")); /** * Usage deprecated by RFC4945 - was { id-kp 5 } */ public static final KeyPurposeId id_kp_ipsecEndSystem = new KeyPurposeId(id_kp.branch("5")); /** * Usage deprecated by RFC4945 - was { id-kp 6 } */ public static final KeyPurposeId id_kp_ipsecTunnel = new KeyPurposeId(id_kp.branch("6")); /** * Usage deprecated by RFC4945 - was { idkp 7 } */ public static final KeyPurposeId id_kp_ipsecUser = new KeyPurposeId(id_kp.branch("7")); /** * { id-kp 8 } */ public static final KeyPurposeId id_kp_timeStamping = new KeyPurposeId(id_kp.branch("8")); /** * { id-kp 9 } */ public static final KeyPurposeId id_kp_OCSPSigning = new KeyPurposeId(id_kp.branch("9")); /** * { id-kp 10 } */ public static final KeyPurposeId id_kp_dvcs = new KeyPurposeId(id_kp.branch("10")); /** * { id-kp 11 } */ public static final KeyPurposeId id_kp_sbgpCertAAServerAuth = new KeyPurposeId(id_kp.branch("11")); /** * { id-kp 12 } */ public static final KeyPurposeId id_kp_scvp_responder = new KeyPurposeId(id_kp.branch("12")); /** * { id-kp 13 } */ public static final KeyPurposeId id_kp_eapOverPPP = new KeyPurposeId(id_kp.branch("13")); /** * { id-kp 14 } */ public static final KeyPurposeId id_kp_eapOverLAN = new KeyPurposeId(id_kp.branch("14")); /** * { id-kp 15 } */ public static final KeyPurposeId id_kp_scvpServer = new KeyPurposeId(id_kp.branch("15")); /** * { id-kp 16 } */ public static final KeyPurposeId id_kp_scvpClient = new KeyPurposeId(id_kp.branch("16")); /** * { id-kp 17 } */ public static final KeyPurposeId id_kp_ipsecIKE = new KeyPurposeId(id_kp.branch("17")); /** * { id-kp 18 } */ public static final KeyPurposeId id_kp_capwapAC = new KeyPurposeId(id_kp.branch("18")); /** * { id-kp 19 } */ public static final KeyPurposeId id_kp_capwapWTP = new KeyPurposeId(id_kp.branch("19")); // // microsoft key purpose ids // /** * { 1 3 6 1 4 1 311 20 2 2 } */ public static final KeyPurposeId id_kp_smartcardlogon = new KeyPurposeId(new ASN1ObjectIdentifier("1.3.6.1.4.1.311.20.2.2")); private ASN1ObjectIdentifier id; private KeyPurposeId(ASN1ObjectIdentifier id) { this.id = id; } /** * @deprecated use getInstance and an OID or one of the constants above. * @param id string representation of an OID. */ public KeyPurposeId(String id) { this(new ASN1ObjectIdentifier(id)); } public static KeyPurposeId getInstance(Object o) { if (o instanceof KeyPurposeId) { return (KeyPurposeId)o; } else if (o != null) { return new KeyPurposeId(ASN1ObjectIdentifier.getInstance(o)); } return null; } public ASN1ObjectIdentifier toOID() { return id; } public ASN1Primitive toASN1Primitive() { return id; } public String getId() { return id.getId(); } public String toString() { return id.toString(); } }
core/src/main/java/org/bouncycastle/asn1/x509/KeyPurposeId.java
package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; /** * The KeyPurposeId object. * <pre> * KeyPurposeId ::= OBJECT IDENTIFIER * * id-kp ::= OBJECT IDENTIFIER { iso(1) identified-organization(3) * dod(6) internet(1) security(5) mechanisms(5) pkix(7) 3} * * </pre> * To create a new KeyPurposeId where none of the below suit, use * <pre> * ASN1ObjectIdentifier newKeyPurposeIdOID = new ASN1ObjectIdentifier("1.3.6.1..."); * * KeyPurposeId newKeyPurposeId = KeyPurposeId.getInstance(newKeyPurposeIdOID); * </pre> */ public class KeyPurposeId extends ASN1Object { private static final ASN1ObjectIdentifier id_kp = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.3"); /** * { 2 5 29 37 0 } */ public static final KeyPurposeId anyExtendedKeyUsage = new KeyPurposeId(Extension.extendedKeyUsage.branch("0")); /** * { id-kp 1 } */ public static final KeyPurposeId id_kp_serverAuth = new KeyPurposeId(id_kp.branch("1")); /** * { id-kp 2 } */ public static final KeyPurposeId id_kp_clientAuth = new KeyPurposeId(id_kp.branch("2")); /** * { id-kp 3 } */ public static final KeyPurposeId id_kp_codeSigning = new KeyPurposeId(id_kp.branch("3")); /** * { id-kp 4 } */ public static final KeyPurposeId id_kp_emailProtection = new KeyPurposeId(id_kp.branch("4")); /** * Usage deprecated by RFC4945 - was { id-kp 5 } */ public static final KeyPurposeId id_kp_ipsecEndSystem = new KeyPurposeId(id_kp.branch("5")); /** * Usage deprecated by RFC4945 - was { id-kp 6 } */ public static final KeyPurposeId id_kp_ipsecTunnel = new KeyPurposeId(id_kp.branch("6")); /** * Usage deprecated by RFC4945 - was { idkp 7 } */ public static final KeyPurposeId id_kp_ipsecUser = new KeyPurposeId(id_kp.branch("7")); /** * { id-kp 8 } */ public static final KeyPurposeId id_kp_timeStamping = new KeyPurposeId(id_kp.branch("8")); /** * { id-kp 9 } */ public static final KeyPurposeId id_kp_OCSPSigning = new KeyPurposeId(id_kp.branch("9")); /** * { id-kp 10 } */ public static final KeyPurposeId id_kp_dvcs = new KeyPurposeId(id_kp.branch("10")); /** * { id-kp 11 } */ public static final KeyPurposeId id_kp_sbgpCertAAServerAuth = new KeyPurposeId(id_kp.branch("11")); /** * { id-kp 12 } */ public static final KeyPurposeId id_kp_scvp_responder = new KeyPurposeId(id_kp.branch("12")); /** * { id-kp 13 } */ public static final KeyPurposeId id_kp_eapOverPPP = new KeyPurposeId(id_kp.branch("13")); /** * { id-kp 14 } */ public static final KeyPurposeId id_kp_eapOverLAN = new KeyPurposeId(id_kp.branch("14")); /** * { id-kp 15 } */ public static final KeyPurposeId id_kp_scvpServer = new KeyPurposeId(id_kp.branch("15")); /** * { id-kp 16 } */ public static final KeyPurposeId id_kp_scvpClient = new KeyPurposeId(id_kp.branch("16")); /** * { id-kp 17 } */ public static final KeyPurposeId id_kp_ipsecIKE = new KeyPurposeId(id_kp.branch("17")); /** * { id-kp 18 } */ public static final KeyPurposeId id_kp_capwapAC = new KeyPurposeId(id_kp.branch("18")); /** * { id-kp 19 } */ public static final KeyPurposeId id_kp_capwapWTP = new KeyPurposeId(id_kp.branch("19")); // // microsoft key purpose ids // /** * { 1 3 6 1 4 1 311 20 2 2 } */ public static final KeyPurposeId id_kp_smartcardlogon = new KeyPurposeId(new ASN1ObjectIdentifier("1.3.6.1.4.1.311.20.2.2")); private ASN1ObjectIdentifier id; private KeyPurposeId(ASN1ObjectIdentifier id) { this.id = id; } /** * @deprecated use getInstance and an OID or one of the constants above. * @param id string representation of an OID. */ public KeyPurposeId(String id) { this(new ASN1ObjectIdentifier(id)); } public static KeyPurposeId getInstance(Object o) { if (o instanceof KeyPurposeId) { return (KeyPurposeId)o; } else if (o != null) { return new KeyPurposeId(ASN1ObjectIdentifier.getInstance(o)); } return null; } public ASN1ObjectIdentifier toOID() { return id; } public ASN1Primitive toASN1Primitive() { return id; } public String getId() { return id.getId(); } }
Added toString() method.
core/src/main/java/org/bouncycastle/asn1/x509/KeyPurposeId.java
Added toString() method.
<ide><path>ore/src/main/java/org/bouncycastle/asn1/x509/KeyPurposeId.java <ide> { <ide> return id.getId(); <ide> } <add> <add> public String toString() <add> { <add> return id.toString(); <add> } <ide> }
Java
agpl-3.0
f7f4385d5d4fac6336f53fb0d5c7538d7c73769e
0
Heiner1/AndroidAPS,MilosKozak/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,winni67/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,PoweRGbg/AndroidAPS,PoweRGbg/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,MilosKozak/AndroidAPS
package info.nightscout.androidaps.plugins.IobCobCalculator; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.LongSparseArray; import com.squareup.otto.Subscribe; import org.json.JSONArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Date; import java.util.List; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventAppInitialized; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import static info.nightscout.utils.DateUtil.now; /** * Created by mike on 24.04.2017. */ public class IobCobCalculatorPlugin extends PluginBase { private Logger log = LoggerFactory.getLogger(IobCobCalculatorPlugin.class); private static IobCobCalculatorPlugin plugin = null; public static IobCobCalculatorPlugin getPlugin() { if (plugin == null) plugin = new IobCobCalculatorPlugin(); return plugin; } private LongSparseArray<IobTotal> iobTable = new LongSparseArray<>(); // oldest at index 0 private LongSparseArray<AutosensData> autosensDataTable = new LongSparseArray<>(); // oldest at index 0 private LongSparseArray<BasalData> basalDataTable = new LongSparseArray<>(); // oldest at index 0 private volatile List<BgReading> bgReadings = null; // newest at index 0 private volatile List<BgReading> bucketed_data = null; private double dia = Constants.defaultDIA; final Object dataLock = new Object(); boolean stopCalculationTrigger = false; private Thread thread = null; public IobCobCalculatorPlugin() { super(new PluginDescription() .mainType(PluginType.GENERAL) .pluginName(R.string.iobcobcalculator) .showInList(false) .neverVisible(true) .alwaysEnabled(true) ); } @Override protected void onStart() { MainApp.bus().register(this); super.onStart(); } @Override protected void onStop() { super.onStop(); MainApp.bus().unregister(this); } public LongSparseArray<AutosensData> getAutosensDataTable() { return autosensDataTable; } public List<BgReading> getBucketedData() { return bucketed_data; } @Nullable public List<BgReading> getBucketedData(long fromTime) { //log.debug("Locking getBucketedData"); synchronized (dataLock) { if (bucketed_data == null) { log.debug("No bucketed data available"); return null; } int index = indexNewerThan(fromTime); if (index > -1) { List<BgReading> part = bucketed_data.subList(0, index); log.debug("Bucketed data striped off: " + part.size() + "/" + bucketed_data.size()); return part; } } //log.debug("Releasing getBucketedData"); return null; } private int indexNewerThan(long time) { for (int index = 0; index < bucketed_data.size(); index++) { if (bucketed_data.get(index).date < time) return index - 1; } return -1; } public static long roundUpTime(long time) { if (time % 60000 == 0) return time; long rouded = (time / 60000 + 1) * 60000; return rouded; } void loadBgData(long start) { bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (start - 60 * 60 * 1000L * (24 + dia)), false); log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start)); } private boolean isAbout5minData() { synchronized (dataLock) { if (bgReadings == null || bgReadings.size() < 3) { return true; } long totalDiff = 0; for (int i = 1; i < bgReadings.size(); ++i) { long bgTime = bgReadings.get(i).date; long lastbgTime = bgReadings.get(i - 1).date; long diff = lastbgTime - bgTime; totalDiff += diff; if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30 log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false); return false; } } double intervals = totalDiff / (5 * 60 * 1000d); double variability = Math.abs(intervals - Math.round(intervals)); boolean is5mindata = variability < 0.02; log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata); return is5mindata; } } void createBucketedData() { if (isAbout5minData()) createBucketedData5min(); else createBucketedDataRecalculated(); } @Nullable private BgReading findNewer(long time) { BgReading lastFound = bgReadings.get(0); if (lastFound.date < time) return null; for (int i = 1; i < bgReadings.size(); ++i) { if (bgReadings.get(i).date > time) continue; lastFound = bgReadings.get(i); if (bgReadings.get(i).date < time) break; } return lastFound; } @Nullable private BgReading findOlder(long time) { BgReading lastFound = bgReadings.get(bgReadings.size() - 1); if (lastFound.date > time) return null; for (int i = bgReadings.size() - 2; i >= 0; --i) { if (bgReadings.get(i).date < time) continue; lastFound = bgReadings.get(i); if (bgReadings.get(i).date > time) break; } return lastFound; } private void createBucketedDataRecalculated() { if (bgReadings == null || bgReadings.size() < 3) { bucketed_data = null; return; } bucketed_data = new ArrayList<>(); long currentTime = bgReadings.get(0).date + 5 * 60 * 1000 - bgReadings.get(0).date % (5 * 60 * 1000) - 5 * 60 * 1000L; //log.debug("First reading: " + new Date(currentTime).toLocaleString()); while (true) { // test if current value is older than current time BgReading newer = findNewer(currentTime); BgReading older = findOlder(currentTime); if (newer == null || older == null) break; double bgDelta = newer.value - older.value; long timeDiffToNew = newer.date - currentTime; double currentBg = newer.value - (double) timeDiffToNew / (newer.date - older.date) * bgDelta; BgReading newBgreading = new BgReading(); newBgreading.date = currentTime; newBgreading.value = Math.round(currentBg); bucketed_data.add(newBgreading); //log.debug("BG: " + newBgreading.value + " (" + new Date(newBgreading.date).toLocaleString() + ") Prev: " + older.value + " (" + new Date(older.date).toLocaleString() + ") Newer: " + newer.value + " (" + new Date(newer.date).toLocaleString() + ")"); currentTime -= 5 * 60 * 1000L; } } private void createBucketedData5min() { if (bgReadings == null || bgReadings.size() < 3) { bucketed_data = null; return; } bucketed_data = new ArrayList<>(); bucketed_data.add(bgReadings.get(0)); int j = 0; for (int i = 1; i < bgReadings.size(); ++i) { long bgTime = bgReadings.get(i).date; long lastbgTime = bgReadings.get(i - 1).date; //log.error("Processing " + i + ": " + new Date(bgTime).toString() + " " + bgReadings.get(i).value + " Previous: " + new Date(lastbgTime).toString() + " " + bgReadings.get(i - 1).value); if (bgReadings.get(i).value < 39 || bgReadings.get(i - 1).value < 39) { continue; } long elapsed_minutes = (bgTime - lastbgTime) / (60 * 1000); if (Math.abs(elapsed_minutes) > 8) { // interpolate missing data points double lastbg = bgReadings.get(i - 1).value; elapsed_minutes = Math.abs(elapsed_minutes); //console.error(elapsed_minutes); long nextbgTime; while (elapsed_minutes > 5) { nextbgTime = lastbgTime - 5 * 60 * 1000; j++; BgReading newBgreading = new BgReading(); newBgreading.date = nextbgTime; double gapDelta = bgReadings.get(i).value - lastbg; //console.error(gapDelta, lastbg, elapsed_minutes); double nextbg = lastbg + (5d / elapsed_minutes * gapDelta); newBgreading.value = Math.round(nextbg); //console.error("Interpolated", bucketed_data[j]); bucketed_data.add(newBgreading); //log.error("******************************************************************************************************* Adding:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); elapsed_minutes = elapsed_minutes - 5; lastbg = nextbg; lastbgTime = nextbgTime; } j++; BgReading newBgreading = new BgReading(); newBgreading.value = bgReadings.get(i).value; newBgreading.date = bgTime; bucketed_data.add(newBgreading); //log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); } else if (Math.abs(elapsed_minutes) > 2) { j++; BgReading newBgreading = new BgReading(); newBgreading.value = bgReadings.get(i).value; newBgreading.date = bgTime; bucketed_data.add(newBgreading); //log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); } else { bucketed_data.get(j).value = (bucketed_data.get(j).value + bgReadings.get(i).value) / 2; //log.error("***** Average"); } } log.debug("Bucketed data created. Size: " + bucketed_data.size()); } public long oldestDataAvailable() { long now = System.currentTimeMillis(); long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable(); long getBGDataFrom = Math.max(oldestDataAvailable, (long) (now - 60 * 60 * 1000L * (24 + MainApp.getConfigBuilder().getProfile().getDia()))); log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); return getBGDataFrom; } public IobTotal calculateFromTreatmentsAndTempsSynchronized(long time, Profile profile) { synchronized (dataLock) { return calculateFromTreatmentsAndTemps(time, profile); } } public IobTotal calculateFromTreatmentsAndTemps(long time, Profile profile) { long now = System.currentTimeMillis(); time = roundUpTime(time); if (time < now && iobTable.get(time) != null) { //og.debug(">>> calculateFromTreatmentsAndTemps Cache hit " + new Date(time).toLocaleString()); return iobTable.get(time); } else { //log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); } IobTotal bolusIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTreatments(time).round(); IobTotal basalIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTempBasals(time, profile, true, now).round(); if (OpenAPSSMBPlugin.getPlugin().isEnabled(PluginType.APS)) { // Add expected zero temp basal for next 240 mins IobTotal basalIobWithZeroTemp = basalIob.copy(); TemporaryBasal t = new TemporaryBasal() .date(now + 60 * 1000L) .duration(240) .absolute(0); if (t.date < time) { IobTotal calc = t.iobCalc(time, profile); basalIobWithZeroTemp.plus(calc); } basalIob.iobWithZeroTemp = IobTotal.combine(bolusIob, basalIobWithZeroTemp).round(); } IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round(); if (time < System.currentTimeMillis()) { iobTable.put(time, iobTotal); } return iobTotal; } @Nullable private Long findPreviousTimeFromBucketedData(long time) { if (bucketed_data == null) return null; for (int index = 0; index < bucketed_data.size(); index++) { if (bucketed_data.get(index).date < time) return bucketed_data.get(index).date; } return null; } public BasalData getBasalData(Profile profile, long time) { long now = System.currentTimeMillis(); time = roundUpTime(time); BasalData retval = basalDataTable.get(time); if (retval == null) { retval = new BasalData(); TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(time); retval.basal = profile.getBasal(time); if (tb != null) { retval.isTempBasalRunning = true; retval.tempBasalAbsolute = tb.tempBasalConvertedToAbsolute(time, profile); } else { retval.isTempBasalRunning = false; retval.tempBasalAbsolute = retval.basal; } if (time < now) { basalDataTable.append(time, retval); } //log.debug(">>> getBasalData Cache miss " + new Date(time).toLocaleString()); } else { //log.debug(">>> getBasalData Cache hit " + new Date(time).toLocaleString()); } return retval; } @Nullable public AutosensData getAutosensData(long time) { synchronized (dataLock) { long now = System.currentTimeMillis(); if (time > now) return null; Long previous = findPreviousTimeFromBucketedData(time); if (previous == null) return null; time = roundUpTime(previous); AutosensData data = autosensDataTable.get(time); if (data != null) { //log.debug(">>> getAutosensData Cache hit " + data.log(time)); return data; } else { //log.debug(">>> getAutosensData Cache miss " + new Date(time).toLocaleString()); return null; } } } @Nullable public AutosensData getLastAutosensDataSynchronized(String reason) { synchronized (dataLock) { return getLastAutosensData(reason); } } @NonNull public CobInfo getCobInfo(boolean _synchronized, String reason) { AutosensData autosensData = _synchronized ? getLastAutosensDataSynchronized(reason) : getLastAutosensData(reason); Double displayCob = null; double futureCarbs = 0; long now = now(); List<Treatment> treatments = TreatmentsPlugin.getPlugin().getTreatmentsFromHistory(); if (autosensData != null) { displayCob = autosensData.cob; for (Treatment treatment : treatments) { if (!treatment.isValid) continue; if (IobCobCalculatorPlugin.roundUpTime(treatment.date) > IobCobCalculatorPlugin.roundUpTime(autosensData.time) && treatment.date <= now && treatment.carbs > 0) { displayCob += treatment.carbs; } } } for (Treatment treatment : treatments) { if (!treatment.isValid) continue; if (treatment.date > now && treatment.carbs > 0) { futureCarbs += treatment.carbs; } } return new CobInfo(displayCob, futureCarbs); } @Nullable public AutosensData getLastAutosensData(String reason) { if (autosensDataTable.size() < 1) { log.debug("AUTOSENSDATA null: autosensDataTable empty (" + reason + ")"); return null; } AutosensData data; try { data = autosensDataTable.valueAt(autosensDataTable.size() - 1); } catch (Exception e) { // data can be processed on the background // in this rare case better return null and do not block UI // APS plugin should use getLastAutosensDataSynchronized where the blocking is not an issue log.debug("AUTOSENSDATA null: Exception catched (" + reason + ")"); return null; } if (data.time < System.currentTimeMillis() - 11 * 60 * 1000) { log.debug("AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time)); return null; } else { return data; } } public IobTotal[] calculateIobArrayInDia(Profile profile) { // predict IOB out to DIA plus 30m long time = System.currentTimeMillis(); time = roundUpTime(time); int len = (int) ((profile.getDia() * 60 + 30) / 5); IobTotal[] array = new IobTotal[len]; int pos = 0; for (int i = 0; i < len; i++) { long t = time + i * 5 * 60000; IobTotal iob = calculateFromTreatmentsAndTempsSynchronized(t, profile); array[pos] = iob; pos++; } return array; } public IobTotal[] calculateIobArrayForSMB(Profile profile) { // predict IOB out to DIA plus 30m long time = System.currentTimeMillis(); time = roundUpTime(time); int len = (4 * 60) / 5; IobTotal[] array = new IobTotal[len]; int pos = 0; for (int i = 0; i < len; i++) { long t = time + i * 5 * 60000; IobTotal iob = calculateFromTreatmentsAndTempsSynchronized(t, profile); array[pos] = iob; pos++; } return array; } public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) { synchronized (dataLock) { return detectSensitivity(fromTime, toTime); } } static AutosensResult detectSensitivity(long fromTime, long toTime) { return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(fromTime, toTime); } public static JSONArray convertToJSONArray(IobTotal[] iobArray) { JSONArray array = new JSONArray(); for (int i = 0; i < iobArray.length; i++) { array.put(iobArray[i].determineBasalJson()); } return array; } @Subscribe @SuppressWarnings("unused") public void onEventAppInitialized(EventAppInitialized ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, ev); } @Subscribe @SuppressWarnings("unused") public void onEventNewBG(EventNewBG ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } stopCalculation("onEventNewBG"); runCalculation("onEventNewBG", System.currentTimeMillis(), true, ev); } private void stopCalculation(String from) { if (thread != null && thread.getState() != Thread.State.TERMINATED) { stopCalculationTrigger = true; log.debug("Stopping calculation thread: " + from); while (thread.getState() != Thread.State.TERMINATED) { SystemClock.sleep(100); } log.debug("Calculation thread stopped: " + from); } } public void runCalculation(String from, long start, boolean bgDataReload, Event cause) { log.debug("Starting calculation thread: " + from); if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) thread = new IobCobOref1Thread(this, from, start, bgDataReload, cause); else thread = new IobCobThread(this, from, start, bgDataReload, cause); thread.start(); } } @Subscribe public void onNewProfile(EventNewBasalProfile ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } if (MainApp.getConfigBuilder() == null) return; // app still initializing Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) return; // app still initializing dia = profile.getDia(); if (ev == null) { // on init no need of reset return; } stopCalculation("onNewProfile"); synchronized (dataLock) { log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } runCalculation("onNewProfile", System.currentTimeMillis(), false, ev); } @Subscribe public void onEventPreferenceChange(EventPreferenceChange ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } if (ev.isChanged(R.string.key_openapsama_autosens_period) || ev.isChanged(R.string.key_age) || ev.isChanged(R.string.key_absorption_maxtime) || ev.isChanged(R.string.key_openapsama_min_5m_carbimpact) || ev.isChanged(R.string.key_absorption_cutoff) || ev.isChanged(R.string.key_openapsama_autosens_max) || ev.isChanged(R.string.key_openapsama_autosens_min) ) { stopCalculation("onEventPreferenceChange"); synchronized (dataLock) { log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, ev); } } @Subscribe public void onEventConfigBuilderChange(EventConfigBuilderChange ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } stopCalculation("onEventConfigBuilderChange"); synchronized (dataLock) { log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, ev); } // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated @Subscribe public void onEventNewHistoryData(EventNewHistoryData ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } //log.debug("Locking onNewHistoryData"); stopCalculation("onEventNewHistoryData"); synchronized (dataLock) { // clear up 5 min back for proper COB calculation long time = ev.time - 5 * 60 * 1000L; log.debug("Invalidating cached data to: " + new Date(time).toLocaleString()); for (int index = iobTable.size() - 1; index >= 0; index--) { if (iobTable.keyAt(index) > time) { if (Config.logAutosensData) log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString()); iobTable.removeAt(index); } else { break; } } for (int index = autosensDataTable.size() - 1; index >= 0; index--) { if (autosensDataTable.keyAt(index) > time) { if (Config.logAutosensData) log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString()); autosensDataTable.removeAt(index); } else { break; } } for (int index = basalDataTable.size() - 1; index >= 0; index--) { if (basalDataTable.keyAt(index) > time) { if (Config.logAutosensData) log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString()); basalDataTable.removeAt(index); } else { break; } } } runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, ev); //log.debug("Releasing onNewHistoryData"); } public void clearCache() { synchronized (dataLock) { log.debug("Clearing cached data."); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } } // From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 // Returns the value at a given percentile in a sorted numeric array. // "Linear interpolation between closest ranks" method public static double percentile(Double[] arr, double p) { if (arr.length == 0) return 0; if (p <= 0) return arr[0]; if (p >= 1) return arr[arr.length - 1]; double index = arr.length * p, lower = Math.floor(index), upper = lower + 1, weight = index % 1; if (upper >= arr.length) return arr[(int) lower]; return arr[(int) lower] * (1 - weight) + arr[(int) upper] * weight; } }
app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java
package info.nightscout.androidaps.plugins.IobCobCalculator; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.LongSparseArray; import com.squareup.otto.Subscribe; import org.json.JSONArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Date; import java.util.List; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventAppInitialized; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import static info.nightscout.utils.DateUtil.now; /** * Created by mike on 24.04.2017. */ public class IobCobCalculatorPlugin extends PluginBase { private Logger log = LoggerFactory.getLogger(IobCobCalculatorPlugin.class); private static IobCobCalculatorPlugin plugin = null; public static IobCobCalculatorPlugin getPlugin() { if (plugin == null) plugin = new IobCobCalculatorPlugin(); return plugin; } private LongSparseArray<IobTotal> iobTable = new LongSparseArray<>(); // oldest at index 0 private LongSparseArray<AutosensData> autosensDataTable = new LongSparseArray<>(); // oldest at index 0 private LongSparseArray<BasalData> basalDataTable = new LongSparseArray<>(); // oldest at index 0 private volatile List<BgReading> bgReadings = null; // newest at index 0 private volatile List<BgReading> bucketed_data = null; private double dia = Constants.defaultDIA; final Object dataLock = new Object(); boolean stopCalculationTrigger = false; private Thread thread = null; public IobCobCalculatorPlugin() { super(new PluginDescription() .mainType(PluginType.GENERAL) .pluginName(R.string.iobcobcalculator) .showInList(false) .neverVisible(true) .alwaysEnabled(true) ); } @Override protected void onStart() { MainApp.bus().register(this); super.onStart(); } @Override protected void onStop() { super.onStop(); MainApp.bus().unregister(this); } public LongSparseArray<AutosensData> getAutosensDataTable() { return autosensDataTable; } public List<BgReading> getBucketedData() { return bucketed_data; } @Nullable public List<BgReading> getBucketedData(long fromTime) { //log.debug("Locking getBucketedData"); synchronized (dataLock) { if (bucketed_data == null) { log.debug("No bucketed data available"); return null; } int index = indexNewerThan(fromTime); if (index > -1) { List<BgReading> part = bucketed_data.subList(0, index); log.debug("Bucketed data striped off: " + part.size() + "/" + bucketed_data.size()); return part; } } //log.debug("Releasing getBucketedData"); return null; } private int indexNewerThan(long time) { for (int index = 0; index < bucketed_data.size(); index++) { if (bucketed_data.get(index).date < time) return index - 1; } return -1; } public static long roundUpTime(long time) { if (time % 60000 == 0) return time; long rouded = (time / 60000 + 1) * 60000; return rouded; } void loadBgData(long start) { bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (start - 60 * 60 * 1000L * (24 + dia)), false); log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start)); } private boolean isAbout5minData() { synchronized (dataLock) { if (bgReadings == null || bgReadings.size() < 3) { return true; } long totalDiff = 0; for (int i = 1; i < bgReadings.size(); ++i) { long bgTime = bgReadings.get(i).date; long lastbgTime = bgReadings.get(i - 1).date; long diff = lastbgTime - bgTime; totalDiff += diff; if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30 log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false); return false; } } double intervals = totalDiff / (5 * 60 * 1000d); double variability = Math.abs(intervals - Math.round(intervals)); boolean is5mindata = variability < 0.02; log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata); return is5mindata; } } void createBucketedData() { if (isAbout5minData()) createBucketedData5min(); else createBucketedDataRecalculated(); } @Nullable private BgReading findNewer(long time) { BgReading lastFound = bgReadings.get(0); if (lastFound.date < time) return null; for (int i = 1; i < bgReadings.size(); ++i) { if (bgReadings.get(i).date > time) continue; lastFound = bgReadings.get(i); if (bgReadings.get(i).date < time) break; } return lastFound; } @Nullable private BgReading findOlder(long time) { BgReading lastFound = bgReadings.get(bgReadings.size() - 1); if (lastFound.date > time) return null; for (int i = bgReadings.size() - 2; i >= 0; --i) { if (bgReadings.get(i).date < time) continue; lastFound = bgReadings.get(i); if (bgReadings.get(i).date > time) break; } return lastFound; } private void createBucketedDataRecalculated() { if (bgReadings == null || bgReadings.size() < 3) { bucketed_data = null; return; } bucketed_data = new ArrayList<>(); long currentTime = bgReadings.get(0).date + 5 * 60 * 1000 - bgReadings.get(0).date % (5 * 60 * 1000) - 5 * 60 * 1000L; //log.debug("First reading: " + new Date(currentTime).toLocaleString()); while (true) { // test if current value is older than current time BgReading newer = findNewer(currentTime); BgReading older = findOlder(currentTime); if (newer == null || older == null) break; double bgDelta = newer.value - older.value; long timeDiffToNew = newer.date - currentTime; double currentBg = newer.value - (double) timeDiffToNew / (newer.date - older.date) * bgDelta; BgReading newBgreading = new BgReading(); newBgreading.date = currentTime; newBgreading.value = Math.round(currentBg); bucketed_data.add(newBgreading); //log.debug("BG: " + newBgreading.value + " (" + new Date(newBgreading.date).toLocaleString() + ") Prev: " + older.value + " (" + new Date(older.date).toLocaleString() + ") Newer: " + newer.value + " (" + new Date(newer.date).toLocaleString() + ")"); currentTime -= 5 * 60 * 1000L; } } private void createBucketedData5min() { if (bgReadings == null || bgReadings.size() < 3) { bucketed_data = null; return; } bucketed_data = new ArrayList<>(); bucketed_data.add(bgReadings.get(0)); int j = 0; for (int i = 1; i < bgReadings.size(); ++i) { long bgTime = bgReadings.get(i).date; long lastbgTime = bgReadings.get(i - 1).date; //log.error("Processing " + i + ": " + new Date(bgTime).toString() + " " + bgReadings.get(i).value + " Previous: " + new Date(lastbgTime).toString() + " " + bgReadings.get(i - 1).value); if (bgReadings.get(i).value < 39 || bgReadings.get(i - 1).value < 39) { continue; } long elapsed_minutes = (bgTime - lastbgTime) / (60 * 1000); if (Math.abs(elapsed_minutes) > 8) { // interpolate missing data points double lastbg = bgReadings.get(i - 1).value; elapsed_minutes = Math.abs(elapsed_minutes); //console.error(elapsed_minutes); long nextbgTime; while (elapsed_minutes > 5) { nextbgTime = lastbgTime - 5 * 60 * 1000; j++; BgReading newBgreading = new BgReading(); newBgreading.date = nextbgTime; double gapDelta = bgReadings.get(i).value - lastbg; //console.error(gapDelta, lastbg, elapsed_minutes); double nextbg = lastbg + (5d / elapsed_minutes * gapDelta); newBgreading.value = Math.round(nextbg); //console.error("Interpolated", bucketed_data[j]); bucketed_data.add(newBgreading); //log.error("******************************************************************************************************* Adding:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); elapsed_minutes = elapsed_minutes - 5; lastbg = nextbg; lastbgTime = nextbgTime; } j++; BgReading newBgreading = new BgReading(); newBgreading.value = bgReadings.get(i).value; newBgreading.date = bgTime; bucketed_data.add(newBgreading); //log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); } else if (Math.abs(elapsed_minutes) > 2) { j++; BgReading newBgreading = new BgReading(); newBgreading.value = bgReadings.get(i).value; newBgreading.date = bgTime; bucketed_data.add(newBgreading); //log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); } else { bucketed_data.get(j).value = (bucketed_data.get(j).value + bgReadings.get(i).value) / 2; //log.error("***** Average"); } } log.debug("Bucketed data created. Size: " + bucketed_data.size()); } public long oldestDataAvailable() { long now = System.currentTimeMillis(); long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable(); long getBGDataFrom = Math.max(oldestDataAvailable, (long) (now - 60 * 60 * 1000L * (24 + MainApp.getConfigBuilder().getProfile().getDia()))); log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); return getBGDataFrom; } public IobTotal calculateFromTreatmentsAndTempsSynchronized(long time, Profile profile) { synchronized (dataLock) { return calculateFromTreatmentsAndTemps(time, profile); } } public IobTotal calculateFromTreatmentsAndTemps(long time, Profile profile) { long now = System.currentTimeMillis(); time = roundUpTime(time); if (time < now && iobTable.get(time) != null) { //og.debug(">>> calculateFromTreatmentsAndTemps Cache hit " + new Date(time).toLocaleString()); return iobTable.get(time); } else { //log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); } IobTotal bolusIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTreatments(time).round(); IobTotal basalIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTempBasals(time, profile, true, now).round(); if (OpenAPSSMBPlugin.getPlugin().isEnabled(PluginType.APS)) { // Add expected zero temp basal for next 240 mins IobTotal basalIobWithZeroTemp = basalIob.copy(); TemporaryBasal t = new TemporaryBasal() .date(now + 60 * 1000L) .duration(240) .absolute(0); if (t.date < time) { IobTotal calc = t.iobCalc(time, profile); basalIobWithZeroTemp.plus(calc); } basalIob.iobWithZeroTemp = IobTotal.combine(bolusIob, basalIobWithZeroTemp).round(); } IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round(); if (time < System.currentTimeMillis()) { iobTable.put(time, iobTotal); } return iobTotal; } @Nullable private Long findPreviousTimeFromBucketedData(long time) { if (bucketed_data == null) return null; for (int index = 0; index < bucketed_data.size(); index++) { if (bucketed_data.get(index).date < time) return bucketed_data.get(index).date; } return null; } public BasalData getBasalData(Profile profile, long time) { long now = System.currentTimeMillis(); time = roundUpTime(time); BasalData retval = basalDataTable.get(time); if (retval == null) { retval = new BasalData(); TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(time); retval.basal = profile.getBasal(time); if (tb != null) { retval.isTempBasalRunning = true; retval.tempBasalAbsolute = tb.tempBasalConvertedToAbsolute(time, profile); } else { retval.isTempBasalRunning = false; retval.tempBasalAbsolute = retval.basal; } if (time < now) { basalDataTable.append(time, retval); } //log.debug(">>> getBasalData Cache miss " + new Date(time).toLocaleString()); } else { //log.debug(">>> getBasalData Cache hit " + new Date(time).toLocaleString()); } return retval; } @Nullable public AutosensData getAutosensData(long time) { synchronized (dataLock) { long now = System.currentTimeMillis(); if (time > now) return null; Long previous = findPreviousTimeFromBucketedData(time); if (previous == null) return null; time = roundUpTime(previous); AutosensData data = autosensDataTable.get(time); if (data != null) { //log.debug(">>> getAutosensData Cache hit " + data.log(time)); return data; } else { if (time > now) { // data may not be calculated yet, use last data return getLastAutosensData("getAutosensData"); } //log.debug(">>> getAutosensData Cache miss " + new Date(time).toLocaleString()); return null; } } } @Nullable public AutosensData getLastAutosensDataSynchronized(String reason) { synchronized (dataLock) { return getLastAutosensData(reason); } } @NonNull public CobInfo getCobInfo(boolean _synchronized, String reason) { AutosensData autosensData = _synchronized ? getLastAutosensDataSynchronized(reason) : getLastAutosensData(reason); Double displayCob = null; double futureCarbs = 0; long now = now(); List<Treatment> treatments = TreatmentsPlugin.getPlugin().getTreatmentsFromHistory(); if (autosensData != null) { displayCob = autosensData.cob; for (Treatment treatment : treatments) { if (!treatment.isValid) continue; if (IobCobCalculatorPlugin.roundUpTime(treatment.date) > IobCobCalculatorPlugin.roundUpTime(autosensData.time) && treatment.date <= now && treatment.carbs > 0) { displayCob += treatment.carbs; } } } for (Treatment treatment : treatments) { if (!treatment.isValid) continue; if (treatment.date > now && treatment.carbs > 0) { futureCarbs += treatment.carbs; } } return new CobInfo(displayCob, futureCarbs); } @Nullable public AutosensData getLastAutosensData(String reason) { if (autosensDataTable.size() < 1) { log.debug("AUTOSENSDATA null: autosensDataTable empty (" + reason + ")"); return null; } AutosensData data; try { data = autosensDataTable.valueAt(autosensDataTable.size() - 1); } catch (Exception e) { // data can be processed on the background // in this rare case better return null and do not block UI // APS plugin should use getLastAutosensDataSynchronized where the blocking is not an issue log.debug("AUTOSENSDATA null: Exception catched (" + reason + ")"); return null; } if (data.time < System.currentTimeMillis() - 11 * 60 * 1000) { log.debug("AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time)); return null; } else { return data; } } public IobTotal[] calculateIobArrayInDia(Profile profile) { // predict IOB out to DIA plus 30m long time = System.currentTimeMillis(); time = roundUpTime(time); int len = (int) ((profile.getDia() * 60 + 30) / 5); IobTotal[] array = new IobTotal[len]; int pos = 0; for (int i = 0; i < len; i++) { long t = time + i * 5 * 60000; IobTotal iob = calculateFromTreatmentsAndTempsSynchronized(t, profile); array[pos] = iob; pos++; } return array; } public IobTotal[] calculateIobArrayForSMB(Profile profile) { // predict IOB out to DIA plus 30m long time = System.currentTimeMillis(); time = roundUpTime(time); int len = (4 * 60) / 5; IobTotal[] array = new IobTotal[len]; int pos = 0; for (int i = 0; i < len; i++) { long t = time + i * 5 * 60000; IobTotal iob = calculateFromTreatmentsAndTempsSynchronized(t, profile); array[pos] = iob; pos++; } return array; } public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) { synchronized (dataLock) { return detectSensitivity(fromTime, toTime); } } static AutosensResult detectSensitivity(long fromTime, long toTime) { return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(fromTime, toTime); } public static JSONArray convertToJSONArray(IobTotal[] iobArray) { JSONArray array = new JSONArray(); for (int i = 0; i < iobArray.length; i++) { array.put(iobArray[i].determineBasalJson()); } return array; } @Subscribe @SuppressWarnings("unused") public void onEventAppInitialized(EventAppInitialized ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, ev); } @Subscribe @SuppressWarnings("unused") public void onEventNewBG(EventNewBG ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } stopCalculation("onEventNewBG"); runCalculation("onEventNewBG", System.currentTimeMillis(), true, ev); } private void stopCalculation(String from) { if (thread != null && thread.getState() != Thread.State.TERMINATED) { stopCalculationTrigger = true; log.debug("Stopping calculation thread: " + from); while (thread.getState() != Thread.State.TERMINATED) { SystemClock.sleep(100); } log.debug("Calculation thread stopped: " + from); } } public void runCalculation(String from, long start, boolean bgDataReload, Event cause) { log.debug("Starting calculation thread: " + from); if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) thread = new IobCobOref1Thread(this, from, start, bgDataReload, cause); else thread = new IobCobThread(this, from, start, bgDataReload, cause); thread.start(); } } @Subscribe public void onNewProfile(EventNewBasalProfile ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } if (MainApp.getConfigBuilder() == null) return; // app still initializing Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) return; // app still initializing dia = profile.getDia(); if (ev == null) { // on init no need of reset return; } stopCalculation("onNewProfile"); synchronized (dataLock) { log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } runCalculation("onNewProfile", System.currentTimeMillis(), false, ev); } @Subscribe public void onEventPreferenceChange(EventPreferenceChange ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } if (ev.isChanged(R.string.key_openapsama_autosens_period) || ev.isChanged(R.string.key_age) || ev.isChanged(R.string.key_absorption_maxtime) || ev.isChanged(R.string.key_openapsama_min_5m_carbimpact) || ev.isChanged(R.string.key_absorption_cutoff) || ev.isChanged(R.string.key_openapsama_autosens_max) || ev.isChanged(R.string.key_openapsama_autosens_min) ) { stopCalculation("onEventPreferenceChange"); synchronized (dataLock) { log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, ev); } } @Subscribe public void onEventConfigBuilderChange(EventConfigBuilderChange ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } stopCalculation("onEventConfigBuilderChange"); synchronized (dataLock) { log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, ev); } // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated @Subscribe public void onEventNewHistoryData(EventNewHistoryData ev) { if (this != getPlugin()) { log.debug("Ignoring event for non default instance"); return; } //log.debug("Locking onNewHistoryData"); stopCalculation("onEventNewHistoryData"); synchronized (dataLock) { // clear up 5 min back for proper COB calculation long time = ev.time - 5 * 60 * 1000L; log.debug("Invalidating cached data to: " + new Date(time).toLocaleString()); for (int index = iobTable.size() - 1; index >= 0; index--) { if (iobTable.keyAt(index) > time) { if (Config.logAutosensData) log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString()); iobTable.removeAt(index); } else { break; } } for (int index = autosensDataTable.size() - 1; index >= 0; index--) { if (autosensDataTable.keyAt(index) > time) { if (Config.logAutosensData) log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString()); autosensDataTable.removeAt(index); } else { break; } } for (int index = basalDataTable.size() - 1; index >= 0; index--) { if (basalDataTable.keyAt(index) > time) { if (Config.logAutosensData) log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString()); basalDataTable.removeAt(index); } else { break; } } } runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, ev); //log.debug("Releasing onNewHistoryData"); } public void clearCache() { synchronized (dataLock) { log.debug("Clearing cached data."); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } } // From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 // Returns the value at a given percentile in a sorted numeric array. // "Linear interpolation between closest ranks" method public static double percentile(Double[] arr, double p) { if (arr.length == 0) return 0; if (p <= 0) return arr[0]; if (p >= 1) return arr[arr.length - 1]; double index = arr.length * p, lower = Math.floor(index), upper = lower + 1, weight = index % 1; if (upper >= arr.length) return arr[(int) lower]; return arr[(int) lower] * (1 - weight) + arr[(int) upper] * weight; } }
cleanup
app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java
cleanup
<ide><path>pp/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java <ide> //log.debug(">>> getAutosensData Cache hit " + data.log(time)); <ide> return data; <ide> } else { <del> if (time > now) { <del> // data may not be calculated yet, use last data <del> return getLastAutosensData("getAutosensData"); <del> } <ide> //log.debug(">>> getAutosensData Cache miss " + new Date(time).toLocaleString()); <ide> return null; <ide> }
Java
agpl-3.0
6a3e352b058ee51e371f504bea1cae096a5788a9
0
mbenguig/scheduling,ShatalovYaroslav/scheduling,laurianed/scheduling,paraita/scheduling,zeineb/scheduling,youribonnaffe/scheduling,tobwiens/scheduling,lpellegr/scheduling,fviale/scheduling,ShatalovYaroslav/scheduling,sgRomaric/scheduling,yinan-liu/scheduling,tobwiens/scheduling,zeineb/scheduling,laurianed/scheduling,sgRomaric/scheduling,marcocast/scheduling,tobwiens/scheduling,tobwiens/scheduling,yinan-liu/scheduling,lpellegr/scheduling,sandrineBeauche/scheduling,lpellegr/scheduling,sgRomaric/scheduling,paraita/scheduling,sgRomaric/scheduling,fviale/scheduling,youribonnaffe/scheduling,yinan-liu/scheduling,marcocast/scheduling,lpellegr/scheduling,sandrineBeauche/scheduling,youribonnaffe/scheduling,mbenguig/scheduling,ow2-proactive/scheduling,sandrineBeauche/scheduling,paraita/scheduling,ShatalovYaroslav/scheduling,marcocast/scheduling,sgRomaric/scheduling,sandrineBeauche/scheduling,laurianed/scheduling,tobwiens/scheduling,laurianed/scheduling,jrochas/scheduling,jrochas/scheduling,fviale/scheduling,youribonnaffe/scheduling,paraita/scheduling,sgRomaric/scheduling,jrochas/scheduling,yinan-liu/scheduling,mbenguig/scheduling,ow2-proactive/scheduling,mbenguig/scheduling,mbenguig/scheduling,lpellegr/scheduling,fviale/scheduling,tobwiens/scheduling,tobwiens/scheduling,ow2-proactive/scheduling,youribonnaffe/scheduling,yinan-liu/scheduling,jrochas/scheduling,mbenguig/scheduling,ShatalovYaroslav/scheduling,ow2-proactive/scheduling,youribonnaffe/scheduling,ShatalovYaroslav/scheduling,sgRomaric/scheduling,laurianed/scheduling,marcocast/scheduling,lpellegr/scheduling,sandrineBeauche/scheduling,paraita/scheduling,ShatalovYaroslav/scheduling,marcocast/scheduling,zeineb/scheduling,zeineb/scheduling,laurianed/scheduling,laurianed/scheduling,jrochas/scheduling,zeineb/scheduling,marcocast/scheduling,jrochas/scheduling,mbenguig/scheduling,ow2-proactive/scheduling,jrochas/scheduling,youribonnaffe/scheduling,yinan-liu/scheduling,ShatalovYaroslav/scheduling,zeineb/scheduling,lpellegr/scheduling,sandrineBeauche/scheduling,paraita/scheduling,yinan-liu/scheduling,marcocast/scheduling,ow2-proactive/scheduling,fviale/scheduling,zeineb/scheduling,fviale/scheduling,paraita/scheduling,ow2-proactive/scheduling,sandrineBeauche/scheduling,fviale/scheduling
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library 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 * 2 of the License, or 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 * General Public License for more details. * * You should have received a copy of the GNU 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 * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.examples.userguide.distributedprimes; import java.io.Serializable; import java.util.Vector; import org.objectweb.proactive.api.PAFuture; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; public class PrimeManager implements Serializable { private Vector<PrimeWorker> workers = new Vector<PrimeWorker>(); public PrimeManager() { } ////empty no-arg constructor needed by ProActive //1. send number to all workers and if all of them say the //number is prime then it is //2. send the number randomly to one worker if prime //3. try the next number public void startComputation(long maxNumber) { boolean prime;//true after checking if a number is prime int futureIndex;//updated future index; long primeCheck = 2; //start number long primeCounter = 1; int k = 0; Vector<BooleanWrapper> answers = new Vector<BooleanWrapper>(); while (primeCounter < maxNumber) { //1. send request to all workers for (PrimeWorker worker : workers) // Non blocking (asynchronous method call) // adds the futures to the vector answers.add(worker.isPrime(primeCheck)); //2. wait for all the answers, or an answer that says NO prime = true; while (!answers.isEmpty() && prime) {//repeat until a worker says no or all the workers responded (i.e. vector is emptied) // Will block until a new response is available futureIndex = PAFuture.waitForAny(answers); //blocks until a future is actualized prime = answers.get(futureIndex).booleanValue(); //check the answer answers.remove(futureIndex); //remove the actualized future }// end while check for primes if (prime) { //print if prime sendPrime(primeCheck); System.out.print(primeCheck + ", "); primeCounter++;//prime number found //flush print buffer every 20 numbers if (k % 20 == 0) System.out.println("\n"); k++; } //flush the answers vector answers.clear(); primeCheck++; }//end while number loop }// end StartComputation //add a workers to the worker Vector public void addWorker(PrimeWorker worker) { workers.add(worker); } //sends the prime numbers found to one worker randomly public void sendPrime(long number) { int destination = (int) Math.round(Math.random() * (workers.size() - 1)); workers.get(destination).addPrime(new Long(number)); } }
src/Examples/org/objectweb/proactive/examples/userguide/distributedprimes/PrimeManager.java
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library 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 * 2 of the License, or 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 * General Public License for more details. * * You should have received a copy of the GNU 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 * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.examples.userguide.distributedprimes; import java.io.Serializable; import java.util.Vector; import org.objectweb.proactive.api.PAFuture; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; public class PrimeManager implements Serializable { private Vector<PrimeWorker> workers = new Vector<PrimeWorker>(); public PrimeManager() { } ////empty no-arg constructor needed by ProActive //1. send number to all workers and if all of them say the //number is prime then it is //2. send the number randomly to one worker if prime //3. try the next number public void startComputation(long maxNumber) { boolean prime;//true after checking if a number is prime int futureIndex;//updated future index; long primeCheck = 2; //start number long primeCounter = 1; int k = 0; Vector<BooleanWrapper> answers = new Vector<BooleanWrapper>(); while (primeCounter < maxNumber) { //1. send request to all workers for (PrimeWorker worker : workers) // Non blocking (asynchronous method call) // adds the futures to the vector answers.add(worker.isPrime(primeCheck)); //2. wait for all the answers, or an answer that says NO prime = true; while (!answers.isEmpty() && prime) {//repeat until a worker says no or all the workers responded (i.e. vector is emptied) // Will block until a new response is available futureIndex = PAFuture.waitForAny(answers); //blocks until a future is actualized prime = answers.get(futureIndex).booleanValue(); //check the answer answers.remove(futureIndex); //remove the actualized future }// end while check for primes if (prime) { //print if prime sendPrime(primeCheck); System.out.print(primeCheck + ", "); primeCounter++;//prime number found //flush print buffer every 20 numbers if (k % 20 == 0) System.out.println("\n"); k++; } primeCheck++; }//end while number loop }// end StartComputation //add a workers to the worker Vector public void addWorker(PrimeWorker worker) { workers.add(worker); } //sends the prime numbers found to one worker randomly public void sendPrime(long number) { int destination = (int) Math.round(Math.random() * (workers.size() - 1)); workers.get(destination).addPrime(new Long(number)); } }
bug fix to clear the answers vector git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@8047 28e8926c-6b08-0410-baaa-805c5e19b8d6
src/Examples/org/objectweb/proactive/examples/userguide/distributedprimes/PrimeManager.java
bug fix to clear the answers vector
<ide><path>rc/Examples/org/objectweb/proactive/examples/userguide/distributedprimes/PrimeManager.java <ide> System.out.println("\n"); <ide> k++; <ide> } <del> primeCheck++; <add> //flush the answers vector <add> answers.clear(); <add> primeCheck++; <ide> }//end while number loop <ide> }// end StartComputation <ide>
JavaScript
bsd-3-clause
f7b8940b58794f6177bd06a7a3e3fc8df96a56d8
0
future-analytics/cartodb,thorncp/cartodb,UCL-ShippingGroup/cartodb-1,bloomberg/cartodb,dbirchak/cartodb,thorncp/cartodb,codeandtheory/cartodb,future-analytics/cartodb,splashblot/dronedb,DigitalCoder/cartodb,dbirchak/cartodb,bloomberg/cartodb,thorncp/cartodb,nyimbi/cartodb,future-analytics/cartodb,DigitalCoder/cartodb,codeandtheory/cartodb,DigitalCoder/cartodb,splashblot/dronedb,UCL-ShippingGroup/cartodb-1,bloomberg/cartodb,nyimbi/cartodb,codeandtheory/cartodb,DigitalCoder/cartodb,CartoDB/cartodb,DigitalCoder/cartodb,UCL-ShippingGroup/cartodb-1,nyimbi/cartodb,thorncp/cartodb,codeandtheory/cartodb,nuxcode/cartodb,CartoDB/cartodb,future-analytics/cartodb,UCL-ShippingGroup/cartodb-1,nuxcode/cartodb,nuxcode/cartodb,future-analytics/cartodb,CartoDB/cartodb,splashblot/dronedb,CartoDB/cartodb,dbirchak/cartodb,splashblot/dronedb,nyimbi/cartodb,nyimbi/cartodb,CartoDB/cartodb,splashblot/dronedb,UCL-ShippingGroup/cartodb-1,thorncp/cartodb,nuxcode/cartodb,bloomberg/cartodb,bloomberg/cartodb,dbirchak/cartodb,codeandtheory/cartodb,nuxcode/cartodb,dbirchak/cartodb
var cdb = require('cartodb.js'); var _ = require('underscore'); var $ = require('jquery'); var PermissionView = require('./permission_view'); var PaginationView = require('../../../views/pagination/view'); /** * Content view of the share dialog, lists of users to share item with. */ module.exports = cdb.core.View.extend({ initialize: function() { this.paginationModel = this.options.paginationModel; this._initBinds(); }, render: function() { this.clearSubViews(); this.$el.empty(); if (!this.collection.getSearch()) { this._renderOrganizationPermissionView() } this._renderUsersPermissionView(); this._renderPaginationView(); return this; }, _initBinds: function() { this.collection.bind('reset', this.render, this); this.add_related_model(this.collection); }, _renderUsersPermissionView: function() { var usersUsingVis = this.model.usersUsingVis(); this.collection.each(function(user) { this._appendPermissionView( new PermissionView({ model: user, permission: this.model.get('permission'), canChangeWriteAccess: this.model.canChangeWriteAccess(), title: user.get('username'), desc: user.get('name'), email: user.get('email'), avatarUrl: user.get('avatar_url'), isUsingVis: _.any(usersUsingVis, function(u) { return u.id === user.get('id'); }) }) ) }, this); }, _renderOrganizationPermissionView: function() { this._appendPermissionView( new PermissionView({ model: this.model.get('organization'), permission: this.model.get('permission'), canChangeWriteAccess: this.model.canChangeWriteAccess(), title: 'Default settings for your Organization', desc: 'New users will have this permission' }) ); }, _renderPaginationView: function() { var $paginatorWrapper = $('<div>').addClass('ChangePrivacy-shareListPagination'); this.$el.append($paginatorWrapper); var paginationView = new PaginationView({ model: this.paginationModel }); $paginatorWrapper.append(paginationView.render().el); this.addView(paginationView); }, _appendPermissionView: function(view) { this.$el.append(view.render().el); this.addView(view); } });
lib/assets/javascripts/cartodb/common/dialogs/change_privacy/share/permission_users_view.js
var cdb = require('cartodb.js'); var _ = require('underscore'); var $ = require('jquery'); var PermissionView = require('./permission_view'); var PaginationView = require('../../../views/pagination/view'); /** * Content view of the share dialog, lists of users to share item with. */ module.exports = cdb.core.View.extend({ initialize: function() { this.paginationModel = this.options.paginationModel; this._initBinds(); }, render: function() { this.clearSubViews(); this.$el.empty() // Organization permissions if (!this.collection.getSearch()) { this._renderOrganizationPermissionView() } // User permissions list var usersUsingVis = this.model.usersUsingVis(); this.collection.each(function(user) { this._appendPermissionView( new PermissionView({ model: user, permission: this.model.get('permission'), canChangeWriteAccess: this.model.canChangeWriteAccess(), title: user.get('username'), desc: user.get('name'), email: user.get('email'), avatarUrl: user.get('avatar_url'), isUsingVis: _.any(usersUsingVis, function(u) { return u.id === user.get('id'); }) }) ) }, this); // Paginator var $paginatorWrapper = $('<div>').addClass('ChangePrivacy-shareListPagination'); this.$el.append($paginatorWrapper); var paginationView = new PaginationView({ model: this.paginationModel }); $paginatorWrapper.append(paginationView.render().el); this.addView(paginationView); return this; }, _initBinds: function() { this.collection.bind('reset', this.render, this); this.add_related_model(this.collection); }, _renderOrganizationPermissionView: function() { this._appendPermissionView( new PermissionView({ model: this.model.get('organization'), permission: this.model.get('permission'), canChangeWriteAccess: this.model.canChangeWriteAccess(), title: 'Default settings for your Organization', desc: 'New users will have this permission' }) ); }, _appendPermissionView: function(view) { this.$el.append(view.render().el); this.addView(view); } });
Moving render elements to functions
lib/assets/javascripts/cartodb/common/dialogs/change_privacy/share/permission_users_view.js
Moving render elements to functions
<ide><path>ib/assets/javascripts/cartodb/common/dialogs/change_privacy/share/permission_users_view.js <ide> render: function() { <ide> this.clearSubViews(); <ide> <del> this.$el.empty() <add> this.$el.empty(); <ide> <del> // Organization permissions <ide> if (!this.collection.getSearch()) { <ide> this._renderOrganizationPermissionView() <ide> } <add> this._renderUsersPermissionView(); <add> this._renderPaginationView(); <add> return this; <add> }, <ide> <del> // User permissions list <add> _initBinds: function() { <add> this.collection.bind('reset', this.render, this); <add> this.add_related_model(this.collection); <add> }, <add> <add> _renderUsersPermissionView: function() { <ide> var usersUsingVis = this.model.usersUsingVis(); <ide> this.collection.each(function(user) { <ide> this._appendPermissionView( <ide> }) <ide> ) <ide> }, this); <del> <del> // Paginator <del> var $paginatorWrapper = $('<div>').addClass('ChangePrivacy-shareListPagination'); <del> this.$el.append($paginatorWrapper); <del> var paginationView = new PaginationView({ <del> model: this.paginationModel <del> }); <del> $paginatorWrapper.append(paginationView.render().el); <del> this.addView(paginationView); <del> <del> return this; <del> }, <del> <del> _initBinds: function() { <del> this.collection.bind('reset', this.render, this); <del> this.add_related_model(this.collection); <ide> }, <ide> <ide> _renderOrganizationPermissionView: function() { <ide> ); <ide> }, <ide> <add> _renderPaginationView: function() { <add> var $paginatorWrapper = $('<div>').addClass('ChangePrivacy-shareListPagination'); <add> this.$el.append($paginatorWrapper); <add> var paginationView = new PaginationView({ <add> model: this.paginationModel <add> }); <add> $paginatorWrapper.append(paginationView.render().el); <add> this.addView(paginationView); <add> }, <add> <ide> _appendPermissionView: function(view) { <ide> this.$el.append(view.render().el); <ide> this.addView(view);
Java
apache-2.0
d406a956b5dd99662c8c2f2cf206a4aeb7d5f704
0
doanduyhai/Achilles,doanduyhai/Achilles
package info.archinnov.achilles.columnFamily; import static info.archinnov.achilles.serializer.SerializerUtils.OBJECT_SRZ; import static info.archinnov.achilles.serializer.SerializerUtils.STRING_SRZ; import info.archinnov.achilles.entity.PropertyHelper; import info.archinnov.achilles.entity.metadata.EntityMeta; import info.archinnov.achilles.entity.metadata.PropertyMeta; import info.archinnov.achilles.exception.InvalidColumnFamilyException; import java.util.regex.Matcher; import java.util.regex.Pattern; import me.prettyprint.cassandra.serializers.SerializerTypeInferer; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition; import me.prettyprint.hector.api.ddl.ComparatorType; import me.prettyprint.hector.api.factory.HFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ColumnFamilyBuilder * * @author DuyHai DOAN * */ public class ColumnFamilyBuilder { private static final Logger log = LoggerFactory.getLogger(ColumnFamilyBuilder.class); private static final String DYNAMIC_TYPE_ALIASES = "(a=>AsciiType,b=>BytesType,c=>BooleanType,d=>DateType,e=>DecimalType,z=>DoubleType,f=>FloatType,i=>IntegerType,j=>Int32Type,x=>LexicalUUIDType,l=>LongType,t=>TimeUUIDType,s=>UTF8Type,u=>UUIDType)"; public static final Pattern CF_PATTERN = Pattern.compile("[a-zA-Z0-9_]{1,48}"); public PropertyHelper helper = new PropertyHelper(); public <ID> ColumnFamilyDefinition buildDynamicCompositeCF(EntityMeta<ID> entityMeta, String keyspaceName) { String entityName = entityMeta.getClassName(); String columnFamilyName = entityMeta.getColumnFamilyName(); ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(keyspaceName, columnFamilyName, ComparatorType.DYNAMICCOMPOSITETYPE); String keyValidationType = entityMeta.getIdSerializer().getComparatorType().getTypeName(); cfDef.setKeyValidationClass(keyValidationType); cfDef.setComparatorTypeAlias(DYNAMIC_TYPE_ALIASES); cfDef.setDefaultValidationClass(STRING_SRZ.getComparatorType().getTypeName()); cfDef.setComment("Column family for entity '" + entityName + "'"); StringBuilder builder = new StringBuilder("\n\n"); builder.append("Create Dynamic Composite-based column family for entity "); builder.append("'").append(entityName).append("' : \n"); builder.append("\tcreate column family ").append(columnFamilyName).append("\n"); builder.append("\t\twith key_validation_class = ").append(keyValidationType).append("\n"); builder.append("\t\tand comparator = '").append( ComparatorType.DYNAMICCOMPOSITETYPE.getTypeName()); builder.append(DYNAMIC_TYPE_ALIASES).append("'\n"); builder.append("\t\tand default_validation_class = ") .append(ComparatorType.UTF8TYPE.getTypeName()).append("\n"); builder.append("\t\tand comment = 'Column family for entity ").append(entityName) .append("'\n\n"); log.debug(builder.toString()); return cfDef; } public <ID> ColumnFamilyDefinition buildCompositeCF(String keyspaceName, PropertyMeta<?, ?> propertyMeta, Class<ID> keyClass, String columnFamilyName, String entityName) { Class<?> valueClass = propertyMeta.getValueClass(); Serializer<?> keySerializer = SerializerTypeInferer.getSerializer(keyClass); ComparatorType comparatorType = ComparatorType.COMPOSITETYPE; String comparatorTypesAlias = helper.determineCompatatorTypeAliasForCompositeCF( propertyMeta, true); ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(keyspaceName, columnFamilyName, comparatorType); String keyValidationType = keySerializer.getComparatorType().getTypeName(); cfDef.setKeyValidationClass(keyValidationType); cfDef.setComparatorTypeAlias(comparatorTypesAlias); Serializer<?> valueSerializer = SerializerTypeInferer.getSerializer(valueClass); if (valueSerializer == OBJECT_SRZ) { if (propertyMeta.type().isJoinColumn()) { valueSerializer = propertyMeta.getJoinProperties().getEntityMeta().getIdMeta() .getValueSerializer(); } else { valueSerializer = STRING_SRZ; } } String defaultValidationType = valueSerializer.getComparatorType().getTypeName(); cfDef.setDefaultValidationClass(defaultValidationType); cfDef.setComment("Column family for entity '" + columnFamilyName + "'"); String propertyName = propertyMeta.getPropertyName(); StringBuilder builder = new StringBuilder("\n\n"); builder.append("Create Composite-based column family for property "); builder.append("'").append(propertyName).append("' of entity '"); builder.append(entityName).append("' : \n"); builder.append("\tcreate column family ").append(columnFamilyName).append("\n"); builder.append("\t\twith key_validation_class = ").append(keyValidationType).append("\n"); builder.append("\t\tand comparator = '").append(ComparatorType.COMPOSITETYPE.getTypeName()); builder.append(comparatorTypesAlias).append("'\n"); builder.append("\t\tand default_validation_class = ").append(defaultValidationType) .append("\n"); builder.append("\t\tand comment = 'Column family for property ").append(propertyName); builder.append(" of entity ").append(entityName).append("'\n\n"); log.debug(builder.toString()); return cfDef; } public static String normalizerAndValidateColumnFamilyName(String cfName) { log.trace("Normalizing column family '{}' name agains Cassandra restrictions", cfName); Matcher nameMatcher = CF_PATTERN.matcher(cfName); if (nameMatcher.matches()) { return cfName; } else if (cfName.contains(".")) { String className = cfName.replaceAll(".+\\.(.+)", "$1"); return normalizerAndValidateColumnFamilyName(className); } else { throw new InvalidColumnFamilyException( "The column family name '" + cfName + "' is invalid. It should be respect the pattern [a-zA-Z0-9_] and be at most 48 characters long"); } } }
src/main/java/info/archinnov/achilles/columnFamily/ColumnFamilyBuilder.java
package info.archinnov.achilles.columnFamily; import static info.archinnov.achilles.serializer.SerializerUtils.OBJECT_SRZ; import static info.archinnov.achilles.serializer.SerializerUtils.STRING_SRZ; import info.archinnov.achilles.entity.PropertyHelper; import info.archinnov.achilles.entity.metadata.EntityMeta; import info.archinnov.achilles.entity.metadata.PropertyMeta; import info.archinnov.achilles.exception.InvalidColumnFamilyException; import java.util.regex.Matcher; import java.util.regex.Pattern; import me.prettyprint.cassandra.serializers.SerializerTypeInferer; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition; import me.prettyprint.hector.api.ddl.ComparatorType; import me.prettyprint.hector.api.factory.HFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ColumnFamilyBuilder * * @author DuyHai DOAN * */ public class ColumnFamilyBuilder { private static final Logger log = LoggerFactory.getLogger(ColumnFamilyBuilder.class); private static final String DYNAMIC_TYPE_ALIASES = "(a=>AsciiType,b=>BytesType,c=>BooleanType,d=>DateType,e=>DecimalType,z=>DoubleType,f=>FloatType,i=>IntegerType,j=>Int32Type,x=>LexicalUUIDType,l=>LongType,t=>TimeUUIDType,s=>UTF8Type,u=>UUIDType)"; public static final Pattern CF_PATTERN = Pattern.compile("[a-zA-Z0-9_]{1,48}"); public PropertyHelper helper = new PropertyHelper(); public <ID> ColumnFamilyDefinition buildDynamicCompositeCF(EntityMeta<ID> entityMeta, String keyspaceName) { String entityName = entityMeta.getClassName(); String columnFamilyName = entityMeta.getColumnFamilyName(); ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(keyspaceName, columnFamilyName, ComparatorType.DYNAMICCOMPOSITETYPE); String keyValidationType = entityMeta.getIdSerializer().getComparatorType().getTypeName(); cfDef.setKeyValidationClass(keyValidationType); cfDef.setComparatorTypeAlias(DYNAMIC_TYPE_ALIASES); cfDef.setDefaultValidationClass(STRING_SRZ.getComparatorType().getTypeName()); cfDef.setComment("Column family for entity '" + entityName + "'"); StringBuilder builder = new StringBuilder("\n\n"); builder.append("Create Dynamic Composite-based column family for entity "); builder.append("'").append(entityName).append("' : \n"); builder.append("\tcreate column family ").append(columnFamilyName).append("\n"); builder.append("\t\twith key_validation_class = ").append(keyValidationType).append("\n"); builder.append("\t\tand comparator = '").append( ComparatorType.DYNAMICCOMPOSITETYPE.getTypeName()); builder.append(DYNAMIC_TYPE_ALIASES).append("'\n"); builder.append("\t\tand default_validation_class = ") .append(ComparatorType.UTF8TYPE.getTypeName()).append("\n"); builder.append("\t\tand comment = 'Column family for entity ").append(entityName) .append("'\n\n"); log.debug(builder.toString()); return cfDef; } public <ID> ColumnFamilyDefinition buildCompositeCF(String keyspaceName, PropertyMeta<?, ?> propertyMeta, Class<ID> keyClass, String columnFamilyName, String entityName) { Class<?> valueClass = propertyMeta.getValueClass(); Serializer<?> keySerializer = SerializerTypeInferer.getSerializer(keyClass); ComparatorType comparatorType = ComparatorType.COMPOSITETYPE; String comparatorTypesAlias = helper.determineCompatatorTypeAliasForCompositeCF( propertyMeta, true); ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(keyspaceName, columnFamilyName, comparatorType); String keyValidationType = keySerializer.getComparatorType().getTypeName(); cfDef.setKeyValidationClass(keyValidationType); cfDef.setComparatorTypeAlias(comparatorTypesAlias); Serializer<?> valueSerializer = SerializerTypeInferer.getSerializer(valueClass); if (valueSerializer == OBJECT_SRZ && !propertyMeta.type().isJoinColumn()) { valueSerializer = STRING_SRZ; } String defaultValidationType = valueSerializer.getComparatorType().getTypeName(); cfDef.setDefaultValidationClass(defaultValidationType); cfDef.setComment("Column family for entity '" + columnFamilyName + "'"); String propertyName = propertyMeta.getPropertyName(); StringBuilder builder = new StringBuilder("\n\n"); builder.append("Create Composite-based column family for property "); builder.append("'").append(propertyName).append("' of entity '"); builder.append(entityName).append("' : \n"); builder.append("\tcreate column family ").append(columnFamilyName).append("\n"); builder.append("\t\twith key_validation_class = ").append(keyValidationType).append("\n"); builder.append("\t\tand comparator = '").append(ComparatorType.COMPOSITETYPE.getTypeName()); builder.append(comparatorTypesAlias).append("'\n"); builder.append("\t\tand default_validation_class = ").append(defaultValidationType) .append("\n"); builder.append("\t\tand comment = 'Column family for property ").append(propertyName); builder.append(" of entity ").append(entityName).append("'\n\n"); log.debug(builder.toString()); return cfDef; } public static String normalizerAndValidateColumnFamilyName(String cfName) { log.trace("Normalizing column family '{}' name agains Cassandra restrictions", cfName); Matcher nameMatcher = CF_PATTERN.matcher(cfName); if (nameMatcher.matches()) { return cfName; } else if (cfName.contains(".")) { String className = cfName.replaceAll(".+\\.(.+)", "$1"); return normalizerAndValidateColumnFamilyName(className); } else { throw new InvalidColumnFamilyException( "The column family name '" + cfName + "' is invalid. It should be respect the pattern [a-zA-Z0-9_] and be at most 48 characters long"); } } }
Fix bug on validation class for Dynamic Composite CF
src/main/java/info/archinnov/achilles/columnFamily/ColumnFamilyBuilder.java
Fix bug on validation class for Dynamic Composite CF
<ide><path>rc/main/java/info/archinnov/achilles/columnFamily/ColumnFamilyBuilder.java <ide> <ide> Serializer<?> valueSerializer = SerializerTypeInferer.getSerializer(valueClass); <ide> <del> if (valueSerializer == OBJECT_SRZ && !propertyMeta.type().isJoinColumn()) <add> if (valueSerializer == OBJECT_SRZ) <ide> { <del> valueSerializer = STRING_SRZ; <add> if (propertyMeta.type().isJoinColumn()) <add> { <add> valueSerializer = propertyMeta.getJoinProperties().getEntityMeta().getIdMeta() <add> .getValueSerializer(); <add> } <add> else <add> { <add> valueSerializer = STRING_SRZ; <add> } <ide> } <ide> <ide> String defaultValidationType = valueSerializer.getComparatorType().getTypeName();
Java
mit
8e428c43c37349481cc9b31638017bbfbaa823c4
0
jwbenham/jfmi,jwbenham/jfmi
package jfmi.control; import java.io.File; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Vector; import jfmi.dao.TaggedFileDAO; import jfmi.gui.GUIUtil; import jfmi.gui.JFMIFrame; import jfmi.gui.TaggedFileHandlerGUI; /** A controller class for handling the logic of updating/adding/deleting which files kept in the database. */ public class TaggedFileHandler { // PRIVATE INSTANCE Fields private JFMIApp jfmiApp; private TaggedFileHandlerGUI fileGUI; private TaggedFileDAO taggedFileDAO; private Vector<TaggedFile> taggedFiles; //************************************************************ // PUBLIC INSTANCE Methods //************************************************************ /** Constructs a new TaggedFileHandler associated with the specified JFMIApp. @param jfmiApp_ the JFMIApp to associate with this handler @throws IllegalArgumentException if jfmiApp_ is null */ public TaggedFileHandler(JFMIApp jfmiApp_) { setJFMIApp(jfmiApp_); taggedFileDAO = new TaggedFileDAO(); fileGUI = new TaggedFileHandlerGUI(jfmiApp.getJFMIGUI(), this); } /** Given an array of File objects, attempts to create TaggedFile objects and insert them into the repository. @param files an array of File to be newly created in the repository */ public void addFilesToRepo(File[] files) { TaggedFile newFile; if (files == null) { return; } for (File f : files) { newFile = new TaggedFile(); newFile.setFile(f); addTaggedFileToRepo(newFile, true); } } /** Attempts to add a TaggedFile to the repository. If showErrors is true, any errors which occur are displayed to the user. @param file the TaggedFile to be added to the repository @param showErrors if true, the user receives error messages @return true if the file was added successfully */ public boolean addTaggedFileToRepo(TaggedFile file, boolean showErrors) { try { boolean creationSuccess = taggedFileDAO.create(file); if (!creationSuccess && showErrors) { GUIUtil.showErrorDialog( "The following file could not be added: " + file.getFilePath() ); } return creationSuccess; } catch (SQLException e) { if (showErrors) { GUIUtil.showErrorDialog( "An error occurred while adding the file: " + file.getFilePath(), e.toString() ); } } return false; } /** Begins an interaction with the user that allows them to add new files to the repository for tagging. */ public void beginAddFileInteraction() { File[] selectedFiles = fileGUI.displayFileChooser(); addFilesToRepo(selectedFiles); updateDataAndGUI(true); } /** Begins an interaction with the user that allows them to delete selected files from the repository. @param selectedFiles files selected by the user for deletion */ public void beginDeleteFilesInteraction(List<TaggedFile> selectedFiles) { if (fileGUI.getConfirmation("Confirm deletion of files.") == false) { return; } deleteFilesFromRepo(selectedFiles); updateDataAndGUI(true); } public void beginUpdateFilePathInteraction(TaggedFile updateMe) { // Get an updated path from the user // Confirm the update // Update the repository // Update the current file // Redisplay the current file } /** Begins an interaction with the user that allows them to view and update a file. @param viewMe the file to view */ public void beginViewFileInteraction(TaggedFile viewMe) { fileGUI.displayFileViewer(viewMe); } /** Deletes the TaggedFiles in the specified list from the repository. @param files list of files to be deleted */ public void deleteFilesFromRepo(List<TaggedFile> files) { if (files == null) { return; } for (TaggedFile tf : files) { deleteTaggedFileFromRepo(tf, true); } } /** Deletes a TaggedFile from the underlying repository. @param file the file to delete @param showErrors if true, the method displays any error messages @return true if the file was deleted successfully */ public boolean deleteTaggedFileFromRepo(TaggedFile file, boolean showErrors) { try { return taggedFileDAO.delete(file); } catch (SQLException e) { if (showErrors) { GUIUtil.showErrorDialog( "Failed to delete file: " + file.getFilePath(), e.toString() ); } } return false; } /** Sets this instance's associated JFMIApp. @param jfmiApp_ the JFMIApp to associate this handler with @throws IllegalArgumentException if jfmiApp_ is null */ public final void setJFMIApp(JFMIApp jfmiApp_) { if (jfmiApp_ == null) { throw new IllegalArgumentException("jfmiApp_ cannot be null"); } jfmiApp = jfmiApp_; } /** Constructs a new Vector<TaggedFile> for this instance from the specified Collection. @param collection The Collection to construct a new Vector from. */ public void setTaggedFiles(Collection<TaggedFile> collection) { taggedFiles = new Vector<TaggedFile>(collection); } /** Refreshes the handler's data from the repository, and updates its associated GUI. @param showErrors if true, the method displays errors @return true if data was updated and sent to GUI successfully */ public boolean updateDataAndGUI(boolean showErrors) { boolean readSuccess = readTaggedFilesFromRepo(true); if (readSuccess) { updateGUITaggedFileJList(); } return readSuccess; } //************************************************************ // PRIVATE INSTANCE Methods //************************************************************ /** Gets an updated list of TaggedFiles from the repository, and updates the taggedFiles field. @param showError if true, and an error occurs, display a message @return true if the files were refreshed successfully */ private boolean readTaggedFilesFromRepo(boolean showError) { try { setTaggedFiles(taggedFileDAO.readAll()); } catch (SQLException e) { if (showError) { GUIUtil.showErrorDialog( "Failed to refresh the list of files from the database.", e.toString() ); } return false; } return true; } /** Updates this instance's GUI with the latest values in the Vector of TaggedFile objects. */ private void updateGUITaggedFileJList() { jfmiApp.getJFMIGUI().setTaggedFileJListData(taggedFiles); } }
src/jfmi/control/TaggedFileHandler.java
package jfmi.control; import java.io.File; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Vector; import jfmi.dao.TaggedFileDAO; import jfmi.gui.GUIUtil; import jfmi.gui.JFMIFrame; import jfmi.gui.TaggedFileHandlerGUI; /** A controller class for handling the logic of updating/adding/deleting which files kept in the database. */ public class TaggedFileHandler { // PRIVATE INSTANCE Fields private JFMIApp jfmiApp; private TaggedFileHandlerGUI fileGUI; private TaggedFileDAO taggedFileDAO; private Vector<TaggedFile> taggedFiles; //************************************************************ // PUBLIC INSTANCE Methods //************************************************************ /** Constructs a new TaggedFileHandler associated with the specified JFMIApp. @param jfmiApp_ the JFMIApp to associate with this handler @throws IllegalArgumentException if jfmiApp_ is null */ public TaggedFileHandler(JFMIApp jfmiApp_) { setJFMIApp(jfmiApp_); taggedFileDAO = new TaggedFileDAO(); fileGUI = new TaggedFileHandlerGUI(jfmiApp.getJFMIGUI(), this); } /** Given an array of File objects, attempts to create TaggedFile objects and insert them into the repository. @param files an array of File to be newly created in the repository */ public void addFilesToRepo(File[] files) { TaggedFile newFile; if (files == null) { return; } for (File f : files) { newFile = new TaggedFile(); newFile.setFile(f); addTaggedFileToRepo(newFile, true); } } /** Attempts to add a TaggedFile to the repository. If showErrors is true, any errors which occur are displayed to the user. @param file the TaggedFile to be added to the repository @param showErrors if true, the user receives error messages @return true if the file was added successfully */ public boolean addTaggedFileToRepo(TaggedFile file, boolean showErrors) { try { boolean creationSuccess = taggedFileDAO.create(file); if (!creationSuccess && showErrors) { GUIUtil.showErrorDialog( "The following file could not be added: " + file.getFilePath() ); } return creationSuccess; } catch (SQLException e) { if (showErrors) { GUIUtil.showErrorDialog( "An error occurred while adding the file: " + file.getFilePath(), e.toString() ); } } return false; } /** Begins an interaction with the user that allows them to add new files to the repository for tagging. */ public void beginAddFileInteraction() { File[] selectedFiles = fileGUI.displayFileChooser(); addFilesToRepo(selectedFiles); updateDataAndGUI(true); } /** Begins an interaction with the user that allows them to delete selected files from the repository. @param selectedFiles files selected by the user for deletion */ public void beginDeleteFilesInteraction(List<TaggedFile> selectedFiles) { if (fileGUI.getConfirmation("Confirm deletion of files.") == false) { return; } deleteFilesFromRepo(selectedFiles); updateDataAndGUI(true); } /** Begins an interaction with the user that allows them to view and update a file. @param viewMe the file to view */ public void beginViewFileInteraction(TaggedFile viewMe) { fileGUI.displayFileViewer(viewMe); } /** Deletes the TaggedFiles in the specified list from the repository. @param files list of files to be deleted */ public void deleteFilesFromRepo(List<TaggedFile> files) { if (files == null) { return; } for (TaggedFile tf : files) { deleteTaggedFileFromRepo(tf, true); } } /** Deletes a TaggedFile from the underlying repository. @param file the file to delete @param showErrors if true, the method displays any error messages @return true if the file was deleted successfully */ public boolean deleteTaggedFileFromRepo(TaggedFile file, boolean showErrors) { try { return taggedFileDAO.delete(file); } catch (SQLException e) { if (showErrors) { GUIUtil.showErrorDialog( "Failed to delete file: " + file.getFilePath(), e.toString() ); } } return false; } /** Sets this instance's associated JFMIApp. @param jfmiApp_ the JFMIApp to associate this handler with @throws IllegalArgumentException if jfmiApp_ is null */ public final void setJFMIApp(JFMIApp jfmiApp_) { if (jfmiApp_ == null) { throw new IllegalArgumentException("jfmiApp_ cannot be null"); } jfmiApp = jfmiApp_; } /** Constructs a new Vector<TaggedFile> for this instance from the specified Collection. @param collection The Collection to construct a new Vector from. */ public void setTaggedFiles(Collection<TaggedFile> collection) { taggedFiles = new Vector<TaggedFile>(collection); } /** Refreshes the handler's data from the repository, and updates its associated GUI. @param showErrors if true, the method displays errors @return true if data was updated and sent to GUI successfully */ public boolean updateDataAndGUI(boolean showErrors) { boolean readSuccess = readTaggedFilesFromRepo(true); if (readSuccess) { updateGUITaggedFileJList(); } return readSuccess; } //************************************************************ // PRIVATE INSTANCE Methods //************************************************************ /** Gets an updated list of TaggedFiles from the repository, and updates the taggedFiles field. @param showError if true, and an error occurs, display a message @return true if the files were refreshed successfully */ private boolean readTaggedFilesFromRepo(boolean showError) { try { setTaggedFiles(taggedFileDAO.readAll()); } catch (SQLException e) { if (showError) { GUIUtil.showErrorDialog( "Failed to refresh the list of files from the database.", e.toString() ); } return false; } return true; } /** Updates this instance's GUI with the latest values in the Vector of TaggedFile objects. */ private void updateGUITaggedFileJList() { jfmiApp.getJFMIGUI().setTaggedFileJListData(taggedFiles); } }
TaggedFileHandler.beginUpdateFilePathInteraction() added
src/jfmi/control/TaggedFileHandler.java
TaggedFileHandler.beginUpdateFilePathInteraction() added
<ide><path>rc/jfmi/control/TaggedFileHandler.java <ide> updateDataAndGUI(true); <ide> } <ide> <add> public void beginUpdateFilePathInteraction(TaggedFile updateMe) <add> { <add> // Get an updated path from the user <add> // Confirm the update <add> // Update the repository <add> // Update the current file <add> // Redisplay the current file <add> } <add> <ide> /** Begins an interaction with the user that allows them to view and <ide> update a file. <ide> @param viewMe the file to view
JavaScript
agpl-3.0
eb62b78a8ca8f6f7c6f1d7f5bb7ed97587ff1429
0
timelapseplus/VIEW,timelapseplus/VIEW,timelapseplus/VIEW,timelapseplus/VIEW,timelapseplus/VIEW
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.services' is found in services.js // 'starter.controllers' is found in controllers.js angular.module('app', ['ionic', 'ngWebSocket', 'LocalStorageModule']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider .state('app', { url: "/app", abstract: true, templateUrl: "templates/menu.html", controller: 'AppCtrl' }) .state('app.capture', { cache: false, url: "/capture", views: { 'menuContent': { templateUrl: "templates/capture.html" } } }) .state('app.timelapse', { cache: false, url: "/timelapse", views: { 'menuContent': { templateUrl: "templates/timelapse.html" } } }) .state('app.view', { cache: false, url: "/view", views: { 'menuContent': { templateUrl: "templates/view.html" } } }) // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/app/capture'); }) .controller('AppCtrl', ['$scope', '$timeout', '$http', '$websocket', '$location', '$ionicPopup', '$ionicActionSheet', '$interval', '$ionicModal', '$state', 'localStorageService', '$ionicHistory', '$ionicSideMenuDelegate', '$ionicScrollDelegate', function($scope, $timeout, $http, $websocket, $location, $ionicPopup, $ionicActionSheet, $interval, $ionicModal, $state, localStorageService, $ionicHistory, $ionicSideMenuDelegate, $ionicScrollDelegate) { console.log("AppCtrl"); $scope.moment = moment; $scope.sid = localStorageService.get('sid'); console.log("current sid: ", $scope.sid); $scope.secondsDescription = function(seconds, index) { var hours = Math.floor(seconds / 3600); seconds -= (hours * 3600); var minutes = Math.floor(seconds / 60); seconds -= (minutes * 60); var seconds = Math.round(seconds); var time = ""; if (hours > 0) time += hours + 'h '; if (minutes > 0) time += minutes + 'm '; if (hours == 0 && minutes < 10) time += seconds + 's '; if (index > 1) { time += "from last keyframe"; } else { time += "from start"; } return time; } /*var previousState = localStorageService.get('state'); if(previousState != null && typeof previousState == "string" && previousState.match(/^app\./)) { console.log("starting at " + previousState); $ionicHistory.nextViewOptions({ // I have no idea why this simply does not work disableAnimate: true, historyRoot: true }); $state.go(previousState); $ionicHistory.clearCache(); $ionicHistory.clearHistory(); }*/ var controls = {}; $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { console.log("new state:", toState); localStorageService.set('state', toState.name); if (toState.name == "app.view") { $scope.getClips(); } /*else if(toState.name == "app.capture") { if(controls.joystick) { controls.joystick.delete(); delete controls.joystick; } if(controls.slider) { controls.slider.delete(); delete controls.slider; } $timeout(function(){ controls.joystick = new window.TouchControl('joystick'); controls.joystick.on('pos', function(x, y) { $scope.joystick('pan', x); $scope.joystick('tilt', y); console.log("joystick pos", x, y); }); controls.joystick.on('start', function(x, y) { $scope.$apply(function(){ console.log("disabing scroll"); $ionicSideMenuDelegate.canDragContent(false); $ionicScrollDelegate.freezeAllScrolls(false); //$ionicScrollDelegate.getScrollView().options.scrollingY = false; }); }); controls.joystick.on('stop', function(x, y) { $scope.$apply(function(){ console.log("enabling scroll"); $ionicSideMenuDelegate.canDragContent(true); $ionicScrollDelegate.freezeAllScrolls(true); //$ionicScrollDelegate.getScrollView().options.scrollingY = true; }); }); controls.slider = new window.TouchControl('slider'); controls.slider.on('pos', function(x) { $scope.joystick('slide', x); console.log("slider pos", x); }); controls.slider.on('start', function(x, y) { $scope.$apply(function(){ console.log("disabing scroll"); $ionicSideMenuDelegate.canDragContent(false); $ionicScrollDelegate.freezeAllScrolls(false); //$ionicScrollDelegate.getScrollView().options.scrollingY = false; }); }); controls.slider.on('stop', function(x, y) { $scope.$apply(function(){ console.log("enabling scroll"); $ionicSideMenuDelegate.canDragContent(true); $ionicScrollDelegate.freezeAllScrolls(true); //$ionicScrollDelegate.getScrollView().options.scrollingY = true; }); }); }); }*/ }); function updateCache() { console.log("updating cache"); window.applicationCache.swapCache(); window.location.reload(); } var confirmReload = function() { var confirmPopup = $ionicPopup.show({ title: 'Update Available', template: 'Reload app with new version?', buttons: [{ text: 'Next Launch' }, { text: '<b>Update Now</b>', type: 'button-positive', onTap: function(e) { return true; } }] }); confirmPopup.then(function(res) { console.log(res); if (res) { updateCache(); } else { console.log('Next Launch'); } }); }; $scope.confirmStop = function() { var confirmPopup = $ionicPopup.show({ title: 'Confirm', template: 'Stop Time-lapse?', buttons: [{ text: 'Cancel' }, { text: '<b>Stop</b>', type: 'button-alert', onTap: function(e) { return true; } }] }); confirmPopup.then(function(res) { console.log(res); if (res) { $scope.stopProgram(); } }); }; $scope.popupMessage = function(title, message, callback) { var confirmPopup = $ionicPopup.show({ title: title, template: message, buttons: [{ text: 'Close', onTap: function(e) { callback && callback(); } }] }); }; // Triggered on a button click, or some other target $scope.showAddDevice = function() { $scope.data = {}; // An elaborate, custom popup var addDevicePopup = $ionicPopup.show({ template: '<input type="number" ng-model="data.code">', title: 'Enter code shown on VIEW device', subTitle: "if a code isn't shown, make sure the VIEW is connected via WiFi", scope: $scope, buttons: [ { text: 'Cancel' }, { text: '<b>Add</b>', type: 'button-positive', onTap: function(e) { if (!$scope.data.code) { //don't allow the user to close unless he enters wifi password e.preventDefault(); } else { $scope.addDevice($scope.data.code); return $scope.data.code; } } } ] }); addDevicePopup.then(function(res) { console.log('Tapped!', res); }); $timeout(function() { addDevicePopup.close(); //close the popup after 3 seconds for some reason }, 60000); }; $scope.confirmDelete = function(clip) { var confirmPopup = $ionicPopup.show({ title: 'Confirm', template: 'Delete Preview for ' + clip.name + '?', buttons: [{ text: 'Cancel' }, { text: '<b>Delete</b>', type: 'button-alert', onTap: function(e) { return true; } }] }); confirmPopup.then(function(res) { console.log(res); if (res) { sendMessage('delete-clip', { index: clip.index }); } }); }; window.applicationCache.addEventListener('updateready', confirmReload, false); $scope.loginState = ""; $scope.loginBusy = false; $scope.evSetFromApp = false; $scope.connected = 0; $scope.camera = { connected: false }; $scope.timelapse = { rampMode: "fixed", intervalMode: "fixed", interval: 6, dayInterval: 10, nightInterval: 36, frames: 300, destination: 'camera', nightCompensation: -1, isoMax: -6, isoMin: 0, manualAperture: -5, keyframes: [{ focus: 0, ev: "not set", motor: {} }] }; $scope.setup = { state: 0 }; $scope.axis = []; $scope.presets = [{ selected: true, name: "Daytime Time-lapse", key: "daytime", show: ['interval', 'frames'], defaults: [{ key: 'interval', value: 3 }, { key: 'frames', value: 300 }] }, { selected: false, name: "Night Time-lapse", key: "night", show: ['interval', 'frames'], defaults: [{ key: 'interval', value: 30 }, { key: 'frames', value: 300 }] }, { selected: false, name: "HDR Time-lapse", key: "hdr", show: ['interval', 'frames', 'sets', 'bracket'], defaults: [{ key: 'interval', value: 15 }, { key: 'frames', value: 300 }, { key: 'sets', value: 3 }, { key: 'bracket', value: 1 }] }, { selected: false, name: "Sunset Bulb-ramp", key: "sunset", show: ['duration'], defaults: [{ key: 'duration', value: 4 * 60 }] }, { selected: false, name: "Sunrise Bulb-ramp", key: "sunrise", show: ['duration'], defaults: [{ key: 'duration', value: 4 * 60 }] }, { selected: false, name: "24-hour+ Bulb-ramp", key: "24-hour", show: ['duration'], defaults: [{ key: 'duration', value: 24 * 60 }] }, { selected: false, name: "Expert Mode: All Features", key: "expert", show: [], defaults: [] }]; $scope.previewActive = false; var ws; var connecting; var timelapseImages = {}; $scope.view = { connected: false }; var retrievedTimelapseProgram = false; var timelapseFragments = {}; function connect(wsAddress) { if (ws || connecting) { return; } else if (!wsAddress) { console.log("-> Looking up websocket address..."); $http.get('/socket/address', {headers: {'x-view-session': $scope.sid}}).success(function(data) { console.log(data); if (data && data.address) { connect(data.address); } else if(data && data.action == 'login_required') { $scope.openLogin(); } else { connecting = false; } }).error(function(err) { connecting = false; }); return; } console.log("Connecting to websocket: " + wsAddress); ws = $websocket(wsAddress); connecting = false; ws.onMessage(function(message) { var msg = JSON.parse(message.data); console.log("message received: ", msg); var callback = function() {}; if (msg._cbId) { for (var i = 0; i < callbackList.length; i++) { if (callbackList[i].id == msg._cbId) { //console.log("cb found:", msg._cbId); callback = callbackList[i].callback; callbackList.splice(i, 1); break; } } } switch (msg.type) { case 'nodevice': $scope.camera = {}; $scope.lastImage = null; $scope.camera.model = ''; $scope.camera.connected = false; $scope.view.connected = false; $scope.nodevice = true; $scope.status = "No VIEW device available. Check that the VIEW is powered on and connected via Wifi"; callback($scope.status, null); break; case 'camera': $scope.nodevice = false; $scope.view.connected = true; $scope.camera = {}; $scope.lastImage = null; $scope.camera.model = msg.model; $scope.camera.connected = msg.connected; callback(null, $scope.camera); if (msg.connected) { $scope.status = ''; $timeout(function() { sendMessage('get', { key: 'settings' }); }, 1000); } else { $scope.status = 'Connect a camera to the VIEW via USB'; callback("no camera", null); } break; case 'motion': if(msg.available) { $scope.motionAvailable = true; for(var i = 0; i < msg.motors.length; i++) { setupAxis(msg.motors[i]); } } else { $scope.motionAvailable = false; for(var i = 0; i < $scope.axis.length; i++) { $scope.axis[i].connected = false; } } callback(null, $scope.axis); case 'move': var index = $scope.getAxisIndex(msg.driver + '-' + msg.motor); if (msg.complete && msg.driver && $scope.axis[index]) { $scope.axis[index].moving = false; if($scope.axis[index].callback) { $scope.axis[index].pos = msg.position; $scope.axis[index].callback(msg.position); $scope.axis[index].callback = null; } else if(!$scope.currentKf && $scope.axis[index].pos == 0) { sendMessage('motion', { key: 'zero', driver: msg.driver, motor: msg.motor }); } else { $scope.axis[index].pos = msg.position; } } callback(null, msg.complete); case 'settings': if (!$scope.camera.connected) break; $scope.camera.config = msg.settings; if (msg.settings) { if (msg.settings.lists) $scope.camera.lists = msg.settings.lists; if (msg.settings.shutter) { $scope.camera.shutter = msg.settings.shutter; if($scope.camera.shutter == $scope.camera.shutterNew) { $scope.camera.shutterChanged = false; } else if(!$scope.camera.shutterNew) { $scope.camera.shutterNew = $scope.camera.shutter; } else if($scope.camera.shutterChanged) { updateParams(); } else { $scope.camera.shutterNew = $scope.camera.shutter; } } else { $scope.camera.shutterChanged = false; $scope.camera.shutter = "--"; $scope.camera.shutterNew = "--"; } if (msg.settings.iso) { $scope.camera.iso = msg.settings.iso; if($scope.camera.iso == $scope.camera.isoNew) { $scope.camera.isoChanged = false; } else if(!$scope.camera.isoNew) { $scope.camera.isoNew = $scope.camera.iso; } else if($scope.camera.isoChanged) { updateParams(); } else { $scope.camera.isoNew = $scope.camera.iso; } } else { $scope.camera.isoChanged = false; $scope.camera.iso = "--"; $scope.camera.isoNew = "--"; } if (msg.settings.aperture) { $scope.camera.aperture = msg.settings.aperture; if($scope.camera.aperture == $scope.camera.apertureNew) { $scope.camera.apertureChanged = false; } else if(!$scope.camera.apertureNew) { $scope.camera.apertureNew = $scope.camera.aperture; } else if($scope.camera.apertureChanged) { updateParams(); } else { $scope.camera.apertureNew = $scope.camera.aperture; } } else { $scope.camera.apertureChanged = false; $scope.camera.aperture = "--"; $scope.camera.apertureNew = "--"; } if (msg.settings.stats) { $scope.camera.evMax3 = msg.settings.stats.maxEv * 3; $scope.camera.evMin3 = msg.settings.stats.minEv * 3; $scope.camera.ev = msg.settings.stats.ev; if ($scope.evSetFromApp === false) { $scope.camera.ev3 = $scope.camera.ev * 3; } else if ($scope.evSetFromApp === $scope.camera.ev * 3) { $scope.evSetFromApp = false; } } checkUpDown('shutter'); checkUpDown('aperture'); checkUpDown('iso'); } callback(null, $scope.camera); break; case 'thumbnail': if ($scope.previewActive) sendMessage('preview'); $scope.lastImage = msg; callback(null, msg); break; case 'status': $scope.status = msg.status ? msg.status : ''; callback(null, $scope.status); break; case 'intervalometerStatus': $scope.intervalometerStatus = msg.status ? msg.status : {}; callback(null, $scope.intervalometerStatus); break; case 'intervalometerError': $scope.intervalometerErrorMessage = msg.msg; $scope.popupMessage("Error", $scope.intervalometerErrorMessage, function() { sendMessage('dismiss-error'); }); callback(null, $scope.intervalometerErrorMessage); break; case 'captureError': $scope.intervalometerErrorMessage = msg.msg; $scope.popupMessage("Error", $scope.intervalometerErrorMessage, function() { }); callback(null, $scope.intervalometerErrorMessage); break; case 'timelapse-clips': $scope.clips = msg.clips ? msg.clips : []; callback(null, $scope.clips); break; case 'timelapse-images': if(msg.error) { callback(msg.error); } else if(msg.fragment != null) { if(!timelapseFragments[msg.index]) timelapseFragments[msg.index] = {}; timelapseFragments[msg.index][msg.fragment] = msg.images; console.log("adding fragment of " + timelapseFragments[msg.index][msg.fragment].length + ""); var complete = true; for(var i = 0; i < msg.fragments; i++) { if(!timelapseFragments[msg.index][i]) { complete = false; break; } } if(complete) { timelapseImages[msg.index] = []; for(var i = 0; i < msg.fragments; i++) { timelapseImages[msg.index] = timelapseImages[msg.index].concat(timelapseFragments[msg.index][i]); } timelapseFragments[msg.index] = null; console.log("received all image fragements, count = " + timelapseImages[msg.index].length); callback(null, msg); playTimelapse(msg.index); } } else { timelapseImages[msg.index] = msg.images; callback(null, msg); playTimelapse(msg.index); } break; case 'xmp-to-card': if (msg.error) { $scope.popupMessage("Error", "Failed to save XMPs for TL-" + msg.index + ": " + msg.error); callback(msg.error, msg); } else { $scope.popupMessage("Success", "Saved XMPs for TL-" + msg.index + ". It's safe to remove the SD card now"); callback(null, msg); } break; case 'timelapseProgram': if(!retrievedTimelapseProgram && msg.program) { if(msg.program.keyframes) { // arrays come back as object in the VIEW db var kfs = []; for(var key in msg.program.keyframes) { if(msg.program.keyframes.hasOwnProperty(key)) { kfs.push(msg.program.keyframes[key]); } } if(kfs.length > 0) msg.program.keyframes = kfs; } angular.extend($scope.timelapse, msg.program); retrievedTimelapseProgram = true; } default: { if (msg.error) { callback(msg.error, msg); } else { callback(null, msg); } } } }); ws.onOpen(function() { $scope.connected = 1; $scope.view.connected = false; $scope.nodevice = false; $scope.status = ''; setTimeout(function() { sendMessage('auth', { session: $scope.sid }); sendMessage('get', { key: 'camera' }); sendMessage('get', { key: 'motion' }); if(!retrievedTimelapseProgram) { sendMessage('get', { key: 'program' }); } setTimeout(function() { if ($state.current.name == "app.view") { $timeout(function() { $scope.getClips(); }); } }, 1000); //sendMessage('auth', { // pass: $scope.passwd //}); }); }); ws.onClose(function() { $scope.camera = {}; $scope.lastImage = null; $scope.camera.model = ''; $scope.camera.connected = false; $scope.view.connected = false; $scope.nodevice = false; $scope.status = "Lost connection to view.tl"; $scope.connected = -1; $timeout(connect, 3000); ws = null; }) ws.onError(function(err) { console.log("ws error: ", err); }); } connect(); $scope.reconnect = function() { connect(); } var callbackList = []; function sendMessage(type, object, callback) { if (!object) object = {}; object.type = type; if (ws) { if (callback) { if (callbackList.length > 0) { // manage callback buffer and generate next id var maxId = 1; removeItems = []; for (var i = 0; i < callbackList.length; i++) { cbItem = callbackList[i]; if (cbItem.id > maxId) maxId = cbItem.id; if (moment(cbItem.time).isBefore(moment().subtract(15, 'minutes'))) { removeItems.push(i); } } for (var i = 0; i < removeItems.length; i++) { callbackList.splice(i, 1); } } else { maxId = 0; } var cbId = maxId + 1; callbackList.push({ id: cbId, time: new Date(), callback: callback }); object._cbId = cbId; } ws.send(JSON.stringify(object)); } else { if (callback) callback("not connected", null); } } setInterval(function() { $scope.$apply(function() { sendMessage('ping'); }); }, 2000); $scope.update = function() { console.log("Update"); sendMessage('get', { key: 'settings' }); } $scope.capture = function() { //$scope.previewActive = false; console.log("Capture"); sendMessage('capture'); } $scope.getClips = function() { sendMessage('timelapse-clips'); } function playTimelapse(index) { var tl = null; for (i = 0; i < $scope.clips.length; i++) { if ($scope.clips[i].index == index) { tl = $scope.clips[i]; break; } } if (tl) { tl.playing = true; tl.loading = false; var frame = 0; var intervalHandle = $interval(function() { frame++; if (frame < tl.frames) { tl.image = timelapseImages[index][frame]; } else { $interval.cancel(intervalHandle); tl.playing = false; } }, 1000 / 24); } } $scope.playTimelapse = function(index) { if (timelapseImages[index]) { playTimelapse(index); } else { var tl = null; for (i = 0; i < $scope.clips.length; i++) { if ($scope.clips[i].index == index) { tl = $scope.clips[i]; break; } } if (tl && !tl.loading) { tl.loading = true; console.log("fetching timelapse-images for " + index); sendMessage('timelapse-images', { index: index }); } } } $scope.preview = function(status) { if (status != null) $scope.previewActive = !status; if ($scope.previewActive) { $scope.previewActive = false; sendMessage('previewStop'); } else { $scope.previewActive = true; console.log("Preview"); sendMessage('preview'); } } $scope.captureDelay = function(seconds) { if (!seconds) seconds = 2; $timeout($scope.capture, seconds * 1000); } $scope.focusMode = false; $scope.zoom = function(event) { if ($scope.previewActive) { $scope.focusMode = !$scope.focusMode; var pos = { reset: true, } if ($scope.focusMode && event) { var xp = event.offsetX / event.toElement.clientWidth; var yp = event.offsetY / event.toElement.clientHeight; var pos = { xPercent: xp, yPercent: yp } } sendMessage('zoom', pos); } } $scope.updateParam = function(name, val) { if(val == null) { if (name == "iso") { val = $scope.camera.iso; } else if (name == "shutter") { val = $scope.camera.shutter; } else if (name == "aperture") { val = $scope.camera.aperture; } else { return; } } console.log("Updating " + name + " to " + val); sendMessage('set', { key: name, val: val }); } function checkUpDown(param) { if($scope.camera.lists && $scope.camera.lists[param]) { var list = $scope.camera.lists[param].filter(function(item){ return item.ev != null; }); for(var i = 0; i < list.length; i++) { if($scope.camera[param + 'New'] == list[i].name) { if(i < list.length - 1) { $scope.camera[param + 'Up'] = true; } else { $scope.camera[param + 'Up'] = false; } if(i > 0) { $scope.camera[param + 'Down'] = true; } else { $scope.camera[param + 'Down'] = false; } return; } } } $scope.camera[param + 'Up'] = false; $scope.camera[param + 'Down'] = false; } var updateTimer = null; function updateParams() { updateTimer = $timeout(function(){ $scope.update(); updateTimer = null; }, 500); } var paramTimer = {}; $scope.paramClick = function(param, direction) { if($scope.camera.lists && $scope.camera.lists[param]) { var list = $scope.camera.lists[param].filter(function(item){ return item.ev != null; }); var newItem = list[0].name; for(var i = 0; i < list.length; i++) { if($scope.camera[param + 'New'] == list[i].name) { newItem = list[i].name; if(direction == 'up') { if(i < list.length - 1) { newItem = list[i + 1].name; } } else { if(i > 0) { newItem = list[i - 1].name; } } break; } } $scope.camera[param + 'New'] = newItem; $scope.camera[param + 'Changed'] = true; checkUpDown(param); if(paramTimer[param]) { $timeout.cancel(paramTimer[param]); paramTimer[param] = null; } paramTimer[param] = $timeout(function(){ paramTimer[param] = null; $scope.updateParam(param, newItem); if(updateTimer) { $timeout.cancel(updateTimer); updateTimer = null; } updateParams(); }, 1500); } else { return null; } } $scope.getAxisIndex = function(axisId) { for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].id == axisId) return i; } return null; } $scope.move = function(axisId, steps, noReverse) { console.log("moving ", axisId); if($scope.currentKf) $scope.currentKf.motionEdited = true; var index = $scope.getAxisIndex(axisId); if(index === null) return false; var parts = axisId.split('-'); if (steps && parts.length == 2) { var driver = parts[0]; var motor = parts[1]; if($scope.axis[index].reverse && !noReverse) steps = 0 - steps; console.log("moving motor" + axisId, steps); $scope.axis[index].moving = true; if($scope.currentKf || $scope.axis[index].pos != 0) $scope.axis[index].pos -= steps; // will be overwritten by motor driver response sendMessage('motion', { key: 'move', val: steps, driver: driver, motor: motor }); } } $scope.atHomePosition = function() { for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected && $scope.axis[i].pos != 0) return false; } return true; } $scope.setHomePosition = function() { for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected && $scope.axis[i].pos != 0) $scope.zeroAxis($scope.axis[i].id); } } $scope.zeroAxis = function(axisId) { console.log("zeroing ", axisId); var index = $scope.getAxisIndex(axisId); if(index === null) return false; var parts = axisId.split('-'); if (steps && parts.length == 2) { var driver = parts[0]; var motor = parts[1]; $scope.axis[index].pos = 0; // will be overwritten by motor driver response sendMessage('motion', { key: 'zero', driver: driver, motor: motor }); } } var joystickTimers = {}; $scope.joystick = function(axisName, speed) { var index = null; var axisId = null; for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].name.toLowerCase() == axisName.toLowerCase()) { index = i; axisId = $scope.axis[index].id; break; } } if(index === null) return false; if(joystickTimers[axisName]) $timeout.cancel(joystickTimers[axisName]); // rate limit per axis joystickTimers[axisName] = $timeout(function(){ console.log("moving ", axisId); var parts = axisId.split('-'); if (parts.length == 2) { var driver = parts[0]; var motor = parts[1]; console.log("joystick motor" + axisId, speed); sendMessage('motion', { key: 'joystick', val: speed * 100, driver: driver, motor: motor }); } }, 200); } $scope.focusPos = 0; $scope.focus = function(dir, repeat, noUpdate) { if (!repeat) repeat = 1; if(!noUpdate) { if (dir > 0) $scope.focusPos += repeat; if (dir < 0) $scope.focusPos -= repeat; if($scope.currentKf) $scope.currentKf.focusEdited = true; } sendMessage('focus', { key: 'manual', val: dir, repeat: repeat }); console.log("focusPos:", $scope.focusPos); } function dbGet(key, callback) { sendMessage('dbGet', { key: key }, function(err, res){ callback && callback(err, res.val); console.log("dbGet result", res); }); } function dbSet(key, val, callback) { sendMessage('dbSet', { key: key, val: val }, function(err){ callback && callback(err); console.log("dbSet err", err); }); } $scope.testBulb = function() { sendMessage('test'); } var setEvTimerHandle = null; $scope.setEv = function(ev) { if (setEvTimerHandle) $timeout.cancel(setEvTimerHandle); $scope.evSetFromApp = ev; setEvTimerHandle = $timeout(function() { console.log("setting ev to ", ev); sendMessage('setEv', { ev: ev }); }, 300); } $scope.incEv = function() { if ($scope.camera.ev3 < $scope.camera.evMax3) { $scope.camera.ev3++; $scope.setEv($scope.camera.ev3 / 3); } } $scope.decEv = function() { if ($scope.camera.ev3 > $scope.camera.evMin3) { $scope.camera.ev3--; $scope.setEv($scope.camera.ev3 / 3); } } $scope.incSecondsRange = function(kf) { if ($scope.secondsRange.val < TIMING_SLIDER_RANGE) $scope.secondsRange.val++; $scope.updateSeconds(kf, $scope.secondsRange.val); } $scope.decSecondsRange = function(kf) { if ($scope.secondsRange.val > 0) $scope.secondsRange.val--; $scope.updateSeconds(kf, $scope.secondsRange.val); } $scope.updateSeconds = function(kf, val) { kf.seconds = MAX_KF_SECONDS * Math.pow((val / TIMING_SLIDER_RANGE), (1 / TIMING_CURVE)); $scope.secondsRange.val = val; } $scope.setState = function(state) { $scope.setup.state = state; } $scope.setupTimelapse = function(preset) { if (preset.selected) { $scope.timelapse.mode = preset.key; } //$scope.setState(1); } $scope.mode = 'exposure'; $scope.setMode = function(mode) { if (mode != 'focus' && $scope.focusMode) { $scope.zoom(); } $scope.mode = mode; } $scope.runProgram = function(program) { program.focusPos = $scope.focusPos; for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected) program['motor-' + $scope.axis[i].id + 'Pos'] = $scope.axis[i].pos; } //program.rampMode = 'auto'; //program.intervalMode = 'fixed'; sendMessage('run', { program: program }); } $scope.stopProgram = function() { sendMessage('stop'); } $ionicModal.fromTemplateUrl('templates/modal-exposure.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modalExposure = modal; }); $scope.currentKf = null; $scope.currentKfIndex = null; $scope.secondsRange = { val: 0 }; var MAX_KF_SECONDS = 3600 * 24; var TIMING_SLIDER_RANGE = 100; var TIMING_CURVE = 1 / 2.5; $scope.timingSliderMax = TIMING_SLIDER_RANGE; $scope.openExposure = function(kf, index) { $scope.currentKf = kf; if(!$scope.currentKf.focus) $scope.currentKf.focus = 0; $scope.currentKfIndex = index; $scope.currentKf.focusEdited = false; $scope.currentKf.motionEdited = false; if (kf) { $scope.secondsRange.val = TIMING_SLIDER_RANGE * Math.pow((kf.seconds / MAX_KF_SECONDS), TIMING_CURVE); $scope.ev3 = kf.ev * 3; //if (kf.ev != null) $scope.setEv(kf.ev); //if (kf.focus != null) { // var focusDiff = kf.focus - $scope.focusPos; // var dir = focusDiff < 0 ? -1 : 1; // var repeat = Math.abs(focusDiff); // if (repeat > 0) $scope.focus(dir, repeat); //} if(!kf.motor) kf.motor = {}; for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected) { var id = $scope.axis[i].id; if(!kf.motor[id]) kf.motor[id] = 0; var diff = kf.motor[id] - $scope.axis[i].pos; $scope.move(id, 0 - diff, true); } } } $scope.preview(true); $scope.modalExposure.show(); }; $scope.focusMoveToKeyframe = function(currentKf) { var focusDiff = $scope.focusCurrentDistance(currentKf); var dir = focusDiff < 0 ? -1 : 1; var repeat = Math.abs(focusDiff); if (repeat > 0) $scope.focus(dir, repeat); } $scope.focusCurrentDistance = function(currentKf) { return currentKf ? currentKf.focus - $scope.focusPos : 0; } $scope.focusResetKeyframe = function(currentKf) { currentKf.focus = $scope.focusPos; } $scope.closeExposure = function() { var delay = 0; if ($scope.focusMode) { $scope.zoom(); delay = 1000; } if($scope.currentKf.focusEdited || $scope.currentKf.motionEdited) { $timeout(function() { $scope.preview(false); if ($scope.currentKf) { $scope.currentKf.jpeg = $scope.lastImage ? $scope.lastImage.jpeg : null; } }, delay); } if ($scope.currentKfIndex == 0) { for (var i = 1; i < $scope.timelapse.keyframes.length; i++) { if($scope.currentKf.focusEdited) $scope.timelapse.keyframes[i].focus -= $scope.focusPos; if($scope.currentKf.motionEdited) { for(var j = 0; j < $scope.axis.length; j++) { if($scope.axis[j].connected) { var id = $scope.axis[j].id; if($scope.axis[j].moving) { (function(kfIndex, axisIndex){ $scope.axis[j].callback = function() { $scope.timelapse.keyframes[i].motor[id] -= $scope.axis[j].pos; } })(i, j); } else { $scope.timelapse.keyframes[i].motor[id] -= $scope.axis[j].pos; } } } } } if($scope.currentKf.focusEdited) $scope.focusPos = 0; if($scope.currentKf.motionEdited) { for(var i = 0; i < $scope.axis.length; i++) { var parts = $scope.axis[i].id.split('-'); if (parts.length == 2) { var driver = parts[0]; var motor = parts[1]; if($scope.axis[i].moving) { (function(d, m, index){ $scope.axis[index].callback = function(position) { sendMessage('motion', { key: 'zero', driver: d, motor: m }); }; })(driver, motor, i); } else { sendMessage('motion', { key: 'zero', driver: driver, motor: motor }); } //$scope.axis[i].pos = 0; } } } } if($scope.currentKf.focusEdited) $scope.currentKf.focus = $scope.focusPos; if($scope.currentKf.motionEdited) { for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected) { var id = $scope.axis[i].id; $scope.currentKf.motor[id] = $scope.axis[i].pos; } } } $scope.currentKf.ev = $scope.camera.ev; $scope.modalExposure.hide(); }; $scope.addKeyframe = function() { if (!$scope.timelapse.keyframes) $scope.timelapse.keyframes = [{motor:{}}]; var lastKf = $scope.timelapse.keyframes[$scope.timelapse.keyframes.length - 1]; var kf = { focus: lastKf.focus, seconds: 600 } for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected) { var id = $scope.axis[i].id; if(!kf.motor) kf.motor = {}; kf.motor[id] = lastKf.motor[id]; } } $scope.timelapse.keyframes.push(kf); } $scope.removeKeyframe = function(index) { $scope.timelapse.keyframes.splice(index, 1); } $ionicModal.fromTemplateUrl('templates/modal-motion-setup.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modalMotionSetup = modal; }); $scope.openMotionSetup = function(axisId) { var axisIndex = $scope.getAxisIndex(axisId); if(axisIndex === null) return; $scope.setupAxis = $scope.axis[axisIndex]; $scope.modalMotionSetup.show(); }; $scope.closeMotionSetup = function() { if($scope.setupAxis.name) $scope.setupAxis.setup = true; if($scope.setupAxis.unit == 's') $scope.setupAxis.unitSteps = 1; $scope.setupAxis.moveSteps = $scope.setupAxis.unitMove * $scope.setupAxis.unitSteps; //localStorageService.set('motion-' + $scope.setupAxis.id, $scope.setupAxis); dbSet('motion-' + $scope.setupAxis.id, $scope.setupAxis); var axisIndex = $scope.getAxisIndex($scope.setupAxis.id); $scope.axis[axisIndex] = $scope.setupAxis; $scope.modalMotionSetup.hide(); }; $scope.changeAxisType = function(type) { $scope.setupAxis.name = type; if(type == 'Pan' || type == 'Tilt') { $scope.setupAxis.unit = '°'; $scope.setupAxis.unitSteps = 560; $scope.setupAxis.unitMove = 5; } else { $scope.setupAxis.unit = 's'; $scope.setupAxis.unitSteps = 1; $scope.setupAxis.unitMove = 500; } } $scope.changeAxisUnit = function(unit) { $scope.setupAxis.unit = unit; } $scope.changeAxisUnitSteps = function(unitSteps) { $scope.setupAxis.unitSteps = unitSteps; } $scope.changeAxisUnitMove = function(unitMove) { $scope.setupAxis.unitMove = unitMove; } $scope.changeAxisReverse = function(reverse) { $scope.setupAxis.reverse = reverse; } function setupAxis(axisInfo) { var axisId = axisInfo.driver + '-' + axisInfo.motor; console.log("setting up axis: ", axisId); //var axis = localStorageService.get('motion-' + axisId); dbGet('motion-' + axisId, function(err, axis) { console.log("VIEW db err:", err); console.log("VIEW db axis:", axis); if(!axis) { axis = { name: '', unit: 's', unitSteps: 1, unitMove: 500, reverse: false, pos: 0, moving: false, setup: false } } axis.id = axisId; axis.motor = axisInfo.motor; axis.driver = axisInfo.driver; axis.connected = axisInfo.connected; axis.pos = axisInfo.position; var axisIndex = $scope.getAxisIndex(axisId); if(!$scope.axis) $scope.axis = []; if(axisIndex === null) { $scope.axis.push(axis); } else { //axis.pos = $scope.axis[axisIndex].pos; axis.moving = false;//$scope.axis[axisIndex].moving; $scope.axis[axisIndex] = axis; } console.log("$scope.axis", $scope.axis); }); } $ionicModal.fromTemplateUrl('templates/modal-login.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modalLogin = modal; }); $scope.openLogin = function() { if($scope.modalLogin) { $scope.loginState = "email"; $scope.loginBusy = false; $scope.modalLogin.show(); } else { $timeout($scope.openLogin, 1000); } }; $scope.closeLogin = function() { $scope.modalLogin.hide(); }; $scope.loginCheckEmail = function(email) { $scope.loginBusy = true; $http.post('/api/email', {email: email}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "login") { $scope.loginState = 'login-password' } if(res == "register") { $scope.loginState = 'register-subdomain' } if(res == "error") { $scope.loginState = 'noemail' } } $scope.loginBusy = false; }).error(function(err) { $scope.loginBusy = false; }); } $scope.loginCheckSubdomain = function(subdomain) { $scope.loginBusy = true; $http.post('/api/subdomain/check', {subdomain: subdomain}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "available") { $scope.loginState = 'register-password' } else { $scope.loginState = 'register-unavailable' } } $scope.loginBusy = false; }).error(function(err) { $scope.loginBusy = false; }); } $scope.loginRegister = function(email, subdomain, password) { $scope.loginBusy = true; $http.post('/api/register', {email: email, subdomain: subdomain, password:password}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "login") { $scope.closeLogin(); } else { $scope.loginState = 'register-unavailable' } } $scope.loginBusy = false; }).error(function(err) { $scope.loginBusy = false; }); } $scope.login = function(email, password) { $scope.loginBusy = true; $http.post('/api/login', {email: email, password:password}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "login") { $scope.sid = data.session; localStorageService.set('sid', $scope.sid); $scope.closeLogin(); connect(); } else { $scope.loginState = 'login-failed' } } $scope.loginBusy = false; }).error(function(err) { $scope.loginBusy = false; }); } $scope.addDevice = function(code) { $http.post('/api/device/new', {code: code}, {headers: {'x-view-session': $scope.sid}}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "device_added") { $scope.popupMessage("Successfully added VIEW device to this account"); } else { $scope.popupMessage("Failed to add VIEW device. Please try again."); } } }).error(function(err) { $scope.popupMessage("Failed to add VIEW device. Please try again."); }); } $scope.saveToCard = function(clip) { sendMessage('xmp-to-card', { index: clip.index }); } $scope.showClipOptions = function(clip) { // Show the action sheet var hideSheet = $ionicActionSheet.show({ buttons: [{ text: 'Write XMP folder to SD card' }], destructiveText: 'Delete Clip', titleText: clip.name, cancelText: 'Cancel', cancel: function() { // add cancel code.. }, destructiveButtonClicked: function() { $scope.confirmDelete(clip); }, buttonClicked: function(index) { if (index === 0) { $scope.saveToCard(clip); } return true; } }); // For example's sake, hide the sheet after two seconds $timeout(function() { hideSheet(); }, 8000); }; $scope.setTimelapse = function(param, val) { $scope.timelapse[param] = val; console.log("Setting timelapse." + param + " = " + val); } $scope.toggleIntervalMode = function() { if ($scope.timelapse.intervalMode == 'fixed') $scope.timelapse.intervalMode = 'auto' else $scope.timelapse.intervalMode = 'fixed'; } $scope.passwd = ""; //Cleanup the modal when we're done with it! $scope.$on('$destroy', function() { $scope.modalLogin.remove(); $scope.modalExposure.remove(); }); //$scope.setupTimelapse($scope.presets[0]); }]) ;
frontend/www/js/app.js
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.services' is found in services.js // 'starter.controllers' is found in controllers.js angular.module('app', ['ionic', 'ngWebSocket', 'LocalStorageModule']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider .state('app', { url: "/app", abstract: true, templateUrl: "templates/menu.html", controller: 'AppCtrl' }) .state('app.capture', { cache: false, url: "/capture", views: { 'menuContent': { templateUrl: "templates/capture.html" } } }) .state('app.timelapse', { cache: false, url: "/timelapse", views: { 'menuContent': { templateUrl: "templates/timelapse.html" } } }) .state('app.view', { cache: false, url: "/view", views: { 'menuContent': { templateUrl: "templates/view.html" } } }) // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/app/capture'); }) .controller('AppCtrl', ['$scope', '$timeout', '$http', '$websocket', '$location', '$ionicPopup', '$ionicActionSheet', '$interval', '$ionicModal', '$state', 'localStorageService', '$ionicHistory', '$ionicSideMenuDelegate', '$ionicScrollDelegate', function($scope, $timeout, $http, $websocket, $location, $ionicPopup, $ionicActionSheet, $interval, $ionicModal, $state, localStorageService, $ionicHistory, $ionicSideMenuDelegate, $ionicScrollDelegate) { console.log("AppCtrl"); $scope.moment = moment; $scope.sid = localStorageService.get('sid'); console.log("current sid: ", $scope.sid); $scope.secondsDescription = function(seconds, index) { var hours = Math.floor(seconds / 3600); seconds -= (hours * 3600); var minutes = Math.floor(seconds / 60); seconds -= (minutes * 60); var seconds = Math.round(seconds); var time = ""; if (hours > 0) time += hours + 'h '; if (minutes > 0) time += minutes + 'm '; if (hours == 0 && minutes < 10) time += seconds + 's '; if (index > 1) { time += "from last keyframe"; } else { time += "from start"; } return time; } /*var previousState = localStorageService.get('state'); if(previousState != null && typeof previousState == "string" && previousState.match(/^app\./)) { console.log("starting at " + previousState); $ionicHistory.nextViewOptions({ // I have no idea why this simply does not work disableAnimate: true, historyRoot: true }); $state.go(previousState); $ionicHistory.clearCache(); $ionicHistory.clearHistory(); }*/ var controls = {}; $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { console.log("new state:", toState); localStorageService.set('state', toState.name); if (toState.name == "app.view") { $scope.getClips(); } /*else if(toState.name == "app.capture") { if(controls.joystick) { controls.joystick.delete(); delete controls.joystick; } if(controls.slider) { controls.slider.delete(); delete controls.slider; } $timeout(function(){ controls.joystick = new window.TouchControl('joystick'); controls.joystick.on('pos', function(x, y) { $scope.joystick('pan', x); $scope.joystick('tilt', y); console.log("joystick pos", x, y); }); controls.joystick.on('start', function(x, y) { $scope.$apply(function(){ console.log("disabing scroll"); $ionicSideMenuDelegate.canDragContent(false); $ionicScrollDelegate.freezeAllScrolls(false); //$ionicScrollDelegate.getScrollView().options.scrollingY = false; }); }); controls.joystick.on('stop', function(x, y) { $scope.$apply(function(){ console.log("enabling scroll"); $ionicSideMenuDelegate.canDragContent(true); $ionicScrollDelegate.freezeAllScrolls(true); //$ionicScrollDelegate.getScrollView().options.scrollingY = true; }); }); controls.slider = new window.TouchControl('slider'); controls.slider.on('pos', function(x) { $scope.joystick('slide', x); console.log("slider pos", x); }); controls.slider.on('start', function(x, y) { $scope.$apply(function(){ console.log("disabing scroll"); $ionicSideMenuDelegate.canDragContent(false); $ionicScrollDelegate.freezeAllScrolls(false); //$ionicScrollDelegate.getScrollView().options.scrollingY = false; }); }); controls.slider.on('stop', function(x, y) { $scope.$apply(function(){ console.log("enabling scroll"); $ionicSideMenuDelegate.canDragContent(true); $ionicScrollDelegate.freezeAllScrolls(true); //$ionicScrollDelegate.getScrollView().options.scrollingY = true; }); }); }); }*/ }); function updateCache() { console.log("updating cache"); window.applicationCache.swapCache(); window.location.reload(); } var confirmReload = function() { var confirmPopup = $ionicPopup.show({ title: 'Update Available', template: 'Reload app with new version?', buttons: [{ text: 'Next Launch' }, { text: '<b>Update Now</b>', type: 'button-positive', onTap: function(e) { return true; } }] }); confirmPopup.then(function(res) { console.log(res); if (res) { updateCache(); } else { console.log('Next Launch'); } }); }; $scope.confirmStop = function() { var confirmPopup = $ionicPopup.show({ title: 'Confirm', template: 'Stop Time-lapse?', buttons: [{ text: 'Cancel' }, { text: '<b>Stop</b>', type: 'button-alert', onTap: function(e) { return true; } }] }); confirmPopup.then(function(res) { console.log(res); if (res) { $scope.stopProgram(); } }); }; $scope.popupMessage = function(title, message, callback) { var confirmPopup = $ionicPopup.show({ title: title, template: message, buttons: [{ text: 'Close', onTap: function(e) { callback && callback(); } }] }); }; // Triggered on a button click, or some other target $scope.showAddDevice = function() { $scope.data = {}; // An elaborate, custom popup var addDevicePopup = $ionicPopup.show({ template: '<input type="number" ng-model="data.code">', title: 'Enter code shown on VIEW device', subTitle: "if a code isn't shown, make sure the VIEW is connected via WiFi", scope: $scope, buttons: [ { text: 'Cancel' }, { text: '<b>Add</b>', type: 'button-positive', onTap: function(e) { if (!$scope.data.code) { //don't allow the user to close unless he enters wifi password e.preventDefault(); } else { $scope.addDevice($scope.data.code); return $scope.data.code; } } } ] }); addDevicePopup.then(function(res) { console.log('Tapped!', res); }); $timeout(function() { addDevicePopup.close(); //close the popup after 3 seconds for some reason }, 60000); }; $scope.confirmDelete = function(clip) { var confirmPopup = $ionicPopup.show({ title: 'Confirm', template: 'Delete Preview for ' + clip.name + '?', buttons: [{ text: 'Cancel' }, { text: '<b>Delete</b>', type: 'button-alert', onTap: function(e) { return true; } }] }); confirmPopup.then(function(res) { console.log(res); if (res) { sendMessage('delete-clip', { index: clip.index }); } }); }; window.applicationCache.addEventListener('updateready', confirmReload, false); $scope.loginState = ""; $scope.loginBusy = false; $scope.evSetFromApp = false; $scope.connected = 0; $scope.camera = { connected: false }; $scope.timelapse = { rampMode: "fixed", intervalMode: "fixed", interval: 6, dayInterval: 10, nightInterval: 36, frames: 300, destination: 'camera', nightCompensation: -1, isoMax: -6, isoMin: 0, manualAperture: -5, keyframes: [{ focus: 0, ev: "not set", motor: {} }] }; $scope.setup = { state: 0 }; $scope.axis = []; $scope.presets = [{ selected: true, name: "Daytime Time-lapse", key: "daytime", show: ['interval', 'frames'], defaults: [{ key: 'interval', value: 3 }, { key: 'frames', value: 300 }] }, { selected: false, name: "Night Time-lapse", key: "night", show: ['interval', 'frames'], defaults: [{ key: 'interval', value: 30 }, { key: 'frames', value: 300 }] }, { selected: false, name: "HDR Time-lapse", key: "hdr", show: ['interval', 'frames', 'sets', 'bracket'], defaults: [{ key: 'interval', value: 15 }, { key: 'frames', value: 300 }, { key: 'sets', value: 3 }, { key: 'bracket', value: 1 }] }, { selected: false, name: "Sunset Bulb-ramp", key: "sunset", show: ['duration'], defaults: [{ key: 'duration', value: 4 * 60 }] }, { selected: false, name: "Sunrise Bulb-ramp", key: "sunrise", show: ['duration'], defaults: [{ key: 'duration', value: 4 * 60 }] }, { selected: false, name: "24-hour+ Bulb-ramp", key: "24-hour", show: ['duration'], defaults: [{ key: 'duration', value: 24 * 60 }] }, { selected: false, name: "Expert Mode: All Features", key: "expert", show: [], defaults: [] }]; $scope.previewActive = false; var ws; var connecting; var timelapseImages = {}; $scope.view = { connected: false }; var retrievedTimelapseProgram = false; var timelapseFragments = {}; function connect(wsAddress) { if (ws || connecting) { return; } else if (!wsAddress) { console.log("-> Looking up websocket address..."); $http.get('/socket/address', {headers: {'x-view-session': $scope.sid}}).success(function(data) { console.log(data); if (data && data.address) { connect(data.address); } else if(data && data.action == 'login_required') { $scope.openLogin(); } else { connecting = false; } }).error(function(err) { connecting = false; }); return; } console.log("Connecting to websocket: " + wsAddress); ws = $websocket(wsAddress); connecting = false; ws.onMessage(function(message) { var msg = JSON.parse(message.data); console.log("message received: ", msg); var callback = function() {}; if (msg._cbId) { for (var i = 0; i < callbackList.length; i++) { if (callbackList[i].id == msg._cbId) { //console.log("cb found:", msg._cbId); callback = callbackList[i].callback; callbackList.splice(i, 1); break; } } } switch (msg.type) { case 'nodevice': $scope.camera = {}; $scope.lastImage = null; $scope.camera.model = ''; $scope.camera.connected = false; $scope.view.connected = false; $scope.nodevice = true; $scope.status = "No VIEW device available. Check that the VIEW is powered on and connected via Wifi"; callback($scope.status, null); break; case 'camera': $scope.nodevice = false; $scope.view.connected = true; $scope.camera = {}; $scope.lastImage = null; $scope.camera.model = msg.model; $scope.camera.connected = msg.connected; callback(null, $scope.camera); if (msg.connected) { $scope.status = ''; $timeout(function() { sendMessage('get', { key: 'settings' }); }, 1000); } else { $scope.status = 'Connect a camera to the VIEW via USB'; callback("no camera", null); } break; case 'motion': if(msg.available) { $scope.motionAvailable = true; for(var i = 0; i < msg.motors.length; i++) { setupAxis(msg.motors[i]); } } else { $scope.motionAvailable = false; for(var i = 0; i < $scope.axis.length; i++) { $scope.axis[i].connected = false; } } callback(null, $scope.axis); case 'move': var index = $scope.getAxisIndex(msg.driver + '-' + msg.motor); if (msg.complete && msg.driver && $scope.axis[index]) { $scope.axis[index].moving = false; if($scope.axis[index].callback) { $scope.axis[index].pos = msg.position; $scope.axis[index].callback(msg.position); $scope.axis[index].callback = null; } else if(!$scope.currentKf && $scope.axis[index].pos == 0) { sendMessage('motion', { key: 'zero', driver: msg.driver, motor: msg.motor }); } else { $scope.axis[index].pos = msg.position; } } callback(null, msg.complete); case 'settings': if (!$scope.camera.connected) break; $scope.camera.config = msg.settings; if (msg.settings) { if (msg.settings.lists) $scope.camera.lists = msg.settings.lists; if (msg.settings.shutter) { $scope.camera.shutter = msg.settings.shutter; if($scope.camera.shutter == $scope.camera.shutterNew) { $scope.camera.shutterChanged = false; } else if(!$scope.camera.shutterNew) { $scope.camera.shutterNew = $scope.camera.shutter; } else if($scope.camera.shutterChanged) { updateParams(); } else { $scope.camera.shutterNew = $scope.camera.shutter; } } else { $scope.camera.shutterChanged = false; $scope.camera.shutter = "--"; $scope.camera.shutterNew = "--"; } if (msg.settings.iso) { $scope.camera.iso = msg.settings.iso; if($scope.camera.iso == $scope.camera.isoNew) { $scope.camera.isoChanged = false; } else if(!$scope.camera.isoNew) { $scope.camera.isoNew = $scope.camera.iso; } else if($scope.camera.isoChanged) { updateParams(); } else { $scope.camera.isoNew = $scope.camera.iso; } } else { $scope.camera.isoChanged = false; $scope.camera.iso = "--"; $scope.camera.isoNew = "--"; } if (msg.settings.aperture) { $scope.camera.aperture = msg.settings.aperture; if($scope.camera.aperture == $scope.camera.apertureNew) { $scope.camera.apertureChanged = false; } else if(!$scope.camera.apertureNew) { $scope.camera.apertureNew = $scope.camera.aperture; } else if($scope.camera.apertureChanged) { updateParams(); } else { $scope.camera.apertureNew = $scope.camera.aperture; } } else { $scope.camera.apertureChanged = false; $scope.camera.aperture = "--"; $scope.camera.apertureNew = "--"; } if (msg.settings.stats) { $scope.camera.evMax3 = msg.settings.stats.maxEv * 3; $scope.camera.evMin3 = msg.settings.stats.minEv * 3; $scope.camera.ev = msg.settings.stats.ev; if ($scope.evSetFromApp === false) { $scope.camera.ev3 = $scope.camera.ev * 3; } else if ($scope.evSetFromApp === $scope.camera.ev * 3) { $scope.evSetFromApp = false; } } checkUpDown('shutter'); checkUpDown('aperture'); checkUpDown('iso'); } callback(null, $scope.camera); break; case 'thumbnail': if ($scope.previewActive) sendMessage('preview'); $scope.lastImage = msg; callback(null, msg); break; case 'status': $scope.status = msg.status ? msg.status : ''; callback(null, $scope.status); break; case 'intervalometerStatus': $scope.intervalometerStatus = msg.status ? msg.status : {}; callback(null, $scope.intervalometerStatus); break; case 'intervalometerError': $scope.intervalometerErrorMessage = msg.msg; $scope.popupMessage("Error", $scope.intervalometerErrorMessage, function() { sendMessage('dismiss-error'); }); callback(null, $scope.intervalometerErrorMessage); break; case 'captureError': $scope.intervalometerErrorMessage = msg.msg; $scope.popupMessage("Error", $scope.intervalometerErrorMessage, function() { }); callback(null, $scope.intervalometerErrorMessage); break; case 'timelapse-clips': $scope.clips = msg.clips ? msg.clips : []; callback(null, $scope.clips); break; case 'timelapse-images': if(msg.error) { callback(msg.error); } else if(msg.fragment != null) { if(!timelapseFragments[msg.index]) timelapseFragments[msg.index] = {}; timelapseFragments[msg.index][msg.fragment] = msg.images; console.log("adding fragment of " + timelapseFragments[msg.index][msg.fragment].length + ""); var complete = true; for(var i = 0; i < msg.fragments; i++) { if(!timelapseFragments[msg.index][i]) { complete = false; break; } } if(complete) { timelapseImages[msg.index] = []; for(var i = 0; i < msg.fragments; i++) { timelapseImages[msg.index] = timelapseImages[msg.index].concat(timelapseFragments[msg.index][i]); } timelapseFragments[msg.index] = null; console.log("received all image fragements, count = " + timelapseImages[msg.index].length); callback(null, msg); playTimelapse(msg.index); } } else { timelapseImages[msg.index] = msg.images; callback(null, msg); playTimelapse(msg.index); } break; case 'xmp-to-card': if (msg.error) { $scope.popupMessage("Error", "Failed to save XMPs for TL-" + msg.index + ": " + msg.error); callback(msg.error, msg); } else { $scope.popupMessage("Success", "Saved XMPs for TL-" + msg.index + ". It's safe to remove the SD card now"); callback(null, msg); } break; case 'timelapseProgram': if(!retrievedTimelapseProgram && msg.program) { if(msg.program.keyframes) { // arrays come back as object in the VIEW db var kfs = []; for(var key in msg.program.keyframes) { if(msg.program.keyframes.hasOwnProperty(key)) { kfs.push(msg.program.keyframes[key]); } } if(kfs.length > 0) msg.program.keyframes = kfs; } angular.extend($scope.timelapse, msg.program); retrievedTimelapseProgram = true; } default: { if (msg.error) { callback(msg.error, msg); } else { callback(null, msg); } } } }); ws.onOpen(function() { $scope.connected = 1; $scope.view.connected = false; $scope.nodevice = false; $scope.status = ''; setTimeout(function() { sendMessage('auth', { session: $scope.sid }); sendMessage('get', { key: 'camera' }); sendMessage('get', { key: 'motion' }); if(!retrievedTimelapseProgram) { sendMessage('get', { key: 'program' }); } setTimeout(function() { if ($state.current.name == "app.view") { $timeout(function() { $scope.getClips(); }); } }, 1000); //sendMessage('auth', { // pass: $scope.passwd //}); }); }); ws.onClose(function() { $scope.camera = {}; $scope.lastImage = null; $scope.camera.model = ''; $scope.camera.connected = false; $scope.view.connected = false; $scope.nodevice = false; $scope.status = "Lost connection to view.tl"; $scope.connected = -1; $timeout(connect, 3000); ws = null; }) ws.onError(function(err) { console.log("ws error: ", err); }); } connect(); $scope.reconnect = function() { connect(); } var callbackList = []; function sendMessage(type, object, callback) { if (!object) object = {}; object.type = type; if (ws) { if (callback) { if (callbackList.length > 0) { // manage callback buffer and generate next id var maxId = 1; removeItems = []; for (var i = 0; i < callbackList.length; i++) { cbItem = callbackList[i]; if (cbItem.id > maxId) maxId = cbItem.id; if (moment(cbItem.time).isBefore(moment().subtract(15, 'minutes'))) { removeItems.push(i); } } for (var i = 0; i < removeItems.length; i++) { callbackList.splice(i, 1); } } else { maxId = 0; } var cbId = maxId + 1; callbackList.push({ id: cbId, time: new Date(), callback: callback }); object._cbId = cbId; } ws.send(JSON.stringify(object)); } else { if (callback) callback("not connected", null); } } setInterval(function() { $scope.$apply(function() { sendMessage('ping'); }); }, 2000); $scope.update = function() { console.log("Update"); sendMessage('get', { key: 'settings' }); } $scope.capture = function() { //$scope.previewActive = false; console.log("Capture"); sendMessage('capture'); } $scope.getClips = function() { sendMessage('timelapse-clips'); } function playTimelapse(index) { var tl = null; for (i = 0; i < $scope.clips.length; i++) { if ($scope.clips[i].index == index) { tl = $scope.clips[i]; break; } } if (tl) { tl.playing = true; tl.loading = false; var frame = 0; var intervalHandle = $interval(function() { frame++; if (frame < tl.frames) { tl.image = timelapseImages[index][frame]; } else { $interval.cancel(intervalHandle); tl.playing = false; } }, 1000 / 24); } } $scope.playTimelapse = function(index) { if (timelapseImages[index]) { playTimelapse(index); } else { var tl = null; for (i = 0; i < $scope.clips.length; i++) { if ($scope.clips[i].index == index) { tl = $scope.clips[i]; break; } } if (tl && !tl.loading) { tl.loading = true; console.log("fetching timelapse-images for " + index); sendMessage('timelapse-images', { index: index }); } } } $scope.preview = function(status) { if (status != null) $scope.previewActive = !status; if ($scope.previewActive) { $scope.previewActive = false; sendMessage('previewStop'); } else { $scope.previewActive = true; console.log("Preview"); sendMessage('preview'); } } $scope.captureDelay = function(seconds) { if (!seconds) seconds = 2; $timeout($scope.capture, seconds * 1000); } $scope.focusMode = false; $scope.zoom = function(event) { if ($scope.previewActive) { $scope.focusMode = !$scope.focusMode; var pos = { reset: true, } if ($scope.focusMode && event) { var xp = event.offsetX / event.toElement.clientWidth; var yp = event.offsetY / event.toElement.clientHeight; var pos = { xPercent: xp, yPercent: yp } } sendMessage('zoom', pos); } } $scope.updateParam = function(name, val) { if(val == null) { if (name == "iso") { val = $scope.camera.iso; } else if (name == "shutter") { val = $scope.camera.shutter; } else if (name == "aperture") { val = $scope.camera.aperture; } else { return; } } console.log("Updating " + name + " to " + val); sendMessage('set', { key: name, val: val }); } function checkUpDown(param) { if($scope.camera.lists && $scope.camera.lists[param]) { var list = $scope.camera.lists[param].filter(function(item){ return item.ev != null; }); for(var i = 0; i < list.length; i++) { if($scope.camera[param + 'New'] == list[i].name) { if(i < list.length - 1) { $scope.camera[param + 'Up'] = true; } else { $scope.camera[param + 'Up'] = false; } if(i > 0) { $scope.camera[param + 'Down'] = true; } else { $scope.camera[param + 'Down'] = false; } return; } } } $scope.camera[param + 'Up'] = false; $scope.camera[param + 'Down'] = false; } var updateTimer = null; function updateParams() { updateTimer = $timeout(function(){ $scope.update(); updateTimer = null; }, 500); } var paramTimer = {}; $scope.paramClick = function(param, direction) { if($scope.camera.lists && $scope.camera.lists[param]) { var list = $scope.camera.lists[param].filter(function(item){ return item.ev != null; }); var newItem = list[0].name; for(var i = 0; i < list.length; i++) { if($scope.camera[param + 'New'] == list[i].name) { newItem = list[i].name; if(direction == 'up') { if(i < list.length - 1) { newItem = list[i + 1].name; } } else { if(i > 0) { newItem = list[i - 1].name; } } break; } } $scope.camera[param + 'New'] = newItem; $scope.camera[param + 'Changed'] = true; checkUpDown(param); if(paramTimer[param]) { $timeout.cancel(paramTimer[param]); paramTimer[param] = null; } paramTimer[param] = $timeout(function(){ paramTimer[param] = null; $scope.updateParam(param, newItem); if(updateTimer) { $timeout.cancel(updateTimer); updateTimer = null; } updateParams(); }, 1500); } else { return null; } } $scope.getAxisIndex = function(axisId) { for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].id == axisId) return i; } return null; } $scope.move = function(axisId, steps, noReverse) { console.log("moving ", axisId); if($scope.currentKf) $scope.currentKf.motionEdited = true; var index = $scope.getAxisIndex(axisId); if(index === null) return false; var parts = axisId.split('-'); if (steps && parts.length == 2) { var driver = parts[0]; var motor = parts[1]; if($scope.axis[index].reverse && !noReverse) steps = 0 - steps; console.log("moving motor" + axisId, steps); $scope.axis[index].moving = true; if($scope.currentKf || $scope.axis[index].pos != 0) $scope.axis[index].pos -= steps; // will be overwritten by motor driver response sendMessage('motion', { key: 'move', val: steps, driver: driver, motor: motor }); } } $scope.atHomePosition = function() { for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected && $scope.axis[i].pos != 0) return false; } return true; } $scope.setHomePosition = function() { for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected && $scope.axis[i].pos != 0) $scope.zeroAxis($scope.axis[i].id); } } $scope.zeroAxis = function(axisName) { console.log("zeroing ", axisId); var index = $scope.getAxisIndex(axisId); if(index === null) return false; var parts = axisId.split('-'); if (steps && parts.length == 2) { var driver = parts[0]; var motor = parts[1]; $scope.axis[index].pos = 0; // will be overwritten by motor driver response sendMessage('motion', { key: 'zero', driver: driver, motor: motor }); } } var joystickTimers = {}; $scope.joystick = function(axisName, speed) { var index = null; var axisId = null; for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].name.toLowerCase() == axisName.toLowerCase()) { index = i; axisId = $scope.axis[index].id; break; } } if(index === null) return false; if(joystickTimers[axisName]) $timeout.cancel(joystickTimers[axisName]); // rate limit per axis joystickTimers[axisName] = $timeout(function(){ console.log("moving ", axisId); var parts = axisId.split('-'); if (parts.length == 2) { var driver = parts[0]; var motor = parts[1]; console.log("joystick motor" + axisId, speed); sendMessage('motion', { key: 'joystick', val: speed * 100, driver: driver, motor: motor }); } }, 200); } $scope.focusPos = 0; $scope.focus = function(dir, repeat, noUpdate) { if (!repeat) repeat = 1; if(!noUpdate) { if (dir > 0) $scope.focusPos += repeat; if (dir < 0) $scope.focusPos -= repeat; if($scope.currentKf) $scope.currentKf.focusEdited = true; } sendMessage('focus', { key: 'manual', val: dir, repeat: repeat }); console.log("focusPos:", $scope.focusPos); } function dbGet(key, callback) { sendMessage('dbGet', { key: key }, function(err, res){ callback && callback(err, res.val); console.log("dbGet result", res); }); } function dbSet(key, val, callback) { sendMessage('dbSet', { key: key, val: val }, function(err){ callback && callback(err); console.log("dbSet err", err); }); } $scope.testBulb = function() { sendMessage('test'); } var setEvTimerHandle = null; $scope.setEv = function(ev) { if (setEvTimerHandle) $timeout.cancel(setEvTimerHandle); $scope.evSetFromApp = ev; setEvTimerHandle = $timeout(function() { console.log("setting ev to ", ev); sendMessage('setEv', { ev: ev }); }, 300); } $scope.incEv = function() { if ($scope.camera.ev3 < $scope.camera.evMax3) { $scope.camera.ev3++; $scope.setEv($scope.camera.ev3 / 3); } } $scope.decEv = function() { if ($scope.camera.ev3 > $scope.camera.evMin3) { $scope.camera.ev3--; $scope.setEv($scope.camera.ev3 / 3); } } $scope.incSecondsRange = function(kf) { if ($scope.secondsRange.val < TIMING_SLIDER_RANGE) $scope.secondsRange.val++; $scope.updateSeconds(kf, $scope.secondsRange.val); } $scope.decSecondsRange = function(kf) { if ($scope.secondsRange.val > 0) $scope.secondsRange.val--; $scope.updateSeconds(kf, $scope.secondsRange.val); } $scope.updateSeconds = function(kf, val) { kf.seconds = MAX_KF_SECONDS * Math.pow((val / TIMING_SLIDER_RANGE), (1 / TIMING_CURVE)); $scope.secondsRange.val = val; } $scope.setState = function(state) { $scope.setup.state = state; } $scope.setupTimelapse = function(preset) { if (preset.selected) { $scope.timelapse.mode = preset.key; } //$scope.setState(1); } $scope.mode = 'exposure'; $scope.setMode = function(mode) { if (mode != 'focus' && $scope.focusMode) { $scope.zoom(); } $scope.mode = mode; } $scope.runProgram = function(program) { program.focusPos = $scope.focusPos; for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected) program['motor-' + $scope.axis[i].id + 'Pos'] = $scope.axis[i].pos; } //program.rampMode = 'auto'; //program.intervalMode = 'fixed'; sendMessage('run', { program: program }); } $scope.stopProgram = function() { sendMessage('stop'); } $ionicModal.fromTemplateUrl('templates/modal-exposure.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modalExposure = modal; }); $scope.currentKf = null; $scope.currentKfIndex = null; $scope.secondsRange = { val: 0 }; var MAX_KF_SECONDS = 3600 * 24; var TIMING_SLIDER_RANGE = 100; var TIMING_CURVE = 1 / 2.5; $scope.timingSliderMax = TIMING_SLIDER_RANGE; $scope.openExposure = function(kf, index) { $scope.currentKf = kf; if(!$scope.currentKf.focus) $scope.currentKf.focus = 0; $scope.currentKfIndex = index; $scope.currentKf.focusEdited = false; $scope.currentKf.motionEdited = false; if (kf) { $scope.secondsRange.val = TIMING_SLIDER_RANGE * Math.pow((kf.seconds / MAX_KF_SECONDS), TIMING_CURVE); $scope.ev3 = kf.ev * 3; //if (kf.ev != null) $scope.setEv(kf.ev); //if (kf.focus != null) { // var focusDiff = kf.focus - $scope.focusPos; // var dir = focusDiff < 0 ? -1 : 1; // var repeat = Math.abs(focusDiff); // if (repeat > 0) $scope.focus(dir, repeat); //} if(!kf.motor) kf.motor = {}; for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected) { var id = $scope.axis[i].id; if(!kf.motor[id]) kf.motor[id] = 0; var diff = kf.motor[id] - $scope.axis[i].pos; $scope.move(id, 0 - diff, true); } } } $scope.preview(true); $scope.modalExposure.show(); }; $scope.focusMoveToKeyframe = function(currentKf) { var focusDiff = $scope.focusCurrentDistance(currentKf); var dir = focusDiff < 0 ? -1 : 1; var repeat = Math.abs(focusDiff); if (repeat > 0) $scope.focus(dir, repeat); } $scope.focusCurrentDistance = function(currentKf) { return currentKf ? currentKf.focus - $scope.focusPos : 0; } $scope.focusResetKeyframe = function(currentKf) { currentKf.focus = $scope.focusPos; } $scope.closeExposure = function() { var delay = 0; if ($scope.focusMode) { $scope.zoom(); delay = 1000; } if($scope.currentKf.focusEdited || $scope.currentKf.motionEdited) { $timeout(function() { $scope.preview(false); if ($scope.currentKf) { $scope.currentKf.jpeg = $scope.lastImage ? $scope.lastImage.jpeg : null; } }, delay); } if ($scope.currentKfIndex == 0) { for (var i = 1; i < $scope.timelapse.keyframes.length; i++) { if($scope.currentKf.focusEdited) $scope.timelapse.keyframes[i].focus -= $scope.focusPos; if($scope.currentKf.motionEdited) { for(var j = 0; j < $scope.axis.length; j++) { if($scope.axis[j].connected) { var id = $scope.axis[j].id; if($scope.axis[j].moving) { (function(kfIndex, axisIndex){ $scope.axis[j].callback = function() { $scope.timelapse.keyframes[i].motor[id] -= $scope.axis[j].pos; } })(i, j); } else { $scope.timelapse.keyframes[i].motor[id] -= $scope.axis[j].pos; } } } } } if($scope.currentKf.focusEdited) $scope.focusPos = 0; if($scope.currentKf.motionEdited) { for(var i = 0; i < $scope.axis.length; i++) { var parts = $scope.axis[i].id.split('-'); if (parts.length == 2) { var driver = parts[0]; var motor = parts[1]; if($scope.axis[i].moving) { (function(d, m, index){ $scope.axis[index].callback = function(position) { sendMessage('motion', { key: 'zero', driver: d, motor: m }); }; })(driver, motor, i); } else { sendMessage('motion', { key: 'zero', driver: driver, motor: motor }); } //$scope.axis[i].pos = 0; } } } } if($scope.currentKf.focusEdited) $scope.currentKf.focus = $scope.focusPos; if($scope.currentKf.motionEdited) { for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected) { var id = $scope.axis[i].id; $scope.currentKf.motor[id] = $scope.axis[i].pos; } } } $scope.currentKf.ev = $scope.camera.ev; $scope.modalExposure.hide(); }; $scope.addKeyframe = function() { if (!$scope.timelapse.keyframes) $scope.timelapse.keyframes = [{motor:{}}]; var lastKf = $scope.timelapse.keyframes[$scope.timelapse.keyframes.length - 1]; var kf = { focus: lastKf.focus, seconds: 600 } for(var i = 0; i < $scope.axis.length; i++) { if($scope.axis[i].connected) { var id = $scope.axis[i].id; if(!kf.motor) kf.motor = {}; kf.motor[id] = lastKf.motor[id]; } } $scope.timelapse.keyframes.push(kf); } $scope.removeKeyframe = function(index) { $scope.timelapse.keyframes.splice(index, 1); } $ionicModal.fromTemplateUrl('templates/modal-motion-setup.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modalMotionSetup = modal; }); $scope.openMotionSetup = function(axisId) { var axisIndex = $scope.getAxisIndex(axisId); if(axisIndex === null) return; $scope.setupAxis = $scope.axis[axisIndex]; $scope.modalMotionSetup.show(); }; $scope.closeMotionSetup = function() { if($scope.setupAxis.name) $scope.setupAxis.setup = true; if($scope.setupAxis.unit == 's') $scope.setupAxis.unitSteps = 1; $scope.setupAxis.moveSteps = $scope.setupAxis.unitMove * $scope.setupAxis.unitSteps; //localStorageService.set('motion-' + $scope.setupAxis.id, $scope.setupAxis); dbSet('motion-' + $scope.setupAxis.id, $scope.setupAxis); var axisIndex = $scope.getAxisIndex($scope.setupAxis.id); $scope.axis[axisIndex] = $scope.setupAxis; $scope.modalMotionSetup.hide(); }; $scope.changeAxisType = function(type) { $scope.setupAxis.name = type; if(type == 'Pan' || type == 'Tilt') { $scope.setupAxis.unit = '°'; $scope.setupAxis.unitSteps = 560; $scope.setupAxis.unitMove = 5; } else { $scope.setupAxis.unit = 's'; $scope.setupAxis.unitSteps = 1; $scope.setupAxis.unitMove = 500; } } $scope.changeAxisUnit = function(unit) { $scope.setupAxis.unit = unit; } $scope.changeAxisUnitSteps = function(unitSteps) { $scope.setupAxis.unitSteps = unitSteps; } $scope.changeAxisUnitMove = function(unitMove) { $scope.setupAxis.unitMove = unitMove; } $scope.changeAxisReverse = function(reverse) { $scope.setupAxis.reverse = reverse; } function setupAxis(axisInfo) { var axisId = axisInfo.driver + '-' + axisInfo.motor; console.log("setting up axis: ", axisId); //var axis = localStorageService.get('motion-' + axisId); dbGet('motion-' + axisId, function(err, axis) { console.log("VIEW db err:", err); console.log("VIEW db axis:", axis); if(!axis) { axis = { name: '', unit: 's', unitSteps: 1, unitMove: 500, reverse: false, pos: 0, moving: false, setup: false } } axis.id = axisId; axis.motor = axisInfo.motor; axis.driver = axisInfo.driver; axis.connected = axisInfo.connected; axis.pos = axisInfo.position; var axisIndex = $scope.getAxisIndex(axisId); if(!$scope.axis) $scope.axis = []; if(axisIndex === null) { $scope.axis.push(axis); } else { //axis.pos = $scope.axis[axisIndex].pos; axis.moving = false;//$scope.axis[axisIndex].moving; $scope.axis[axisIndex] = axis; } console.log("$scope.axis", $scope.axis); }); } $ionicModal.fromTemplateUrl('templates/modal-login.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modalLogin = modal; }); $scope.openLogin = function() { if($scope.modalLogin) { $scope.loginState = "email"; $scope.loginBusy = false; $scope.modalLogin.show(); } else { $timeout($scope.openLogin, 1000); } }; $scope.closeLogin = function() { $scope.modalLogin.hide(); }; $scope.loginCheckEmail = function(email) { $scope.loginBusy = true; $http.post('/api/email', {email: email}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "login") { $scope.loginState = 'login-password' } if(res == "register") { $scope.loginState = 'register-subdomain' } if(res == "error") { $scope.loginState = 'noemail' } } $scope.loginBusy = false; }).error(function(err) { $scope.loginBusy = false; }); } $scope.loginCheckSubdomain = function(subdomain) { $scope.loginBusy = true; $http.post('/api/subdomain/check', {subdomain: subdomain}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "available") { $scope.loginState = 'register-password' } else { $scope.loginState = 'register-unavailable' } } $scope.loginBusy = false; }).error(function(err) { $scope.loginBusy = false; }); } $scope.loginRegister = function(email, subdomain, password) { $scope.loginBusy = true; $http.post('/api/register', {email: email, subdomain: subdomain, password:password}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "login") { $scope.closeLogin(); } else { $scope.loginState = 'register-unavailable' } } $scope.loginBusy = false; }).error(function(err) { $scope.loginBusy = false; }); } $scope.login = function(email, password) { $scope.loginBusy = true; $http.post('/api/login', {email: email, password:password}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "login") { $scope.sid = data.session; localStorageService.set('sid', $scope.sid); $scope.closeLogin(); connect(); } else { $scope.loginState = 'login-failed' } } $scope.loginBusy = false; }).error(function(err) { $scope.loginBusy = false; }); } $scope.addDevice = function(code) { $http.post('/api/device/new', {code: code}, {headers: {'x-view-session': $scope.sid}}).success(function(data) { console.log(data); if (data && data.action) { var res = data.action; if(res == "device_added") { $scope.popupMessage("Successfully added VIEW device to this account"); } else { $scope.popupMessage("Failed to add VIEW device. Please try again."); } } }).error(function(err) { $scope.popupMessage("Failed to add VIEW device. Please try again."); }); } $scope.saveToCard = function(clip) { sendMessage('xmp-to-card', { index: clip.index }); } $scope.showClipOptions = function(clip) { // Show the action sheet var hideSheet = $ionicActionSheet.show({ buttons: [{ text: 'Write XMP folder to SD card' }], destructiveText: 'Delete Clip', titleText: clip.name, cancelText: 'Cancel', cancel: function() { // add cancel code.. }, destructiveButtonClicked: function() { $scope.confirmDelete(clip); }, buttonClicked: function(index) { if (index === 0) { $scope.saveToCard(clip); } return true; } }); // For example's sake, hide the sheet after two seconds $timeout(function() { hideSheet(); }, 8000); }; $scope.setTimelapse = function(param, val) { $scope.timelapse[param] = val; console.log("Setting timelapse." + param + " = " + val); } $scope.toggleIntervalMode = function() { if ($scope.timelapse.intervalMode == 'fixed') $scope.timelapse.intervalMode = 'auto' else $scope.timelapse.intervalMode = 'fixed'; } $scope.passwd = ""; //Cleanup the modal when we're done with it! $scope.$on('$destroy', function() { $scope.modalLogin.remove(); $scope.modalExposure.remove(); }); //$scope.setupTimelapse($scope.presets[0]); }]) ;
adding option to set home pos
frontend/www/js/app.js
adding option to set home pos
<ide><path>rontend/www/js/app.js <ide> } <ide> } <ide> <del> $scope.zeroAxis = function(axisName) { <add> $scope.zeroAxis = function(axisId) { <ide> console.log("zeroing ", axisId); <ide> var index = $scope.getAxisIndex(axisId); <ide> if(index === null) return false;
Java
apache-2.0
54689caa9f2f83e40853e963d6c91369237b3ddc
0
john9x/jdbi,jdbi/jdbi,omidp/jdbi,stevenschlansker/jdbi,zanebenefits/jdbi,john9x/jdbi,christophercurrie/jdbi,fengshao0907/jdbi,hgschmie/jdbi,voidifremoved/jdbi,HubSpot/jdbi,11xor6/jdbi,voidifremoved/jdbi,fengshao0907/jdbi,pennello/jdbi,omidp/jdbi,jdbi/jdbi,11xor6/jdbi,zanebenefits/jdbi,stevenschlansker/jdbi,BernhardBln/jdbi,HubSpot/jdbi,kentyeh/jdbi,hgschmie/jdbi,BernhardBln/jdbi,hgschmie/jdbi,christophercurrie/jdbi,pennello/jdbi,jdbi/jdbi,kentyeh/jdbi
/* * Copyright 2004 - 2011 Brian McCallister * * 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.skife.jdbi.v2.unstable.eod; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public interface Transactional<SelfType extends Transactional<SelfType>> { public void begin(); public void commit(); public void rollback(); public void checkpoint(String name); public void release(String name); public void rollback(String name); public <ReturnType> ReturnType inTransaction(Transaction<ReturnType, SelfType> func); static class BeginHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.begin(); return null; } } static class CheckpointHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.checkpoint(String.valueOf(args[0])); return null; } } static class ReleaseCheckpointHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.release(String.valueOf(args[0])); return null; } } static class RollbackCheckpointHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.rollback(String.valueOf(args[0])); return null; } } static class CommitHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.commit(); return null; } } static class RollbackHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.rollback(); return null; } } static class InTransactionHandler implements Handler { public Object invoke(Handle h, final Object target, Object[] args) { final Transaction t = (Transaction) args[0]; return h.inTransaction(new TransactionCallback() { public Object inTransaction(Object conn, TransactionStatus status) throws Exception { return t.inTransaction(target, status); } }); } } static class Helper { static Map<Method, Handler> handlers() { try { Map<Method, Handler> h = new HashMap<Method, Handler>(); h.put(Transactional.class.getMethod("begin"), new BeginHandler()); h.put(Transactional.class.getMethod("commit"), new CommitHandler()); h.put(Transactional.class.getMethod("rollback"), new RollbackHandler()); h.put(Transactional.class.getMethod("checkpoint", String.class), new CheckpointHandler()); h.put(Transactional.class.getMethod("release", String.class), new ReleaseCheckpointHandler()); h.put(Transactional.class.getMethod("rollback", String.class), new RollbackCheckpointHandler()); h.put(Transactional.class.getMethod("inTransaction", Transaction.class), new InTransactionHandler()); return h; } catch (NoSuchMethodException e) { throw new IllegalStateException("someone wonkered up the bytecode", e); } } } }
src/main/java/org/skife/jdbi/v2/unstable/eod/Transactional.java
/* * Copyright 2004 - 2011 Brian McCallister * * 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.skife.jdbi.v2.unstable.eod; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public interface Transactional<SelfType extends Transactional> { public void begin(); public void commit(); public void rollback(); public void checkpoint(String name); public void release(String name); public void rollback(String name); public <ReturnType> ReturnType inTransaction(Transaction<ReturnType, SelfType> func); static class BeginHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.begin(); return null; } } static class CheckpointHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.checkpoint(String.valueOf(args[0])); return null; } } static class ReleaseCheckpointHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.release(String.valueOf(args[0])); return null; } } static class RollbackCheckpointHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.rollback(String.valueOf(args[0])); return null; } } static class CommitHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.commit(); return null; } } static class RollbackHandler implements Handler { public Object invoke(Handle h, Object target, Object[] args) { h.rollback(); return null; } } static class InTransactionHandler implements Handler { public Object invoke(Handle h, final Object target, Object[] args) { final Transaction t = (Transaction) args[0]; return h.inTransaction(new TransactionCallback() { public Object inTransaction(Object conn, TransactionStatus status) throws Exception { return t.inTransaction(target, status); } }); } } static class Helper { static Map<Method, Handler> handlers() { try { Map<Method, Handler> h = new HashMap<Method, Handler>(); h.put(Transactional.class.getMethod("begin"), new BeginHandler()); h.put(Transactional.class.getMethod("commit"), new CommitHandler()); h.put(Transactional.class.getMethod("rollback"), new RollbackHandler()); h.put(Transactional.class.getMethod("checkpoint", String.class), new CheckpointHandler()); h.put(Transactional.class.getMethod("release", String.class), new ReleaseCheckpointHandler()); h.put(Transactional.class.getMethod("rollback", String.class), new RollbackCheckpointHandler()); h.put(Transactional.class.getMethod("inTransaction", Transaction.class), new InTransactionHandler()); return h; } catch (NoSuchMethodException e) { throw new IllegalStateException("someone wonkered up the bytecode", e); } } } }
stronger self-type declaration
src/main/java/org/skife/jdbi/v2/unstable/eod/Transactional.java
stronger self-type declaration
<ide><path>rc/main/java/org/skife/jdbi/v2/unstable/eod/Transactional.java <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <del>public interface Transactional<SelfType extends Transactional> <add>public interface Transactional<SelfType extends Transactional<SelfType>> <ide> { <ide> public void begin(); <ide>
Java
apache-2.0
13b23379f5c9b1b59587aca02519d63a08b67df7
0
Blazebit/blaze-persistence,Blazebit/blaze-persistence,Blazebit/blaze-persistence,Blazebit/blaze-persistence
/* * Copyright 2014 Blazebit. * * 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.blazebit.persistence.view.impl; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import com.blazebit.persistence.impl.expression.ArrayExpression; import com.blazebit.persistence.impl.expression.CompositeExpression; import com.blazebit.persistence.impl.expression.Expression; import com.blazebit.persistence.impl.expression.FooExpression; import com.blazebit.persistence.impl.expression.FunctionExpression; import com.blazebit.persistence.impl.expression.GeneralCaseExpression; import com.blazebit.persistence.impl.expression.LiteralExpression; import com.blazebit.persistence.impl.expression.NullExpression; import com.blazebit.persistence.impl.expression.ParameterExpression; import com.blazebit.persistence.impl.expression.PathElementExpression; import com.blazebit.persistence.impl.expression.PathExpression; import com.blazebit.persistence.impl.expression.PropertyExpression; import com.blazebit.persistence.impl.expression.SimpleCaseExpression; import com.blazebit.persistence.impl.expression.SubqueryExpression; import com.blazebit.persistence.impl.expression.WhenClauseExpression; import com.blazebit.persistence.impl.predicate.AndPredicate; import com.blazebit.persistence.impl.predicate.BetweenPredicate; import com.blazebit.persistence.impl.predicate.EqPredicate; import com.blazebit.persistence.impl.predicate.ExistsPredicate; import com.blazebit.persistence.impl.predicate.GePredicate; import com.blazebit.persistence.impl.predicate.GtPredicate; import com.blazebit.persistence.impl.predicate.InPredicate; import com.blazebit.persistence.impl.predicate.IsEmptyPredicate; import com.blazebit.persistence.impl.predicate.IsNullPredicate; import com.blazebit.persistence.impl.predicate.LePredicate; import com.blazebit.persistence.impl.predicate.LikePredicate; import com.blazebit.persistence.impl.predicate.LtPredicate; import com.blazebit.persistence.impl.predicate.MemberOfPredicate; import com.blazebit.persistence.impl.predicate.NotPredicate; import com.blazebit.persistence.impl.predicate.OrPredicate; import com.blazebit.reflection.ReflectionUtils; /** * * @author Christian Beikov * @since 1.0 */ public class TargetResolvingExpressionVisitor implements Expression.Visitor { private PathPosition currentPosition; private List<PathPosition> pathPositions; private static class PathPosition { private Class<?> currentClass; private Class<?> valueClass; private Method method; PathPosition(Class<?> currentClass, Method method) { this.currentClass = currentClass; this.method = method; } Class<?> getRealCurrentClass() { return currentClass; } Class<?> getCurrentClass() { if (valueClass != null) { return valueClass; } return currentClass; } void setCurrentClass(Class<?> currentClass) { this.currentClass = currentClass; this.valueClass = null; } Method getMethod() { return method; } void setMethod(Method method) { this.method = method; } void setValueClass(Class<?> valueClass) { this.valueClass = valueClass; } } public TargetResolvingExpressionVisitor(Class<?> startClass) { this.pathPositions = new ArrayList<PathPosition>(); this.pathPositions.add(currentPosition = new PathPosition(startClass, null)); } private Method resolve(Class<?> currentClass, String property) { return ReflectionUtils.getGetter(currentClass, property); } private Class<?> getType(Class<?> baseClass, Method element) { return ReflectionUtils.getResolvedMethodReturnType(baseClass, element); } public Map<Method, Class<?>> getPossibleTargets() { Map<Method, Class<?>> possibleTargets = new HashMap<Method, Class<?>>(); for (PathPosition position : pathPositions) { possibleTargets.put(position.getMethod(), position.getRealCurrentClass()); } return possibleTargets; } @Override public void visit(PropertyExpression expression) { currentPosition.setMethod(resolve(currentPosition.getCurrentClass(), expression.getProperty())); if (currentPosition.getMethod() == null) { currentPosition.setCurrentClass(null); } else { Class<?> type = getType(currentPosition.getCurrentClass(), currentPosition.getMethod()); Class<?> valueType = null; if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) { Class<?>[] typeArguments = ReflectionUtils.getResolvedMethodReturnTypeArguments(currentPosition.getCurrentClass(), currentPosition.getMethod()); valueType = typeArguments[typeArguments.length - 1]; } else { valueType = type; } currentPosition.setCurrentClass(type); currentPosition.setValueClass(valueType); } } @Override public void visit(GeneralCaseExpression expression) { List<PathPosition> currentPositions = pathPositions; List<PathPosition> newPositions = new ArrayList<PathPosition>(); for (PathPosition position : currentPositions) { for (WhenClauseExpression whenClause : expression.getWhenClauses()) { pathPositions = new ArrayList<PathPosition>(); pathPositions.add(currentPosition = position); whenClause.accept(this); newPositions.addAll(pathPositions); } pathPositions = new ArrayList<PathPosition>(); pathPositions.add(currentPosition = position); expression.getDefaultExpr().accept(this); newPositions.addAll(pathPositions); } currentPosition = null; pathPositions = newPositions; } @Override public void visit(PathExpression expression) { for (PathElementExpression pathElementExpression : expression.getExpressions()) { pathElementExpression.accept(this); } } @Override public void visit(ArrayExpression expression) { // Only need the base to navigate down the path expression.getBase().accept(this); } @Override public void visit(ParameterExpression expression) { invalid(expression); } @Override public void visit(CompositeExpression expression) { invalid(expression); } @Override public void visit(LiteralExpression expression) { invalid(expression); } @Override public void visit(NullExpression expression) { invalid(expression); } @Override public void visit(FooExpression expression) { invalid(expression); } @Override public void visit(SubqueryExpression expression) { invalid(expression); } @Override public void visit(FunctionExpression expression) { String name = expression.getFunctionName(); if ("KEY".equalsIgnoreCase(name)) { PropertyExpression property = resolveBase(expression); currentPosition.setMethod(resolve(currentPosition.getCurrentClass(), property.getProperty())); Class<?> type = ReflectionUtils.getResolvedMethodReturnType(currentPosition.getCurrentClass(), currentPosition.getMethod()); Class<?>[] typeArguments = ReflectionUtils.getResolvedMethodReturnTypeArguments(currentPosition.getCurrentClass(), currentPosition.getMethod()); if (!Map.class.isAssignableFrom(type)) { invalid(expression, "Does not resolve to java.util.Map!"); } else { currentPosition.setCurrentClass(type); currentPosition.setValueClass(typeArguments[0]); } } else if ("INDEX".equalsIgnoreCase(name)) { PropertyExpression property = resolveBase(expression); currentPosition.setMethod(resolve(currentPosition.getCurrentClass(), property.getProperty())); Class<?> type = ReflectionUtils.getResolvedMethodReturnType(currentPosition.getCurrentClass(), currentPosition.getMethod()); if (!List.class.isAssignableFrom(type)) { invalid(expression, "Does not resolve to java.util.List!"); } else { currentPosition.setCurrentClass(type); currentPosition.setValueClass(Integer.class); } } else if ("VALUE".equalsIgnoreCase(name)) { PropertyExpression property = resolveBase(expression); currentPosition.setMethod(resolve(currentPosition.getCurrentClass(), property.getProperty())); Class<?> type = ReflectionUtils.getResolvedMethodReturnType(currentPosition.getCurrentClass(), currentPosition.getMethod()); Class<?>[] typeArguments = ReflectionUtils.getResolvedMethodReturnTypeArguments(currentPosition.getCurrentClass(), currentPosition.getMethod()); if (!Map.class.isAssignableFrom(type)) { invalid(expression, "Does not resolve to java.util.Map!"); } else { currentPosition.setCurrentClass(type); currentPosition.setValueClass(typeArguments[1]); } } else { invalid(expression); } } private PropertyExpression resolveBase(FunctionExpression expression) { // According to our grammar, we can only get a path here PathExpression path = (PathExpression) expression.getExpressions().get(0); int lastIndex = path.getExpressions().size() - 1; for (int i = 0; i < lastIndex; i++) { path.getExpressions().get(i).accept(this); } // According to our grammar, the last element must be a property return (PropertyExpression) path.getExpressions().get(lastIndex); } @Override public void visit(SimpleCaseExpression expression) { visit((GeneralCaseExpression) expression); } @Override public void visit(WhenClauseExpression expression) { expression.getResult().accept(this); } @Override public void visit(AndPredicate predicate) { invalid(predicate); } @Override public void visit(OrPredicate predicate) { invalid(predicate); } @Override public void visit(NotPredicate predicate) { invalid(predicate); } @Override public void visit(EqPredicate predicate) { invalid(predicate); } @Override public void visit(IsNullPredicate predicate) { invalid(predicate); } @Override public void visit(IsEmptyPredicate predicate) { invalid(predicate); } @Override public void visit(MemberOfPredicate predicate) { invalid(predicate); } @Override public void visit(LikePredicate predicate) { invalid(predicate); } @Override public void visit(BetweenPredicate predicate) { invalid(predicate); } @Override public void visit(InPredicate predicate) { invalid(predicate); } @Override public void visit(GtPredicate predicate) { invalid(predicate); } @Override public void visit(GePredicate predicate) { invalid(predicate); } @Override public void visit(LtPredicate predicate) { invalid(predicate); } @Override public void visit(LePredicate predicate) { invalid(predicate); } @Override public void visit(ExistsPredicate predicate) { invalid(predicate); } private void invalid(Object o) { throw new IllegalArgumentException("Illegal occurence of [" + o + "] in path chain resolver!"); } private void invalid(Object o, String reason) { throw new IllegalArgumentException("Illegal occurence of [" + o + "] in path chain resolver! " + reason); } }
entity-view/impl/src/main/java/com/blazebit/persistence/view/impl/TargetResolvingExpressionVisitor.java
/* * Copyright 2014 Blazebit. * * 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.blazebit.persistence.view.impl; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.blazebit.persistence.impl.expression.ArrayExpression; import com.blazebit.persistence.impl.expression.CompositeExpression; import com.blazebit.persistence.impl.expression.Expression; import com.blazebit.persistence.impl.expression.FooExpression; import com.blazebit.persistence.impl.expression.FunctionExpression; import com.blazebit.persistence.impl.expression.GeneralCaseExpression; import com.blazebit.persistence.impl.expression.LiteralExpression; import com.blazebit.persistence.impl.expression.NullExpression; import com.blazebit.persistence.impl.expression.ParameterExpression; import com.blazebit.persistence.impl.expression.PathElementExpression; import com.blazebit.persistence.impl.expression.PathExpression; import com.blazebit.persistence.impl.expression.PropertyExpression; import com.blazebit.persistence.impl.expression.SimpleCaseExpression; import com.blazebit.persistence.impl.expression.SubqueryExpression; import com.blazebit.persistence.impl.expression.WhenClauseExpression; import com.blazebit.persistence.impl.predicate.AndPredicate; import com.blazebit.persistence.impl.predicate.BetweenPredicate; import com.blazebit.persistence.impl.predicate.EqPredicate; import com.blazebit.persistence.impl.predicate.ExistsPredicate; import com.blazebit.persistence.impl.predicate.GePredicate; import com.blazebit.persistence.impl.predicate.GtPredicate; import com.blazebit.persistence.impl.predicate.InPredicate; import com.blazebit.persistence.impl.predicate.IsEmptyPredicate; import com.blazebit.persistence.impl.predicate.IsNullPredicate; import com.blazebit.persistence.impl.predicate.LePredicate; import com.blazebit.persistence.impl.predicate.LikePredicate; import com.blazebit.persistence.impl.predicate.LtPredicate; import com.blazebit.persistence.impl.predicate.MemberOfPredicate; import com.blazebit.persistence.impl.predicate.NotPredicate; import com.blazebit.persistence.impl.predicate.OrPredicate; import com.blazebit.reflection.ReflectionUtils; /** * * @author Christian Beikov * @since 1.0 */ public class TargetResolvingExpressionVisitor implements Expression.Visitor { private PathPosition currentPosition; private List<PathPosition> pathPositions; private static class PathPosition { Class<?> currentClass; Method method; PathPosition(Class<?> currentClass, Method method) { this.currentClass = currentClass; this.method = method; } } public TargetResolvingExpressionVisitor(Class<?> startClass) { this.pathPositions = new ArrayList<PathPosition>(); this.pathPositions.add(currentPosition = new PathPosition(startClass, null)); } private Method resolve(Class<?> currentClass, String property) { return ReflectionUtils.getGetter(currentClass, property); } private Class<?> getType(Class<?> baseClass, Method element) { return ReflectionUtils.getResolvedMethodReturnType(baseClass, element); } public Map<Method, Class<?>> getPossibleTargets() { Map<Method, Class<?>> possibleTargets = new HashMap<Method, Class<?>>(); for (PathPosition position : pathPositions) { possibleTargets.put(position.method, position.currentClass); } return possibleTargets; } @Override public void visit(PropertyExpression expression) { currentPosition.method = resolve(currentPosition.currentClass, expression.getProperty()); if (currentPosition.method == null) { currentPosition.currentClass = null; } else { currentPosition.currentClass = getType(currentPosition.currentClass, currentPosition.method); } } @Override public void visit(GeneralCaseExpression expression) { List<PathPosition> currentPositions = pathPositions; List<PathPosition> newPositions = new ArrayList<PathPosition>(); for (PathPosition position : currentPositions) { for (WhenClauseExpression whenClause : expression.getWhenClauses()) { pathPositions = new ArrayList<PathPosition>(); pathPositions.add(currentPosition = position); whenClause.accept(this); newPositions.addAll(pathPositions); } pathPositions = new ArrayList<PathPosition>(); pathPositions.add(currentPosition = position); expression.getDefaultExpr().accept(this); newPositions.addAll(pathPositions); } currentPosition = null; pathPositions = newPositions; } @Override public void visit(PathExpression expression) { for (PathElementExpression pathElementExpression : expression.getExpressions()) { pathElementExpression.accept(this); } } @Override public void visit(ArrayExpression expression) { // Only need the base to navigate down the path expression.getBase().accept(this); } @Override public void visit(ParameterExpression expression) { invalid(expression); } @Override public void visit(CompositeExpression expression) { invalid(expression); } @Override public void visit(LiteralExpression expression) { invalid(expression); } @Override public void visit(NullExpression expression) { invalid(expression); } @Override public void visit(FooExpression expression) { invalid(expression); } @Override public void visit(SubqueryExpression expression) { invalid(expression); } @Override public void visit(FunctionExpression expression) { invalid(expression); } @Override public void visit(SimpleCaseExpression expression) { visit((GeneralCaseExpression) expression); } @Override public void visit(WhenClauseExpression expression) { expression.getResult().accept(this); } @Override public void visit(AndPredicate predicate) { invalid(predicate); } @Override public void visit(OrPredicate predicate) { invalid(predicate); } @Override public void visit(NotPredicate predicate) { invalid(predicate); } @Override public void visit(EqPredicate predicate) { invalid(predicate); } @Override public void visit(IsNullPredicate predicate) { invalid(predicate); } @Override public void visit(IsEmptyPredicate predicate) { invalid(predicate); } @Override public void visit(MemberOfPredicate predicate) { invalid(predicate); } @Override public void visit(LikePredicate predicate) { invalid(predicate); } @Override public void visit(BetweenPredicate predicate) { invalid(predicate); } @Override public void visit(InPredicate predicate) { invalid(predicate); } @Override public void visit(GtPredicate predicate) { invalid(predicate); } @Override public void visit(GePredicate predicate) { invalid(predicate); } @Override public void visit(LtPredicate predicate) { invalid(predicate); } @Override public void visit(LePredicate predicate) { invalid(predicate); } @Override public void visit(ExistsPredicate predicate) { invalid(predicate); } private void invalid(Object o) { throw new IllegalArgumentException("Illegal occurenc of [" + o + "] in path chain resolver!"); } }
Fix #149 and #150
entity-view/impl/src/main/java/com/blazebit/persistence/view/impl/TargetResolvingExpressionVisitor.java
Fix #149 and #150
<ide><path>ntity-view/impl/src/main/java/com/blazebit/persistence/view/impl/TargetResolvingExpressionVisitor.java <ide> <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <add>import java.util.Collection; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> private static class PathPosition { <ide> <del> Class<?> currentClass; <del> Method method; <add> private Class<?> currentClass; <add> private Class<?> valueClass; <add> private Method method; <ide> <ide> PathPosition(Class<?> currentClass, Method method) { <ide> this.currentClass = currentClass; <ide> this.method = method; <ide> } <add> <add> Class<?> getRealCurrentClass() { <add> return currentClass; <add> } <add> <add> Class<?> getCurrentClass() { <add> if (valueClass != null) { <add> return valueClass; <add> } <add> <add> return currentClass; <add> } <add> <add> void setCurrentClass(Class<?> currentClass) { <add> this.currentClass = currentClass; <add> this.valueClass = null; <add> } <add> <add> Method getMethod() { <add> return method; <add> } <add> <add> void setMethod(Method method) { <add> this.method = method; <add> } <add> <add> void setValueClass(Class<?> valueClass) { <add> this.valueClass = valueClass; <add> } <ide> } <ide> <ide> public TargetResolvingExpressionVisitor(Class<?> startClass) { <ide> Map<Method, Class<?>> possibleTargets = new HashMap<Method, Class<?>>(); <ide> <ide> for (PathPosition position : pathPositions) { <del> possibleTargets.put(position.method, position.currentClass); <add> possibleTargets.put(position.getMethod(), position.getRealCurrentClass()); <ide> } <ide> <ide> return possibleTargets; <ide> <ide> @Override <ide> public void visit(PropertyExpression expression) { <del> currentPosition.method = resolve(currentPosition.currentClass, expression.getProperty()); <del> if (currentPosition.method == null) { <del> currentPosition.currentClass = null; <add> currentPosition.setMethod(resolve(currentPosition.getCurrentClass(), expression.getProperty())); <add> if (currentPosition.getMethod() == null) { <add> currentPosition.setCurrentClass(null); <ide> } else { <del> currentPosition.currentClass = getType(currentPosition.currentClass, currentPosition.method); <add> Class<?> type = getType(currentPosition.getCurrentClass(), currentPosition.getMethod()); <add> Class<?> valueType = null; <add> <add> if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) { <add> Class<?>[] typeArguments = ReflectionUtils.getResolvedMethodReturnTypeArguments(currentPosition.getCurrentClass(), currentPosition.getMethod()); <add> valueType = typeArguments[typeArguments.length - 1]; <add> } else { <add> valueType = type; <add> } <add> <add> currentPosition.setCurrentClass(type); <add> currentPosition.setValueClass(valueType); <ide> } <ide> } <ide> <ide> <ide> @Override <ide> public void visit(FunctionExpression expression) { <del> invalid(expression); <add> String name = expression.getFunctionName(); <add> if ("KEY".equalsIgnoreCase(name)) { <add> PropertyExpression property = resolveBase(expression); <add> currentPosition.setMethod(resolve(currentPosition.getCurrentClass(), property.getProperty())); <add> Class<?> type = ReflectionUtils.getResolvedMethodReturnType(currentPosition.getCurrentClass(), currentPosition.getMethod()); <add> Class<?>[] typeArguments = ReflectionUtils.getResolvedMethodReturnTypeArguments(currentPosition.getCurrentClass(), currentPosition.getMethod()); <add> <add> if (!Map.class.isAssignableFrom(type)) { <add> invalid(expression, "Does not resolve to java.util.Map!"); <add> } else { <add> currentPosition.setCurrentClass(type); <add> currentPosition.setValueClass(typeArguments[0]); <add> } <add> } else if ("INDEX".equalsIgnoreCase(name)) { <add> PropertyExpression property = resolveBase(expression); <add> currentPosition.setMethod(resolve(currentPosition.getCurrentClass(), property.getProperty())); <add> Class<?> type = ReflectionUtils.getResolvedMethodReturnType(currentPosition.getCurrentClass(), currentPosition.getMethod()); <add> <add> if (!List.class.isAssignableFrom(type)) { <add> invalid(expression, "Does not resolve to java.util.List!"); <add> } else { <add> currentPosition.setCurrentClass(type); <add> currentPosition.setValueClass(Integer.class); <add> } <add> } else if ("VALUE".equalsIgnoreCase(name)) { <add> PropertyExpression property = resolveBase(expression); <add> currentPosition.setMethod(resolve(currentPosition.getCurrentClass(), property.getProperty())); <add> Class<?> type = ReflectionUtils.getResolvedMethodReturnType(currentPosition.getCurrentClass(), currentPosition.getMethod()); <add> Class<?>[] typeArguments = ReflectionUtils.getResolvedMethodReturnTypeArguments(currentPosition.getCurrentClass(), currentPosition.getMethod()); <add> <add> if (!Map.class.isAssignableFrom(type)) { <add> invalid(expression, "Does not resolve to java.util.Map!"); <add> } else { <add> currentPosition.setCurrentClass(type); <add> currentPosition.setValueClass(typeArguments[1]); <add> } <add> } else { <add> invalid(expression); <add> } <add> } <add> <add> private PropertyExpression resolveBase(FunctionExpression expression) { <add> // According to our grammar, we can only get a path here <add> PathExpression path = (PathExpression) expression.getExpressions().get(0); <add> int lastIndex = path.getExpressions().size() - 1; <add> <add> for (int i = 0; i < lastIndex; i++) { <add> path.getExpressions().get(i).accept(this); <add> } <add> <add> // According to our grammar, the last element must be a property <add> return (PropertyExpression) path.getExpressions().get(lastIndex); <ide> } <ide> <ide> @Override <ide> } <ide> <ide> private void invalid(Object o) { <del> throw new IllegalArgumentException("Illegal occurenc of [" + o + "] in path chain resolver!"); <add> throw new IllegalArgumentException("Illegal occurence of [" + o + "] in path chain resolver!"); <add> } <add> <add> private void invalid(Object o, String reason) { <add> throw new IllegalArgumentException("Illegal occurence of [" + o + "] in path chain resolver! " + reason); <ide> } <ide> <ide> }
Java
mit
8e5e5c08503ea56d074df8d4d10aac8d7b3c8c76
0
martindisch/Networking
package com.martin.dchat; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class ClientManager implements Runnable { Socket clSocket; public ClientManager(Socket clSocket) { super(); this.clSocket = clSocket; } @Override public void run() { try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clSocket.getOutputStream(), "UTF-8")); BufferedReader in = new BufferedReader(new InputStreamReader(clSocket.getInputStream(), "UTF-8")); out.write("Hi, I'm your handler. You can start typing, when you're done type 'END'."); out.newLine(); out.flush(); String msg; while ((msg = in.readLine()) != null) { if (msg.contentEquals("END")) { break; } out.write(msg); out.newLine(); out.flush(); } out.close(); in.close(); clSocket.close(); } catch (IOException e) { System.err.println(e); e.printStackTrace(); } } }
src/com/martin/dchat/ClientManager.java
package com.martin.dchat; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class ClientManager implements Runnable { Socket clSocket; public ClientManager(Socket clSocket) { super(); this.clSocket = clSocket; } @Override public void run() { try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clSocket.getOutputStream(), "UTF-8")); BufferedReader in = new BufferedReader(new InputStreamReader(clSocket.getInputStream(), "UTF-8")); out.write("Hi, I'm your handler. You can start typing, when you're done type 'END'."); out.newLine(); out.flush(); String msg; //while ((msg = in.readLine()) != null) { while (!(msg = in.readLine()).contentEquals("END")) { out.write(msg); out.newLine(); out.flush(); } out.close(); in.close(); clSocket.close(); } catch (IOException e) { System.err.println(e); e.printStackTrace(); } } }
The reading inside ClientManager is the way to go.
src/com/martin/dchat/ClientManager.java
The reading inside ClientManager is the way to go.
<ide><path>rc/com/martin/dchat/ClientManager.java <ide> out.flush(); <ide> <ide> String msg; <del> //while ((msg = in.readLine()) != null) { <del> while (!(msg = in.readLine()).contentEquals("END")) { <add> while ((msg = in.readLine()) != null) { <add> if (msg.contentEquals("END")) { <add> break; <add> } <ide> out.write(msg); <ide> out.newLine(); <ide> out.flush();
Java
epl-1.0
585bcb6e121cce9214644ad1ef944dcca661b665
0
Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1
/******************************************************************************* * Copyright (c) 2008,2009 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.emitter.wpml.writer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.birt.report.engine.content.IAutoTextContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.css.engine.StyleConstants; import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants; import org.eclipse.birt.report.engine.emitter.XMLWriter; import org.eclipse.birt.report.engine.emitter.wpml.AbstractEmitterImpl.TextFlag; import org.eclipse.birt.report.engine.emitter.wpml.DiagonalLineInfo; import org.eclipse.birt.report.engine.emitter.wpml.DiagonalLineInfo.Line; import org.eclipse.birt.report.engine.emitter.wpml.HyperlinkInfo; import org.eclipse.birt.report.engine.emitter.wpml.SpanInfo; import org.eclipse.birt.report.engine.emitter.wpml.WordUtil; import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil; import org.w3c.dom.css.CSSValue; public abstract class AbstractWordXmlWriter { protected XMLWriter writer; protected final String RIGHT = "right"; protected final String LEFT = "left"; protected final String TOP = "top"; protected final String BOTTOM = "bottom"; protected int imageId = 75; protected int bookmarkId = 0; private int lineId = 0; // Holds the global layout orientation. protected boolean rtl = false; protected abstract void writeTableLayout( ); protected abstract void writeFontSize( IStyle style ); protected abstract void writeFont( String fontFamily ); protected abstract void writeFontStyle( IStyle style ); protected abstract void writeFontWeight(IStyle style); protected abstract void openHyperlink( HyperlinkInfo info ); protected abstract void closeHyperlink( HyperlinkInfo info ); protected abstract void writeVmerge( SpanInfo spanInfo ); protected abstract void writeIndent( int indent ); public void startSectionInParagraph( ) { writer.openTag( "w:p" ); writer.openTag( "w:pPr" ); startSection( ); } public void endSectionInParagraph( ) { endSection( ); writer.closeTag( "w:pPr" ); writer.closeTag( "w:p" ); } public void startSection( ) { writer.openTag( "w:sectPr" ); } public void endSection( ) { writer.closeTag( "w:sectPr" ); } protected void drawImageShapeType( int imageId ) { writer.openTag( "v:shapetype" ); writer.attribute( "id", "_x0000_t" + imageId ); writer.attribute( "coordsize", "21600,21600" ); writer.attribute( "o:spt", "75" ); writer.attribute( "o:preferrelative", "t" ); writer.attribute( "path", "m@4@5l@4@11@9@11@9@5xe" ); writer.attribute( "filled", "f" ); writer.attribute( "stroked", "f" ); writer.openTag( "v:stroke" ); writer.attribute( "imagealignshape", "false" ); writer.attribute( "joinstyle", "miter" ); writer.closeTag( "v:stroke" ); writer.openTag( "v:formulas" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "if lineDrawn pixelLineWidth 0" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum @0 1 0" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum 0 0 @1" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @2 1 2" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @3 21600 pixelWidth" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @3 21600 pixelHeight" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum @0 0 1" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @6 1 2" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @7 21600 pixelWidth" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum @8 21600 0 " ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @7 21600 pixelHeight" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum @10 21600 0" ); writer.closeTag( "v:f" ); writer.closeTag( "v:formulas" ); writer.openTag( "v:path" ); writer.attribute( "o:extrusionok", "f" ); writer.attribute( "gradientshapeok", "t" ); writer.attribute( "o:connecttype", "rect" ); writer.closeTag( "v:path" ); writer.openTag( "o:lock" ); writer.attribute( "v:ext", "edit" ); writer.attribute( "aspectratio", "t" ); writer.closeTag( "o:lock" ); writer.closeTag( "v:shapetype" ); } protected void drawImageBordersStyle( IStyle style ) { drawImageBorderStyle( BOTTOM, style.getBorderBottomStyle( ), style .getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ) ); drawImageBorderStyle( TOP, style.getBorderTopStyle( ), style .getProperty( StyleConstants.STYLE_BORDER_TOP_WIDTH ) ); drawImageBorderStyle( LEFT, style.getBorderLeftStyle( ), style .getProperty( StyleConstants.STYLE_BORDER_LEFT_WIDTH ) ); drawImageBorderStyle( RIGHT, style.getBorderRightStyle( ), style .getProperty( StyleConstants.STYLE_BORDER_RIGHT_WIDTH ) ); } private void drawImageBorderStyle( String pos, String style, CSSValue width ) { String direct = "w10:border" + pos; writer.openTag( direct ); writer.attribute( "type", WordUtil.parseImageBorderStyle( style ) ); writer.attribute( "width", WordUtil.parseBorderSize( PropertyUtil .getDimensionValue( width ) ) ); writer.closeTag( direct ); } protected void drawImageBordersColor( IStyle style ) { drawImageBorderColor( BOTTOM, style.getBorderBottomColor( ) ); drawImageBorderColor( TOP, style.getBorderTopColor( ) ); drawImageBorderColor( LEFT, style.getBorderLeftColor( ) ); drawImageBorderColor( RIGHT, style.getBorderRightColor( ) ); } private void drawImageBorderColor( String pos, String color ) { String borderColor = "#" + WordUtil.parseColor( color ); String direct = "o:border" + pos + "color"; writer.attribute( direct, borderColor ); } public void writePageProperties( int pageHeight, int pageWidth, int headerHeight, int footerHeight, int topMargin, int bottomMargin, int leftMargin, int rightMargin, String orient ) { writer.openTag( "w:pgSz" ); writer.attribute( "w:w", pageWidth ); writer.attribute( "w:h", pageHeight ); writer.attribute( "w:orient", orient ); writer.closeTag( "w:pgSz" ); writer.openTag( "w:pgMar" ); writer.attribute( "w:top", topMargin ); writer.attribute( "w:bottom", bottomMargin ); writer.attribute( "w:left", leftMargin ); writer.attribute( "w:right", rightMargin ); writer.attribute( "w:header", topMargin ); writer.attribute( "w:footer", bottomMargin ); writer.closeTag( "w:pgMar" ); } // write the table properties to the output stream public void startTable( IStyle style, int tablewidth ) { startTable( style, tablewidth, false ); } // write the table properties to the output stream public void startTable( IStyle style, int tablewidth, boolean inForeign ) { writer.openTag( "w:tbl" ); writer.openTag( "w:tblPr" ); writeTableIndent( ); writeAttrTag( "w:tblStyle", "TableGrid" ); writeAttrTag( "w:tblOverlap", "Never" ); writeBidiTable( ); writeTableWidth( tablewidth ); writeAttrTag( "w:tblLook", "01E0" ); writeTableLayout( ); writeTableBorders( style ); writeBackgroundColor( style.getBackgroundColor( ) ); //"justify" is not an option for table alignment in word if ( "justify".equalsIgnoreCase( style.getTextAlign( ) ) ) { writeAlign( "left", style.getDirection( ) ); } else { writeAlign( style.getTextAlign( ), style.getDirection( ) ); } if (inForeign) { writer.openTag( "w:tblCellMar" ); writer.openTag( "w:top" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:top" ); writer.openTag( "w:left" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:left" ); writer.openTag( "w:bottom" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:bottom" ); writer.openTag( "w:right" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:right" ); writer.closeTag( "w:tblCellMar" ); } writer.closeTag( "w:tblPr" ); } private void writeTableBorders( IStyle style ) { writer.openTag( "w:tblBorders" ); writeBorders( style, 0, 0, 0, 0 ); writer.closeTag( "w:tblBorders" ); } public void endTable( ) { writer.closeTag( "w:tbl" ); } private void writeTableWidth( int tablewidth ) { writer.openTag( "w:tblW" ); writer.attribute( "w:w", tablewidth ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:tblW" ); } private void writeTableIndent( ) { writer.openTag( "w:tblInd" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:tblInd" ); } protected void writeBorders( IStyle style, int bottomMargin, int topMargin, int leftMargin, int rightMargin ) { String borderStyle = style.getBorderBottomStyle( ); if ( hasBorder( borderStyle ) ) { writeSingleBorder( BOTTOM, borderStyle, style .getBorderBottomColor( ), style .getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ), bottomMargin ); } borderStyle = style.getBorderTopStyle( ); if ( hasBorder( borderStyle ) ) { writeSingleBorder( TOP, borderStyle, style.getBorderTopColor( ), style.getProperty( StyleConstants.STYLE_BORDER_TOP_WIDTH ), topMargin ); } borderStyle = style.getBorderLeftStyle( ); if ( hasBorder( borderStyle ) ) { writeSingleBorder( LEFT, borderStyle, style.getBorderLeftColor( ), style.getProperty( StyleConstants.STYLE_BORDER_LEFT_WIDTH ), leftMargin ); } borderStyle = style.getBorderRightStyle( ); if ( hasBorder( borderStyle ) ) { writeSingleBorder( RIGHT, borderStyle, style.getBorderRightColor( ), style.getProperty( StyleConstants.STYLE_BORDER_RIGHT_WIDTH ), rightMargin ); } } private void writeSingleBorder( String type, String borderStyle, String color, CSSValue width, int margin ) { writer.openTag( "w:" + type ); writeBorderProperty( borderStyle, color, width, margin ); writer.closeTag( "w:" + type ); } private void writeBorderProperty( String style, String color, CSSValue width, int margin ) { writer.attribute( "w:val", WordUtil.parseBorderStyle( style ) ); writer.attribute( "w:sz", WordUtil.parseBorderSize( PropertyUtil .getDimensionValue( width ) ) ); writer.attribute( "w:space", validateBorderSpace( margin ) ); writer.attribute( "w:color", WordUtil.parseColor( color ) ); } private int validateBorderSpace( int margin ) { // word only accept 0-31 pt int space = (int) WordUtil.twipToPt( margin ); if ( space > 31 ) space = 31; return space; } protected void writeAlign( String align, String direction ) { if ( null == align ) { return; } String textAlign = align; if ( "justify".equalsIgnoreCase( align ) ) { textAlign = "both"; } // Need to swap 'left' and 'right' when orientation is RTL. if ( CSSConstants.CSS_RTL_VALUE.equalsIgnoreCase( direction ) ) { if ( IStyle.CSS_RIGHT_VALUE.equals( textAlign ) ) writeAttrTag( "w:jc", IStyle.CSS_LEFT_VALUE ); else if ( IStyle.CSS_LEFT_VALUE.equals( textAlign ) ) writeAttrTag( "w:jc", IStyle.CSS_RIGHT_VALUE ); else writeAttrTag( "w:jc", textAlign ); } else writeAttrTag( "w:jc", textAlign ); } protected void writeBackgroundColor( String color ) { String cssColor = WordUtil.parseColor( color ); if ( cssColor == null ) { return; } writer.openTag( "w:shd" ); writer.attribute( "w:val", "clear" ); writer.attribute( "w:color", "auto" ); writer.attribute( "w:fill", cssColor ); writer.closeTag( "w:shd" ); } /** * @param direction * * @author bidi_hcg */ private void writeBidiTable( ) { if ( this.rtl ) { writer.openTag( "w:bidiVisual" ); writer.closeTag( "w:bidiVisual" ); } } protected void writeRunBorders( IStyle style ) { String borderStyle = style.getBorderTopStyle( ); if ( hasBorder( borderStyle ) ) { writeRunBorder( borderStyle, style.getBorderTopColor( ), style .getProperty( StyleConstants.STYLE_BORDER_TOP_WIDTH ) ); return; } borderStyle = style.getBorderBottomStyle( ); if ( hasBorder( borderStyle ) ) { writeRunBorder( borderStyle, style.getBorderBottomColor( ), style .getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ) ); return; } borderStyle = style.getBorderLeftStyle( ); if ( hasBorder( borderStyle ) ) { writeRunBorder( borderStyle, style.getBorderLeftColor( ), style .getProperty( StyleConstants.STYLE_BORDER_LEFT_WIDTH ) ); return; } borderStyle = style.getBorderRightStyle( ); if ( hasBorder( borderStyle ) ) { writeRunBorder( borderStyle, style.getBorderRightColor( ), style .getProperty( StyleConstants.STYLE_BORDER_RIGHT_WIDTH ) ); return; } } private boolean hasBorder( String borderStyle ) { return !( borderStyle == null || "none".equalsIgnoreCase( borderStyle ) ); } private void writeRunBorder( String borderStyle, String color, CSSValue borderWidth ) { writer.openTag( "w:bdr" ); writeBorderProperty( borderStyle, color, borderWidth, 0 ); writer.closeTag( "w:bdr" ); } private boolean needNewParagraph( String txt ) { return ( "\n".equals( txt ) || "\r".equalsIgnoreCase( txt ) || "\r\n" .equals( txt ) ); } public void startParagraph( IStyle style, boolean isInline, int paragraphWidth ) { writer.openTag( "w:p" ); writer.openTag( "w:pPr" ); writeSpacing( ( style.getProperty( StyleConstants.STYLE_MARGIN_TOP ) ), ( style.getProperty( StyleConstants.STYLE_MARGIN_BOTTOM ) ) ); writeAlign( style.getTextAlign( ), style.getDirection( ) ); int indent = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_TEXT_INDENT ), paragraphWidth ) / 1000 * 20; if ( indent != 0 ) { writeIndent( indent ); } if ( !isInline ) { writeBackgroundColor( style.getBackgroundColor( ) ); writeParagraphBorders( style ); } writer.closeTag( "w:pPr" ); } private void writeSpacing( CSSValue height ) { // unit: twentieths of a point(twips) float spacingValue = PropertyUtil.getDimensionValue( height ); int spacing = WordUtil.milliPt2Twips( spacingValue ) / 2; writeSpacing( spacing, spacing ); } private void writeSpacing( CSSValue top, CSSValue bottom ) { float topSpacingValue = PropertyUtil.getDimensionValue( top ); float bottomSpacingValue = PropertyUtil.getDimensionValue( bottom ); writeSpacing( WordUtil.milliPt2Twips( topSpacingValue ) / 2, WordUtil .milliPt2Twips( bottomSpacingValue ) / 2 ); } private void writeSpacing( int beforeValue, int afterValue ) { writer.openTag( "w:spacing" ); writer.attribute( "w:before", beforeValue ); writer.attribute( "w:after", afterValue ); writer.closeTag( "w:spacing" ); } protected void writeAutoText( int type ) { writer.openTag( "w:instrText" ); if ( type == IAutoTextContent.PAGE_NUMBER ) { writer.text( "PAGE" ); } else if ( type == IAutoTextContent.TOTAL_PAGE ) { writer.text( "NUMPAGES" ); } writer.closeTag( "w:instrText" ); } private void writeString( String txt, IStyle style ) { if ( txt == null ) { return; } if ( style != null ) { String textTransform = style.getTextTransform( ); if ( CSSConstants.CSS_CAPITALIZE_VALUE .equalsIgnoreCase( textTransform ) ) { txt = WordUtil.capitalize( txt ); } else if ( CSSConstants.CSS_UPPERCASE_VALUE .equalsIgnoreCase( textTransform ) ) { txt = txt.toUpperCase( ); } else if ( CSSConstants.CSS_LOWERCASE_VALUE .equalsIgnoreCase( textTransform ) ) { txt = txt.toLowerCase( ); } } writer.openTag( "w:t" ); Pattern p = Pattern.compile( "\r|\n" ); Matcher m = p.matcher( txt ); int length = txt.length( ); int index = 0; while ( m.find( index ) ) { int start = m.start( ); if ( start > index ) { writer.cdata("<![CDATA[" + txt.substring( index, start )+ "]]>"); } int end = m.end( ); if (txt.charAt( end - 1 ) != '\r' || end == length || txt.charAt( end ) != '\n' ) { writer.cdata("<w:br/>"); } index = end; } if ( index < length ) { writer.cdata("<![CDATA[" + txt.substring( index ) + "]]>"); } writer.closeTag( "w:t" ); } private void writeLetterSpacing( IStyle style ) { int letterSpacing = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_LETTER_SPACING ) ); writeAttrTag( "w:spacing", WordUtil.milliPt2Twips( letterSpacing ) ); } private void writeHyperlinkStyle( HyperlinkInfo info, IStyle style ) { // deal with hyperlink if ( info != null ) { String color = info.getColor( ); if ( color != null ) { writeAttrTag( "w:color", color ); } writeAttrTag( "w:rStyle", "Hyperlink" ); } else { writeTextUnderline( style ); writeTextColor( style ); } } protected void writeTocText( String tocText, int level ) { writer.openTag( "w:r" ); writer.openTag( "w:instrText" ); writer.text( " TC \"" + tocText + "\"" + " \\f C \\l \"" + String.valueOf( level ) + "\"" ); writer.closeTag( "w:instrText" ); writer.closeTag( "w:r" ); } /** * @param direction * * @author bidi_hcg */ protected void writeBidi( boolean rtl ) { writeAttrTag( "w:bidi", rtl ? "" : "off"); } protected void writeField( boolean isStart ) { String fldCharType = isStart ? "begin" : "end"; writer.openTag( "w:r" ); writer.openTag( "w:fldChar" ); writer.attribute( "w:fldCharType", fldCharType ); writer.closeTag( "w:fldChar" ); writer.closeTag( "w:r" ); } protected void writeField( boolean isStart, IStyle style, String fontName ) { String fldCharType = isStart ? "begin" : "end"; writer.openTag( "w:r" ); writeFieldRunProperties( style, fontName ); writer.openTag( "w:fldChar" ); writer.attribute( "w:fldCharType", fldCharType ); writer.closeTag( "w:fldChar" ); writer.closeTag( "w:r" ); } public void writeColumn( int[] cols ) { // unit: twips writer.openTag( "w:tblGrid" ); for ( int i = 0; i < cols.length; i++ ) { writeAttrTag( "w:gridCol", cols[i] ); } writer.closeTag( "w:tblGrid" ); } /** * * @param style * style of the row * @param height * height of current row, if heigh equals 1 then ignore height * @param type * header or normal */ public void startTableRow( double height, boolean isHeader, boolean repeatHeader, boolean fixedLayout ) { writer.openTag( "w:tr" ); // write the row height, unit: twips writer.openTag( "w:trPr" ); if ( height != -1 ) { writer.openTag( "w:trHeight" ); if ( fixedLayout ) { writer.attribute( "w:h-rule", "exact" ); } writer.attribute( "w:val", height ); writer.closeTag( "w:trHeight" ); } // if value is "off",the header will be not repeated if ( isHeader ) { String headerOnOff = repeatHeader ? "on" : "off"; writeAttrTag( "w:tblHeader", headerOnOff ); } writer.closeTag( "w:trPr" ); } public void endTableRow( ) { writer.closeTag( "w:tr" ); } public void startTableCell( int width, IStyle style, SpanInfo spanInfo ) { writer.openTag( "w:tc" ); writer.openTag( "w:tcPr" ); writeCellWidth( width ); if ( spanInfo != null ) { writeGridSpan( spanInfo ); writeVmerge( spanInfo ); } writeCellProperties( style ); writer.closeTag( "w:tcPr" ); String align = style.getTextAlign( ); if ( align == null ) { return; } String direction = style.getDirection( ); // bidi_hcg if ( CSSConstants.CSS_LEFT_VALUE.equals( align ) ) { if ( !CSSConstants.CSS_RTL_VALUE.equals( direction ) ) return; } writer.openTag( "w:pPr" ); writeAlign( align, direction ); writer.closeTag( "w:pPr" ); } private void writeCellWidth( int width ) { writer.openTag( "w:tcW" ); writer.attribute( "w:w", width ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:tcW" ); } private void writeGridSpan( SpanInfo spanInfo ) { int columnSpan = spanInfo.getColumnSpan( ); if ( columnSpan > 1 ) { writeAttrTag( "w:gridSpan", columnSpan ); } } public void writeSpanCell( SpanInfo info ) { writer.openTag( "w:tc" ); writer.openTag( "w:tcPr" ); writeCellWidth( info.getCellWidth( ) ); writeGridSpan( info ); writeVmerge( info ); writeCellProperties( info.getStyle( ) ); writer.closeTag( "w:tcPr" ); insertEmptyParagraph( ); writer.closeTag( "w:tc" ); } public void endTableCell( boolean empty ) { if ( empty ) { insertEmptyParagraph( ); } writer.closeTag( "w:tc" ); } public void writeEmptyCell( ) { writer.openTag( "w:tc" ); writer.openTag( "w:tcPr" ); writer.openTag( "w:tcW" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:tcW" ); writer.closeTag( "w:tcPr" ); insertEmptyParagraph( ); writer.closeTag( "w:tc" ); } public void insertEmptyParagraph( ) { writer.openTag( "w:p" ); writer.closeTag( "w:p" ); } public void insertHiddenParagraph( ) { writer.openTag( "w:p" ); writeHiddenProperty( ); writer.closeTag( "w:p" ); } public void writeHiddenProperty( ) { writer.openTag( "w:rPr" ); writeAttrTag( "w:vanish", "on" ); writer.closeTag( "w:rPr" ); } public void endParagraph( ) { writer.closeTag( "w:p" ); } public void writeCaption( String txt ) { writer.openTag( "w:p" ); writer.openTag( "w:pPr" ); writeAlign( "center", null ); writer.closeTag( "w:pPr" ); writer.openTag( "w:r" ); writer.openTag( "w:rPr" ); writeString( txt, null ); writer.closeTag( "w:rPr" ); writer.closeTag( "w:r" ); writer.closeTag( "w:p" ); } /** * If the cell properties is not set, then check the row properties and * write those properties. * * @param style * this cell style */ private void writeCellProperties( IStyle style ) { // A cell background color may inherit from row background, // so we should get the row background color here, // if the cell background is transparent if ( style == null ) { return; } writeBackgroundColor( style.getBackgroundColor( ) ); writeCellBorders( style ); writeCellPadding( style ); String verticalAlign = style.getVerticalAlign( ); if ( verticalAlign != null ) { writeAttrTag( "w:vAlign", WordUtil .parseVerticalAlign( verticalAlign ) ); } String noWrap = CSSConstants.CSS_NOWRAP_VALUE.equalsIgnoreCase( style .getWhiteSpace( ) ) ? "on" : "off"; writeAttrTag( "w:noWrap", noWrap ); } private void writeCellBorders( IStyle style ) { writer.openTag( "w:tcBorders" ); writeBorders( style, 0, 0, 0, 0 ); writer.closeTag( "w:tcBorders" ); } private void writeCellPadding( IStyle style ) { int bottomPadding = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_PADDING_BOTTOM ) ); int leftPadding = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_PADDING_LEFT ) ); int topPadding = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_PADDING_TOP ) ); int rightPadding = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_PADDING_RIGHT ) ); // the cell padding in DOC is tcMar writer.openTag( "w:tcMar" ); writeCellPadding( bottomPadding, BOTTOM ); writeCellPadding( leftPadding, LEFT ); writeCellPadding( topPadding, TOP ); writeCellPadding( rightPadding, RIGHT ); writer.closeTag( "w:tcMar" ); } /** * * @param padding milliPoint * @param position top/right/bottom/left */ private void writeCellPadding( int padding, String position ) { writer.openTag( "w:" + position ); writer.attribute( "w:w", WordUtil.milliPt2Twips( padding ) ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:" + position ); } protected void writeAttrTag( String name, String val ) { writer.openTag( name ); writer.attribute( "w:val", val ); writer.closeTag( name ); } protected void writeAttrTag( String name, int val ) { writer.openTag( name ); writer.attribute( "w:val", val ); writer.closeTag( name ); } protected void writeAttrTag( String name, double val ) { writer.openTag( name ); writer.attribute( "w:val", val ); writer.closeTag( name ); } protected int getImageID( ) { return imageId++; } private void writeTextInParagraph( int type, String txt, IStyle style, String fontFamily, HyperlinkInfo info, int paragraphWidth, boolean runIsRtl ) { writer.openTag( "w:p" ); writer.openTag( "w:pPr" ); CSSValue lineHeight = style .getProperty( StyleConstants.STYLE_LINE_HEIGHT ); if ( !"normal".equalsIgnoreCase( lineHeight.getCssText( ) ) ) { writeSpacing( lineHeight ); } writeAlign( style.getTextAlign( ), style.getDirection( ) ); writeBackgroundColor( style.getBackgroundColor( ) ); writeParagraphBorders( style ); int indent = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_TEXT_INDENT ), paragraphWidth * 1000 ) / 1000 * 20; if ( indent != 0 ) { writeIndent( indent ); } writeBidi( CSSConstants.CSS_RTL_VALUE.equals( style.getDirection( ) ) ); // bidi_hcg // We need to apply the text font style to the paragraph. It is useful // if the end user want to paste some text into this paragraph and // changes the text to the paragraph's font style. writer.openTag( "w:rPr" ); writeRunProperties( style, fontFamily, info ); writer.closeTag( "w:rPr" ); writer.closeTag( "w:pPr" ); writeTextInRun( type, txt, style, fontFamily, info, false, paragraphWidth, runIsRtl ); } private void writeParagraphBorders( IStyle style ) { writer.openTag( "w:pBdr" ); writeBorders( style, 0, 0, 0, 0 ); writer.closeTag( "w:pBdr" ); } public void writeText( int type, String txt, IStyle style, String fontFamily, HyperlinkInfo info, TextFlag flag, int paragraphWidth, boolean runIsRtl ) { if ( flag == TextFlag.START ) { writeTextInParagraph( type, txt, style, fontFamily, info, paragraphWidth, runIsRtl ); } else if ( flag == TextFlag.END ) { writer.closeTag( "w:p" ); } else if ( flag == TextFlag.MIDDLE ) { writeTextInRun( type, txt, style, fontFamily, info, false, paragraphWidth, runIsRtl ); } else { writeTextInParagraph( type, txt, style, fontFamily, info, paragraphWidth, runIsRtl ); writer.closeTag( "w:p" ); } } public void writeTextInRun( int type, String txt, IStyle style, String fontFamily, HyperlinkInfo info, boolean isInline, int paragraphWidth, boolean runIsRtl ) { if ( "".equals( txt ) ) { return; } if ( needNewParagraph( txt ) ) { writer.closeTag( "w:p" ); startParagraph( style, isInline, paragraphWidth ); return; } openHyperlink( info ); boolean isField = WordUtil.isField( type ); String direction = style.getDirection( ); if ( isField ) { writeField( true, style, fontFamily ); } writer.openTag( "w:r" ); writer.openTag( "w:rPr" ); writeRunProperties( style, fontFamily, info ); if ( isInline ) { writeAlign( style.getTextAlign( ), direction ); writeBackgroundColor( style.getBackgroundColor( ) ); writePosition( style.getVerticalAlign( ), style .getProperty( StyleConstants.STYLE_FONT_SIZE ) ); writeRunBorders( style ); } if ( !isField && runIsRtl ) { writer.openTag( "w:rtl" ); writer.closeTag( "w:rtl" ); } writer.closeTag( "w:rPr" ); if ( isField ) { writeAutoText( type ); } else { writeString( txt, style ); } writer.closeTag( "w:r" ); if ( isField ) { writeField( false, style, fontFamily ); } closeHyperlink( info ); } private void writePosition( String verticalAlign, CSSValue fontSize ) { int size = WordUtil.parseFontSize( PropertyUtil .getDimensionValue( fontSize ) ); if ( "top".equalsIgnoreCase( verticalAlign ) ) { writeAttrTag( "w:position", (int) ( size * 1 / 3 ) ); } else if ( "bottom".equalsIgnoreCase( verticalAlign ) ) { writeAttrTag( "w:position", (int) ( -size * 1 / 3 ) ); } } protected void writeRunProperties( IStyle style, String fontFamily, HyperlinkInfo info ) { writeHyperlinkStyle( info, style ); writeFont( fontFamily ); writeFontSize( style ); writeLetterSpacing( style ); writeTextLineThrough( style ); writeFontStyle( style ); writeFontWeight( style ); } protected void writeFieldRunProperties( IStyle style, String fontFamily ) { writeFont( fontFamily ); writeFontSize( style ); writeLetterSpacing( style ); writeTextLineThrough( style ); writeFontStyle( style ); writeFontWeight( style ); } private void writeTextColor( IStyle style ) { String val = WordUtil.parseColor( style.getColor( ) ); if ( val != null ) { writeAttrTag( "w:color", val ); } } private void writeTextUnderline( IStyle style ) { String val = WordUtil.removeQuote( style.getTextUnderline( ) ); if ( !"none".equalsIgnoreCase( val ) ) { writeAttrTag( "w:u", "single" ); } } private void writeTextLineThrough( IStyle style ) { String val = WordUtil.removeQuote( style.getTextLineThrough( ) ); if ( !"none".equalsIgnoreCase( val ) ) { writeAttrTag( "w:strike", "on" ); } } protected void startHeaderFooterContainer( int headerHeight, int headerWidth ) { startHeaderFooterContainer( headerHeight, headerWidth, false ); } protected void startHeaderFooterContainer( int headerHeight, int headerWidth, boolean writeColumns ) { // the tableGrid in DOC has a 0.19cm cell margin by default on left and right. // so the header or footer width should be 2*0.19cm larger. that is 215.433 twips. headerWidth += 215; writer.openTag( "w:tbl" ); writer.openTag( "w:tblPr" ); writeTableWidth( headerWidth ); writeAttrTag( "w:tblLook", "01E0" ); writeTableLayout( ); writer.closeTag( "w:tblPr" ); if ( writeColumns ) { writeColumn( new int[]{headerWidth} ); } writer.openTag( "w:tr" ); // write the row height, unit: twips writer.openTag( "w:trPr" ); writeAttrTag( "w:trHeight", headerHeight ); writer.closeTag( "w:trPr" ); writer.openTag( "w:tc" ); writer.openTag( "w:tcPr" ); writeCellWidth( headerWidth ); writer.closeTag( "w:tcPr" ); } protected void endHeaderFooterContainer( ) { insertEmptyParagraph( ); writer.closeTag( "w:tc" ); writer.closeTag( "w:tr" ); writer.closeTag( "w:tbl" ); } public void drawDiagonalLine( DiagonalLineInfo diagonalLineInfo ) { if ( diagonalLineInfo.getDiagonalNumber( ) <= 0 && diagonalLineInfo.getAntiDiagonalNumber( ) <= 0 ) return; writer.openTag( "w:p" ); writer.openTag( "w:r" ); writer.openTag( "w:pict" ); double diagonalLineWidth = diagonalLineInfo.getDiagonalLineWidth( ); String diagonalLineStyle = diagonalLineInfo.getDiagonalStyle( ); double antidiagonalLineWidth = diagonalLineInfo .getAntiDiagonalLineWidth( ); String antidiagonalLineStyle = diagonalLineInfo.getAntiDiagonalStyle( ); String lineColor = diagonalLineInfo.getColor( ); for ( Line line : diagonalLineInfo .getDiagonalLine( ) ) { drawLine( diagonalLineWidth, diagonalLineStyle, lineColor, line ); } for ( Line antiLine : diagonalLineInfo .getAntidiagonalLine( ) ) { drawLine( antidiagonalLineWidth, antidiagonalLineStyle, lineColor, antiLine ); } writer.closeTag( "w:pict" ); writer.closeTag( "w:r" ); writer.closeTag( "w:p" ); } private void drawLine( double width, String style, String color, Line line ) { writer.openTag( "v:line" ); writer.attribute( "id", "Line" + getLineId( ) ); writer.attribute( "style", "position:absolute;left:0;text-align:left;z-index:1" ); writer.attribute( "from", line.getXCoordinateFrom( ) + "pt," + line.getYCoordinateFrom( ) + "pt" ); writer.attribute( "to", line.getXCoordinateTo( ) + "pt," + line.getYCoordinateTo( ) + "pt" ); writer.attribute( "strokeweight", width + "pt" ); writer.attribute( "strokecolor", "#" + color ); writer.openTag( "v:stroke" ); writer.attribute( "dashstyle", WordUtil.parseLineStyle( style ) ); writer.closeTag( "v:stroke" ); writer.closeTag( "v:line" ); } private int getLineId( ) { return lineId++; } }
engine/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/writer/AbstractWordXmlWriter.java
/******************************************************************************* * Copyright (c) 2008,2009 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.emitter.wpml.writer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.birt.report.engine.content.IAutoTextContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.css.engine.StyleConstants; import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants; import org.eclipse.birt.report.engine.emitter.XMLWriter; import org.eclipse.birt.report.engine.emitter.wpml.AbstractEmitterImpl.TextFlag; import org.eclipse.birt.report.engine.emitter.wpml.DiagonalLineInfo; import org.eclipse.birt.report.engine.emitter.wpml.DiagonalLineInfo.Line; import org.eclipse.birt.report.engine.emitter.wpml.HyperlinkInfo; import org.eclipse.birt.report.engine.emitter.wpml.SpanInfo; import org.eclipse.birt.report.engine.emitter.wpml.WordUtil; import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil; import org.w3c.dom.css.CSSValue; public abstract class AbstractWordXmlWriter { protected XMLWriter writer; protected final String RIGHT = "right"; protected final String LEFT = "left"; protected final String TOP = "top"; protected final String BOTTOM = "bottom"; protected int imageId = 75; protected int bookmarkId = 0; private int lineId = 0; // Holds the global layout orientation. protected boolean rtl = false; protected abstract void writeTableLayout( ); protected abstract void writeFontSize( IStyle style ); protected abstract void writeFont( String fontFamily ); protected abstract void writeFontStyle( IStyle style ); protected abstract void writeFontWeight(IStyle style); protected abstract void openHyperlink( HyperlinkInfo info ); protected abstract void closeHyperlink( HyperlinkInfo info ); protected abstract void writeVmerge( SpanInfo spanInfo ); protected abstract void writeIndent( int indent ); public void startSectionInParagraph( ) { writer.openTag( "w:p" ); writer.openTag( "w:pPr" ); startSection( ); } public void endSectionInParagraph( ) { endSection( ); writer.closeTag( "w:pPr" ); writer.closeTag( "w:p" ); } public void startSection( ) { writer.openTag( "w:sectPr" ); } public void endSection( ) { writer.closeTag( "w:sectPr" ); } protected void drawImageShapeType( int imageId ) { writer.openTag( "v:shapetype" ); writer.attribute( "id", "_x0000_t" + imageId ); writer.attribute( "coordsize", "21600,21600" ); writer.attribute( "o:spt", "75" ); writer.attribute( "o:preferrelative", "t" ); writer.attribute( "path", "m@4@5l@4@11@9@11@9@5xe" ); writer.attribute( "filled", "f" ); writer.attribute( "stroked", "f" ); writer.openTag( "v:stroke" ); writer.attribute( "imagealignshape", "false" ); writer.attribute( "joinstyle", "miter" ); writer.closeTag( "v:stroke" ); writer.openTag( "v:formulas" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "if lineDrawn pixelLineWidth 0" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum @0 1 0" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum 0 0 @1" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @2 1 2" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @3 21600 pixelWidth" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @3 21600 pixelHeight" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum @0 0 1" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @6 1 2" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @7 21600 pixelWidth" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum @8 21600 0 " ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "prod @7 21600 pixelHeight" ); writer.closeTag( "v:f" ); writer.openTag( "v:f" ); writer.attribute( "eqn", "sum @10 21600 0" ); writer.closeTag( "v:f" ); writer.closeTag( "v:formulas" ); writer.openTag( "v:path" ); writer.attribute( "o:extrusionok", "f" ); writer.attribute( "gradientshapeok", "t" ); writer.attribute( "o:connecttype", "rect" ); writer.closeTag( "v:path" ); writer.openTag( "o:lock" ); writer.attribute( "v:ext", "edit" ); writer.attribute( "aspectratio", "t" ); writer.closeTag( "o:lock" ); writer.closeTag( "v:shapetype" ); } protected void drawImageBordersStyle( IStyle style ) { drawImageBorderStyle( BOTTOM, style.getBorderBottomStyle( ), style .getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ) ); drawImageBorderStyle( TOP, style.getBorderTopStyle( ), style .getProperty( StyleConstants.STYLE_BORDER_TOP_WIDTH ) ); drawImageBorderStyle( LEFT, style.getBorderLeftStyle( ), style .getProperty( StyleConstants.STYLE_BORDER_LEFT_WIDTH ) ); drawImageBorderStyle( RIGHT, style.getBorderRightStyle( ), style .getProperty( StyleConstants.STYLE_BORDER_RIGHT_WIDTH ) ); } private void drawImageBorderStyle( String pos, String style, CSSValue width ) { String direct = "w10:border" + pos; writer.openTag( direct ); writer.attribute( "type", WordUtil.parseImageBorderStyle( style ) ); writer.attribute( "width", WordUtil.parseBorderSize( PropertyUtil .getDimensionValue( width ) ) ); writer.closeTag( direct ); } protected void drawImageBordersColor( IStyle style ) { drawImageBorderColor( BOTTOM, style.getBorderBottomColor( ) ); drawImageBorderColor( TOP, style.getBorderTopColor( ) ); drawImageBorderColor( LEFT, style.getBorderLeftColor( ) ); drawImageBorderColor( RIGHT, style.getBorderRightColor( ) ); } private void drawImageBorderColor( String pos, String color ) { String borderColor = "#" + WordUtil.parseColor( color ); String direct = "o:border" + pos + "color"; writer.attribute( direct, borderColor ); } public void writePageProperties( int pageHeight, int pageWidth, int headerHeight, int footerHeight, int topMargin, int bottomMargin, int leftMargin, int rightMargin, String orient ) { writer.openTag( "w:pgSz" ); writer.attribute( "w:w", pageWidth ); writer.attribute( "w:h", pageHeight ); writer.attribute( "w:orient", orient ); writer.closeTag( "w:pgSz" ); writer.openTag( "w:pgMar" ); writer.attribute( "w:top", topMargin ); writer.attribute( "w:bottom", bottomMargin ); writer.attribute( "w:left", leftMargin ); writer.attribute( "w:right", rightMargin ); writer.attribute( "w:header", topMargin ); writer.attribute( "w:footer", bottomMargin ); writer.closeTag( "w:pgMar" ); } // write the table properties to the output stream public void startTable( IStyle style, int tablewidth ) { startTable( style, tablewidth, false ); } // write the table properties to the output stream public void startTable( IStyle style, int tablewidth, boolean inForeign ) { writer.openTag( "w:tbl" ); writer.openTag( "w:tblPr" ); writeTableIndent( ); writeAttrTag( "w:tblStyle", "TableGrid" ); writeAttrTag( "w:tblOverlap", "Never" ); writeBidiTable( ); writeTableWidth( tablewidth ); writeAttrTag( "w:tblLook", "01E0" ); writeTableLayout( ); writeTableBorders( style ); writeBackgroundColor( style.getBackgroundColor( ) ); //"justify" is not an option for table alignment in word if ( "justify".equalsIgnoreCase( style.getTextAlign( ) ) ) { writeAlign( "left", style.getDirection( ) ); } else { writeAlign( style.getTextAlign( ), style.getDirection( ) ); } if (inForeign) { writer.openTag( "w:tblCellMar" ); writer.openTag( "w:top" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:top" ); writer.openTag( "w:left" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:left" ); writer.openTag( "w:bottom" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:bottom" ); writer.openTag( "w:right" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:right" ); writer.closeTag( "w:tblCellMar" ); } writer.closeTag( "w:tblPr" ); } private void writeTableBorders( IStyle style ) { writer.openTag( "w:tblBorders" ); writeBorders( style, 0, 0, 0, 0 ); writer.closeTag( "w:tblBorders" ); } public void endTable( ) { writer.closeTag( "w:tbl" ); } private void writeTableWidth( int tablewidth ) { writer.openTag( "w:tblW" ); writer.attribute( "w:w", tablewidth ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:tblW" ); } private void writeTableIndent( ) { writer.openTag( "w:tblInd" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:tblInd" ); } protected void writeBorders( IStyle style, int bottomMargin, int topMargin, int leftMargin, int rightMargin ) { String borderStyle = style.getBorderBottomStyle( ); if ( hasBorder( borderStyle ) ) { writeSingleBorder( BOTTOM, borderStyle, style .getBorderBottomColor( ), style .getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ), bottomMargin ); } borderStyle = style.getBorderTopStyle( ); if ( hasBorder( borderStyle ) ) { writeSingleBorder( TOP, borderStyle, style.getBorderTopColor( ), style.getProperty( StyleConstants.STYLE_BORDER_TOP_WIDTH ), topMargin ); } borderStyle = style.getBorderLeftStyle( ); if ( hasBorder( borderStyle ) ) { writeSingleBorder( LEFT, borderStyle, style.getBorderLeftColor( ), style.getProperty( StyleConstants.STYLE_BORDER_LEFT_WIDTH ), leftMargin ); } borderStyle = style.getBorderRightStyle( ); if ( hasBorder( borderStyle ) ) { writeSingleBorder( RIGHT, borderStyle, style.getBorderRightColor( ), style.getProperty( StyleConstants.STYLE_BORDER_RIGHT_WIDTH ), rightMargin ); } } private void writeSingleBorder( String type, String borderStyle, String color, CSSValue width, int margin ) { writer.openTag( "w:" + type ); writeBorderProperty( borderStyle, color, width, margin ); writer.closeTag( "w:" + type ); } private void writeBorderProperty( String style, String color, CSSValue width, int margin ) { writer.attribute( "w:val", WordUtil.parseBorderStyle( style ) ); writer.attribute( "w:sz", WordUtil.parseBorderSize( PropertyUtil .getDimensionValue( width ) ) ); writer.attribute( "w:space", validateBorderSpace( margin ) ); writer.attribute( "w:color", WordUtil.parseColor( color ) ); } private int validateBorderSpace( int margin ) { // word only accept 0-31 pt int space = (int) WordUtil.twipToPt( margin ); if ( space > 31 ) space = 31; return space; } protected void writeAlign( String align, String direction ) { if ( null == align ) { return; } String textAlign = align; if ( "justify".equalsIgnoreCase( align ) ) { textAlign = "both"; } // Need to swap 'left' and 'right' when orientation is RTL. if ( CSSConstants.CSS_RTL_VALUE.equalsIgnoreCase( direction ) ) { if ( IStyle.CSS_RIGHT_VALUE.equals( textAlign ) ) writeAttrTag( "w:jc", IStyle.CSS_LEFT_VALUE ); else if ( IStyle.CSS_LEFT_VALUE.equals( textAlign ) ) writeAttrTag( "w:jc", IStyle.CSS_RIGHT_VALUE ); else writeAttrTag( "w:jc", textAlign ); } else writeAttrTag( "w:jc", textAlign ); } protected void writeBackgroundColor( String color ) { String cssColor = WordUtil.parseColor( color ); if ( cssColor == null ) { return; } writer.openTag( "w:shd" ); writer.attribute( "w:val", "clear" ); writer.attribute( "w:color", "auto" ); writer.attribute( "w:fill", cssColor ); writer.closeTag( "w:shd" ); } /** * @param direction * * @author bidi_hcg */ private void writeBidiTable( ) { if ( this.rtl ) { writer.openTag( "w:bidiVisual" ); writer.closeTag( "w:bidiVisual" ); } } protected void writeRunBorders( IStyle style ) { String borderStyle = style.getBorderTopStyle( ); if ( hasBorder( borderStyle ) ) { writeRunBorder( borderStyle, style.getBorderTopColor( ), style .getProperty( StyleConstants.STYLE_BORDER_TOP_WIDTH ) ); return; } borderStyle = style.getBorderBottomStyle( ); if ( hasBorder( borderStyle ) ) { writeRunBorder( borderStyle, style.getBorderBottomColor( ), style .getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ) ); return; } borderStyle = style.getBorderLeftStyle( ); if ( hasBorder( borderStyle ) ) { writeRunBorder( borderStyle, style.getBorderLeftColor( ), style .getProperty( StyleConstants.STYLE_BORDER_LEFT_WIDTH ) ); return; } borderStyle = style.getBorderRightStyle( ); if ( hasBorder( borderStyle ) ) { writeRunBorder( borderStyle, style.getBorderRightColor( ), style .getProperty( StyleConstants.STYLE_BORDER_RIGHT_WIDTH ) ); return; } } private boolean hasBorder( String borderStyle ) { return !( borderStyle == null || "none".equalsIgnoreCase( borderStyle ) ); } private void writeRunBorder( String borderStyle, String color, CSSValue borderWidth ) { writer.openTag( "w:bdr" ); writeBorderProperty( borderStyle, color, borderWidth, 0 ); writer.closeTag( "w:bdr" ); } private boolean needNewParagraph( String txt ) { return ( "\n".equals( txt ) || "\r".equalsIgnoreCase( txt ) || "\r\n" .equals( txt ) ); } public void startParagraph( IStyle style, boolean isInline, int paragraphWidth ) { writer.openTag( "w:p" ); writer.openTag( "w:pPr" ); writeSpacing( ( style.getProperty( StyleConstants.STYLE_MARGIN_TOP ) ), ( style.getProperty( StyleConstants.STYLE_MARGIN_BOTTOM ) ) ); writeAlign( style.getTextAlign( ), style.getDirection( ) ); int indent = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_TEXT_INDENT ), paragraphWidth ) / 1000 * 20; if ( indent != 0 ) { writeIndent( indent ); } if ( !isInline ) { writeBackgroundColor( style.getBackgroundColor( ) ); writeParagraphBorders( style ); } writer.closeTag( "w:pPr" ); } private void writeSpacing( CSSValue height ) { // unit: twentieths of a point(twips) float spacingValue = PropertyUtil.getDimensionValue( height ); int spacing = WordUtil.milliPt2Twips( spacingValue ) / 2; writeSpacing( spacing, spacing ); } private void writeSpacing( CSSValue top, CSSValue bottom ) { float topSpacingValue = PropertyUtil.getDimensionValue( top ); float bottomSpacingValue = PropertyUtil.getDimensionValue( bottom ); writeSpacing( WordUtil.milliPt2Twips( topSpacingValue ) / 2, WordUtil .milliPt2Twips( bottomSpacingValue ) / 2 ); } private void writeSpacing( int beforeValue, int afterValue ) { writer.openTag( "w:spacing" ); writer.attribute( "w:before", beforeValue ); writer.attribute( "w:after", afterValue ); writer.closeTag( "w:spacing" ); } protected void writeAutoText( int type ) { writer.openTag( "w:instrText" ); if ( type == IAutoTextContent.PAGE_NUMBER ) { writer.text( "PAGE" ); } else if ( type == IAutoTextContent.TOTAL_PAGE ) { writer.text( "NUMPAGES" ); } writer.closeTag( "w:instrText" ); } private void writeString( String txt, IStyle style ) { if ( txt == null ) { return; } if ( style != null ) { String textTransform = style.getTextTransform( ); if ( CSSConstants.CSS_CAPITALIZE_VALUE .equalsIgnoreCase( textTransform ) ) { txt = WordUtil.capitalize( txt ); } else if ( CSSConstants.CSS_UPPERCASE_VALUE .equalsIgnoreCase( textTransform ) ) { txt = txt.toUpperCase( ); } else if ( CSSConstants.CSS_LOWERCASE_VALUE .equalsIgnoreCase( textTransform ) ) { txt = txt.toLowerCase( ); } } writer.openTag( "w:t" ); Pattern p = Pattern.compile( "\r|\n" ); Matcher m = p.matcher( txt ); int length = txt.length( ); int index = 0; while ( m.find( index ) ) { int start = m.start( ); if ( start > index ) { writer.cdata("<![CDATA[" + txt.substring( index, start )+ "]]>"); } int end = m.end( ); if (txt.charAt( end - 1 ) != '\r' || end == length || txt.charAt( end ) != '\n' ) { writer.cdata("<w:br/>"); } index = end; } if ( index < length ) { writer.cdata("<![CDATA[" + txt.substring( index ) + "]]>"); } writer.closeTag( "w:t" ); } private void writeLetterSpacing( IStyle style ) { int letterSpacing = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_LETTER_SPACING ) ); writeAttrTag( "w:spacing", WordUtil.milliPt2Twips( letterSpacing ) ); } private void writeHyperlinkStyle( HyperlinkInfo info, IStyle style ) { // deal with hyperlink if ( info != null ) { String color = info.getColor( ); if ( color != null ) { writeAttrTag( "w:color", color ); } writeAttrTag( "w:rStyle", "Hyperlink" ); } else { writeTextUnderline( style ); writeTextColor( style ); } } protected void writeTocText( String tocText, int level ) { writer.openTag( "w:r" ); writer.openTag( "w:instrText" ); writer.text( " TC \"" + tocText + "\"" + " \\f C \\l \"" + String.valueOf( level ) + "\"" ); writer.closeTag( "w:instrText" ); writer.closeTag( "w:r" ); } /** * @param direction * * @author bidi_hcg */ protected void writeBidi( boolean rtl ) { writeAttrTag( "w:bidi", rtl ? "" : "off"); } protected void writeField( boolean isStart ) { String fldCharType = isStart ? "begin" : "end"; writer.openTag( "w:r" ); writer.openTag( "w:fldChar" ); writer.attribute( "w:fldCharType", fldCharType ); writer.closeTag( "w:fldChar" ); writer.closeTag( "w:r" ); } protected void writeField( boolean isStart, IStyle style, String fontName ) { String fldCharType = isStart ? "begin" : "end"; writer.openTag( "w:r" ); writeFieldRunProperties( style, fontName ); writer.openTag( "w:fldChar" ); writer.attribute( "w:fldCharType", fldCharType ); writer.closeTag( "w:fldChar" ); writer.closeTag( "w:r" ); } public void writeColumn( int[] cols ) { // unit: twips writer.openTag( "w:tblGrid" ); for ( int i = 0; i < cols.length; i++ ) { writeAttrTag( "w:gridCol", cols[i] ); } writer.closeTag( "w:tblGrid" ); } /** * * @param style * style of the row * @param height * height of current row, if heigh equals 1 then ignore height * @param type * header or normal */ public void startTableRow( double height, boolean isHeader, boolean repeatHeader, boolean fixedLayout ) { writer.openTag( "w:tr" ); // write the row height, unit: twips writer.openTag( "w:trPr" ); if ( height != -1 ) { writer.openTag( "w:trHeight" ); if ( fixedLayout ) { writer.attribute( "w:h-rule", "exact" ); } writer.attribute( "w:val", height ); writer.closeTag( "w:trHeight" ); } // if value is "off",the header will be not repeated if ( isHeader ) { String headerOnOff = repeatHeader ? "on" : "off"; writeAttrTag( "w:tblHeader", headerOnOff ); } writer.closeTag( "w:trPr" ); } public void endTableRow( ) { writer.closeTag( "w:tr" ); } public void startTableCell( int width, IStyle style, SpanInfo spanInfo ) { writer.openTag( "w:tc" ); writer.openTag( "w:tcPr" ); writeCellWidth( width ); if ( spanInfo != null ) { writeGridSpan( spanInfo ); writeVmerge( spanInfo ); } writeCellProperties( style ); writer.closeTag( "w:tcPr" ); String align = style.getTextAlign( ); if ( align == null ) { return; } String direction = style.getDirection( ); // bidi_hcg if ( CSSConstants.CSS_LEFT_VALUE.equals( align ) ) { if ( !CSSConstants.CSS_RTL_VALUE.equals( direction ) ) return; } writer.openTag( "w:pPr" ); writeAlign( align, direction ); writer.closeTag( "w:pPr" ); } private void writeCellWidth( int width ) { writer.openTag( "w:tcW" ); writer.attribute( "w:w", width ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:tcW" ); } private void writeGridSpan( SpanInfo spanInfo ) { int columnSpan = spanInfo.getColumnSpan( ); if ( columnSpan > 1 ) { writeAttrTag( "w:gridSpan", columnSpan ); } } public void writeSpanCell( SpanInfo info ) { writer.openTag( "w:tc" ); writer.openTag( "w:tcPr" ); writeCellWidth( info.getCellWidth( ) ); writeGridSpan( info ); writeVmerge( info ); writeCellProperties( info.getStyle( ) ); writer.closeTag( "w:tcPr" ); insertEmptyParagraph( ); writer.closeTag( "w:tc" ); } public void endTableCell( boolean empty ) { if ( empty ) { insertEmptyParagraph( ); } writer.closeTag( "w:tc" ); } public void writeEmptyCell( ) { writer.openTag( "w:tc" ); writer.openTag( "w:tcPr" ); writer.openTag( "w:tcW" ); writer.attribute( "w:w", 0 ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:tcW" ); writer.closeTag( "w:tcPr" ); insertEmptyParagraph( ); writer.closeTag( "w:tc" ); } public void insertEmptyParagraph( ) { writer.openTag( "w:p" ); writer.closeTag( "w:p" ); } public void insertHiddenParagraph( ) { writer.openTag( "w:p" ); writeHiddenProperty( ); writer.closeTag( "w:p" ); } public void writeHiddenProperty( ) { writer.openTag( "w:rPr" ); writeAttrTag( "w:vanish", "on" ); writer.closeTag( "w:rPr" ); } public void endParagraph( ) { writer.closeTag( "w:p" ); } public void writeCaption( String txt ) { writer.openTag( "w:p" ); writer.openTag( "w:pPr" ); writeAlign( "center", null ); writer.closeTag( "w:pPr" ); writer.openTag( "w:r" ); writer.openTag( "w:rPr" ); writeString( txt, null ); writer.closeTag( "w:rPr" ); writer.closeTag( "w:r" ); writer.closeTag( "w:p" ); } /** * If the cell properties is not set, then check the row properties and * write those properties. * * @param style * this cell style */ private void writeCellProperties( IStyle style ) { // A cell background color may inherit from row background, // so we should get the row background color here, // if the cell background is transparent if ( style == null ) { return; } writeBackgroundColor( style.getBackgroundColor( ) ); writeCellBorders( style ); writeCellPadding( style ); String verticalAlign = style.getVerticalAlign( ); if ( verticalAlign != null ) { writeAttrTag( "w:vAlign", WordUtil .parseVerticalAlign( verticalAlign ) ); } String noWrap = CSSConstants.CSS_NOWRAP_VALUE.equalsIgnoreCase( style .getWhiteSpace( ) ) ? "on" : "off"; writeAttrTag( "w:noWrap", noWrap ); } private void writeCellBorders( IStyle style ) { writer.openTag( "w:tcBorders" ); writeBorders( style, 0, 0, 0, 0 ); writer.closeTag( "w:tcBorders" ); } private void writeCellPadding( IStyle style ) { int bottomPadding = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_PADDING_BOTTOM ) ); int leftPadding = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_PADDING_LEFT ) ); int topPadding = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_PADDING_TOP ) ); int rightPadding = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_PADDING_RIGHT ) ); // the cell padding in DOC is tcMar writer.openTag( "w:tcMar" ); writeCellPadding( bottomPadding, BOTTOM ); writeCellPadding( leftPadding, LEFT ); writeCellPadding( topPadding, TOP ); writeCellPadding( rightPadding, RIGHT ); writer.closeTag( "w:tcMar" ); } /** * * @param padding milliPoint * @param position top/right/bottom/left */ private void writeCellPadding( int padding, String position ) { writer.openTag( "w:" + position ); writer.attribute( "w:w", WordUtil.milliPt2Twips( padding ) ); writer.attribute( "w:type", "dxa" ); writer.closeTag( "w:" + position ); } protected void writeAttrTag( String name, String val ) { writer.openTag( name ); writer.attribute( "w:val", val ); writer.closeTag( name ); } protected void writeAttrTag( String name, int val ) { writer.openTag( name ); writer.attribute( "w:val", val ); writer.closeTag( name ); } protected void writeAttrTag( String name, double val ) { writer.openTag( name ); writer.attribute( "w:val", val ); writer.closeTag( name ); } protected int getImageID( ) { return imageId++; } private void writeTextInParagraph( int type, String txt, IStyle style, String fontFamily, HyperlinkInfo info, int paragraphWidth, boolean runIsRtl ) { writer.openTag( "w:p" ); writer.openTag( "w:pPr" ); CSSValue lineHeight = style .getProperty( StyleConstants.STYLE_LINE_HEIGHT ); if ( !"normal".equalsIgnoreCase( lineHeight.getCssText( ) ) ) { writeSpacing( lineHeight ); } writeAlign( style.getTextAlign( ), style.getDirection( ) ); writeBackgroundColor( style.getBackgroundColor( ) ); writeParagraphBorders( style ); int indent = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_TEXT_INDENT ), paragraphWidth * 1000 ) / 1000 * 20; if ( indent != 0 ) { writeIndent( indent ); } writeBidi( CSSConstants.CSS_RTL_VALUE.equals( style.getDirection( ) ) ); // bidi_hcg writer.closeTag( "w:pPr" ); writeTextInRun( type, txt, style, fontFamily, info, false, paragraphWidth, runIsRtl ); } private void writeParagraphBorders( IStyle style ) { writer.openTag( "w:pBdr" ); writeBorders( style, 0, 0, 0, 0 ); writer.closeTag( "w:pBdr" ); } public void writeText( int type, String txt, IStyle style, String fontFamily, HyperlinkInfo info, TextFlag flag, int paragraphWidth, boolean runIsRtl ) { if ( flag == TextFlag.START ) { writeTextInParagraph( type, txt, style, fontFamily, info, paragraphWidth, runIsRtl ); } else if ( flag == TextFlag.END ) { writer.closeTag( "w:p" ); } else if ( flag == TextFlag.MIDDLE ) { writeTextInRun( type, txt, style, fontFamily, info, false, paragraphWidth, runIsRtl ); } else { writeTextInParagraph( type, txt, style, fontFamily, info, paragraphWidth, runIsRtl ); writer.closeTag( "w:p" ); } } public void writeTextInRun( int type, String txt, IStyle style, String fontFamily, HyperlinkInfo info, boolean isInline, int paragraphWidth, boolean runIsRtl ) { if ( "".equals( txt ) ) { return; } if ( needNewParagraph( txt ) ) { writer.closeTag( "w:p" ); startParagraph( style, isInline, paragraphWidth ); return; } openHyperlink( info ); boolean isField = WordUtil.isField( type ); String direction = style.getDirection( ); if ( isField ) { writeField( true, style, fontFamily ); } writer.openTag( "w:r" ); writer.openTag( "w:rPr" ); writeRunProperties( style, fontFamily, info ); if ( isInline ) { writeAlign( style.getTextAlign( ), direction ); writeBackgroundColor( style.getBackgroundColor( ) ); writePosition( style.getVerticalAlign( ), style .getProperty( StyleConstants.STYLE_FONT_SIZE ) ); writeRunBorders( style ); } if ( !isField && runIsRtl ) { writer.openTag( "w:rtl" ); writer.closeTag( "w:rtl" ); } writer.closeTag( "w:rPr" ); if ( isField ) { writeAutoText( type ); } else { writeString( txt, style ); } writer.closeTag( "w:r" ); if ( isField ) { writeField( false, style, fontFamily ); } closeHyperlink( info ); } private void writePosition( String verticalAlign, CSSValue fontSize ) { int size = WordUtil.parseFontSize( PropertyUtil .getDimensionValue( fontSize ) ); if ( "top".equalsIgnoreCase( verticalAlign ) ) { writeAttrTag( "w:position", (int) ( size * 1 / 3 ) ); } else if ( "bottom".equalsIgnoreCase( verticalAlign ) ) { writeAttrTag( "w:position", (int) ( -size * 1 / 3 ) ); } } protected void writeRunProperties( IStyle style, String fontFamily, HyperlinkInfo info ) { writeHyperlinkStyle( info, style ); writeFont( fontFamily ); writeFontSize( style ); writeLetterSpacing( style ); writeTextLineThrough( style ); writeFontStyle( style ); writeFontWeight( style ); } protected void writeFieldRunProperties( IStyle style, String fontFamily ) { writeFont( fontFamily ); writeFontSize( style ); writeLetterSpacing( style ); writeTextLineThrough( style ); writeFontStyle( style ); writeFontWeight( style ); } private void writeTextColor( IStyle style ) { String val = WordUtil.parseColor( style.getColor( ) ); if ( val != null ) { writeAttrTag( "w:color", val ); } } private void writeTextUnderline( IStyle style ) { String val = WordUtil.removeQuote( style.getTextUnderline( ) ); if ( !"none".equalsIgnoreCase( val ) ) { writeAttrTag( "w:u", "single" ); } } private void writeTextLineThrough( IStyle style ) { String val = WordUtil.removeQuote( style.getTextLineThrough( ) ); if ( !"none".equalsIgnoreCase( val ) ) { writeAttrTag( "w:strike", "on" ); } } protected void startHeaderFooterContainer( int headerHeight, int headerWidth ) { startHeaderFooterContainer( headerHeight, headerWidth, false ); } protected void startHeaderFooterContainer( int headerHeight, int headerWidth, boolean writeColumns ) { // the tableGrid in DOC has a 0.19cm cell margin by default on left and right. // so the header or footer width should be 2*0.19cm larger. that is 215.433 twips. headerWidth += 215; writer.openTag( "w:tbl" ); writer.openTag( "w:tblPr" ); writeTableWidth( headerWidth ); writeAttrTag( "w:tblLook", "01E0" ); writeTableLayout( ); writer.closeTag( "w:tblPr" ); if ( writeColumns ) { writeColumn( new int[]{headerWidth} ); } writer.openTag( "w:tr" ); // write the row height, unit: twips writer.openTag( "w:trPr" ); writeAttrTag( "w:trHeight", headerHeight ); writer.closeTag( "w:trPr" ); writer.openTag( "w:tc" ); writer.openTag( "w:tcPr" ); writeCellWidth( headerWidth ); writer.closeTag( "w:tcPr" ); } protected void endHeaderFooterContainer( ) { insertEmptyParagraph( ); writer.closeTag( "w:tc" ); writer.closeTag( "w:tr" ); writer.closeTag( "w:tbl" ); } public void drawDiagonalLine( DiagonalLineInfo diagonalLineInfo ) { if ( diagonalLineInfo.getDiagonalNumber( ) <= 0 && diagonalLineInfo.getAntiDiagonalNumber( ) <= 0 ) return; writer.openTag( "w:p" ); writer.openTag( "w:r" ); writer.openTag( "w:pict" ); double diagonalLineWidth = diagonalLineInfo.getDiagonalLineWidth( ); String diagonalLineStyle = diagonalLineInfo.getDiagonalStyle( ); double antidiagonalLineWidth = diagonalLineInfo .getAntiDiagonalLineWidth( ); String antidiagonalLineStyle = diagonalLineInfo.getAntiDiagonalStyle( ); String lineColor = diagonalLineInfo.getColor( ); for ( Line line : diagonalLineInfo .getDiagonalLine( ) ) { drawLine( diagonalLineWidth, diagonalLineStyle, lineColor, line ); } for ( Line antiLine : diagonalLineInfo .getAntidiagonalLine( ) ) { drawLine( antidiagonalLineWidth, antidiagonalLineStyle, lineColor, antiLine ); } writer.closeTag( "w:pict" ); writer.closeTag( "w:r" ); writer.closeTag( "w:p" ); } private void drawLine( double width, String style, String color, Line line ) { writer.openTag( "v:line" ); writer.attribute( "id", "Line" + getLineId( ) ); writer.attribute( "style", "position:absolute;left:0;text-align:left;z-index:1" ); writer.attribute( "from", line.getXCoordinateFrom( ) + "pt," + line.getYCoordinateFrom( ) + "pt" ); writer.attribute( "to", line.getXCoordinateTo( ) + "pt," + line.getYCoordinateTo( ) + "pt" ); writer.attribute( "strokeweight", width + "pt" ); writer.attribute( "strokecolor", "#" + color ); writer.openTag( "v:stroke" ); writer.attribute( "dashstyle", WordUtil.parseLineStyle( style ) ); writer.closeTag( "v:stroke" ); writer.closeTag( "v:line" ); } private int getLineId( ) { return lineId++; } }
Fixed Paragraph symbol automatically added with Time New Roman fonts 48330
engine/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/writer/AbstractWordXmlWriter.java
Fixed Paragraph symbol automatically added with Time New Roman fonts 48330
<ide><path>ngine/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/writer/AbstractWordXmlWriter.java <ide> writeIndent( indent ); <ide> } <ide> writeBidi( CSSConstants.CSS_RTL_VALUE.equals( style.getDirection( ) ) ); // bidi_hcg <del> <add> // We need to apply the text font style to the paragraph. It is useful <add> // if the end user want to paste some text into this paragraph and <add> // changes the text to the paragraph's font style. <add> writer.openTag( "w:rPr" ); <add> writeRunProperties( style, fontFamily, info ); <add> writer.closeTag( "w:rPr" ); <ide> writer.closeTag( "w:pPr" ); <ide> writeTextInRun( type, txt, style, fontFamily, info, false, <ide> paragraphWidth, runIsRtl );
Java
mpl-2.0
7c64beeae67bd59d2809f1bd45561dc58450d167
0
openelisglobal/openelisglobal-core,CalebSLane/openelisglobal-core,pfschwartz/openelisglobal-core,phassoa/openelisglobal-core,pfschwartz/openelisglobal-core,pfschwartz/openelisglobal-core,pfschwartz/openelisglobal-core,pfschwartz/openelisglobal-core,phassoa/openelisglobal-core,openelisglobal/openelisglobal-core,openelisglobal/openelisglobal-core,openelisglobal/openelisglobal-core,phassoa/openelisglobal-core,CalebSLane/openelisglobal-core,openelisglobal/openelisglobal-core,CalebSLane/openelisglobal-core,CalebSLane/openelisglobal-core,CalebSLane/openelisglobal-core,phassoa/openelisglobal-core,phassoa/openelisglobal-core
/** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * 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. * * The Original Code is OpenELIS code. * * Copyright (C) The Minnesota Department of Health. All Rights Reserved. * * Contributor(s): CIRG, University of Washington, Seattle WA. */ package us.mn.state.health.lims.common.util; import org.apache.commons.validator.GenericValidator; import us.mn.state.health.lims.common.exception.LIMSRuntimeException; import us.mn.state.health.lims.common.log.LogEvent; import us.mn.state.health.lims.common.util.ConfigurationProperties.Property; import us.mn.state.health.lims.common.util.resources.ResourceLocator; import java.util.*; import java.util.regex.Pattern; /** * @author diane benz * * To change this generated comment edit the template variable * "typecomment": Window>Preferences>Java>Templates. To enable and * disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class StringUtil { private static final String COMMA = ","; private static final Character CHAR_COMA = ','; private static final Character CHAR_TIDDLE = '~'; private static final String TIDDLE = "~"; private static final String QUOTE = "\""; private static String STRING_KEY_SUFFIX = null; private static Pattern INTEGER_REG_EX = Pattern.compile("^-?\\d+$"); // private static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); /** * bugzilla 2311 request parameter values coming back as string "null" when * checked for isNullorNill in an Action class need to return true */ public static boolean isNullorNill(String string) { if (string == null || string.equals("") || string.equals("null")) { return true; } return false; } /** * Search for tags in a String with oldValue tags and replace the tag with * the newValue text. * * @param input * @param oldValue * @param newValue * @return String of the text after replacement is completed */ public static String replace(String input, String oldValue, String newValue) { StringBuffer retValue = new StringBuffer(); String retString = null; if (input != null) { // Set up work string. (Extra space is so substring will work // without // extra coding when a oldValue label appears at the very end.) String workValue = input + " "; int pos = 0; int pos_end = 0; // Loop through the original text while there are still oldValue // tags // to be processed. pos = workValue.indexOf(oldValue); while (pos >= 0) { // If the tag is not the first character take all the text up to // the tag and append it to the new value. if (pos > 0) { retValue.append(workValue.substring(0, pos)); } // Find the closing marker for the tag pos_end = pos + (oldValue.length() - 1); // Put in the new value retValue.append(newValue); // Truncate the translated text off the front of the string and // continue workValue = workValue.substring(pos_end + 1); pos = workValue.indexOf(oldValue); } // Now append any remaining text in the work string. retValue.append(workValue); retString = retValue.toString().trim(); } return retString; } public static String replaceNullWithEmptyString(String in) { return in == null ? " " : in; } public static String[] toArray(String str) { String retArr[]; if (null == str) { retArr = new String[0]; } else { StringTokenizer tokenizer = new StringTokenizer(str, COMMA); retArr = new String[tokenizer.countTokens()]; // String token; int idx = 0; while (tokenizer.hasMoreTokens()) { retArr[idx] = tokenizer.nextToken().trim(); idx++; } } return retArr; } public static String[] toArray(String str, String delimiter) { String retArr[]; if (null == str) { retArr = new String[0]; } else { StringTokenizer tokenizer = new StringTokenizer(str, delimiter); retArr = new String[tokenizer.countTokens()]; // String token; int idx = 0; while (tokenizer.hasMoreTokens()) { retArr[idx] = tokenizer.nextToken().trim(); idx++; } } return retArr; } // from format (999)999-9999 and ext to 999/999-9999.ext public static String formatPhone(String phone, String ext) throws LIMSRuntimeException { String returnPhone = null; if (phone != null) { try { String area = phone.substring(1, 4); String pre = phone.substring(5, 8); String post = phone.substring(9, 13); returnPhone = area + "/" + pre + "-" + post; } catch (Exception e) { LogEvent.logError("StringUtil", "formatPhone()", e.toString()); } } if (!StringUtil.isNullorNill(ext)) { returnPhone = returnPhone + "." + ext; } // System.out.println("This is phone " + returnPhone); return returnPhone; } // from format 999/999-9999.ext to (999)999-9999 public static String formatPhoneForDisplay(String phone) throws LIMSRuntimeException { String returnPhone = null; if (phone != null) { try { String area = phone.substring(0, 3); String pre = phone.substring(4, 7); String post = phone.substring(8, 12); returnPhone = "(" + area + ")" + pre + "-" + post; } catch (Exception e) { LogEvent.logError("StringUtil", "formatPhoneForDisplay()", e.toString()); } } return returnPhone; } // from format 999/999-9999.ext to ext public static String formatExtensionForDisplay(String phone) throws LIMSRuntimeException { String returnPhone = null; if (phone != null) { try { String ext = phone.substring(13); returnPhone = ext; } catch (Exception e) { LogEvent.logError("StringUtil", "formatExtensionForDisplay()", e.toString()); } } return returnPhone; } // Returns true if string s is blank from position p to the end. public static boolean isRestOfStringBlank(String s, int p) { while (p < s.length() && Character.isWhitespace(s.charAt(p))) { p++; } return p >= s.length(); } public static String convertStringToRegEx(String str) throws LIMSRuntimeException { try { String strArr[] = str.split(""); StringBuffer sb = new StringBuffer(); // discard first token for (int i = 1; i < strArr.length; i++) { sb.append("\\" + strArr[i]); } return sb.toString(); } catch (Exception e) { LogEvent.logError("StringUtil", "convertStringToRegEx()", e.toString()); throw new LIMSRuntimeException("Error converting string to regular expression ", e); } } public static String trim(String obj) throws LIMSRuntimeException { try { if (obj != null) { return obj.trim(); } return ""; } catch (Exception e) { LogEvent.logError("StringUtil", "trim()", e.toString()); throw new LIMSRuntimeException("Error trimming string ", e); } } @SuppressWarnings({ "unchecked", "rawtypes" }) public static List loadListFromStringOfElements(String str, String textSeparator, boolean validate) throws Exception { List list = new ArrayList(); String arr[] = str.split(textSeparator); for (int i = 0; i < arr.length; i++) { String element = arr[i]; element = element.trim(); if (validate && StringUtil.isNullorNill(element)) { throw new Exception("empty data"); } list.add(element.trim()); } return list; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static List createChunksOfText(String text, int maxWidth, boolean observeSpaces) throws Exception { List list = new ArrayList(); int indx = -1; while (text != null && text.length() > 0) { if (text.length() <= maxWidth) { list.add(text); text = ""; } else { if (observeSpaces) { indx = text.indexOf(" ", maxWidth); if (indx >= 0) { list.add(text.substring(0, indx)); text = text.substring(indx); } else { list.add(text); text = ""; } } else { list.add(text.substring(0, maxWidth)); text = text.substring(maxWidth); } } } return list; } public static String getMessageForKey(String messageKey) { if (null == messageKey) { return null; } String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); return ResourceLocator.getInstance().getMessageResources().getMessage(new Locale(locale), messageKey); } public static String getMessageForKeyAndLocale(String messageKey, Locale locale) { if (null == messageKey) { return null; } return ResourceLocator.getInstance().getMessageResources().getMessage(locale, messageKey); } public static String getMessageForKeyAndLocale(String messageKey, String arg0, String arg1, Locale locale) { if (null == messageKey) { return null; } return ResourceLocator.getInstance().getMessageResources().getMessage(locale, messageKey, arg0, arg1); } public static String getMessageForKey(String messageKey, String arg) { if (null == messageKey) { return null; } String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); return ResourceLocator.getInstance().getMessageResources().getMessage(new Locale(locale), messageKey, arg); } public static String getMessageForKey(String messageKey, String arg0, String arg1) { if (null == messageKey) { return null; } String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); return ResourceLocator.getInstance().getMessageResources().getMessage(new Locale(locale), messageKey, arg0, arg1); } public static String getContextualMessageForKey(String messageKey) { if (null == messageKey) { return null; } // Note that if there is no suffix then the suffix key will be the same // as the message key // and the first search will be successful, there is no reason to test // for the suffix String suffixedKey = messageKey + getSuffix(); String suffixedValue = getMessageForKey(suffixedKey); if (!GenericValidator.isBlankOrNull(suffixedValue)) { return suffixedValue; } else { return getMessageForKey(messageKey); } } private static String getSuffix() { if (STRING_KEY_SUFFIX == null) { STRING_KEY_SUFFIX = ConfigurationProperties.getInstance().getPropertyValue(Property.StringContext); if (!GenericValidator.isBlankOrNull(STRING_KEY_SUFFIX)) { STRING_KEY_SUFFIX = "." + STRING_KEY_SUFFIX.trim(); } } return STRING_KEY_SUFFIX; } public static String getContextualKeyForKey(String key) { if (null == key) { return null; } // Note that if there is no suffix then the suffix key will be the same // as the message key // and the first search will be successful, there is no reason to test // for the suffix String suffixedKey = key + getSuffix(); String suffixedValue = getMessageForKey(suffixedKey); return GenericValidator.isBlankOrNull(suffixedValue) ? key : suffixedKey; } /* * No bounds checking for size */ public static boolean isInteger(String result) { return INTEGER_REG_EX.matcher(result).matches(); } public static boolean textInCommaSeperatedValues(String target, String csv) { if (!GenericValidator.isBlankOrNull(csv)) { String[] seperatedText = csv.split(COMMA); for (String text : seperatedText) { if (text.trim().equals(target)) { return true; } } } return false; } /** * Limit the chars in a string to the simple Java identifiers, A-Z, a-z, $, * _ etc. code taken from * http://www.exampledepot.com/egs/java.lang/IsJavaId.html * * @see Character#isJavaIdentifierPart(char) etc. for details. * @param s * - some string to test * @return True => all is well */ public static boolean isJavaIdentifier(String s) { if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < s.length(); i++) { if (!Character.isJavaIdentifierPart(s.charAt(i))) { return false; } } return true; } /** * A realy dumb CSV column value escaper. It deals with imbedded commas and * double quotes, that is all. Commas means the string needs quotes around * it. Including a quote means we need to double up that character for * Excell. */ public static String escapeCSVValue(String original) { // quotes StringBuilder out = new StringBuilder(); if (GenericValidator.isBlankOrNull(original) || !original.contains(QUOTE) && !original.contains(COMMA)) { return original; } out.append(QUOTE); for (int i = 0; i < original.length(); i++) { Character c = original.charAt(i); if (c == '"') { out.append('"'); } out.append(c); } out.append(QUOTE); return out.toString(); } /** * Solves the problem of how to deal with commas within quoted strings for csv. I couldn't figure out a regex that would cover * it so we're doing it the hard way. It will stumble if '~' is embedded in the string. This will fail on mixed fields such as * 1,2,"something, else", 4,5 * */ public static String[] separateCSVWithEmbededQuotes(String line){ String[] breakOnQuotes = line.split(QUOTE); StringBuffer substitutedString = new StringBuffer(); for( String subString : breakOnQuotes){ if(subString.startsWith(COMMA)){ substitutedString.append( subString.replace(CHAR_COMA, CHAR_TIDDLE)); }else{ substitutedString.append(QUOTE); substitutedString.append(subString); substitutedString.append(QUOTE); } } return substitutedString.toString().split(TIDDLE); } /** * Similar to separateCSVWithEmbededQuotes(String line) but deals with mixed fields * i.e. 1,2,"something, else", 4,5 , "more of that thing", 8 * * */ public static String[] separateCSVWithMixedEmbededQuotes(String line){ String[] breakOnQuotes = line.split(QUOTE); StringBuffer substitutedString = new StringBuffer(); for( String subString : breakOnQuotes){ if(subString.startsWith(COMMA) || subString.endsWith(COMMA)){ substitutedString.append( subString.replace(CHAR_COMA, CHAR_TIDDLE)); }else{ substitutedString.append(QUOTE); substitutedString.append(subString); substitutedString.append(QUOTE); } } return substitutedString.toString().split(TIDDLE); } /** * Compare two strings returning the appropriate -1,0,1; but deal with * possible null strings which will compare the same as "", aka before any * other string. * * @author pahill * @param left * @param right * @return -1 if left is lexically less then right; 0 if they are equal; 1 * if left is lexically greater than right. */ public static int compareWithNulls(String left, String right) { if (left == null) { left = ""; } if (right == null) { right = ""; } return left.compareTo(right); } /** * Tests for equals without worrying about null. If they are both null they are equal * * * @param left * @param right * @return */ public static boolean safeEquals(String left, String right) { if( left == right){ return true; } if (left == null) { left = ""; } if (right == null) { right = ""; } return left.equals(right); } public static String replaceAllChars(String text, char replacement) { if (text == null) { return null; } StringBuilder boringString = new StringBuilder(); for (int i = 0; i < text.length(); i++) { boringString.append(replacement); } return boringString.toString(); } public static boolean containsOnly(String text, char target) { if (text == null) { return false; } for (int i = 0; i < text.length(); i++) { if (text.charAt(i) != target) { return false; } } return true; } public static String strip(String string, String toBeRemoved){ if( string.contains(toBeRemoved)){ String[] subStrings = string.trim().split(toBeRemoved); StringBuffer reconstituted = new StringBuffer(); for( String subString : subStrings){ reconstituted.append( subString ); } return reconstituted.toString(); }else{ return string; } } public static String blankIfNull(String string) { return string == null ? "" : string; } public static String ellipsisString( String text, int ellipsisAt){ if( text.length() > ellipsisAt){ return text.substring(0, ellipsisAt) + "..."; }else{ return text; } } public static String join(Collection<String> collection, String separator){ String constructed = ""; if( collection.isEmpty()){ return constructed; } for (String item : collection) { constructed += item + separator; } return constructed.substring(0, constructed.length() - separator.length()); } public static String replaceTail(String value, String tail){ return value.substring(0, value.length() - tail.length() ) + tail; } public static String doubleWithSignificantDigits( double value, String significantDigits ){ if( GenericValidator.isBlankOrNull(significantDigits) || significantDigits.equals( "-1" )){ return String.valueOf( value ); } String format = "%1$." + significantDigits + "f"; return String.format(format, value); } public static String doubleWithSignificantDigits( double value, int significantDigits ){ String format = "%1$." + significantDigits + "f"; return String.format(format, value); } /** * Builds a delimited String from a list of values * * @param values A list of Strings to be concatenated * @param delimiter * @param dropBlanksAndNulls If true then keep blank and null Strings out of the list * @return String */ public static String buildDelimitedStringFromList(List<String> values, String delimiter, boolean dropBlanksAndNulls) { String delimitedString = ""; if (values == null || values.isEmpty()) return ""; int cnt = 0; for (String s : values) { if (GenericValidator.isBlankOrNull(s) && dropBlanksAndNulls) { continue; } else if (GenericValidator.isBlankOrNull(s) && !dropBlanksAndNulls) { s = ""; } if (cnt == 0) { delimitedString = s; cnt++; } else { delimitedString = delimitedString + delimiter + s; cnt++; } } return delimitedString; } }
app/src/us/mn/state/health/lims/common/util/StringUtil.java
/** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * 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. * * The Original Code is OpenELIS code. * * Copyright (C) The Minnesota Department of Health. All Rights Reserved. * * Contributor(s): CIRG, University of Washington, Seattle WA. */ package us.mn.state.health.lims.common.util; import org.apache.commons.validator.GenericValidator; import us.mn.state.health.lims.common.exception.LIMSRuntimeException; import us.mn.state.health.lims.common.log.LogEvent; import us.mn.state.health.lims.common.util.ConfigurationProperties.Property; import us.mn.state.health.lims.common.util.resources.ResourceLocator; import java.util.*; import java.util.regex.Pattern; /** * @author diane benz * * To change this generated comment edit the template variable * "typecomment": Window>Preferences>Java>Templates. To enable and * disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class StringUtil { private static final String COMMA = ","; private static final Character CHAR_COMA = ','; private static final Character CHAR_TIDDLE = '~'; private static final String TIDDLE = "~"; private static final String QUOTE = "\""; private static String STRING_KEY_SUFFIX = null; private static Pattern INTEGER_REG_EX = Pattern.compile("^-?\\d+$"); // private static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); /** * bugzilla 2311 request parameter values coming back as string "null" when * checked for isNullorNill in an Action class need to return true */ public static boolean isNullorNill(String string) { if (string == null || string.equals("") || string.equals("null")) { return true; } return false; } /** * Search for tags in a String with oldValue tags and replace the tag with * the newValue text. * * @param input * @param oldValue * @param newValue * @return String of the text after replacement is completed */ public static String replace(String input, String oldValue, String newValue) { StringBuffer retValue = new StringBuffer(); String retString = null; if (input != null) { // Set up work string. (Extra space is so substring will work // without // extra coding when a oldValue label appears at the very end.) String workValue = input + " "; int pos = 0; int pos_end = 0; // Loop through the original text while there are still oldValue // tags // to be processed. pos = workValue.indexOf(oldValue); while (pos >= 0) { // If the tag is not the first character take all the text up to // the tag and append it to the new value. if (pos > 0) { retValue.append(workValue.substring(0, pos)); } // Find the closing marker for the tag pos_end = pos + (oldValue.length() - 1); // Put in the new value retValue.append(newValue); // Truncate the translated text off the front of the string and // continue workValue = workValue.substring(pos_end + 1); pos = workValue.indexOf(oldValue); } // Now append any remaining text in the work string. retValue.append(workValue); retString = retValue.toString().trim(); } return retString; } public static String replaceNullWithEmptyString(String in) { return in == null ? " " : in; } public static String[] toArray(String str) { String retArr[]; if (null == str) { retArr = new String[0]; } else { StringTokenizer tokenizer = new StringTokenizer(str, COMMA); retArr = new String[tokenizer.countTokens()]; // String token; int idx = 0; while (tokenizer.hasMoreTokens()) { retArr[idx] = tokenizer.nextToken().trim(); idx++; } } return retArr; } public static String[] toArray(String str, String delimiter) { String retArr[]; if (null == str) { retArr = new String[0]; } else { StringTokenizer tokenizer = new StringTokenizer(str, delimiter); retArr = new String[tokenizer.countTokens()]; // String token; int idx = 0; while (tokenizer.hasMoreTokens()) { retArr[idx] = tokenizer.nextToken().trim(); idx++; } } return retArr; } // from format (999)999-9999 and ext to 999/999-9999.ext public static String formatPhone(String phone, String ext) throws LIMSRuntimeException { String returnPhone = null; if (phone != null) { try { String area = phone.substring(1, 4); String pre = phone.substring(5, 8); String post = phone.substring(9, 13); returnPhone = area + "/" + pre + "-" + post; } catch (Exception e) { LogEvent.logError("StringUtil", "formatPhone()", e.toString()); } } if (!StringUtil.isNullorNill(ext)) { returnPhone = returnPhone + "." + ext; } // System.out.println("This is phone " + returnPhone); return returnPhone; } // from format 999/999-9999.ext to (999)999-9999 public static String formatPhoneForDisplay(String phone) throws LIMSRuntimeException { String returnPhone = null; if (phone != null) { try { String area = phone.substring(0, 3); String pre = phone.substring(4, 7); String post = phone.substring(8, 12); returnPhone = "(" + area + ")" + pre + "-" + post; } catch (Exception e) { LogEvent.logError("StringUtil", "formatPhoneForDisplay()", e.toString()); } } return returnPhone; } // from format 999/999-9999.ext to ext public static String formatExtensionForDisplay(String phone) throws LIMSRuntimeException { String returnPhone = null; if (phone != null) { try { String ext = phone.substring(13); returnPhone = ext; } catch (Exception e) { LogEvent.logError("StringUtil", "formatExtensionForDisplay()", e.toString()); } } return returnPhone; } // Returns true if string s is blank from position p to the end. public static boolean isRestOfStringBlank(String s, int p) { while (p < s.length() && Character.isWhitespace(s.charAt(p))) { p++; } return p >= s.length(); } public static String convertStringToRegEx(String str) throws LIMSRuntimeException { try { String strArr[] = str.split(""); StringBuffer sb = new StringBuffer(); // discard first token for (int i = 1; i < strArr.length; i++) { sb.append("\\" + strArr[i]); } return sb.toString(); } catch (Exception e) { LogEvent.logError("StringUtil", "convertStringToRegEx()", e.toString()); throw new LIMSRuntimeException("Error converting string to regular expression ", e); } } public static String trim(String obj) throws LIMSRuntimeException { try { if (obj != null) { return obj.trim(); } return ""; } catch (Exception e) { LogEvent.logError("StringUtil", "trim()", e.toString()); throw new LIMSRuntimeException("Error trimming string ", e); } } @SuppressWarnings({ "unchecked", "rawtypes" }) public static List loadListFromStringOfElements(String str, String textSeparator, boolean validate) throws Exception { List list = new ArrayList(); String arr[] = str.split(textSeparator); for (int i = 0; i < arr.length; i++) { String element = arr[i]; element = element.trim(); if (validate && StringUtil.isNullorNill(element)) { throw new Exception("empty data"); } list.add(element.trim()); } return list; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static List createChunksOfText(String text, int maxWidth, boolean observeSpaces) throws Exception { List list = new ArrayList(); int indx = -1; while (text != null && text.length() > 0) { if (text.length() <= maxWidth) { list.add(text); text = ""; } else { if (observeSpaces) { indx = text.indexOf(" ", maxWidth); if (indx >= 0) { list.add(text.substring(0, indx)); text = text.substring(indx); } else { list.add(text); text = ""; } } else { list.add(text.substring(0, maxWidth)); text = text.substring(maxWidth); } } } return list; } public static String getMessageForKey(String messageKey) { if (null == messageKey) { return null; } String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); return ResourceLocator.getInstance().getMessageResources().getMessage(new Locale(locale), messageKey); } public static String getMessageForKeyAndLocale(String messageKey, Locale locale) { if (null == messageKey) { return null; } return ResourceLocator.getInstance().getMessageResources().getMessage(locale, messageKey); } public static String getMessageForKeyAndLocale(String messageKey, String arg0, String arg1, Locale locale) { if (null == messageKey) { return null; } return ResourceLocator.getInstance().getMessageResources().getMessage(locale, messageKey, arg0, arg1); } public static String getMessageForKey(String messageKey, String arg) { if (null == messageKey) { return null; } String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); return ResourceLocator.getInstance().getMessageResources().getMessage(new Locale(locale), messageKey, arg); } public static String getMessageForKey(String messageKey, String arg0, String arg1) { if (null == messageKey) { return null; } String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); return ResourceLocator.getInstance().getMessageResources().getMessage(new Locale(locale), messageKey, arg0, arg1); } public static String getContextualMessageForKey(String messageKey) { if (null == messageKey) { return null; } // Note that if there is no suffix then the suffix key will be the same // as the message key // and the first search will be successful, there is no reason to test // for the suffix String suffixedKey = messageKey + getSuffix(); String suffixedValue = getMessageForKey(suffixedKey); if (!GenericValidator.isBlankOrNull(suffixedValue)) { return suffixedValue; } else { return getMessageForKey(messageKey); } } private static String getSuffix() { if (STRING_KEY_SUFFIX == null) { STRING_KEY_SUFFIX = ConfigurationProperties.getInstance().getPropertyValue(Property.StringContext); if (!GenericValidator.isBlankOrNull(STRING_KEY_SUFFIX)) { STRING_KEY_SUFFIX = "." + STRING_KEY_SUFFIX.trim(); } } return STRING_KEY_SUFFIX; } public static String getContextualKeyForKey(String key) { if (null == key) { return null; } // Note that if there is no suffix then the suffix key will be the same // as the message key // and the first search will be successful, there is no reason to test // for the suffix String suffixedKey = key + getSuffix(); String suffixedValue = getMessageForKey(suffixedKey); return GenericValidator.isBlankOrNull(suffixedValue) ? key : suffixedKey; } /* * No bounds checking for size */ public static boolean isInteger(String result) { return INTEGER_REG_EX.matcher(result).matches(); } public static boolean textInCommaSeperatedValues(String target, String csv) { if (!GenericValidator.isBlankOrNull(csv)) { String[] seperatedText = csv.split(COMMA); for (String text : seperatedText) { if (text.trim().equals(target)) { return true; } } } return false; } /** * Limit the chars in a string to the simple Java identifiers, A-Z, a-z, $, * _ etc. code taken from * http://www.exampledepot.com/egs/java.lang/IsJavaId.html * * @see Character#isJavaIdentifierPart(char) etc. for details. * @param s * - some string to test * @return True => all is well */ public static boolean isJavaIdentifier(String s) { if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < s.length(); i++) { if (!Character.isJavaIdentifierPart(s.charAt(i))) { return false; } } return true; } /** * A realy dumb CSV column value escaper. It deals with imbedded commas and * double quotes, that is all. Commas means the string needs quotes around * it. Including a quote means we need to double up that character for * Excell. */ public static String escapeCSVValue(String original) { // quotes StringBuilder out = new StringBuilder(); if (GenericValidator.isBlankOrNull(original) || !original.contains(QUOTE) && !original.contains(COMMA)) { return original; } out.append(QUOTE); for (int i = 0; i < original.length(); i++) { Character c = original.charAt(i); if (c == '"') { out.append('"'); } out.append(c); } out.append(QUOTE); return out.toString(); } /** * Solves the problem of how to deal with commas within quoted strings for csv. I couldn't figure out a regex that would cover * it so we're doing it the hard way. It will stumble if '~' is embedded in the string. This will fail on mixed fields such as * 1,2,"something, else", 4,5 * */ public static String[] separateCSVWithEmbededQuotes(String line){ String[] breakOnQuotes = line.split(QUOTE); StringBuffer substitutedString = new StringBuffer(); for( String subString : breakOnQuotes){ if(subString.startsWith(COMMA)){ substitutedString.append( subString.replace(CHAR_COMA, CHAR_TIDDLE)); }else{ substitutedString.append(QUOTE); substitutedString.append(subString); substitutedString.append(QUOTE); } } return substitutedString.toString().split(TIDDLE); } /** * Similar to separateCSVWithEmbededQuotes(String line) but deals with mixed fields * i.e. 1,2,"something, else", 4,5 , "more of that thing", 8 * * */ public static String[] separateCSVWithMixedEmbededQuotes(String line){ String[] breakOnQuotes = line.split(QUOTE); StringBuffer substitutedString = new StringBuffer(); for( String subString : breakOnQuotes){ if(subString.startsWith(COMMA) || subString.endsWith(COMMA)){ substitutedString.append( subString.replace(CHAR_COMA, CHAR_TIDDLE)); }else{ substitutedString.append(QUOTE); substitutedString.append(subString); substitutedString.append(QUOTE); } } return substitutedString.toString().split(TIDDLE); } /** * Compare two strings returning the appropriate -1,0,1; but deal with * possible null strings which will compare the same as "", aka before any * other string. * * @author pahill * @param left * @param right * @return -1 if left is lexically less then right; 0 if they are equal; 1 * if left is lexically greater than right. */ public static int compareWithNulls(String left, String right) { if (left == null) { left = ""; } if (right == null) { right = ""; } return left.compareTo(right); } /** * Tests for equals without worrying about null. If they are both null they are equal * * * @param left * @param right * @return */ public static boolean safeEquals(String left, String right) { if( left == right){ return true; } if (left == null) { left = ""; } if (right == null) { right = ""; } return left.equals(right); } public static String replaceAllChars(String text, char replacement) { if (text == null) { return null; } StringBuilder boringString = new StringBuilder(); for (int i = 0; i < text.length(); i++) { boringString.append(replacement); } return boringString.toString(); } public static boolean containsOnly(String text, char target) { if (text == null) { return false; } for (int i = 0; i < text.length(); i++) { if (text.charAt(i) != target) { return false; } } return true; } public static String strip(String string, String toBeRemoved){ if( string.contains(toBeRemoved)){ String[] subStrings = string.trim().split(toBeRemoved); StringBuffer reconstituted = new StringBuffer(); for( String subString : subStrings){ reconstituted.append( subString ); } return reconstituted.toString(); }else{ return string; } } public static String blankIfNull(String string) { return string == null ? "" : string; } public static String ellipsisString( String text, int ellipsisAt){ if( text.length() > ellipsisAt){ return text.substring(0, ellipsisAt) + "..."; }else{ return text; } } public static String join(Collection<String> collection, String separator){ String constructed = ""; if( collection.isEmpty()){ return constructed; } for (String item : collection) { constructed += item + separator; } return constructed.substring(0, constructed.length() - separator.length()); } public static String replaceTail(String value, String tail){ return value.substring(0, value.length() - tail.length() ) + tail; } public static String doubleWithSignificantDigits( double value, String significantDigits ){ if( significantDigits.equals( "-1" )){ return String.valueOf( value ); } String format = "%1$." + significantDigits + "f"; return String.format(format, value); } public static String doubleWithSignificantDigits( double value, int significantDigits ){ String format = "%1$." + significantDigits + "f"; return String.format(format, value); } /** * Builds a delimited String from a list of values * * @param values A list of Strings to be concatenated * @param delimiter * @param dropBlanksAndNulls If true then keep blank and null Strings out of the list * @return String */ public static String buildDelimitedStringFromList(List<String> values, String delimiter, boolean dropBlanksAndNulls) { String delimitedString = ""; if (values == null || values.isEmpty()) return ""; int cnt = 0; for (String s : values) { if (GenericValidator.isBlankOrNull(s) && dropBlanksAndNulls) { continue; } else if (GenericValidator.isBlankOrNull(s) && !dropBlanksAndNulls) { s = ""; } if (cnt == 0) { delimitedString = s; cnt++; } else { delimitedString = delimitedString + delimiter + s; cnt++; } } return delimitedString; } }
Bug fix. Added sanity check when creating display values with significant digits
app/src/us/mn/state/health/lims/common/util/StringUtil.java
Bug fix. Added sanity check when creating display values with significant digits
<ide><path>pp/src/us/mn/state/health/lims/common/util/StringUtil.java <ide> } <ide> <ide> public static String doubleWithSignificantDigits( double value, String significantDigits ){ <del> if( significantDigits.equals( "-1" )){ <add> if( GenericValidator.isBlankOrNull(significantDigits) || significantDigits.equals( "-1" )){ <ide> return String.valueOf( value ); <ide> } <ide>
Java
apache-2.0
52a4b4b1518595784f0a94b8344a5770bd21398e
0
lpatino10/android-sdk,lpatino10/android-sdk
package com.ibm.watson.developer_cloud.android.library.camera; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore; import android.support.v4.content.CursorLoader; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; public final class GalleryHelper { private final String TAG = GalleryHelper.class.getName(); public static final int PICK_IMAGE_REQUEST = 1001; private Activity activity; /** * Provides convenience access to device gallery * @param activity */ public GalleryHelper(Activity activity) { this.activity = activity; } /** * Starts an activity to select a photo from the device's memory */ public void dispatchGalleryIntent() { Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); if (galleryIntent.resolveActivity(activity.getPackageManager()) != null) { activity.startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST); } } /** * This method returns the file of an image selected in the photo gallery. It should be called * within the onActivityResult method of an Activity. * * @param resultCode Result code of a previous activity * @param data Data returned from a previous activity * @return An image's file if successful, null otherwise */ public File getFile(int resultCode, Intent data) { if(resultCode == activity.RESULT_OK) { Uri targetUri = data.getData(); return new File(getRealPathFromURI(targetUri)); } Log.e(TAG, "Result Code was not OK"); return null; } /** * This method returns a bitmap of an image selected in the photo gallery. It should be called * within the onActivityResult method of an Activity. * * @param resultCode Result code of a previous activity * @param data Data returned from a previous activity * @return A bitmap image if successfully completed, null otherwise */ public Bitmap getBitmap(int resultCode, Intent data) { if(resultCode == activity.RESULT_OK) { Uri targetUri = data.getData(); try { return BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(targetUri)); } catch (FileNotFoundException e) { Log.e(TAG, "File Not Found", e); return null; } } Log.e(TAG, "Result Code was not OK"); return null; } /** * This method returns a path, given a content URI * * @param contentUri URI of some image * @return A string path */ public String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; CursorLoader cLoader = new CursorLoader(activity.getApplicationContext(), contentUri, proj, null, null, null); Cursor cursor = cLoader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } }
library/src/main/java/com/ibm/watson/developer_cloud/android/library/camera/GalleryHelper.java
package com.ibm.watson.developer_cloud.android.library.camera; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore; import android.support.v4.content.CursorLoader; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; public final class GalleryHelper { private final String TAG = GalleryHelper.class.getName(); public static final int PICK_IMAGE_REQUEST = 1001; private Activity activity; /** * Provides convenience access to device gallery * @param activity */ public GalleryHelper(Activity activity) { this.activity = activity; } /** * Starts an activity to select a photo from the device's memory */ public void dispatchGalleryIntent() { Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); if (galleryIntent.resolveActivity(activity.getPackageManager()) != null) { activity.startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST); } } /** * This method returns the file of an image selected in the photo gallery. It should be called * within the onActivityResult method of an Activity. * * @param resultCode Result code of a previous activity * @param data Data returned from a previous activity * @return An image's file if successful, null otherwise */ public File getFile(int resultCode, Intent data) { if(resultCode == activity.RESULT_OK) { Uri targetUri = data.getData(); //return new File(targetUri.getPath()); return new File(getRealPathFromURI(targetUri)); } Log.e(TAG, "Result Code was not OK"); return null; } /** * This method returns a bitmap of an image selected in the photo gallery. It should be called * within the onActivityResult method of an Activity. * * @param resultCode Result code of a previous activity * @param data Data returned from a previous activity * @return A bitmap image if successfully completed, null otherwise */ public Bitmap getBitmap(int resultCode, Intent data) { if(resultCode == activity.RESULT_OK) { Uri targetUri = data.getData(); try { return BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(targetUri)); } catch (FileNotFoundException e) { Log.e(TAG, "File Not Found", e); return null; } } Log.e(TAG, "Result Code was not OK"); return null; } /** * This method returns a path, given a content URI * * @param contentUri URI of some image * @return A string path */ public String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; CursorLoader cLoader = new CursorLoader(activity.getApplicationContext(), contentUri, proj, null, null, null); Cursor cursor = cLoader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } }
Remove unnecessary comments
library/src/main/java/com/ibm/watson/developer_cloud/android/library/camera/GalleryHelper.java
Remove unnecessary comments
<ide><path>ibrary/src/main/java/com/ibm/watson/developer_cloud/android/library/camera/GalleryHelper.java <ide> public File getFile(int resultCode, Intent data) { <ide> if(resultCode == activity.RESULT_OK) { <ide> Uri targetUri = data.getData(); <del> //return new File(targetUri.getPath()); <ide> return new File(getRealPathFromURI(targetUri)); <ide> } <ide> Log.e(TAG, "Result Code was not OK");
Java
apache-2.0
80ebffe518a5149f5eb788806798f9a3610fe09d
0
apache/jackrabbit,apache/jackrabbit,apache/jackrabbit
/* * Copyright 2004-2005 The Apache Software Foundation or its licensors, * as applicable. * * 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.apache.jackrabbit.util; import java.io.UnsupportedEncodingException; import java.io.ByteArrayOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.BitSet; /** * This Class provides some text related utilities */ public class Text { /** * Hidden constructor. */ private Text() { } /** * used for the md5 */ public static final char[] hexTable = "0123456789abcdef".toCharArray(); /** * Calculate an MD5 hash of the string given. * * @param data the data to encode * @param enc the character encoding to use * @return a hex encoded string of the md5 digested input */ public static String md5(String data, String enc) throws UnsupportedEncodingException { try { return digest("MD5", data.getBytes(enc)); } catch (NoSuchAlgorithmException e) { throw new InternalError("MD5 digest not available???"); } } /** * Calculate an MD5 hash of the string given using 'utf-8' encoding. * * @param data the data to encode * @return a hex encoded string of the md5 digested input */ public static String md5(String data) { try { return md5(data, "utf-8"); } catch (UnsupportedEncodingException e) { throw new InternalError("UTF8 digest not available???"); } } /** * Digest the plain string using the given algorithm. * * @param algorithm The alogrithm for the digest. This algorithm must be * supported by the MessageDigest class. * @param data The plain text String to be digested. * @param enc The character encoding to use * @return The digested plain text String represented as Hex digits. * @throws java.security.NoSuchAlgorithmException if the desired algorithm is not supported by * the MessageDigest class. * @throws java.io.UnsupportedEncodingException if the encoding is not supported */ public static String digest(String algorithm, String data, String enc) throws NoSuchAlgorithmException, UnsupportedEncodingException { return digest(algorithm, data.getBytes(enc)); } /** * Digest the plain string using the given algorithm. * * @param algorithm The alogrithm for the digest. This algorithm must be * supported by the MessageDigest class. * @param data the data to digest with the given algorithm * @return The digested plain text String represented as Hex digits. * @throws java.security.NoSuchAlgorithmException if the desired algorithm is not supported by * the MessageDigest class. */ public static String digest(String algorithm, byte[] data) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(algorithm); byte[] digest = md.digest(data); StringBuffer res = new StringBuffer(digest.length * 2); for (int i = 0; i < digest.length; i++) { byte b = digest[i]; res.append(hexTable[(b >> 4) & 15]); res.append(hexTable[b & 15]); } return res.toString(); } /** * returns an array of strings decomposed of the original string, split at * every occurance of 'ch'. if 2 'ch' follow each other with no intermediate * characters, empty "" entries are avoided. * * @param str the string to decompose * @param ch the character to use a split pattern * @return an array of strings */ public static String[] explode(String str, int ch) { return explode(str, ch, false); } /** * returns an array of strings decomposed of the original string, split at * every occurance of 'ch'. * * @param str the string to decompose * @param ch the character to use a split pattern * @param respectEmpty if <code>true</code>, empty elements are generated * @return an array of strings */ public static String[] explode(String str, int ch, boolean respectEmpty) { if (str == null || str.length() == 0) { return new String[0]; } ArrayList strings = new ArrayList(); int pos; int lastpos = 0; // add snipples while ((pos = str.indexOf(ch, lastpos)) >= 0) { if (pos - lastpos > 0 || respectEmpty) { strings.add(str.substring(lastpos, pos)); } lastpos = pos + 1; } // add rest if (lastpos < str.length()) { strings.add(str.substring(lastpos)); } else if (respectEmpty && lastpos == str.length()) { strings.add(""); } // return stringarray return (String[]) strings.toArray(new String[strings.size()]); } /** * Concatenates all strings in the string array using the specified delimiter. * @param arr * @param delim * @return */ public static String implode(String[] arr, String delim) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < arr.length; i++) { if (i > 0) { buf.append(delim); } buf.append(arr[i]); } return buf.toString(); } /** * Replaces all occurences of <code>oldString</code> in <code>text</code> * with <code>newString</code>. * * @param text * @param oldString old substring to be replaced with <code>newString</code> * @param newString new substring to replace occurences of <code>oldString</code> * @return a string */ public static String replace(String text, String oldString, String newString) { if (text == null || oldString == null || newString == null) { throw new IllegalArgumentException("null argument"); } int pos = text.indexOf(oldString); if (pos == -1) { return text; } int lastPos = 0; StringBuffer sb = new StringBuffer(text.length()); while (pos != -1) { sb.append(text.substring(lastPos, pos)); sb.append(newString); lastPos = pos + oldString.length(); pos = text.indexOf(oldString, lastPos); } if (lastPos < text.length()) { sb.append(text.substring(lastPos)); } return sb.toString(); } /** * Replaces illegal XML characters in the given string by their corresponding * predefined entity references. * * @param text text to be escaped * @return a string */ public static String encodeIllegalXMLCharacters(String text) { if (text == null) { throw new IllegalArgumentException("null argument"); } StringBuffer buf = null; int length = text.length(); int pos = 0; for (int i = 0; i < length; i++) { int ch = text.charAt(i); switch (ch) { case '<': case '>': case '&': case '"': case '\'': if (buf == null) { buf = new StringBuffer(); } if (i > 0) { buf.append(text.substring(pos, i)); } pos = i + 1; break; default: continue; } if (ch == '<') { buf.append("&lt;"); } else if (ch == '>') { buf.append("&gt;"); } else if (ch == '&') { buf.append("&amp;"); } else if (ch == '"') { buf.append("&quot;"); } else if (ch == '\'') { buf.append("&apos;"); } } if (buf == null) { return text; } else { if (pos < length) { buf.append(text.substring(pos)); } return buf.toString(); } } /** * The list of characters that are not encoded by the <code>escape()</code> * and <code>unescape()</code> METHODS. They contains the characters as * defined 'unreserved' in section 2.3 of the RFC 2396 'URI genric syntax': * <p/> * <pre> * unreserved = alphanum | mark * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" * </pre> */ public static BitSet URISave; /** * Same as {@link #URISave} but also contains the '/' */ public static BitSet URISaveEx; static { URISave = new BitSet(256); int i; for (i = 'a'; i <= 'z'; i++) { URISave.set(i); } for (i = 'A'; i <= 'Z'; i++) { URISave.set(i); } for (i = '0'; i <= '9'; i++) { URISave.set(i); } URISave.set('-'); URISave.set('_'); URISave.set('.'); URISave.set('!'); URISave.set('~'); URISave.set('*'); URISave.set('\''); URISave.set('('); URISave.set(')'); URISaveEx = (BitSet) URISave.clone(); URISaveEx.set('/'); } /** * Does an URL encoding of the <code>string</code> using the * <code>escape</code> character. The characters that don't need encoding * are those defined 'unreserved' in section 2.3 of the 'URI genric syntax' * RFC 2396, but without the escape character. * * @param string the string to encode. * @param escape the escape character. * @return the escaped string * @throws NullPointerException if <code>string</code> is <code>null</code>. */ public static String escape(String string, char escape) { return escape(string, escape, false); } /** * Does an URL encoding of the <code>string</code> using the * <code>escape</code> character. The characters that don't need encoding * are those defined 'unreserved' in section 2.3 of the 'URI genric syntax' * RFC 2396, but without the escape character. If <code>isPath</code> is * <code>true</code>, additionally the slash '/' is ignored, too. * * @param string the string to encode. * @param escape the escape character. * @param isPath if <code>true</code>, the string is treated as path * @return the escaped string * @throws NullPointerException if <code>string</code> is <code>null</code>. */ public static String escape(String string, char escape, boolean isPath) { try { BitSet validChars = isPath ? URISaveEx : URISave; byte[] bytes = string.getBytes("utf-8"); StringBuffer out = new StringBuffer(bytes.length); for (int i = 0; i < bytes.length; i++) { int c = bytes[i] & 0xff; if (validChars.get(c) && c != escape) { out.append((char) c); } else { out.append(escape); out.append(hexTable[(c >> 4) & 0x0f]); out.append(hexTable[(c) & 0x0f]); } } return out.toString(); } catch (UnsupportedEncodingException e) { throw new InternalError(e.toString()); } } /** * Does a URL encoding of the <code>string</code>. The characters that * don't need encoding are those defined 'unreserved' in section 2.3 of * the 'URI genric syntax' RFC 2396. * * @param string the string to encode * @return the escaped string * @throws NullPointerException if <code>string</code> is <code>null</code>. */ public static String escape(String string) { return escape(string, '%'); } /** * Does a URL encoding of the <code>path</code>. The characters that * don't need encoding are those defined 'unreserved' in section 2.3 of * the 'URI genric syntax' RFC 2396. In contrast to the * {@link #escape(String)} method, not the entire path string is escaped, * but every individual part (i.e. the slashes are not escaped). * * @param path the path to encode * @return the escaped path * @throws NullPointerException if <code>path</code> is <code>null</code>. */ public static String escapePath(String path) { return escape(path, '%', true); } /** * Does a URL decoding of the <code>string</code> using the * <code>escape</code> character. Please note that in opposite to the * {@link java.net.URLDecoder} it does not transform the + into spaces. * * @param string the string to decode * @param escape the escape character * @return the decoded string * @throws NullPointerException if <code>string</code> is <code>null</code>. * @throws ArrayIndexOutOfBoundsException if not enough character follow an * escape character * @throws IllegalArgumentException if the 2 characters following the escape * character do not represent a hex-number. */ public static String unescape(String string, char escape) { ByteArrayOutputStream out = new ByteArrayOutputStream(string.length()); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == escape) { try { out.write(Integer.parseInt(string.substring(i + 1, i + 3), 16)); } catch (NumberFormatException e) { throw new IllegalArgumentException(); } i += 2; } else { out.write(c); } } try { return new String(out.toByteArray(), "utf-8"); } catch (UnsupportedEncodingException e) { throw new InternalError(e.toString()); } } /** * Does a URL decoding of the <code>string</code>. Please note that in * opposite to the {@link java.net.URLDecoder} it does not transform the + * into spaces. * * @param string the string to decode * @return the decoded string * @throws NullPointerException if <code>string</code> is <code>null</code>. * @throws ArrayIndexOutOfBoundsException if not enough character follow an * escape character * @throws IllegalArgumentException if the 2 characters following the escape * character do not represent a hex-number. */ public static String unescape(String string) { return unescape(string, '%'); } /** * Returns the name part of the path * * @param path the path * @return the name part */ public static String getName(String path) { int pos = path.lastIndexOf('/'); return pos >= 0 ? path.substring(pos + 1) : ""; } /** * Returns the namespace prefix of the given <code>qname</code>. If the * prefix is missing, an empty string is returned. Please note, that this * method does not validate the name or prefix. * </p> * the qname has the format: qname := [prefix ':'] local; * * @param qname a qualified name * @return the prefix of the name or "". * * @see #getLocalName(String) * * @throws NullPointerException if <code>qname</code> is <code>null</code> */ public static String getNamespacePrefix(String qname) { int pos = qname.indexOf(':'); return pos >=0 ? qname.substring(0, pos) : ""; } /** * Returns the local name of the given <code>qname</code>. Please note, that * this method does not validate the name. * </p> * the qname has the format: qname := [prefix ':'] local; * * @param qname a qualified name * @return the localname * * @see #getNamespacePrefix(String) * * @throws NullPointerException if <code>qname</code> is <code>null</code> */ public static String getLocalName(String qname) { int pos = qname.indexOf(':'); return pos >=0 ? qname.substring(pos+1) : qname; } /** * Returns the name part of the path, delimited by the given <code>delim</code> * * @param path the path * @param delim the delimiter * @return the name part */ public static String getName(String path, char delim) { int pos = path.lastIndexOf(delim); return pos >= 0 ? path.substring(pos + 1) : ""; } /** * Determines, if two paths denote hierarchical siblins. * * @param p1 first path * @param p2 second path * @return true if on same level, false otherwise */ public static boolean isSibling(String p1, String p2) { int pos1 = p1.lastIndexOf('/'); int pos2 = p2.lastIndexOf('/'); return (pos1 == pos2 && pos1 >= 0 && p1.regionMatches(0, p2, 0, pos1)); } /** * Determines if the <code>descendant</code> path is hierarchical a * descendant of <code>path</code>. * * @param path the current path * @param descendant the potential descendant * @return <code>true</code> if the <code>descendant</code> is a descendant; * <code>false</code> otherwise. */ public static boolean isDescendant(String path, String descendant) { return !path.equals(descendant) && descendant.startsWith(path) && descendant.charAt(path.length()) == '/'; } /** * Determines if the <code>descendant</code> path is hierarchical a * descendant of <code>path</code> or equal to it. * * @param path the path to check * @param descendant the potential descendant * @return <code>true</code> if the <code>descendant</code> is a descendant * or equal; <code>false</code> otherwise. */ public static boolean isDescendantOrEqual(String path, String descendant) { if (path.equals(descendant)) { return true; } else { String pattern = path.endsWith("/") ? path : path + "/"; return descendant.startsWith(pattern); } } /** * Returns the n<sup>th</sup> relative parent of the path, where n=level. * <p>Example:<br> * <code> * Text.getRelativeParent("/foo/bar/test", 1) == "/foo/bar" * </code> * * @param path the path of the page * @param level the level of the parent */ public static String getRelativeParent(String path, int level) { int idx = path.length(); while (level > 0) { idx = path.lastIndexOf('/', idx - 1); if (idx < 0) { return ""; } level--; } return (idx == 0) ? "/" : path.substring(0, idx); } /** * Returns the n<sup>th</sup> absolute parent of the path, where n=level. * <p>Example:<br> * <code> * Text.getAbsoluteParent("/foo/bar/test", 1) == "/foo/bar" * </code> * * @param path the path of the page * @param level the level of the parent */ public static String getAbsoluteParent(String path, int level) { int idx = 0; int len = path.length(); while (level >= 0 && idx < len) { idx = path.indexOf('/', idx + 1); if (idx < 0) { idx = len; } level--; } return level >= 0 ? "" : path.substring(0, idx); } }
commons/src/java/org/apache/jackrabbit/util/Text.java
/* * Copyright 2004-2005 The Apache Software Foundation or its licensors, * as applicable. * * 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.apache.jackrabbit.util; import java.io.UnsupportedEncodingException; import java.io.ByteArrayOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.BitSet; /** * This Class provides some text related utilities */ public class Text { /** * Hidden constructor. */ private Text() { } /** * used for the md5 */ public static final char[] hexTable = "0123456789abcdef".toCharArray(); /** * Calculate an MD5 hash of the string given. * * @param data the data to encode * @param enc the character encoding to use * @return a hex encoded string of the md5 digested input */ public static String md5(String data, String enc) throws UnsupportedEncodingException { try { return digest("MD5", data.getBytes(enc)); } catch (NoSuchAlgorithmException e) { throw new InternalError("MD5 digest not available???"); } } /** * Calculate an MD5 hash of the string given using 'utf-8' encoding. * * @param data the data to encode * @return a hex encoded string of the md5 digested input */ public static String md5(String data) { try { return md5(data, "utf-8"); } catch (UnsupportedEncodingException e) { throw new InternalError("UTF8 digest not available???"); } } /** * Digest the plain string using the given algorithm. * * @param algorithm The alogrithm for the digest. This algorithm must be * supported by the MessageDigest class. * @param data The plain text String to be digested. * @param enc The character encoding to use * @return The digested plain text String represented as Hex digits. * @throws java.security.NoSuchAlgorithmException if the desired algorithm is not supported by * the MessageDigest class. * @throws java.io.UnsupportedEncodingException if the encoding is not supported */ public static String digest(String algorithm, String data, String enc) throws NoSuchAlgorithmException, UnsupportedEncodingException { return digest(algorithm, data.getBytes(enc)); } /** * Digest the plain string using the given algorithm. * * @param algorithm The alogrithm for the digest. This algorithm must be * supported by the MessageDigest class. * @param data the data to digest with the given algorithm * @return The digested plain text String represented as Hex digits. * @throws java.security.NoSuchAlgorithmException if the desired algorithm is not supported by * the MessageDigest class. */ public static String digest(String algorithm, byte[] data) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(algorithm); byte[] digest = md.digest(data); StringBuffer res = new StringBuffer(digest.length * 2); for (int i = 0; i < digest.length; i++) { byte b = digest[i]; res.append(hexTable[(b >> 4) & 15]); res.append(hexTable[b & 15]); } return res.toString(); } /** * returns an array of strings decomposed of the original string, split at * every occurance of 'ch'. if 2 'ch' follow each other with no intermediate * characters, empty "" entries are avoided. * * @param str the string to decompose * @param ch the character to use a split pattern * @return an array of strings */ public static String[] explode(String str, int ch) { return explode(str, ch, false); } /** * returns an array of strings decomposed of the original string, split at * every occurance of 'ch'. * * @param str the string to decompose * @param ch the character to use a split pattern * @param respectEmpty if <code>true</code>, empty elements are generated * @return an array of strings */ public static String[] explode(String str, int ch, boolean respectEmpty) { if (str == null || str.length() == 0) { return new String[0]; } ArrayList strings = new ArrayList(); int pos; int lastpos = 0; // add snipples while ((pos = str.indexOf(ch, lastpos)) >= 0) { if (pos - lastpos > 0 || respectEmpty) { strings.add(str.substring(lastpos, pos)); } lastpos = pos + 1; } // add rest if (lastpos < str.length()) { strings.add(str.substring(lastpos)); } else if (respectEmpty && lastpos == str.length()) { strings.add(""); } // return stringarray return (String[]) strings.toArray(new String[strings.size()]); } /** * Concatenates all strings in the string array using the specified delimiter. * @param arr * @param delim * @return */ public static String implode(String[] arr, String delim) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < arr.length; i++) { if (i > 0) { buf.append(delim); } buf.append(arr[i]); } return buf.toString(); } /** * Replaces all occurences of <code>oldString</code> in <code>text</code> * with <code>newString</code>. * * @param text * @param oldString old substring to be replaced with <code>newString</code> * @param newString new substring to replace occurences of <code>oldString</code> * @return a string */ public static String replace(String text, String oldString, String newString) { if (text == null || oldString == null || newString == null) { throw new IllegalArgumentException("null argument"); } int pos = text.indexOf(oldString); if (pos == -1) { return text; } int lastPos = 0; StringBuffer sb = new StringBuffer(text.length()); while (pos != -1) { sb.append(text.substring(lastPos, pos)); sb.append(newString); lastPos = pos + oldString.length(); pos = text.indexOf(oldString, lastPos); } if (lastPos < text.length()) { sb.append(text.substring(lastPos)); } return sb.toString(); } /** * Replaces illegal XML characters in the given string by their corresponding * predefined entity references. * * @param text text to be escaped * @return a string */ public static String encodeIllegalXMLCharacters(String text) { if (text == null) { throw new IllegalArgumentException("null argument"); } StringBuffer buf = null; int length = text.length(); int pos = 0; for (int i = 0; i < length; i++) { int ch = text.charAt(i); switch (ch) { case '<': case '>': case '&': case '"': case '\'': if (buf == null) { buf = new StringBuffer(); } if (i > 0) { buf.append(text.substring(pos, i)); } pos = i + 1; break; default: continue; } if (ch == '<') { buf.append("&lt;"); } else if (ch == '>') { buf.append("&gt;"); } else if (ch == '&') { buf.append("&amp;"); } else if (ch == '"') { buf.append("&quot;"); } else if (ch == '\'') { buf.append("&apos;"); } } if (buf == null) { return text; } else { if (pos < length) { buf.append(text.substring(pos)); } return buf.toString(); } } /** * The list of characters that are not encoded by the <code>escape()</code> * and <code>unescape()</code> METHODS. They contains the characters as * defined 'unreserved' in section 2.3 of the RFC 2396 'URI genric syntax': * <p/> * <pre> * unreserved = alphanum | mark * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" * </pre> */ public static BitSet URISave; /** * Same as {@link #URISave} but also contains the '/' */ public static BitSet URISaveEx; static { URISave = new BitSet(256); int i; for (i = 'a'; i <= 'z'; i++) { URISave.set(i); } for (i = 'A'; i <= 'Z'; i++) { URISave.set(i); } for (i = '0'; i <= '9'; i++) { URISave.set(i); } URISave.set('-'); URISave.set('_'); URISave.set('.'); URISave.set('!'); URISave.set('~'); URISave.set('*'); URISave.set('\''); URISave.set('('); URISave.set(')'); URISaveEx = (BitSet) URISave.clone(); URISaveEx.set('/'); } /** * Does an URL encoding of the <code>string</code> using the * <code>escape</code> character. The characters that don't need encoding * are those defined 'unreserved' in section 2.3 of the 'URI genric syntax' * RFC 2396, but without the escape character. * * @param string the string to encode. * @param escape the escape character. * @return the escaped string * @throws NullPointerException if <code>string</code> is <code>null</code>. */ public static String escape(String string, char escape) { return escape(string, escape, false); } /** * Does an URL encoding of the <code>string</code> using the * <code>escape</code> character. The characters that don't need encoding * are those defined 'unreserved' in section 2.3 of the 'URI genric syntax' * RFC 2396, but without the escape character. If <code>isPath</code> is * <code>true</code>, additionally the slash '/' is ignored, too. * * @param string the string to encode. * @param escape the escape character. * @param isPath if <code>true</code>, the string is treated as path * @return the escaped string * @throws NullPointerException if <code>string</code> is <code>null</code>. */ public static String escape(String string, char escape, boolean isPath) { try { BitSet validChars = isPath ? URISaveEx : URISave; byte[] bytes = string.getBytes("utf-8"); StringBuffer out = new StringBuffer(bytes.length); for (int i = 0; i < bytes.length; i++) { int c = bytes[i] & 0xff; if (validChars.get(c) && c != escape) { out.append((char) c); } else { out.append(escape); out.append(hexTable[(c >> 4) & 0x0f]); out.append(hexTable[(c) & 0x0f]); } } return out.toString(); } catch (UnsupportedEncodingException e) { throw new InternalError(e.toString()); } } /** * Does a URL encoding of the <code>string</code>. The characters that * don't need encoding are those defined 'unreserved' in section 2.3 of * the 'URI genric syntax' RFC 2396. * * @param string the string to encode * @return the escaped string * @throws NullPointerException if <code>string</code> is <code>null</code>. */ public static String escape(String string) { return escape(string, '%'); } /** * Does a URL encoding of the <code>path</code>. The characters that * don't need encoding are those defined 'unreserved' in section 2.3 of * the 'URI genric syntax' RFC 2396. In contrast to the * {@link #escape(String)} method, not the entire path string is escaped, * but every individual part (i.e. the slashes are not escaped). * * @param path the path to encode * @return the escaped path * @throws NullPointerException if <code>path</code> is <code>null</code>. */ public static String escapePath(String path) { return escape(path, '%', true); } /** * Does a URL decoding of the <code>string</code> using the * <code>escape</code> character. Please note that in opposite to the * {@link java.net.URLDecoder} it does not transform the + into spaces. * * @param string the string to decode * @param escape the escape character * @return the decoded string * @throws NullPointerException if <code>string</code> is <code>null</code>. * @throws ArrayIndexOutOfBoundsException if not enough character follow an * escape character * @throws IllegalArgumentException if the 2 characters following the escape * character do not represent a hex-number. */ public static String unescape(String string, char escape) { ByteArrayOutputStream out = new ByteArrayOutputStream(string.length()); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == escape) { try { out.write(Integer.parseInt(string.substring(i + 1, i + 3), 16)); } catch (NumberFormatException e) { throw new IllegalArgumentException(); } i += 2; } else { out.write(c); } } try { return new String(out.toByteArray(), "utf-8"); } catch (UnsupportedEncodingException e) { throw new InternalError(e.toString()); } } /** * Does a URL decoding of the <code>string</code>. Please note that in * opposite to the {@link java.net.URLDecoder} it does not transform the + * into spaces. * * @param string the string to decode * @return the decoded string * @throws NullPointerException if <code>string</code> is <code>null</code>. * @throws ArrayIndexOutOfBoundsException if not enough character follow an * escape character * @throws IllegalArgumentException if the 2 characters following the escape * character do not represent a hex-number. */ public static String unescape(String string) { return unescape(string, '%'); } /** * Returns the name part of the path * * @param path the path * @return the name part */ public static String getName(String path) { int pos = path.lastIndexOf('/'); return pos >= 0 ? path.substring(pos + 1) : ""; } /** * Returns the name part of the path, delimited by the given <code>delim</code> * * @param path the path * @param delim the delimiter * @return the name part */ public static String getName(String path, char delim) { int pos = path.lastIndexOf(delim); return pos >= 0 ? path.substring(pos + 1) : ""; } /** * Determines, if two paths denote hierarchical siblins. * * @param p1 first path * @param p2 second path * @return true if on same level, false otherwise */ public static boolean isSibling(String p1, String p2) { int pos1 = p1.lastIndexOf('/'); int pos2 = p2.lastIndexOf('/'); return (pos1 == pos2 && pos1 >= 0 && p1.regionMatches(0, p2, 0, pos1)); } /** * Determines if the <code>descendant</code> path is hierarchical a * descendant of <code>path</code>. * * @param path the current path * @param descendant the potential descendant * @return <code>true</code> if the <code>descendant</code> is a descendant; * <code>false</code> otherwise. */ public static boolean isDescendant(String path, String descendant) { return !path.equals(descendant) && descendant.startsWith(path) && descendant.charAt(path.length()) == '/'; } /** * Determines if the <code>descendant</code> path is hierarchical a * descendant of <code>path</code> or equal to it. * * @param path the path to check * @param descendant the potential descendant * @return <code>true</code> if the <code>descendant</code> is a descendant * or equal; <code>false</code> otherwise. */ public static boolean isDescendantOrEqual(String path, String descendant) { if (path.equals(descendant)) { return true; } else { String pattern = path.endsWith("/") ? path : path + "/"; return descendant.startsWith(pattern); } } /** * Returns the n<sup>th</sup> relative parent of the path, where n=level. * <p>Example:<br> * <code> * Text.getRelativeParent("/foo/bar/test", 1) == "/foo/bar" * </code> * * @param path the path of the page * @param level the level of the parent */ public static String getRelativeParent(String path, int level) { int idx = path.length(); while (level > 0) { idx = path.lastIndexOf('/', idx - 1); if (idx < 0) { return ""; } level--; } return (idx == 0) ? "/" : path.substring(0, idx); } /** * Returns the n<sup>th</sup> absolute parent of the path, where n=level. * <p>Example:<br> * <code> * Text.getAbsoluteParent("/foo/bar/test", 1) == "/foo/bar" * </code> * * @param path the path of the page * @param level the level of the parent */ public static String getAbsoluteParent(String path, int level) { int idx = 0; int len = path.length(); while (level >= 0 && idx < len) { idx = path.indexOf('/', idx + 1); if (idx < 0) { idx = len; } level--; } return level >= 0 ? "" : path.substring(0, idx); } }
- adding useful namespace related methods git-svn-id: e3d4743c6b03e3f6fd6d8117e7616b4c02d9b980@220026 13f79535-47bb-0310-9956-ffa450edef68
commons/src/java/org/apache/jackrabbit/util/Text.java
- adding useful namespace related methods
<ide><path>ommons/src/java/org/apache/jackrabbit/util/Text.java <ide> } <ide> <ide> /** <add> * Returns the namespace prefix of the given <code>qname</code>. If the <add> * prefix is missing, an empty string is returned. Please note, that this <add> * method does not validate the name or prefix. <add> * </p> <add> * the qname has the format: qname := [prefix ':'] local; <add> * <add> * @param qname a qualified name <add> * @return the prefix of the name or "". <add> * <add> * @see #getLocalName(String) <add> * <add> * @throws NullPointerException if <code>qname</code> is <code>null</code> <add> */ <add> public static String getNamespacePrefix(String qname) { <add> int pos = qname.indexOf(':'); <add> return pos >=0 ? qname.substring(0, pos) : ""; <add> } <add> <add> /** <add> * Returns the local name of the given <code>qname</code>. Please note, that <add> * this method does not validate the name. <add> * </p> <add> * the qname has the format: qname := [prefix ':'] local; <add> * <add> * @param qname a qualified name <add> * @return the localname <add> * <add> * @see #getNamespacePrefix(String) <add> * <add> * @throws NullPointerException if <code>qname</code> is <code>null</code> <add> */ <add> public static String getLocalName(String qname) { <add> int pos = qname.indexOf(':'); <add> return pos >=0 ? qname.substring(pos+1) : qname; <add> } <add> <add> /** <ide> * Returns the name part of the path, delimited by the given <code>delim</code> <ide> * <ide> * @param path the path
Java
agpl-3.0
ba0aaee8523d045390d4ae40565e0c519e551285
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
f2a24a04-2e61-11e5-9284-b827eb9e62be
hello.java
f29c81dc-2e61-11e5-9284-b827eb9e62be
f2a24a04-2e61-11e5-9284-b827eb9e62be
hello.java
f2a24a04-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>f29c81dc-2e61-11e5-9284-b827eb9e62be <add>f2a24a04-2e61-11e5-9284-b827eb9e62be
Java
apache-2.0
cb9a336f2e70a4a7390e1cc16e458fd1e3639f37
0
liqianggao/BroadleafCommerce,alextiannus/BroadleafCommerce,cloudbearings/BroadleafCommerce,TouK/BroadleafCommerce,cogitoboy/BroadleafCommerce,caosg/BroadleafCommerce,macielbombonato/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,sitexa/BroadleafCommerce,passion1014/metaworks_framework,gengzhengtao/BroadleafCommerce,daniellavoie/BroadleafCommerce,cogitoboy/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,trombka/blc-tmp,wenmangbo/BroadleafCommerce,passion1014/metaworks_framework,caosg/BroadleafCommerce,sanlingdd/broadleaf,sitexa/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,wenmangbo/BroadleafCommerce,rawbenny/BroadleafCommerce,rawbenny/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cloudbearings/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,trombka/blc-tmp,lgscofield/BroadleafCommerce,lgscofield/BroadleafCommerce,trombka/blc-tmp,liqianggao/BroadleafCommerce,gengzhengtao/BroadleafCommerce,TouK/BroadleafCommerce,passion1014/metaworks_framework,shopizer/BroadleafCommerce,cloudbearings/BroadleafCommerce,daniellavoie/BroadleafCommerce,rawbenny/BroadleafCommerce,shopizer/BroadleafCommerce,gengzhengtao/BroadleafCommerce,udayinfy/BroadleafCommerce,wenmangbo/BroadleafCommerce,macielbombonato/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,arshadalisoomro/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,lgscofield/BroadleafCommerce,alextiannus/BroadleafCommerce,macielbombonato/BroadleafCommerce,sitexa/BroadleafCommerce,sanlingdd/broadleaf,alextiannus/BroadleafCommerce,shopizer/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,ljshj/BroadleafCommerce,daniellavoie/BroadleafCommerce,udayinfy/BroadleafCommerce,udayinfy/BroadleafCommerce,cogitoboy/BroadleafCommerce,caosg/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,ljshj/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,liqianggao/BroadleafCommerce,ljshj/BroadleafCommerce,TouK/BroadleafCommerce,bijukunjummen/BroadleafCommerce,zhaorui1/BroadleafCommerce,zhaorui1/BroadleafCommerce,zhaorui1/BroadleafCommerce
/* * Copyright 2008-2009 the original author or authors. * * 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.broadleafcommerce.core.web.controller.checkout; import org.broadleafcommerce.common.web.controller.BroadleafAbstractController; import org.broadleafcommerce.core.checkout.service.CheckoutService; import org.broadleafcommerce.core.order.domain.Order; import org.broadleafcommerce.core.order.service.FulfillmentGroupService; import org.broadleafcommerce.core.order.service.FulfillmentOptionService; import org.broadleafcommerce.core.order.service.OrderMultishipOptionService; import org.broadleafcommerce.core.order.service.OrderService; import org.broadleafcommerce.core.payment.service.PaymentInfoFactory; import org.broadleafcommerce.core.payment.service.SecurePaymentInfoService; import org.broadleafcommerce.core.pricing.service.exception.PricingException; import org.broadleafcommerce.core.web.checkout.validator.BillingInfoFormValidator; import org.broadleafcommerce.core.web.checkout.validator.MultishipAddAddressFormValidator; import org.broadleafcommerce.core.web.checkout.validator.ShippingInfoFormValidator; import org.broadleafcommerce.profile.core.service.AddressService; import org.broadleafcommerce.profile.core.service.CountryService; import org.broadleafcommerce.profile.core.service.CustomerAddressService; import org.broadleafcommerce.profile.core.service.StateService; import javax.annotation.Resource; import java.util.List; /** * An abstract controller that provides convenience methods and resource declarations for its * children. Operations that are shared between controllers that deal with checkout belong here. * * @author elbertbautista */ public abstract class AbstractCheckoutController extends BroadleafAbstractController { /* Services */ @Resource(name = "blOrderService") protected OrderService orderService; @Resource(name = "blFulfillmentOptionService") protected FulfillmentOptionService fulfillmentOptionService; @Resource(name = "blFulfillmentGroupService") protected FulfillmentGroupService fulfillmentGroupService; @Resource(name = "blCheckoutService") protected CheckoutService checkoutService; @Resource(name = "blStateService") protected StateService stateService; @Resource(name = "blCountryService") protected CountryService countryService; @Resource(name = "blCustomerAddressService") protected CustomerAddressService customerAddressService; @Resource(name = "blAddressService") protected AddressService addressService; @Resource(name = "blOrderMultishipOptionService") protected OrderMultishipOptionService orderMultishipOptionService; @Resource(name = "blSecurePaymentInfoService") protected SecurePaymentInfoService securePaymentInfoService; /* Factories */ @Resource(name = "blCreditCardPaymentInfoFactory") protected PaymentInfoFactory creditCardPaymentInfoFactory; /* Validators */ @Resource(name = "blShippingInfoFormValidator") protected ShippingInfoFormValidator shippingInfoFormValidator; @Resource(name = "blMultishipAddAddressFormValidator") protected MultishipAddAddressFormValidator multishipAddAddressFormValidator; @Resource(name = "blBillingInfoFormValidator") protected BillingInfoFormValidator billingInfoFormValidator; }
core/broadleaf-framework-web/src/main/java/org/broadleafcommerce/core/web/controller/checkout/AbstractCheckoutController.java
/* * Copyright 2008-2009 the original author or authors. * * 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.broadleafcommerce.core.web.controller.checkout; import org.broadleafcommerce.common.web.controller.BroadleafAbstractController; import org.broadleafcommerce.core.checkout.service.CheckoutService; import org.broadleafcommerce.core.order.domain.Order; import org.broadleafcommerce.core.order.service.FulfillmentGroupService; import org.broadleafcommerce.core.order.service.FulfillmentOptionService; import org.broadleafcommerce.core.order.service.OrderMultishipOptionService; import org.broadleafcommerce.core.order.service.OrderService; import org.broadleafcommerce.core.payment.service.PaymentInfoFactory; import org.broadleafcommerce.core.payment.service.SecurePaymentInfoService; import org.broadleafcommerce.core.pricing.service.exception.PricingException; import org.broadleafcommerce.core.web.checkout.validator.BillingInfoFormValidator; import org.broadleafcommerce.core.web.checkout.validator.MultishipAddAddressFormValidator; import org.broadleafcommerce.core.web.checkout.validator.ShippingInfoFormValidator; import org.broadleafcommerce.profile.core.service.AddressService; import org.broadleafcommerce.profile.core.service.CountryService; import org.broadleafcommerce.profile.core.service.CustomerAddressService; import org.broadleafcommerce.profile.core.service.StateService; import javax.annotation.Resource; import java.util.List; /** * An abstract controller that provides convenience methods and resource declarations for its * children. Operations that are shared between controllers that deal with checkout belong here. * * @author elbertbautista */ public abstract class AbstractCheckoutController extends BroadleafAbstractController { /* Services */ @Resource(name = "blOrderService") protected OrderService orderService; @Resource(name = "blFulfillmentOptionService") protected FulfillmentOptionService fulfillmentOptionService; @Resource(name = "blFulfillmentGroupService") protected FulfillmentGroupService fulfillmentGroupService; @Resource(name = "blCheckoutService") protected CheckoutService checkoutService; @Resource(name = "blStateService") protected StateService stateService; @Resource(name = "blCountryService") protected CountryService countryService; @Resource(name = "blCustomerAddressService") protected CustomerAddressService customerAddressService; @Resource(name = "blAddressService") protected AddressService addressService; @Resource(name = "blOrderMultishipOptionService") protected OrderMultishipOptionService orderMultishipOptionService; @Resource(name = "blSecurePaymentInfoService") protected SecurePaymentInfoService securePaymentInfoService; /* Factories */ @Resource(name = "blCreditCardPaymentInfoFactory") protected PaymentInfoFactory creditCardPaymentInfoFactory; /* Validators */ @Resource(name = "blShippingInfoFormValidator") protected ShippingInfoFormValidator shippingInfoFormValidator; @Resource(name = "blMultishipAddAddressFormValidator") protected MultishipAddAddressFormValidator multishipAddAddressFormValidator; @Resource(name = "blBillingInfoFormValidator") protected BillingInfoFormValidator billingInfoFormValidator; /* Abstract Methods */ protected abstract void initializeOrderForCheckout(Order order); protected abstract void processFailedOrderCheckout(Order order) throws PricingException; protected abstract boolean hasValidShippingAddresses(Order cart); protected abstract List<String> populateExpirationMonths(); protected abstract List<String> populateExpirationYears(); }
cleaning up abstract controller
core/broadleaf-framework-web/src/main/java/org/broadleafcommerce/core/web/controller/checkout/AbstractCheckoutController.java
cleaning up abstract controller
<ide><path>ore/broadleaf-framework-web/src/main/java/org/broadleafcommerce/core/web/controller/checkout/AbstractCheckoutController.java <ide> @Resource(name = "blBillingInfoFormValidator") <ide> protected BillingInfoFormValidator billingInfoFormValidator; <ide> <del> /* Abstract Methods */ <del> protected abstract void initializeOrderForCheckout(Order order); <del> <del> protected abstract void processFailedOrderCheckout(Order order) throws PricingException; <del> <del> protected abstract boolean hasValidShippingAddresses(Order cart); <del> <del> protected abstract List<String> populateExpirationMonths(); <del> <del> protected abstract List<String> populateExpirationYears(); <del> <ide> }
JavaScript
apache-2.0
b2b904f273a49aa4d86c23d1ddf553c6b2593e13
0
martinpz/Spark-RDF-Analyzer,martinpz/Spark-RDF-Analyzer,martinpz/Spark-RDF-Analyzer
var loader = '<div class="progress progress-striped active page-progress-bar"><div class="progress-bar" style="width: 100%;"></div></div>'; // ########################## Entry Point ########################## function showAutocompletionModal() { var input = $('#entryNode').val(); // Only consider inputs with at least two characters. if (input.length < 2) { $('#modalTitle').text('Query too short!'); $('#modalBody').text( 'Please enter at least two characters before searching!'); $('#btnStartBrowsing').hide(); } else { $('#modalTitle').text('Select your entry point!'); $('#modalBody').html( '<p>Computing the autocomplete suggestions ...</p>' + loader); $('#btnStartBrowsing').show(); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { $('#modalBody').html(xhttp.responseText); } } xhttp.open('GET', REST_API + 'autoComplete/' + getCookie('graphName') + '/' + input + '/Node', true); xhttp.send(); } } function startBrowsing(event) { var selectedText = $('input[name="optradio"]:checked').val(); // When no option is selected, we cannot continue. if (typeof selectedText === 'undefined') { event.stopPropagation(); return false; } var selectedText_arr = selectedText.split(':'); // u52,<http,//www.ins.cwi.nl/sib/user/u52> var selectedValue = selectedText_arr[0]; // u52 var selectedURI = selectedText_arr[1] + ':' + selectedText_arr[2]; // <http://www.ins.cwi.nl/sib/user/u52> // Close modal. $('#btnCloseModal').click(); prepareBrowser(selectedValue, selectedURI); } // ########################## RDF Browser ########################## function prepareBrowser(centralNode, centralNodeURI) { var xhttp = new XMLHttpRequest(); updateBrowsingHistory(centralNode, centralNodeURI); $('#browserModalBody').html( '<p>Computing the neighbors for ' + centralNode + ' ...</p>' + loader); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { displayNodes(centralNode, centralNodeURI, JSON .parse(xhttp.responseText)); } } xhttp.open('GET', REST_API + 'directNeighbors/' + getCookie('graphName') + '?centralNode=' + encodeURIComponent(centralNodeURI) + '&numNeighbors=12', true); xhttp.send(); } function updateBrowsingHistory(currentName, currentURI) { // Add link to pre-last element. Remove active marker. var lastNode = $('#browsingHistory #list li').last(); var lastURI = lastNode.attr('data-uri'); var lastName = lastNode.text(); lastNode.removeClass('active'); lastNode.html('<a href="#" onclick="' + 'prepareBrowser(\'' + lastName + '\', \'' + lastURI + '\')' + '">' + lastName + '</a>'); // Append new last (= current) element. Make it active. $('#browsingHistory #list').append( '<li class="active" data-uri="' + currentURI + '">' + currentName + '</li>'); } function displayNodes(centralNode, centralNodeURI, neighbors) { // Remove < and > from URI. var toShow = '<p><strong>Central Node:</strong> <a href="' + centralNodeURI.slice(1, -1) + '">' + centralNodeURI.slice(1, -1) + '</a></p>'; $.each(neighbors, function(URI, props) { // An arrow. Indicating if central node is source or target. // Right arrow = central node is source. var direction = props.direction == 'out' ? 'right' : 'left'; var arrow = '<span class="glyphicon glyphicon-circle-arrow-' + direction + '" style="margin-right: 10px;"></span>'; var showCentralNode = '<span style="margin-right: 5px;"><strong>' + centralNode + '</strong></span>'; // The type of the connection, e.g. the predicate. var type = '<a href="' + props.predicateURI.slice(1, -1) + '" target="_blank" style="margin-right: 5px;">' + props.predicate + '</a>'; // The link to browse to the neighbor node. // OR the literal to be shown. var neighbor = ''; if (props.name !== '') { // When a name is set, use it for the neighbor. neighbor = '<a href="#" onclick="prepareBrowser'; neighbor += '(\'' + props.name + '\', \'' + URI + '\')'; neighbor += '" style="margin-right: 5px;">'; neighbor += props.name + '</a>'; } else { // When there is no name, we have a literal. neighbor = '<span style="margin-right: 5px; font-style: italic;">'; neighbor += props.URI + '</span>'; } // Central node is source => write it left, otherwise right toShow += '<div>' + arrow; toShow += direction == 'right' ? showCentralNode + type + neighbor : neighbor + type + showCentralNode; toShow += '</div>'; }); $('#browserModalBody').html(toShow); } // ########################## Utility Functions ########################## function getGraphName() { $('#GraphName').html(getCookie('graphName')); } function getCookie(name) { var value = '; ' + document.cookie; var parts = value.split('; ' + name + '='); if (parts.length == 2) { return parts.pop().split(';').shift(); } }
src/main/webapp/js/browser.js
var loader = '<div class="progress progress-striped active page-progress-bar"><div class="progress-bar" style="width: 100%;"></div></div>'; // ########################## Entry Point ########################## function showAutocompletionModal() { var input = $('#entryNode').val(); // Only consider inputs with at least two characters. if (input.length < 2) { $('#modalTitle').text('Query too short!'); $('#modalBody').text( 'Please enter at least two characters before searching!'); $('#btnStartBrowsing').hide(); } else { $('#modalTitle').text('Select your entry point!'); $('#modalBody').html( '<p>Computing the autocomplete suggestions ...</p>' + loader); $('#btnStartBrowsing').show(); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { $('#modalBody').html(xhttp.responseText); } } xhttp.open('GET', REST_API + 'autoComplete/' + getCookie('graphName') + '/' + input + '/Node', true); xhttp.send(); } } function startBrowsing(event) { var selectedText = $('input[name="optradio"]:checked').val(); // When no option is selected, we cannot continue. if (typeof selectedText === 'undefined') { event.stopPropagation(); return false; } var selectedText_arr = selectedText.split(':'); // u52,<http,//www.ins.cwi.nl/sib/user/u52> var selectedValue = selectedText_arr[0]; // u52 var selectedURI = selectedText_arr[1] + ':' + selectedText_arr[2]; // <http://www.ins.cwi.nl/sib/user/u52> // Close modal. $('#btnCloseModal').click(); prepareBrowser(selectedValue, selectedURI); } // ########################## RDF Browser ########################## function prepareBrowser(centralNode, centralNodeURI) { var xhttp = new XMLHttpRequest(); updateBrowsingHistory(centralNode, centralNodeURI); $('#browserModalBody').html( '<p>Computing the neighbors for ' + centralNode + ' ...</p>' + loader); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { displayNodes(centralNode, centralNodeURI, JSON .parse(xhttp.responseText)); } } xhttp.open('GET', REST_API + 'directNeighbors/' + getCookie('graphName') + '?centralNode=' + encodeURIComponent(centralNodeURI) + '&numNeighbors=12', true); xhttp.send(); } function updateBrowsingHistory(currentName, currentURI) { // Add link to pre-last element. Remove active marker. var lastNode = $('#browsingHistory #list li').last(); var lastURI = lastNode.attr('data-uri'); var lastName = lastNode.text(); lastNode.removeClass('active'); lastNode.html('<a href="#" onclick="' + 'prepareBrowser(\'' + lastName + '\', \'' + lastURI + '\')' + '">' + lastName + '</a>'); // Append new last (= current) element. Make it active. $('#browsingHistory #list').append( '<li class="active" data-uri="' + currentURI + '">' + currentName + '</li>'); } function displayNodes(centralNode, centralNodeURI, neighbors) { // Remove < and > from URI. var toShow = '<p><strong>Central Node:</strong> <a href="' + centralNodeURI.slice(1, -1) + '">' + centralNodeURI.slice(1, -1) + '</a></p>'; $.each(neighbors, function(URI, props) { // An arrow. Indicating if central node is source or target. // Right arrow = central node is source. var direction = props.direction == 'out' ? 'right' : 'left'; var arrow = '<span class="glyphicon glyphicon-circle-arrow-' + direction + '" style="margin-right: 10px;"></span>'; var showCentralNode = '<span style="margin-right: 5px;">' + centralNode + '</span>'; // The type of the connection, e.g. the predicate. var type = '<a href="' + props.predicateURI.slice(1, -1) + '" target="_blank" style="margin-right: 5px;">' + props.predicate + '</a>'; // The link to browse to the neighbor node. var neighbor = '<a href="#" onclick="' + 'prepareBrowser(\'' + props.name + '\', \'' + URI + '\')' + '" style="margin-right: 5px;">' + props.name + '</a>'; // Central node is source => write it left, otherwise right toShow += '<div>' + arrow; toShow += direction == 'right' ? showCentralNode + type + neighbor : neighbor + type + showCentralNode; toShow += '</div>'; }); $('#browserModalBody').html(toShow); } // ########################## Utility Functions ########################## function getGraphName() { $('#GraphName').html(getCookie('graphName')); } function getCookie(name) { var value = '; ' + document.cookie; var parts = value.split('; ' + name + '='); if (parts.length == 2) { return parts.pop().split(';').shift(); } }
Displays literals.
src/main/webapp/js/browser.js
Displays literals.
<ide><path>rc/main/webapp/js/browser.js <ide> var arrow = '<span class="glyphicon glyphicon-circle-arrow-' <ide> + direction + '" style="margin-right: 10px;"></span>'; <ide> <del> var showCentralNode = '<span style="margin-right: 5px;">' + centralNode <del> + '</span>'; <add> var showCentralNode = '<span style="margin-right: 5px;"><strong>' <add> + centralNode + '</strong></span>'; <ide> <ide> // The type of the connection, e.g. the predicate. <ide> var type = '<a href="' + props.predicateURI.slice(1, -1) <ide> + props.predicate + '</a>'; <ide> <ide> // The link to browse to the neighbor node. <del> var neighbor = '<a href="#" onclick="' + 'prepareBrowser(\'' <del> + props.name + '\', \'' + URI + '\')' <del> + '" style="margin-right: 5px;">' + props.name + '</a>'; <add> // OR the literal to be shown. <add> var neighbor = ''; <add> <add> if (props.name !== '') { <add> // When a name is set, use it for the neighbor. <add> neighbor = '<a href="#" onclick="prepareBrowser'; <add> neighbor += '(\'' + props.name + '\', \'' + URI + '\')'; <add> neighbor += '" style="margin-right: 5px;">'; <add> neighbor += props.name + '</a>'; <add> } else { <add> // When there is no name, we have a literal. <add> neighbor = '<span style="margin-right: 5px; font-style: italic;">'; <add> neighbor += props.URI + '</span>'; <add> } <ide> <ide> // Central node is source => write it left, otherwise right <ide> toShow += '<div>' + arrow;
Java
apache-2.0
826788a35b717159381e53adb3c5da16eeac360d
0
apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/incubator-kylin
/* * 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.kylin.rest.service; import static org.apache.kylin.common.util.CheckUtil.checkCondition; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; import org.apache.calcite.avatica.ColumnMetaData.Rep; import org.apache.calcite.config.CalciteConnectionConfig; import org.apache.calcite.jdbc.CalcitePrepare; import org.apache.calcite.prepare.CalcitePrepareImpl; import org.apache.calcite.prepare.OnlyPrepareEarlyAbortException; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.sql.type.BasicSqlType; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.QueryContext; import org.apache.kylin.common.debug.BackdoorToggles; import org.apache.kylin.common.exceptions.ResourceLimitExceededException; import org.apache.kylin.common.htrace.HtraceInit; import org.apache.kylin.common.persistence.ResourceStore; import org.apache.kylin.common.persistence.RootPersistentEntity; import org.apache.kylin.common.persistence.Serializer; import org.apache.kylin.common.util.DBUtils; import org.apache.kylin.common.util.JsonUtil; import org.apache.kylin.common.util.Pair; import org.apache.kylin.common.util.SetThreadName; import org.apache.kylin.cube.CubeInstance; import org.apache.kylin.cube.CubeManager; import org.apache.kylin.cube.cuboid.Cuboid; import org.apache.kylin.metadata.badquery.BadQueryEntry; import org.apache.kylin.metadata.model.DataModelDesc; import org.apache.kylin.metadata.model.JoinDesc; import org.apache.kylin.metadata.model.JoinTableDesc; import org.apache.kylin.metadata.model.ModelDimensionDesc; import org.apache.kylin.metadata.model.TableRef; import org.apache.kylin.metadata.project.ProjectInstance; import org.apache.kylin.metadata.project.RealizationEntry; import org.apache.kylin.metadata.querymeta.ColumnMeta; import org.apache.kylin.metadata.querymeta.ColumnMetaWithType; import org.apache.kylin.metadata.querymeta.SelectedColumnMeta; import org.apache.kylin.metadata.querymeta.TableMeta; import org.apache.kylin.metadata.querymeta.TableMetaWithType; import org.apache.kylin.metadata.realization.RealizationType; import org.apache.kylin.query.QueryConnection; import org.apache.kylin.query.relnode.OLAPContext; import org.apache.kylin.query.util.PushDownUtil; import org.apache.kylin.query.util.QueryUtil; import org.apache.kylin.query.util.TempStatementUtil; import org.apache.kylin.rest.constant.Constant; import org.apache.kylin.rest.exception.BadRequestException; import org.apache.kylin.rest.exception.InternalErrorException; import org.apache.kylin.rest.metrics.QueryMetrics2Facade; import org.apache.kylin.rest.metrics.QueryMetricsFacade; import org.apache.kylin.rest.model.Query; import org.apache.kylin.rest.msg.Message; import org.apache.kylin.rest.msg.MsgPicker; import org.apache.kylin.rest.request.PrepareSqlRequest; import org.apache.kylin.rest.request.SQLRequest; import org.apache.kylin.rest.response.SQLResponse; import org.apache.kylin.rest.util.AclEvaluate; import org.apache.kylin.rest.util.AclPermissionUtil; import org.apache.kylin.rest.util.TableauInterceptor; import org.apache.kylin.shaded.htrace.org.apache.htrace.Sampler; import org.apache.kylin.shaded.htrace.org.apache.htrace.Trace; import org.apache.kylin.shaded.htrace.org.apache.htrace.TraceScope; import org.apache.kylin.storage.hybrid.HybridInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * @author xduo */ @Component("queryService") public class QueryService extends BasicService { public static final String SUCCESS_QUERY_CACHE = "StorageCache"; public static final String EXCEPTION_QUERY_CACHE = "ExceptionQueryCache"; public static final String QUERY_STORE_PATH_PREFIX = "/query/"; private static final Logger logger = LoggerFactory.getLogger(QueryService.class); final BadQueryDetector badQueryDetector = new BadQueryDetector(); final ResourceStore queryStore; @Autowired protected CacheManager cacheManager; @Autowired @Qualifier("cacheService") private CacheService cacheService; @Autowired @Qualifier("modelMgmtService") private ModelService modelService; @Autowired private AclEvaluate aclEvaluate; public QueryService() { queryStore = ResourceStore.getStore(getConfig()); badQueryDetector.start(); } protected static void close(ResultSet resultSet, Statement stat, Connection conn) { OLAPContext.clearParameter(); DBUtils.closeQuietly(resultSet); DBUtils.closeQuietly(stat); DBUtils.closeQuietly(conn); } private static String getQueryKeyById(String creator) { return QUERY_STORE_PATH_PREFIX + creator; } @PostConstruct public void init() throws IOException { Preconditions.checkNotNull(cacheManager, "cacheManager is not injected yet"); } public List<TableMeta> getMetadata(String project) throws SQLException { return getMetadata(getCubeManager(), project); } public SQLResponse query(SQLRequest sqlRequest) throws Exception { SQLResponse ret = null; try { final String user = SecurityContextHolder.getContext().getAuthentication().getName(); badQueryDetector.queryStart(Thread.currentThread(), sqlRequest, user); ret = queryWithSqlMassage(sqlRequest); return ret; } finally { String badReason = (ret != null && ret.isPushDown()) ? BadQueryEntry.ADJ_PUSHDOWN : null; badQueryDetector.queryEnd(Thread.currentThread(), badReason); } } public SQLResponse update(SQLRequest sqlRequest) throws Exception { // non select operations, only supported when enable pushdown logger.debug("Query pushdown enabled, redirect the non-select query to pushdown engine."); Connection conn = null; try { conn = QueryConnection.getConnection(sqlRequest.getProject()); Pair<List<List<String>>, List<SelectedColumnMeta>> r = PushDownUtil.tryPushDownNonSelectQuery( sqlRequest.getProject(), sqlRequest.getSql(), conn.getSchema(), BackdoorToggles.getPrepareOnly()); List<SelectedColumnMeta> columnMetas = Lists.newArrayList(); columnMetas.add(new SelectedColumnMeta(false, false, false, false, 1, false, Integer.MAX_VALUE, "c0", "c0", null, null, null, Integer.MAX_VALUE, 128, 1, "char", false, false, false)); return buildSqlResponse(true, r.getFirst(), columnMetas); } catch (Exception e) { logger.info("pushdown engine failed to finish current non-select query"); throw e; } finally { close(null, null, conn); } } public void saveQuery(final String creator, final Query query) throws IOException { List<Query> queries = getQueries(creator); queries.add(query); Query[] queryArray = new Query[queries.size()]; QueryRecord record = new QueryRecord(queries.toArray(queryArray)); queryStore.putResourceWithoutCheck(getQueryKeyById(creator), record, System.currentTimeMillis(), QueryRecordSerializer.getInstance()); return; } public void removeQuery(final String creator, final String id) throws IOException { List<Query> queries = getQueries(creator); Iterator<Query> queryIter = queries.iterator(); boolean changed = false; while (queryIter.hasNext()) { Query temp = queryIter.next(); if (temp.getId().equals(id)) { queryIter.remove(); changed = true; break; } } if (!changed) { return; } Query[] queryArray = new Query[queries.size()]; QueryRecord record = new QueryRecord(queries.toArray(queryArray)); queryStore.putResourceWithoutCheck(getQueryKeyById(creator), record, System.currentTimeMillis(), QueryRecordSerializer.getInstance()); return; } public List<Query> getQueries(final String creator) throws IOException { if (null == creator) { return null; } List<Query> queries = new ArrayList<Query>(); QueryRecord record = queryStore.getResource(getQueryKeyById(creator), QueryRecord.class, QueryRecordSerializer.getInstance()); if (record != null) { for (Query query : record.getQueries()) { queries.add(query); } } return queries; } public void logQuery(final SQLRequest request, final SQLResponse response) { final String user = aclEvaluate.getCurrentUserName(); final List<String> realizationNames = new LinkedList<>(); final Set<Long> cuboidIds = new HashSet<Long>(); float duration = response.getDuration() / (float) 1000; boolean storageCacheUsed = response.isStorageCacheUsed(); boolean isPushDown = response.isPushDown(); if (!response.isHitExceptionCache() && null != OLAPContext.getThreadLocalContexts()) { for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) { Cuboid cuboid = ctx.storageContext.getCuboid(); if (cuboid != null) { //Some queries do not involve cuboid, e.g. lookup table query cuboidIds.add(cuboid.getId()); } if (ctx.realization != null) { realizationNames.add(ctx.realization.getCanonicalName()); } } } int resultRowCount = 0; if (!response.getIsException() && response.getResults() != null) { resultRowCount = response.getResults().size(); } String newLine = System.getProperty("line.separator"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(newLine); stringBuilder.append("==========================[QUERY]===============================").append(newLine); stringBuilder.append("Query Id: ").append(QueryContext.current().getQueryId()).append(newLine); stringBuilder.append("SQL: ").append(request.getSql()).append(newLine); stringBuilder.append("User: ").append(user).append(newLine); stringBuilder.append("Success: ").append((null == response.getExceptionMessage())).append(newLine); stringBuilder.append("Duration: ").append(duration).append(newLine); stringBuilder.append("Project: ").append(request.getProject()).append(newLine); stringBuilder.append("Realization Names: ").append(realizationNames).append(newLine); stringBuilder.append("Cuboid Ids: ").append(cuboidIds).append(newLine); stringBuilder.append("Total scan count: ").append(response.getTotalScanCount()).append(newLine); stringBuilder.append("Total scan bytes: ").append(response.getTotalScanBytes()).append(newLine); stringBuilder.append("Result row count: ").append(resultRowCount).append(newLine); stringBuilder.append("Accept Partial: ").append(request.isAcceptPartial()).append(newLine); stringBuilder.append("Is Partial Result: ").append(response.isPartial()).append(newLine); stringBuilder.append("Hit Exception Cache: ").append(response.isHitExceptionCache()).append(newLine); stringBuilder.append("Storage cache used: ").append(storageCacheUsed).append(newLine); stringBuilder.append("Is Query Push-Down: ").append(isPushDown).append(newLine); stringBuilder.append("Trace URL: ").append(response.getTraceUrl()).append(newLine); stringBuilder.append("Message: ").append(response.getExceptionMessage()).append(newLine); stringBuilder.append("==========================[QUERY]===============================").append(newLine); logger.info(stringBuilder.toString()); } public void checkAuthorization(SQLResponse sqlResponse, String project) throws AccessDeniedException { //project ProjectInstance projectInstance = getProjectManager().getProject(project); try { if (aclEvaluate.hasProjectReadPermission(projectInstance)) { return; } } catch (AccessDeniedException e) { logger.warn( "Current user {} has no READ permission on current project {}, please ask Administrator for permission granting."); //just continue } String realizationsStr = sqlResponse.getCube();//CUBE[name=abc],HYBRID[name=xyz] if (StringUtils.isEmpty(realizationsStr)) { throw new AccessDeniedException( "Query pushdown requires having READ permission on project, please ask Administrator to grant you permissions"); } String[] splits = StringUtils.split(realizationsStr, ","); for (String split : splits) { Iterable<String> parts = Splitter.on(CharMatcher.anyOf("[]=,")).split(split); String[] partsStr = Iterables.toArray(parts, String.class); if (RealizationType.HYBRID.toString().equals(partsStr[0])) { // special care for hybrid HybridInstance hybridInstance = getHybridManager().getHybridInstance(partsStr[2]); Preconditions.checkNotNull(hybridInstance); checkHybridAuthorization(hybridInstance); } else { CubeInstance cubeInstance = getCubeManager().getCube(partsStr[2]); checkCubeAuthorization(cubeInstance); } } } private void checkCubeAuthorization(CubeInstance cube) throws AccessDeniedException { Preconditions.checkState(aclEvaluate.hasCubeReadPermission(cube)); } private void checkHybridAuthorization(HybridInstance hybridInstance) throws AccessDeniedException { List<RealizationEntry> realizationEntries = hybridInstance.getRealizationEntries(); for (RealizationEntry realizationEntry : realizationEntries) { String reName = realizationEntry.getRealization(); if (RealizationType.CUBE == realizationEntry.getType()) { CubeInstance cubeInstance = getCubeManager().getCube(reName); checkCubeAuthorization(cubeInstance); } else if (RealizationType.HYBRID == realizationEntry.getType()) { HybridInstance innerHybridInstance = getHybridManager().getHybridInstance(reName); checkHybridAuthorization(innerHybridInstance); } } } public SQLResponse doQueryWithCache(SQLRequest sqlRequest) { return doQueryWithCache(sqlRequest, false); } public SQLResponse doQueryWithCache(SQLRequest sqlRequest, boolean isQueryInspect) { Message msg = MsgPicker.getMsg(); sqlRequest.setUsername(getUserName()); KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv(); String serverMode = kylinConfig.getServerMode(); if (!(Constant.SERVER_MODE_QUERY.equals(serverMode.toLowerCase()) || Constant.SERVER_MODE_ALL.equals(serverMode.toLowerCase()))) { throw new BadRequestException(String.format(msg.getQUERY_NOT_ALLOWED(), serverMode)); } if (StringUtils.isBlank(sqlRequest.getProject())) { throw new BadRequestException(msg.getEMPTY_PROJECT_NAME()); } if (sqlRequest.getBackdoorToggles() != null) BackdoorToggles.addToggles(sqlRequest.getBackdoorToggles()); final QueryContext queryContext = QueryContext.current(); TraceScope scope = null; if (KylinConfig.getInstanceFromEnv().isHtraceTracingEveryQuery() || BackdoorToggles.getHtraceEnabled()) { logger.info("Current query is under tracing"); HtraceInit.init(); scope = Trace.startSpan("query life cycle for " + queryContext.getQueryId(), Sampler.ALWAYS); } String traceUrl = getTraceUrl(scope); try (SetThreadName ignored = new SetThreadName("Query %s", queryContext.getQueryId())) { String sql = sqlRequest.getSql(); String project = sqlRequest.getProject(); logger.info("Using project: " + project); logger.info("The original query: " + sql); sql = QueryUtil.removeCommentInSql(sql); Pair<Boolean, String> result = TempStatementUtil.handleTempStatement(sql, kylinConfig); boolean isTempStatement = result.getFirst(); sql = result.getSecond(); sqlRequest.setSql(sql); final boolean isSelect = QueryUtil.isSelectStatement(sql); long startTime = System.currentTimeMillis(); SQLResponse sqlResponse = null; boolean queryCacheEnabled = checkCondition(kylinConfig.isQueryCacheEnabled(), "query cache disabled in KylinConfig") && // checkCondition(!BackdoorToggles.getDisableCache(), "query cache disabled in BackdoorToggles"); if (queryCacheEnabled) { sqlResponse = searchQueryInCache(sqlRequest); Trace.addTimelineAnnotation("query cache searched"); } else { Trace.addTimelineAnnotation("query cache skip search"); } try { if (null == sqlResponse) { if (isQueryInspect) { // set query sql to exception message string sqlResponse = new SQLResponse(null, null, 0, false, sqlRequest.getSql()); } else if (isTempStatement) { sqlResponse = new SQLResponse(null, null, 0, false, null); } else if (isSelect) { sqlResponse = query(sqlRequest); Trace.addTimelineAnnotation("query almost done"); } else if (kylinConfig.isPushDownEnabled() && kylinConfig.isPushDownUpdateEnabled()) { sqlResponse = update(sqlRequest); Trace.addTimelineAnnotation("update query almost done"); } else { logger.debug( "Directly return exception as the sql is unsupported, and query pushdown is disabled"); throw new BadRequestException(msg.getNOT_SUPPORTED_SQL()); } long durationThreshold = kylinConfig.getQueryDurationCacheThreshold(); long scanCountThreshold = kylinConfig.getQueryScanCountCacheThreshold(); long scanBytesThreshold = kylinConfig.getQueryScanBytesCacheThreshold(); sqlResponse.setDuration(System.currentTimeMillis() - startTime); logger.info("Stats of SQL response: isException: {}, duration: {}, total scan count {}", // String.valueOf(sqlResponse.getIsException()), String.valueOf(sqlResponse.getDuration()), String.valueOf(sqlResponse.getTotalScanCount())); if (checkCondition(queryCacheEnabled, "query cache is disabled") // && checkCondition(!sqlResponse.getIsException(), "query has exception") // && checkCondition(!(sqlResponse.isPushDown() && (isSelect == false || kylinConfig.isPushdownQueryCacheEnabled() == false)), "query is executed with pushdown, but it is non-select, or the cache for pushdown is disabled") // && checkCondition( sqlResponse.getDuration() > durationThreshold || sqlResponse.getTotalScanCount() > scanCountThreshold || sqlResponse.getTotalScanBytes() > scanBytesThreshold, // "query is too lightweight with duration: {} (threshold {}), scan count: {} (threshold {}), scan bytes: {} (threshold {})", sqlResponse.getDuration(), durationThreshold, sqlResponse.getTotalScanCount(), scanCountThreshold, sqlResponse.getTotalScanBytes(), scanBytesThreshold) && checkCondition(sqlResponse.getResults().size() < kylinConfig.getLargeQueryThreshold(), "query response is too large: {} ({})", sqlResponse.getResults().size(), kylinConfig.getLargeQueryThreshold())) { cacheManager.getCache(SUCCESS_QUERY_CACHE) .put(new Element(sqlRequest.getCacheKey(), sqlResponse)); } Trace.addTimelineAnnotation("response from execution"); } else { sqlResponse.setDuration(System.currentTimeMillis() - startTime); sqlResponse.setTotalScanCount(0); sqlResponse.setTotalScanBytes(0); Trace.addTimelineAnnotation("response from cache"); } checkQueryAuth(sqlResponse, project); } catch (Throwable e) { // calcite may throw AssertError logger.error("Exception while executing query", e); String errMsg = makeErrorMsgUserFriendly(e); sqlResponse = new SQLResponse(null, null, null, 0, true, errMsg, false, false); sqlResponse.setTotalScanCount(queryContext.getScannedRows()); sqlResponse.setTotalScanBytes(queryContext.getScannedBytes()); if (queryCacheEnabled && e.getCause() != null && ExceptionUtils.getRootCause(e) instanceof ResourceLimitExceededException) { Cache exceptionCache = cacheManager.getCache(EXCEPTION_QUERY_CACHE); exceptionCache.put(new Element(sqlRequest.getCacheKey(), sqlResponse)); } Trace.addTimelineAnnotation("error response"); } sqlResponse.setTraceUrl(traceUrl); logQuery(sqlRequest, sqlResponse); try { recordMetric(sqlRequest, sqlResponse); } catch (Throwable th) { logger.warn("Write metric error.", th); } if (sqlResponse.getIsException()) throw new InternalErrorException(sqlResponse.getExceptionMessage()); return sqlResponse; } finally { BackdoorToggles.cleanToggles(); QueryContext.reset(); if (scope != null) { scope.close(); } } } protected void recordMetric(SQLRequest sqlRequest, SQLResponse sqlResponse) throws UnknownHostException { QueryMetricsFacade.updateMetrics(sqlRequest, sqlResponse); QueryMetrics2Facade.updateMetrics(sqlRequest, sqlResponse); } private String getTraceUrl(TraceScope scope) { if (scope == null) { return null; } String hostname = System.getProperty("zipkin.collector-hostname"); if (StringUtils.isEmpty(hostname)) { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.debug("failed to get trace url due to " + e.getMessage()); return null; } } String port = System.getProperty("zipkin.web-ui-port"); if (StringUtils.isEmpty(port)) { port = "9411"; } return "http://" + hostname + ":" + port + "/zipkin/traces/" + Long.toHexString(scope.getSpan().getTraceId()); } private String getUserName() { String username = SecurityContextHolder.getContext().getAuthentication().getName(); if (StringUtils.isEmpty(username)) { username = ""; } return username; } public SQLResponse searchQueryInCache(SQLRequest sqlRequest) { SQLResponse response = null; Cache exceptionCache = cacheManager.getCache(EXCEPTION_QUERY_CACHE); Cache successCache = cacheManager.getCache(SUCCESS_QUERY_CACHE); Element element = null; if ((element = exceptionCache.get(sqlRequest.getCacheKey())) != null) { logger.info("The sqlResponse is found in EXCEPTION_QUERY_CACHE"); response = (SQLResponse) element.getObjectValue(); response.setHitExceptionCache(true); } else if ((element = successCache.get(sqlRequest.getCacheKey())) != null) { logger.info("The sqlResponse is found in SUCCESS_QUERY_CACHE"); response = (SQLResponse) element.getObjectValue(); response.setStorageCacheUsed(true); } return response; } protected void checkQueryAuth(SQLResponse sqlResponse, String project) throws AccessDeniedException { if (!sqlResponse.getIsException() && KylinConfig.getInstanceFromEnv().isQuerySecureEnabled()) { checkAuthorization(sqlResponse, project); } } private SQLResponse queryWithSqlMassage(SQLRequest sqlRequest) throws Exception { Connection conn = null; try { conn = QueryConnection.getConnection(sqlRequest.getProject()); String userInfo = SecurityContextHolder.getContext().getAuthentication().getName(); QueryContext context = QueryContext.current(); context.setUsername(userInfo); context.setGroups(AclPermissionUtil.getCurrentUserGroups()); final Collection<? extends GrantedAuthority> grantedAuthorities = SecurityContextHolder.getContext() .getAuthentication().getAuthorities(); for (GrantedAuthority grantedAuthority : grantedAuthorities) { userInfo += ","; userInfo += grantedAuthority.getAuthority(); } SQLResponse fakeResponse = TableauInterceptor.tableauIntercept(sqlRequest.getSql()); if (null != fakeResponse) { logger.debug("Return fake response, is exception? " + fakeResponse.getIsException()); return fakeResponse; } String correctedSql = QueryUtil.massageSql(sqlRequest.getSql(), sqlRequest.getProject(), sqlRequest.getLimit(), sqlRequest.getOffset(), conn.getSchema()); if (!correctedSql.equals(sqlRequest.getSql())) { logger.info("The corrected query: " + correctedSql); //CAUTION: should not change sqlRequest content! //sqlRequest.setSql(correctedSql); } Trace.addTimelineAnnotation("query massaged"); // add extra parameters into olap context, like acceptPartial Map<String, String> parameters = new HashMap<String, String>(); parameters.put(OLAPContext.PRM_USER_AUTHEN_INFO, userInfo); parameters.put(OLAPContext.PRM_ACCEPT_PARTIAL_RESULT, String.valueOf(sqlRequest.isAcceptPartial())); OLAPContext.setParameters(parameters); // force clear the query context before a new query OLAPContext.clearThreadLocalContexts(); return execute(correctedSql, sqlRequest, conn); } finally { DBUtils.closeQuietly(conn); } } protected List<TableMeta> getMetadata(CubeManager cubeMgr, String project) throws SQLException { Connection conn = null; ResultSet columnMeta = null; List<TableMeta> tableMetas = null; if (StringUtils.isBlank(project)) { return Collections.emptyList(); } ResultSet JDBCTableMeta = null; try { conn = QueryConnection.getConnection(project); DatabaseMetaData metaData = conn.getMetaData(); JDBCTableMeta = metaData.getTables(null, null, null, null); tableMetas = new LinkedList<TableMeta>(); Map<String, TableMeta> tableMap = new HashMap<String, TableMeta>(); while (JDBCTableMeta.next()) { String catalogName = JDBCTableMeta.getString(1); String schemaName = JDBCTableMeta.getString(2); // Not every JDBC data provider offers full 10 columns, e.g., PostgreSQL has only 5 TableMeta tblMeta = new TableMeta(catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3), JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null); if (!"metadata".equalsIgnoreCase(tblMeta.getTABLE_SCHEM())) { tableMetas.add(tblMeta); tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta); } } columnMeta = metaData.getColumns(null, null, null, null); while (columnMeta.next()) { String catalogName = columnMeta.getString(1); String schemaName = columnMeta.getString(2); // kylin(optiq) is not strictly following JDBC specification ColumnMeta colmnMeta = new ColumnMeta(catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3), columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6), columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9), columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12), columnMeta.getString(13), getInt(columnMeta.getString(14)), getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17), columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20), columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23)); if (!"metadata".equalsIgnoreCase(colmnMeta.getTABLE_SCHEM()) && !colmnMeta.getCOLUMN_NAME().toUpperCase().startsWith("_KY_")) { tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta); } } } finally { close(columnMeta, null, conn); if (JDBCTableMeta != null) { JDBCTableMeta.close(); } } return tableMetas; } public List<TableMetaWithType> getMetadataV2(String project) throws SQLException, IOException { return getMetadataV2(getCubeManager(), project); } @SuppressWarnings("checkstyle:methodlength") protected List<TableMetaWithType> getMetadataV2(CubeManager cubeMgr, String project) throws SQLException, IOException { //Message msg = MsgPicker.getMsg(); Connection conn = null; ResultSet columnMeta = null; List<TableMetaWithType> tableMetas = null; Map<String, TableMetaWithType> tableMap = null; Map<String, ColumnMetaWithType> columnMap = null; if (StringUtils.isBlank(project)) { return Collections.emptyList(); } ResultSet JDBCTableMeta = null; try { conn = QueryConnection.getConnection(project); DatabaseMetaData metaData = conn.getMetaData(); JDBCTableMeta = metaData.getTables(null, null, null, null); tableMetas = new LinkedList<TableMetaWithType>(); tableMap = new HashMap<String, TableMetaWithType>(); columnMap = new HashMap<String, ColumnMetaWithType>(); while (JDBCTableMeta.next()) { String catalogName = JDBCTableMeta.getString(1); String schemaName = JDBCTableMeta.getString(2); // Not every JDBC data provider offers full 10 columns, e.g., PostgreSQL has only 5 TableMetaWithType tblMeta = new TableMetaWithType( catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3), JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null); if (!"metadata".equalsIgnoreCase(tblMeta.getTABLE_SCHEM())) { tableMetas.add(tblMeta); tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta); } } columnMeta = metaData.getColumns(null, null, null, null); while (columnMeta.next()) { String catalogName = columnMeta.getString(1); String schemaName = columnMeta.getString(2); // kylin(optiq) is not strictly following JDBC specification ColumnMetaWithType colmnMeta = new ColumnMetaWithType( catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3), columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6), columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9), columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12), columnMeta.getString(13), getInt(columnMeta.getString(14)), getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17), columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20), columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23)); if (!"metadata".equalsIgnoreCase(colmnMeta.getTABLE_SCHEM()) && !colmnMeta.getCOLUMN_NAME().toUpperCase().startsWith("_KY_")) { tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta); columnMap.put(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME() + "#" + colmnMeta.getCOLUMN_NAME(), colmnMeta); } } } finally { close(columnMeta, null, conn); if (JDBCTableMeta != null) { JDBCTableMeta.close(); } } ProjectInstance projectInstance = getProjectManager().getProject(project); for (String modelName : projectInstance.getModels()) { DataModelDesc dataModelDesc = modelService.getModel(modelName, project); if (dataModelDesc != null && !dataModelDesc.isDraft()) { // update table type: FACT for (TableRef factTable : dataModelDesc.getFactTables()) { String factTableName = factTable.getTableIdentity().replace('.', '#'); if (tableMap.containsKey(factTableName)) { tableMap.get(factTableName).getTYPE().add(TableMetaWithType.tableTypeEnum.FACT); } else { // should be used after JDBC exposes all tables and columns // throw new BadRequestException(msg.getTABLE_META_INCONSISTENT()); } } // update table type: LOOKUP for (TableRef lookupTable : dataModelDesc.getLookupTables()) { String lookupTableName = lookupTable.getTableIdentity().replace('.', '#'); if (tableMap.containsKey(lookupTableName)) { tableMap.get(lookupTableName).getTYPE().add(TableMetaWithType.tableTypeEnum.LOOKUP); } else { // throw new BadRequestException(msg.getTABLE_META_INCONSISTENT()); } } // update column type: PK and FK for (JoinTableDesc joinTableDesc : dataModelDesc.getJoinTables()) { JoinDesc joinDesc = joinTableDesc.getJoin(); for (String pk : joinDesc.getPrimaryKey()) { String columnIdentity = (dataModelDesc.findTable(pk.substring(0, pk.indexOf("."))) .getTableIdentity() + pk.substring(pk.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.PK); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } for (String fk : joinDesc.getForeignKey()) { String columnIdentity = (dataModelDesc.findTable(fk.substring(0, fk.indexOf("."))) .getTableIdentity() + fk.substring(fk.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.FK); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } // update column type: DIMENSION AND MEASURE List<ModelDimensionDesc> dimensions = dataModelDesc.getDimensions(); for (ModelDimensionDesc dimension : dimensions) { for (String column : dimension.getColumns()) { String columnIdentity = (dataModelDesc.findTable(dimension.getTable()).getTableIdentity() + "." + column).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.DIMENSION); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } String[] measures = dataModelDesc.getMetrics(); for (String measure : measures) { String columnIdentity = (dataModelDesc.findTable(measure.substring(0, measure.indexOf("."))) .getTableIdentity() + measure.substring(measure.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.MEASURE); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } } return tableMetas; } protected void processStatementAttr(Statement s, SQLRequest sqlRequest) throws SQLException { Integer statementMaxRows = BackdoorToggles.getStatementMaxRows(); if (statementMaxRows != null) { logger.info("Setting current statement's max rows to {}", statementMaxRows); s.setMaxRows(statementMaxRows); } } /** * @param correctedSql * @param sqlRequest * @return * @throws Exception */ private SQLResponse execute(String correctedSql, SQLRequest sqlRequest, Connection conn) throws Exception { Statement stat = null; ResultSet resultSet = null; boolean isPushDown = false; List<List<String>> results = Lists.newArrayList(); List<SelectedColumnMeta> columnMetas = Lists.newArrayList(); try { // special case for prepare query. if (BackdoorToggles.getPrepareOnly()) { return getPrepareOnlySqlResponse(correctedSql, conn, isPushDown, results, columnMetas); } if (isPrepareStatementWithParams(sqlRequest)) { stat = conn.prepareStatement(correctedSql); // to be closed in the finally PreparedStatement prepared = (PreparedStatement) stat; processStatementAttr(prepared, sqlRequest); for (int i = 0; i < ((PrepareSqlRequest) sqlRequest).getParams().length; i++) { setParam(prepared, i + 1, ((PrepareSqlRequest) sqlRequest).getParams()[i]); } resultSet = prepared.executeQuery(); } else { stat = conn.createStatement(); processStatementAttr(stat, sqlRequest); resultSet = stat.executeQuery(correctedSql); } ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); // Fill in selected column meta for (int i = 1; i <= columnCount; ++i) { columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i), metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i), metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i), metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i), metaData.isWritable(i), metaData.isDefinitelyWritable(i))); } // fill in results while (resultSet.next()) { List<String> oneRow = Lists.newArrayListWithCapacity(columnCount); for (int i = 0; i < columnCount; i++) { oneRow.add((resultSet.getString(i + 1))); } results.add(oneRow); } } catch (SQLException sqlException) { Pair<List<List<String>>, List<SelectedColumnMeta>> r = null; try { r = PushDownUtil.tryPushDownSelectQuery(sqlRequest.getProject(), correctedSql, conn.getSchema(), sqlException, BackdoorToggles.getPrepareOnly()); } catch (Exception e2) { logger.error("pushdown engine failed current query too", e2); //exception in pushdown, throw it instead of exception in calcite throw e2; } if (r == null) throw sqlException; isPushDown = true; results = r.getFirst(); columnMetas = r.getSecond(); } finally { close(resultSet, stat, null); //conn is passed in, not my duty to close } return buildSqlResponse(isPushDown, results, columnMetas); } protected String makeErrorMsgUserFriendly(Throwable e) { return QueryUtil.makeErrorMsgUserFriendly(e); } private SQLResponse getPrepareOnlySqlResponse(String correctedSql, Connection conn, Boolean isPushDown, List<List<String>> results, List<SelectedColumnMeta> columnMetas) throws SQLException { CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(true); PreparedStatement preparedStatement = null; try { preparedStatement = conn.prepareStatement(correctedSql); throw new IllegalStateException("Should have thrown OnlyPrepareEarlyAbortException"); } catch (Exception e) { Throwable rootCause = ExceptionUtils.getRootCause(e); if (rootCause != null && rootCause instanceof OnlyPrepareEarlyAbortException) { OnlyPrepareEarlyAbortException abortException = (OnlyPrepareEarlyAbortException) rootCause; CalcitePrepare.Context context = abortException.getContext(); CalcitePrepare.ParseResult preparedResult = abortException.getPreparedResult(); List<RelDataTypeField> fieldList = preparedResult.rowType.getFieldList(); CalciteConnectionConfig config = context.config(); // Fill in selected column meta for (int i = 0; i < fieldList.size(); ++i) { RelDataTypeField field = fieldList.get(i); String columnName = field.getKey(); if (columnName.startsWith("_KY_")) { continue; } BasicSqlType basicSqlType = (BasicSqlType) field.getValue(); columnMetas.add(new SelectedColumnMeta(false, config.caseSensitive(), false, false, basicSqlType.isNullable() ? 1 : 0, true, basicSqlType.getPrecision(), columnName, columnName, null, null, null, basicSqlType.getPrecision(), basicSqlType.getScale() < 0 ? 0 : basicSqlType.getScale(), basicSqlType.getSqlTypeName().getJdbcOrdinal(), basicSqlType.getSqlTypeName().getName(), true, false, false)); } } else { throw e; } } finally { CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(false); DBUtils.closeQuietly(preparedStatement); } return buildSqlResponse(isPushDown, results, columnMetas); } private boolean isPrepareStatementWithParams(SQLRequest sqlRequest) { if (sqlRequest instanceof PrepareSqlRequest && ((PrepareSqlRequest) sqlRequest).getParams() != null && ((PrepareSqlRequest) sqlRequest).getParams().length > 0) return true; return false; } private SQLResponse buildSqlResponse(Boolean isPushDown, List<List<String>> results, List<SelectedColumnMeta> columnMetas) { boolean isPartialResult = false; StringBuilder cubeSb = new StringBuilder(); StringBuilder logSb = new StringBuilder("Processed rows for each storageContext: "); if (OLAPContext.getThreadLocalContexts() != null) { // contexts can be null in case of 'explain plan for' for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) { if (ctx.realization != null) { isPartialResult |= ctx.storageContext.isPartialResultReturned(); if (cubeSb.length() > 0) { cubeSb.append(","); } cubeSb.append(ctx.realization.getCanonicalName()); logSb.append(ctx.storageContext.getProcessedRowCount()).append(" "); } } } logger.info(logSb.toString()); SQLResponse response = new SQLResponse(columnMetas, results, cubeSb.toString(), 0, false, null, isPartialResult, isPushDown); response.setTotalScanCount(QueryContext.current().getScannedRows()); response.setTotalScanBytes(QueryContext.current().getScannedBytes()); return response; } /** * @param preparedState * @param param * @throws SQLException */ private void setParam(PreparedStatement preparedState, int index, PrepareSqlRequest.StateParam param) throws SQLException { boolean isNull = (null == param.getValue()); Class<?> clazz; try { clazz = Class.forName(param.getClassName()); } catch (ClassNotFoundException e) { throw new InternalErrorException(e); } Rep rep = Rep.of(clazz); switch (rep) { case PRIMITIVE_CHAR: case CHARACTER: case STRING: preparedState.setString(index, isNull ? null : String.valueOf(param.getValue())); break; case PRIMITIVE_INT: case INTEGER: preparedState.setInt(index, isNull ? 0 : Integer.valueOf(param.getValue())); break; case PRIMITIVE_SHORT: case SHORT: preparedState.setShort(index, isNull ? 0 : Short.valueOf(param.getValue())); break; case PRIMITIVE_LONG: case LONG: preparedState.setLong(index, isNull ? 0 : Long.valueOf(param.getValue())); break; case PRIMITIVE_FLOAT: case FLOAT: preparedState.setFloat(index, isNull ? 0 : Float.valueOf(param.getValue())); break; case PRIMITIVE_DOUBLE: case DOUBLE: preparedState.setDouble(index, isNull ? 0 : Double.valueOf(param.getValue())); break; case PRIMITIVE_BOOLEAN: case BOOLEAN: preparedState.setBoolean(index, !isNull && Boolean.parseBoolean(param.getValue())); break; case PRIMITIVE_BYTE: case BYTE: preparedState.setByte(index, isNull ? 0 : Byte.valueOf(param.getValue())); break; case JAVA_UTIL_DATE: case JAVA_SQL_DATE: preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue())); break; case JAVA_SQL_TIME: preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue())); break; case JAVA_SQL_TIMESTAMP: preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue())); break; default: preparedState.setObject(index, isNull ? null : param.getValue()); } } protected int getInt(String content) { try { return Integer.parseInt(content); } catch (Exception e) { return -1; } } protected short getShort(String content) { try { return Short.parseShort(content); } catch (Exception e) { return -1; } } public void setCacheManager(CacheManager cacheManager) { this.cacheManager = cacheManager; } private static class QueryRecordSerializer implements Serializer<QueryRecord> { private static final QueryRecordSerializer serializer = new QueryRecordSerializer(); QueryRecordSerializer() { } public static QueryRecordSerializer getInstance() { return serializer; } @Override public void serialize(QueryRecord record, DataOutputStream out) throws IOException { String jsonStr = JsonUtil.writeValueAsString(record); out.writeUTF(jsonStr); } @Override public QueryRecord deserialize(DataInputStream in) throws IOException { String jsonStr = in.readUTF(); return JsonUtil.readValue(jsonStr, QueryRecord.class); } } } @SuppressWarnings("serial") class QueryRecord extends RootPersistentEntity { @JsonProperty() private Query[] queries; public QueryRecord() { } public QueryRecord(Query[] queries) { this.queries = queries; } public Query[] getQueries() { return queries; } public void setQueries(Query[] queries) { this.queries = queries; } }
server-base/src/main/java/org/apache/kylin/rest/service/QueryService.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.kylin.rest.service; import static org.apache.kylin.common.util.CheckUtil.checkCondition; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; import org.apache.calcite.avatica.ColumnMetaData.Rep; import org.apache.calcite.config.CalciteConnectionConfig; import org.apache.calcite.jdbc.CalcitePrepare; import org.apache.calcite.prepare.CalcitePrepareImpl; import org.apache.calcite.prepare.OnlyPrepareEarlyAbortException; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.sql.type.BasicSqlType; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.QueryContext; import org.apache.kylin.common.debug.BackdoorToggles; import org.apache.kylin.common.exceptions.ResourceLimitExceededException; import org.apache.kylin.common.htrace.HtraceInit; import org.apache.kylin.common.persistence.ResourceStore; import org.apache.kylin.common.persistence.RootPersistentEntity; import org.apache.kylin.common.persistence.Serializer; import org.apache.kylin.common.util.DBUtils; import org.apache.kylin.common.util.JsonUtil; import org.apache.kylin.common.util.Pair; import org.apache.kylin.common.util.SetThreadName; import org.apache.kylin.cube.CubeInstance; import org.apache.kylin.cube.CubeManager; import org.apache.kylin.cube.cuboid.Cuboid; import org.apache.kylin.metadata.badquery.BadQueryEntry; import org.apache.kylin.metadata.model.DataModelDesc; import org.apache.kylin.metadata.model.JoinDesc; import org.apache.kylin.metadata.model.JoinTableDesc; import org.apache.kylin.metadata.model.ModelDimensionDesc; import org.apache.kylin.metadata.model.TableRef; import org.apache.kylin.metadata.project.ProjectInstance; import org.apache.kylin.metadata.project.RealizationEntry; import org.apache.kylin.metadata.querymeta.ColumnMeta; import org.apache.kylin.metadata.querymeta.ColumnMetaWithType; import org.apache.kylin.metadata.querymeta.SelectedColumnMeta; import org.apache.kylin.metadata.querymeta.TableMeta; import org.apache.kylin.metadata.querymeta.TableMetaWithType; import org.apache.kylin.metadata.realization.RealizationType; import org.apache.kylin.query.QueryConnection; import org.apache.kylin.query.relnode.OLAPContext; import org.apache.kylin.query.util.PushDownUtil; import org.apache.kylin.query.util.QueryUtil; import org.apache.kylin.query.util.TempStatementUtil; import org.apache.kylin.rest.constant.Constant; import org.apache.kylin.rest.exception.BadRequestException; import org.apache.kylin.rest.exception.InternalErrorException; import org.apache.kylin.rest.metrics.QueryMetrics2Facade; import org.apache.kylin.rest.metrics.QueryMetricsFacade; import org.apache.kylin.rest.model.Query; import org.apache.kylin.rest.msg.Message; import org.apache.kylin.rest.msg.MsgPicker; import org.apache.kylin.rest.request.PrepareSqlRequest; import org.apache.kylin.rest.request.SQLRequest; import org.apache.kylin.rest.response.SQLResponse; import org.apache.kylin.rest.util.AclEvaluate; import org.apache.kylin.rest.util.AclPermissionUtil; import org.apache.kylin.rest.util.TableauInterceptor; import org.apache.kylin.shaded.htrace.org.apache.htrace.Sampler; import org.apache.kylin.shaded.htrace.org.apache.htrace.Trace; import org.apache.kylin.shaded.htrace.org.apache.htrace.TraceScope; import org.apache.kylin.storage.hybrid.HybridInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * @author xduo */ @Component("queryService") public class QueryService extends BasicService { public static final String SUCCESS_QUERY_CACHE = "StorageCache"; public static final String EXCEPTION_QUERY_CACHE = "ExceptionQueryCache"; public static final String QUERY_STORE_PATH_PREFIX = "/query/"; private static final Logger logger = LoggerFactory.getLogger(QueryService.class); final BadQueryDetector badQueryDetector = new BadQueryDetector(); final ResourceStore queryStore; @Autowired protected CacheManager cacheManager; @Autowired @Qualifier("cacheService") private CacheService cacheService; @Autowired @Qualifier("modelMgmtService") private ModelService modelService; @Autowired private AclEvaluate aclEvaluate; public QueryService() { queryStore = ResourceStore.getStore(getConfig()); badQueryDetector.start(); } protected static void close(ResultSet resultSet, Statement stat, Connection conn) { OLAPContext.clearParameter(); DBUtils.closeQuietly(resultSet); DBUtils.closeQuietly(stat); DBUtils.closeQuietly(conn); } private static String getQueryKeyById(String creator) { return QUERY_STORE_PATH_PREFIX + creator; } @PostConstruct public void init() throws IOException { Preconditions.checkNotNull(cacheManager, "cacheManager is not injected yet"); } public List<TableMeta> getMetadata(String project) throws SQLException { return getMetadata(getCubeManager(), project); } public SQLResponse query(SQLRequest sqlRequest) throws Exception { SQLResponse ret = null; try { final String user = SecurityContextHolder.getContext().getAuthentication().getName(); badQueryDetector.queryStart(Thread.currentThread(), sqlRequest, user); ret = queryWithSqlMassage(sqlRequest); return ret; } finally { String badReason = (ret != null && ret.isPushDown()) ? BadQueryEntry.ADJ_PUSHDOWN : null; badQueryDetector.queryEnd(Thread.currentThread(), badReason); } } public SQLResponse update(SQLRequest sqlRequest) throws Exception { // non select operations, only supported when enable pushdown logger.debug("Query pushdown enabled, redirect the non-select query to pushdown engine."); Connection conn = null; try { conn = QueryConnection.getConnection(sqlRequest.getProject()); Pair<List<List<String>>, List<SelectedColumnMeta>> r = PushDownUtil.tryPushDownNonSelectQuery( sqlRequest.getProject(), sqlRequest.getSql(), conn.getSchema(), BackdoorToggles.getPrepareOnly()); List<SelectedColumnMeta> columnMetas = Lists.newArrayList(); columnMetas.add(new SelectedColumnMeta(false, false, false, false, 1, false, Integer.MAX_VALUE, "c0", "c0", null, null, null, Integer.MAX_VALUE, 128, 1, "char", false, false, false)); return buildSqlResponse(true, r.getFirst(), columnMetas); } catch (Exception e) { logger.info("pushdown engine failed to finish current non-select query"); throw e; } finally { close(null, null, conn); } } public void saveQuery(final String creator, final Query query) throws IOException { List<Query> queries = getQueries(creator); queries.add(query); Query[] queryArray = new Query[queries.size()]; QueryRecord record = new QueryRecord(queries.toArray(queryArray)); queryStore.putResourceWithoutCheck(getQueryKeyById(creator), record, System.currentTimeMillis(), QueryRecordSerializer.getInstance()); return; } public void removeQuery(final String creator, final String id) throws IOException { List<Query> queries = getQueries(creator); Iterator<Query> queryIter = queries.iterator(); boolean changed = false; while (queryIter.hasNext()) { Query temp = queryIter.next(); if (temp.getId().equals(id)) { queryIter.remove(); changed = true; break; } } if (!changed) { return; } Query[] queryArray = new Query[queries.size()]; QueryRecord record = new QueryRecord(queries.toArray(queryArray)); queryStore.putResourceWithoutCheck(getQueryKeyById(creator), record, System.currentTimeMillis(), QueryRecordSerializer.getInstance()); return; } public List<Query> getQueries(final String creator) throws IOException { if (null == creator) { return null; } List<Query> queries = new ArrayList<Query>(); QueryRecord record = queryStore.getResource(getQueryKeyById(creator), QueryRecord.class, QueryRecordSerializer.getInstance()); if (record != null) { for (Query query : record.getQueries()) { queries.add(query); } } return queries; } public void logQuery(final SQLRequest request, final SQLResponse response) { final String user = aclEvaluate.getCurrentUserName(); final List<String> realizationNames = new LinkedList<>(); final Set<Long> cuboidIds = new HashSet<Long>(); float duration = response.getDuration() / (float) 1000; boolean storageCacheUsed = response.isStorageCacheUsed(); boolean isPushDown = response.isPushDown(); if (!response.isHitExceptionCache() && null != OLAPContext.getThreadLocalContexts()) { for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) { Cuboid cuboid = ctx.storageContext.getCuboid(); if (cuboid != null) { //Some queries do not involve cuboid, e.g. lookup table query cuboidIds.add(cuboid.getId()); } if (ctx.realization != null) { realizationNames.add(ctx.realization.getCanonicalName()); } } } int resultRowCount = 0; if (!response.getIsException() && response.getResults() != null) { resultRowCount = response.getResults().size(); } String newLine = System.getProperty("line.separator"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(newLine); stringBuilder.append("==========================[QUERY]===============================").append(newLine); stringBuilder.append("Query Id: ").append(QueryContext.current().getQueryId()).append(newLine); stringBuilder.append("SQL: ").append(request.getSql()).append(newLine); stringBuilder.append("User: ").append(user).append(newLine); stringBuilder.append("Success: ").append((null == response.getExceptionMessage())).append(newLine); stringBuilder.append("Duration: ").append(duration).append(newLine); stringBuilder.append("Project: ").append(request.getProject()).append(newLine); stringBuilder.append("Realization Names: ").append(realizationNames).append(newLine); stringBuilder.append("Cuboid Ids: ").append(cuboidIds).append(newLine); stringBuilder.append("Total scan count: ").append(response.getTotalScanCount()).append(newLine); stringBuilder.append("Total scan bytes: ").append(response.getTotalScanBytes()).append(newLine); stringBuilder.append("Result row count: ").append(resultRowCount).append(newLine); stringBuilder.append("Accept Partial: ").append(request.isAcceptPartial()).append(newLine); stringBuilder.append("Is Partial Result: ").append(response.isPartial()).append(newLine); stringBuilder.append("Hit Exception Cache: ").append(response.isHitExceptionCache()).append(newLine); stringBuilder.append("Storage cache used: ").append(storageCacheUsed).append(newLine); stringBuilder.append("Is Query Push-Down: ").append(isPushDown).append(newLine); stringBuilder.append("Trace URL: ").append(response.getTraceUrl()).append(newLine); stringBuilder.append("Message: ").append(response.getExceptionMessage()).append(newLine); stringBuilder.append("==========================[QUERY]===============================").append(newLine); logger.info(stringBuilder.toString()); } public void checkAuthorization(SQLResponse sqlResponse, String project) throws AccessDeniedException { //project ProjectInstance projectInstance = getProjectManager().getProject(project); try { if (aclEvaluate.hasProjectReadPermission(projectInstance)) { return; } } catch (AccessDeniedException e) { logger.warn( "Current user {} has no READ permission on current project {}, please ask Administrator for permission granting."); //just continue } String realizationsStr = sqlResponse.getCube();//CUBE[name=abc],HYBRID[name=xyz] if (StringUtils.isEmpty(realizationsStr)) { throw new AccessDeniedException( "Query pushdown requires having READ permission on project, please ask Administrator to grant you permissions"); } String[] splits = StringUtils.split(realizationsStr, ","); for (String split : splits) { Iterable<String> parts = Splitter.on(CharMatcher.anyOf("[]=,")).split(split); String[] partsStr = Iterables.toArray(parts, String.class); if (RealizationType.HYBRID.toString().equals(partsStr[0])) { // special care for hybrid HybridInstance hybridInstance = getHybridManager().getHybridInstance(partsStr[2]); Preconditions.checkNotNull(hybridInstance); checkHybridAuthorization(hybridInstance); } else { CubeInstance cubeInstance = getCubeManager().getCube(partsStr[2]); checkCubeAuthorization(cubeInstance); } } } private void checkCubeAuthorization(CubeInstance cube) throws AccessDeniedException { Preconditions.checkState(aclEvaluate.hasCubeReadPermission(cube)); } private void checkHybridAuthorization(HybridInstance hybridInstance) throws AccessDeniedException { List<RealizationEntry> realizationEntries = hybridInstance.getRealizationEntries(); for (RealizationEntry realizationEntry : realizationEntries) { String reName = realizationEntry.getRealization(); if (RealizationType.CUBE == realizationEntry.getType()) { CubeInstance cubeInstance = getCubeManager().getCube(reName); checkCubeAuthorization(cubeInstance); } else if (RealizationType.HYBRID == realizationEntry.getType()) { HybridInstance innerHybridInstance = getHybridManager().getHybridInstance(reName); checkHybridAuthorization(innerHybridInstance); } } } public SQLResponse doQueryWithCache(SQLRequest sqlRequest) { return doQueryWithCache(sqlRequest, false); } public SQLResponse doQueryWithCache(SQLRequest sqlRequest, boolean isQueryInspect) { Message msg = MsgPicker.getMsg(); sqlRequest.setUsername(getUserName()); KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv(); String serverMode = kylinConfig.getServerMode(); if (!(Constant.SERVER_MODE_QUERY.equals(serverMode.toLowerCase()) || Constant.SERVER_MODE_ALL.equals(serverMode.toLowerCase()))) { throw new BadRequestException(String.format(msg.getQUERY_NOT_ALLOWED(), serverMode)); } if (StringUtils.isBlank(sqlRequest.getProject())) { throw new BadRequestException(msg.getEMPTY_PROJECT_NAME()); } if (sqlRequest.getBackdoorToggles() != null) BackdoorToggles.addToggles(sqlRequest.getBackdoorToggles()); final QueryContext queryContext = QueryContext.current(); TraceScope scope = null; if (KylinConfig.getInstanceFromEnv().isHtraceTracingEveryQuery() || BackdoorToggles.getHtraceEnabled()) { logger.info("Current query is under tracing"); HtraceInit.init(); scope = Trace.startSpan("query life cycle for " + queryContext.getQueryId(), Sampler.ALWAYS); } String traceUrl = getTraceUrl(scope); try (SetThreadName ignored = new SetThreadName("Query %s", queryContext.getQueryId())) { String sql = sqlRequest.getSql(); String project = sqlRequest.getProject(); logger.info("Using project: " + project); logger.info("The original query: " + sql); sql = QueryUtil.removeCommentInSql(sql); Pair<Boolean, String> result = TempStatementUtil.handleTempStatement(sql, kylinConfig); boolean isTempStatement = result.getFirst(); sql = result.getSecond(); sqlRequest.setSql(sql); final boolean isSelect = QueryUtil.isSelectStatement(sql); long startTime = System.currentTimeMillis(); SQLResponse sqlResponse = null; boolean queryCacheEnabled = checkCondition(kylinConfig.isQueryCacheEnabled(), "query cache disabled in KylinConfig") && // checkCondition(!BackdoorToggles.getDisableCache(), "query cache disabled in BackdoorToggles"); if (queryCacheEnabled) { sqlResponse = searchQueryInCache(sqlRequest); Trace.addTimelineAnnotation("query cache searched"); } else { Trace.addTimelineAnnotation("query cache skip search"); } try { if (null == sqlResponse) { if (isQueryInspect) { // set query sql to exception message string sqlResponse = new SQLResponse(null, null, 0, false, sqlRequest.getSql()); } else if (isTempStatement) { sqlResponse = new SQLResponse(null, null, 0, false, null); } else if (isSelect) { sqlResponse = query(sqlRequest); Trace.addTimelineAnnotation("query almost done"); } else if (kylinConfig.isPushDownEnabled() && kylinConfig.isPushDownUpdateEnabled()) { sqlResponse = update(sqlRequest); Trace.addTimelineAnnotation("update query almost done"); } else { logger.debug( "Directly return exception as the sql is unsupported, and query pushdown is disabled"); throw new BadRequestException(msg.getNOT_SUPPORTED_SQL()); } long durationThreshold = kylinConfig.getQueryDurationCacheThreshold(); long scanCountThreshold = kylinConfig.getQueryScanCountCacheThreshold(); long scanBytesThreshold = kylinConfig.getQueryScanBytesCacheThreshold(); sqlResponse.setDuration(System.currentTimeMillis() - startTime); logger.info("Stats of SQL response: isException: {}, duration: {}, total scan count {}", // String.valueOf(sqlResponse.getIsException()), String.valueOf(sqlResponse.getDuration()), String.valueOf(sqlResponse.getTotalScanCount())); if (checkCondition(queryCacheEnabled, "query cache is disabled") // && checkCondition(!sqlResponse.getIsException(), "query has exception") // && checkCondition(!(sqlResponse.isPushDown() && (isSelect == false || kylinConfig.isPushdownQueryCacheEnabled() == false)), "query is executed with pushdown, but it is non-select, or the cache for pushdown is disabled") // && checkCondition( sqlResponse.getDuration() > durationThreshold || sqlResponse.getTotalScanCount() > scanCountThreshold || sqlResponse.getTotalScanBytes() > scanBytesThreshold, // "query is too lightweight with duration: {} (threshold {}), scan count: {} (threshold {}), scan bytes: {} (threshold {})", sqlResponse.getDuration(), durationThreshold, sqlResponse.getTotalScanCount(), scanCountThreshold, sqlResponse.getTotalScanBytes(), scanBytesThreshold) && checkCondition(sqlResponse.getResults().size() < kylinConfig.getLargeQueryThreshold(), "query response is too large: {} ({})", sqlResponse.getResults().size(), kylinConfig.getLargeQueryThreshold())) { cacheManager.getCache(SUCCESS_QUERY_CACHE) .put(new Element(sqlRequest.getCacheKey(), sqlResponse)); } Trace.addTimelineAnnotation("response from execution"); } else { sqlResponse.setDuration(System.currentTimeMillis() - startTime); sqlResponse.setTotalScanCount(0); sqlResponse.setTotalScanBytes(0); Trace.addTimelineAnnotation("response from cache"); } checkQueryAuth(sqlResponse, project); } catch (Throwable e) { // calcite may throw AssertError logger.error("Exception while executing query", e); String errMsg = makeErrorMsgUserFriendly(e); sqlResponse = new SQLResponse(null, null, null, 0, true, errMsg, false, false); sqlResponse.setTotalScanCount(queryContext.getScannedRows()); sqlResponse.setTotalScanBytes(queryContext.getScannedBytes()); if (queryCacheEnabled && e.getCause() != null && ExceptionUtils.getRootCause(e) instanceof ResourceLimitExceededException) { Cache exceptionCache = cacheManager.getCache(EXCEPTION_QUERY_CACHE); exceptionCache.put(new Element(sqlRequest.getCacheKey(), sqlResponse)); } Trace.addTimelineAnnotation("error response"); } sqlResponse.setTraceUrl(traceUrl); logQuery(sqlRequest, sqlResponse); QueryMetricsFacade.updateMetrics(sqlRequest, sqlResponse); QueryMetrics2Facade.updateMetrics(sqlRequest, sqlResponse); if (sqlResponse.getIsException()) throw new InternalErrorException(sqlResponse.getExceptionMessage()); return sqlResponse; } finally { BackdoorToggles.cleanToggles(); QueryContext.reset(); if (scope != null) { scope.close(); } } } private String getTraceUrl(TraceScope scope) { if (scope == null) { return null; } String hostname = System.getProperty("zipkin.collector-hostname"); if (StringUtils.isEmpty(hostname)) { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.debug("failed to get trace url due to " + e.getMessage()); return null; } } String port = System.getProperty("zipkin.web-ui-port"); if (StringUtils.isEmpty(port)) { port = "9411"; } return "http://" + hostname + ":" + port + "/zipkin/traces/" + Long.toHexString(scope.getSpan().getTraceId()); } private String getUserName() { String username = SecurityContextHolder.getContext().getAuthentication().getName(); if (StringUtils.isEmpty(username)) { username = ""; } return username; } public SQLResponse searchQueryInCache(SQLRequest sqlRequest) { SQLResponse response = null; Cache exceptionCache = cacheManager.getCache(EXCEPTION_QUERY_CACHE); Cache successCache = cacheManager.getCache(SUCCESS_QUERY_CACHE); Element element = null; if ((element = exceptionCache.get(sqlRequest.getCacheKey())) != null) { logger.info("The sqlResponse is found in EXCEPTION_QUERY_CACHE"); response = (SQLResponse) element.getObjectValue(); response.setHitExceptionCache(true); } else if ((element = successCache.get(sqlRequest.getCacheKey())) != null) { logger.info("The sqlResponse is found in SUCCESS_QUERY_CACHE"); response = (SQLResponse) element.getObjectValue(); response.setStorageCacheUsed(true); } return response; } protected void checkQueryAuth(SQLResponse sqlResponse, String project) throws AccessDeniedException { if (!sqlResponse.getIsException() && KylinConfig.getInstanceFromEnv().isQuerySecureEnabled()) { checkAuthorization(sqlResponse, project); } } private SQLResponse queryWithSqlMassage(SQLRequest sqlRequest) throws Exception { Connection conn = null; try { conn = QueryConnection.getConnection(sqlRequest.getProject()); String userInfo = SecurityContextHolder.getContext().getAuthentication().getName(); QueryContext context = QueryContext.current(); context.setUsername(userInfo); context.setGroups(AclPermissionUtil.getCurrentUserGroups()); final Collection<? extends GrantedAuthority> grantedAuthorities = SecurityContextHolder.getContext() .getAuthentication().getAuthorities(); for (GrantedAuthority grantedAuthority : grantedAuthorities) { userInfo += ","; userInfo += grantedAuthority.getAuthority(); } SQLResponse fakeResponse = TableauInterceptor.tableauIntercept(sqlRequest.getSql()); if (null != fakeResponse) { logger.debug("Return fake response, is exception? " + fakeResponse.getIsException()); return fakeResponse; } String correctedSql = QueryUtil.massageSql(sqlRequest.getSql(), sqlRequest.getProject(), sqlRequest.getLimit(), sqlRequest.getOffset(), conn.getSchema()); if (!correctedSql.equals(sqlRequest.getSql())) { logger.info("The corrected query: " + correctedSql); //CAUTION: should not change sqlRequest content! //sqlRequest.setSql(correctedSql); } Trace.addTimelineAnnotation("query massaged"); // add extra parameters into olap context, like acceptPartial Map<String, String> parameters = new HashMap<String, String>(); parameters.put(OLAPContext.PRM_USER_AUTHEN_INFO, userInfo); parameters.put(OLAPContext.PRM_ACCEPT_PARTIAL_RESULT, String.valueOf(sqlRequest.isAcceptPartial())); OLAPContext.setParameters(parameters); // force clear the query context before a new query OLAPContext.clearThreadLocalContexts(); return execute(correctedSql, sqlRequest, conn); } finally { DBUtils.closeQuietly(conn); } } protected List<TableMeta> getMetadata(CubeManager cubeMgr, String project) throws SQLException { Connection conn = null; ResultSet columnMeta = null; List<TableMeta> tableMetas = null; if (StringUtils.isBlank(project)) { return Collections.emptyList(); } ResultSet JDBCTableMeta = null; try { conn = QueryConnection.getConnection(project); DatabaseMetaData metaData = conn.getMetaData(); JDBCTableMeta = metaData.getTables(null, null, null, null); tableMetas = new LinkedList<TableMeta>(); Map<String, TableMeta> tableMap = new HashMap<String, TableMeta>(); while (JDBCTableMeta.next()) { String catalogName = JDBCTableMeta.getString(1); String schemaName = JDBCTableMeta.getString(2); // Not every JDBC data provider offers full 10 columns, e.g., PostgreSQL has only 5 TableMeta tblMeta = new TableMeta(catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3), JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null); if (!"metadata".equalsIgnoreCase(tblMeta.getTABLE_SCHEM())) { tableMetas.add(tblMeta); tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta); } } columnMeta = metaData.getColumns(null, null, null, null); while (columnMeta.next()) { String catalogName = columnMeta.getString(1); String schemaName = columnMeta.getString(2); // kylin(optiq) is not strictly following JDBC specification ColumnMeta colmnMeta = new ColumnMeta(catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3), columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6), columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9), columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12), columnMeta.getString(13), getInt(columnMeta.getString(14)), getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17), columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20), columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23)); if (!"metadata".equalsIgnoreCase(colmnMeta.getTABLE_SCHEM()) && !colmnMeta.getCOLUMN_NAME().toUpperCase().startsWith("_KY_")) { tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta); } } } finally { close(columnMeta, null, conn); if (JDBCTableMeta != null) { JDBCTableMeta.close(); } } return tableMetas; } public List<TableMetaWithType> getMetadataV2(String project) throws SQLException, IOException { return getMetadataV2(getCubeManager(), project); } @SuppressWarnings("checkstyle:methodlength") protected List<TableMetaWithType> getMetadataV2(CubeManager cubeMgr, String project) throws SQLException, IOException { //Message msg = MsgPicker.getMsg(); Connection conn = null; ResultSet columnMeta = null; List<TableMetaWithType> tableMetas = null; Map<String, TableMetaWithType> tableMap = null; Map<String, ColumnMetaWithType> columnMap = null; if (StringUtils.isBlank(project)) { return Collections.emptyList(); } ResultSet JDBCTableMeta = null; try { conn = QueryConnection.getConnection(project); DatabaseMetaData metaData = conn.getMetaData(); JDBCTableMeta = metaData.getTables(null, null, null, null); tableMetas = new LinkedList<TableMetaWithType>(); tableMap = new HashMap<String, TableMetaWithType>(); columnMap = new HashMap<String, ColumnMetaWithType>(); while (JDBCTableMeta.next()) { String catalogName = JDBCTableMeta.getString(1); String schemaName = JDBCTableMeta.getString(2); // Not every JDBC data provider offers full 10 columns, e.g., PostgreSQL has only 5 TableMetaWithType tblMeta = new TableMetaWithType( catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3), JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null); if (!"metadata".equalsIgnoreCase(tblMeta.getTABLE_SCHEM())) { tableMetas.add(tblMeta); tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta); } } columnMeta = metaData.getColumns(null, null, null, null); while (columnMeta.next()) { String catalogName = columnMeta.getString(1); String schemaName = columnMeta.getString(2); // kylin(optiq) is not strictly following JDBC specification ColumnMetaWithType colmnMeta = new ColumnMetaWithType( catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3), columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6), columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9), columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12), columnMeta.getString(13), getInt(columnMeta.getString(14)), getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17), columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20), columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23)); if (!"metadata".equalsIgnoreCase(colmnMeta.getTABLE_SCHEM()) && !colmnMeta.getCOLUMN_NAME().toUpperCase().startsWith("_KY_")) { tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta); columnMap.put(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME() + "#" + colmnMeta.getCOLUMN_NAME(), colmnMeta); } } } finally { close(columnMeta, null, conn); if (JDBCTableMeta != null) { JDBCTableMeta.close(); } } ProjectInstance projectInstance = getProjectManager().getProject(project); for (String modelName : projectInstance.getModels()) { DataModelDesc dataModelDesc = modelService.getModel(modelName, project); if (dataModelDesc != null && !dataModelDesc.isDraft()) { // update table type: FACT for (TableRef factTable : dataModelDesc.getFactTables()) { String factTableName = factTable.getTableIdentity().replace('.', '#'); if (tableMap.containsKey(factTableName)) { tableMap.get(factTableName).getTYPE().add(TableMetaWithType.tableTypeEnum.FACT); } else { // should be used after JDBC exposes all tables and columns // throw new BadRequestException(msg.getTABLE_META_INCONSISTENT()); } } // update table type: LOOKUP for (TableRef lookupTable : dataModelDesc.getLookupTables()) { String lookupTableName = lookupTable.getTableIdentity().replace('.', '#'); if (tableMap.containsKey(lookupTableName)) { tableMap.get(lookupTableName).getTYPE().add(TableMetaWithType.tableTypeEnum.LOOKUP); } else { // throw new BadRequestException(msg.getTABLE_META_INCONSISTENT()); } } // update column type: PK and FK for (JoinTableDesc joinTableDesc : dataModelDesc.getJoinTables()) { JoinDesc joinDesc = joinTableDesc.getJoin(); for (String pk : joinDesc.getPrimaryKey()) { String columnIdentity = (dataModelDesc.findTable(pk.substring(0, pk.indexOf("."))) .getTableIdentity() + pk.substring(pk.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.PK); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } for (String fk : joinDesc.getForeignKey()) { String columnIdentity = (dataModelDesc.findTable(fk.substring(0, fk.indexOf("."))) .getTableIdentity() + fk.substring(fk.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.FK); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } // update column type: DIMENSION AND MEASURE List<ModelDimensionDesc> dimensions = dataModelDesc.getDimensions(); for (ModelDimensionDesc dimension : dimensions) { for (String column : dimension.getColumns()) { String columnIdentity = (dataModelDesc.findTable(dimension.getTable()).getTableIdentity() + "." + column).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.DIMENSION); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } String[] measures = dataModelDesc.getMetrics(); for (String measure : measures) { String columnIdentity = (dataModelDesc.findTable(measure.substring(0, measure.indexOf("."))) .getTableIdentity() + measure.substring(measure.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.MEASURE); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } } return tableMetas; } protected void processStatementAttr(Statement s, SQLRequest sqlRequest) throws SQLException { Integer statementMaxRows = BackdoorToggles.getStatementMaxRows(); if (statementMaxRows != null) { logger.info("Setting current statement's max rows to {}", statementMaxRows); s.setMaxRows(statementMaxRows); } } /** * @param correctedSql * @param sqlRequest * @return * @throws Exception */ private SQLResponse execute(String correctedSql, SQLRequest sqlRequest, Connection conn) throws Exception { Statement stat = null; ResultSet resultSet = null; boolean isPushDown = false; List<List<String>> results = Lists.newArrayList(); List<SelectedColumnMeta> columnMetas = Lists.newArrayList(); try { // special case for prepare query. if (BackdoorToggles.getPrepareOnly()) { return getPrepareOnlySqlResponse(correctedSql, conn, isPushDown, results, columnMetas); } if (isPrepareStatementWithParams(sqlRequest)) { stat = conn.prepareStatement(correctedSql); // to be closed in the finally PreparedStatement prepared = (PreparedStatement) stat; processStatementAttr(prepared, sqlRequest); for (int i = 0; i < ((PrepareSqlRequest) sqlRequest).getParams().length; i++) { setParam(prepared, i + 1, ((PrepareSqlRequest) sqlRequest).getParams()[i]); } resultSet = prepared.executeQuery(); } else { stat = conn.createStatement(); processStatementAttr(stat, sqlRequest); resultSet = stat.executeQuery(correctedSql); } ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); // Fill in selected column meta for (int i = 1; i <= columnCount; ++i) { columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i), metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i), metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i), metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i), metaData.isWritable(i), metaData.isDefinitelyWritable(i))); } // fill in results while (resultSet.next()) { List<String> oneRow = Lists.newArrayListWithCapacity(columnCount); for (int i = 0; i < columnCount; i++) { oneRow.add((resultSet.getString(i + 1))); } results.add(oneRow); } } catch (SQLException sqlException) { Pair<List<List<String>>, List<SelectedColumnMeta>> r = null; try { r = PushDownUtil.tryPushDownSelectQuery(sqlRequest.getProject(), correctedSql, conn.getSchema(), sqlException, BackdoorToggles.getPrepareOnly()); } catch (Exception e2) { logger.error("pushdown engine failed current query too", e2); //exception in pushdown, throw it instead of exception in calcite throw e2; } if (r == null) throw sqlException; isPushDown = true; results = r.getFirst(); columnMetas = r.getSecond(); } finally { close(resultSet, stat, null); //conn is passed in, not my duty to close } return buildSqlResponse(isPushDown, results, columnMetas); } protected String makeErrorMsgUserFriendly(Throwable e) { return QueryUtil.makeErrorMsgUserFriendly(e); } private SQLResponse getPrepareOnlySqlResponse(String correctedSql, Connection conn, Boolean isPushDown, List<List<String>> results, List<SelectedColumnMeta> columnMetas) throws SQLException { CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(true); PreparedStatement preparedStatement = null; try { preparedStatement = conn.prepareStatement(correctedSql); throw new IllegalStateException("Should have thrown OnlyPrepareEarlyAbortException"); } catch (Exception e) { Throwable rootCause = ExceptionUtils.getRootCause(e); if (rootCause != null && rootCause instanceof OnlyPrepareEarlyAbortException) { OnlyPrepareEarlyAbortException abortException = (OnlyPrepareEarlyAbortException) rootCause; CalcitePrepare.Context context = abortException.getContext(); CalcitePrepare.ParseResult preparedResult = abortException.getPreparedResult(); List<RelDataTypeField> fieldList = preparedResult.rowType.getFieldList(); CalciteConnectionConfig config = context.config(); // Fill in selected column meta for (int i = 0; i < fieldList.size(); ++i) { RelDataTypeField field = fieldList.get(i); String columnName = field.getKey(); if (columnName.startsWith("_KY_")) { continue; } BasicSqlType basicSqlType = (BasicSqlType) field.getValue(); columnMetas.add(new SelectedColumnMeta(false, config.caseSensitive(), false, false, basicSqlType.isNullable() ? 1 : 0, true, basicSqlType.getPrecision(), columnName, columnName, null, null, null, basicSqlType.getPrecision(), basicSqlType.getScale() < 0 ? 0 : basicSqlType.getScale(), basicSqlType.getSqlTypeName().getJdbcOrdinal(), basicSqlType.getSqlTypeName().getName(), true, false, false)); } } else { throw e; } } finally { CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(false); DBUtils.closeQuietly(preparedStatement); } return buildSqlResponse(isPushDown, results, columnMetas); } private boolean isPrepareStatementWithParams(SQLRequest sqlRequest) { if (sqlRequest instanceof PrepareSqlRequest && ((PrepareSqlRequest) sqlRequest).getParams() != null && ((PrepareSqlRequest) sqlRequest).getParams().length > 0) return true; return false; } private SQLResponse buildSqlResponse(Boolean isPushDown, List<List<String>> results, List<SelectedColumnMeta> columnMetas) { boolean isPartialResult = false; StringBuilder cubeSb = new StringBuilder(); StringBuilder logSb = new StringBuilder("Processed rows for each storageContext: "); if (OLAPContext.getThreadLocalContexts() != null) { // contexts can be null in case of 'explain plan for' for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) { if (ctx.realization != null) { isPartialResult |= ctx.storageContext.isPartialResultReturned(); if (cubeSb.length() > 0) { cubeSb.append(","); } cubeSb.append(ctx.realization.getCanonicalName()); logSb.append(ctx.storageContext.getProcessedRowCount()).append(" "); } } } logger.info(logSb.toString()); SQLResponse response = new SQLResponse(columnMetas, results, cubeSb.toString(), 0, false, null, isPartialResult, isPushDown); response.setTotalScanCount(QueryContext.current().getScannedRows()); response.setTotalScanBytes(QueryContext.current().getScannedBytes()); return response; } /** * @param preparedState * @param param * @throws SQLException */ private void setParam(PreparedStatement preparedState, int index, PrepareSqlRequest.StateParam param) throws SQLException { boolean isNull = (null == param.getValue()); Class<?> clazz; try { clazz = Class.forName(param.getClassName()); } catch (ClassNotFoundException e) { throw new InternalErrorException(e); } Rep rep = Rep.of(clazz); switch (rep) { case PRIMITIVE_CHAR: case CHARACTER: case STRING: preparedState.setString(index, isNull ? null : String.valueOf(param.getValue())); break; case PRIMITIVE_INT: case INTEGER: preparedState.setInt(index, isNull ? 0 : Integer.valueOf(param.getValue())); break; case PRIMITIVE_SHORT: case SHORT: preparedState.setShort(index, isNull ? 0 : Short.valueOf(param.getValue())); break; case PRIMITIVE_LONG: case LONG: preparedState.setLong(index, isNull ? 0 : Long.valueOf(param.getValue())); break; case PRIMITIVE_FLOAT: case FLOAT: preparedState.setFloat(index, isNull ? 0 : Float.valueOf(param.getValue())); break; case PRIMITIVE_DOUBLE: case DOUBLE: preparedState.setDouble(index, isNull ? 0 : Double.valueOf(param.getValue())); break; case PRIMITIVE_BOOLEAN: case BOOLEAN: preparedState.setBoolean(index, !isNull && Boolean.parseBoolean(param.getValue())); break; case PRIMITIVE_BYTE: case BYTE: preparedState.setByte(index, isNull ? 0 : Byte.valueOf(param.getValue())); break; case JAVA_UTIL_DATE: case JAVA_SQL_DATE: preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue())); break; case JAVA_SQL_TIME: preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue())); break; case JAVA_SQL_TIMESTAMP: preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue())); break; default: preparedState.setObject(index, isNull ? null : param.getValue()); } } protected int getInt(String content) { try { return Integer.parseInt(content); } catch (Exception e) { return -1; } } protected short getShort(String content) { try { return Short.parseShort(content); } catch (Exception e) { return -1; } } public void setCacheManager(CacheManager cacheManager) { this.cacheManager = cacheManager; } private static class QueryRecordSerializer implements Serializer<QueryRecord> { private static final QueryRecordSerializer serializer = new QueryRecordSerializer(); QueryRecordSerializer() { } public static QueryRecordSerializer getInstance() { return serializer; } @Override public void serialize(QueryRecord record, DataOutputStream out) throws IOException { String jsonStr = JsonUtil.writeValueAsString(record); out.writeUTF(jsonStr); } @Override public QueryRecord deserialize(DataInputStream in) throws IOException { String jsonStr = in.readUTF(); return JsonUtil.readValue(jsonStr, QueryRecord.class); } } } @SuppressWarnings("serial") class QueryRecord extends RootPersistentEntity { @JsonProperty() private Query[] queries; public QueryRecord() { } public QueryRecord(Query[] queries) { this.queries = queries; } public Query[] getQueries() { return queries; } public void setQueries(Query[] queries) { this.queries = queries; } }
minor, refine metric.
server-base/src/main/java/org/apache/kylin/rest/service/QueryService.java
minor, refine metric.
<ide><path>erver-base/src/main/java/org/apache/kylin/rest/service/QueryService.java <ide> HtraceInit.init(); <ide> scope = Trace.startSpan("query life cycle for " + queryContext.getQueryId(), Sampler.ALWAYS); <ide> } <del> <ide> String traceUrl = getTraceUrl(scope); <ide> <ide> try (SetThreadName ignored = new SetThreadName("Query %s", queryContext.getQueryId())) { <ide> <ide> sqlResponse.setTraceUrl(traceUrl); <ide> logQuery(sqlRequest, sqlResponse); <del> <del> QueryMetricsFacade.updateMetrics(sqlRequest, sqlResponse); <del> QueryMetrics2Facade.updateMetrics(sqlRequest, sqlResponse); <del> <add> try { <add> recordMetric(sqlRequest, sqlResponse); <add> } catch (Throwable th) { <add> logger.warn("Write metric error.", th); <add> } <ide> if (sqlResponse.getIsException()) <ide> throw new InternalErrorException(sqlResponse.getExceptionMessage()); <ide> <ide> } finally { <ide> BackdoorToggles.cleanToggles(); <ide> QueryContext.reset(); <del> <ide> if (scope != null) { <ide> scope.close(); <ide> } <ide> } <add> } <add> <add> protected void recordMetric(SQLRequest sqlRequest, SQLResponse sqlResponse) throws UnknownHostException { <add> QueryMetricsFacade.updateMetrics(sqlRequest, sqlResponse); <add> QueryMetrics2Facade.updateMetrics(sqlRequest, sqlResponse); <ide> } <ide> <ide> private String getTraceUrl(TraceScope scope) {
JavaScript
apache-2.0
04d94ea4131e2f26defc35349a592038438d7761
0
cnwhy/ejs,zensh/ejs,insidewarehouse/ejs,tyduptyler13/ejs,kolonse/ejs,jtsay362/solveforall-ejs2,mmis1000/ejs-promise,TimothyGu/ejs-tj,rpaterson/ejs,insidewarehouse/ejs,TimothyGu/ejs-tj,xanxiver/ejs,mde/ejs,kolonse/ejs,cnwhy/ejs,operatino/ejs,zensh/ejs
/* * Geddy JavaScript Web development framework * Copyright 2112 Matthew Eernisse ([email protected]) * * 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. * */ var utils = require('utilities') , ejs; ejs = new (function () { this.compile = function (template) { var templ = new Template(template); return templ.compile(); }; this.render = function (template, data) { return (this.compile(template))(data); }; })(); var Template = function (text) { this.templateText = text; this.mode = null; this.truncate = false; this.currentLine = 1; this.source = ''; }; Template.prototype = new function () { var _REGEX = /(<%%)|(%%>)|(<%=)|(<%-)|(<%#)|(<%)|(%>)|(-%>)/ , _GLOBAL = (function () { return this; })(); this.modes = { EVAL: 'eval' , ESCAPED: 'escaped' , RAW: 'raw' , APPEND: 'append' , COMMENT: 'comment' , LITERAL: 'literal' }; this.handleErr = function (e, line) { var src = this.templateText.split('\n') , ctxt = '' , err = new Error() , start = Math.max(line - 3, 0) , end = Math.min(src.length, line + 3) , arr = src.slice(start, end) , curr; for (var i = 0, len = arr.length; i < len; i++) { curr = i + start + 1; ctxt += (curr == line ? ' >> ' : ' ') + curr + '| ' + arr[i] + '\n'; } err.name = e.name; err.message = 'ejs:' + line + '\n' + ctxt + e.message; throw err; }; this.compile = function () { var self = this , src; if (!this.source) { this.generateSource(); } src = 'var __output = "", __line = 1; with (locals) { try {' + this.source + '} catch (e) { rethrow(e, __line); } } return __output;'; fn = new Function('locals', src); rethrow = function (e, line) { self.handleErr(e, line); }; // Return a callable function which will execute the function // created by the source-code, with the passed data as locals return function (data, context) { // Prevent mixin pollution var d = utils.mixin({}, data); var locals = utils.mixin(d, { utils: utils , rethrow: rethrow }); return fn.call(context || _GLOBAL, locals); }; }; this.process = function (params) { var self = this , params = params || {} , domNode = params.node , src , fn , rethrow; this.data = params; this.source = this.source || ''; // Cache the template source for speed if(!this.source) this.generateSource(); src = 'var __output = "", __line = 1; with (locals) { try {' + this.source + '} catch (e) { rethrow(e, __line); } } return __output;'; fn = new Function('locals', src); rethrow = function (e, line) { self.handleErr(e, line); }; this.markup = fn.call(this, utils.mixin({ utils: utils , rethrow: rethrow }, this.data)); if (domNode) { domNode.innerHTML = this.markup; } return this.markup; }; this.generateSource = function () { var matches = this.parseTemplateText() , line , i; if (matches) { i = -1 while (++i < matches.length) { line = matches[i]; if (line) { this.scanLine(line); } } } }; this.parseTemplateText = function () { var str = this.templateText , pat = _REGEX , result = pat.exec(str) , arr = [] , firstPos , lastPos; while (result) { firstPos = result.index; lastPos = pat.lastIndex; if (firstPos !== 0) { arr.push(str.substring(0, firstPos)); str = str.slice(firstPos); } arr.push(result[0]); str = str.slice(result[0].length); result = pat.exec(str); } if (str !== '') { arr.push(str); } return arr; }; this.scanLine = function (line) { var self = this , newLineCount = 0 , _addOutput; _addOutput = function () { if (self.truncate) { line = line.replace('\n', ''); } // Preserve literal slashes line = line.replace(/\\/g, '\\\\'); // Convert linebreaks line = line.replace(/\n/g, '\\n'); line = line.replace(/\r/g, '\\r'); // Escape double-quotes // - this will be the delimiter during execution line = line.replace(/"/g, '\\"'); self.source += '__output += "' + line + '";'; }; newLineCount = (line.split('\n').length - 1); switch (line) { case '<%': this.mode = this.modes.EVAL; break; case '<%=': this.mode = this.modes.ESCAPED; break; case '<%-': this.mode = this.modes.RAW; break; case '<%#': this.mode = this.modes.COMMENT; break; case '<%%': this.mode = this.modes.LITERAL; this.source += '__output += "' + line.replace('<%%', '<%') + '";'; break; case '%>': case '-%>': if (this.mode == this.modes.LITERAL) { _addOutput(); } this.mode = null; this.truncate = line.indexOf('-') == 0; break; default: // In script mode, depends on type of tag if (this.mode) { switch (this.mode) { // Just executing code case this.modes.EVAL: this.source += line; break; // Exec, esc, and output case this.modes.ESCAPED: // Add the exec'd, escaped result to the output this.source += '__output += utils.string.escapeXML(' + line.replace(/;\S*/, '') + ');'; break; // Exec and output case this.modes.RAW: // Add the exec'd result to the output this.source += '__output += ' + line + ';'; break; case this.modes.COMMENT: // Do nothing break; // Literal <%% mode, append as raw output case this.modes.LITERAL: _addOutput(); break; } } // In string mode, just add the output else _addOutput(); } if (newLineCount) { this.currentLine += newLineCount; this.source += '__line = ' + this.currentLine + ';'; } }; }; module.exports = ejs;
lib/template/engines/ejs.js
/* * Geddy JavaScript Web development framework * Copyright 2112 Matthew Eernisse ([email protected]) * * 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. * */ var utils = require('utilities') , ejs; ejs = new (function () { this.compile = function (template) { var templ = new Template(template); return templ.compile(); }; this.render = function (template, data) { return (this.compile(template))(data); }; })(); var Template = function (text) { this.templateText = text; this.mode = null; this.truncate = false; this.currentLine = 1; this.source = ''; }; Template.prototype = new function () { var _REGEX = /(<%%)|(%%>)|(<%=)|(<%-)|(<%#)|(<%)|(%>)|(-%>)/ , _GLOBAL = (function () { return this; })(); this.modes = { EVAL: 'eval' , ESCAPED: 'escaped' , RAW: 'raw' , APPEND: 'append' , COMMENT: 'comment' , LITERAL: 'literal' }; this.handleErr = function (e, line) { var src = this.templateText.split('\n') , ctxt = '' , err = new Error() , start = Math.max(line - 3, 0) , end = Math.min(src.length, line + 3) , arr = src.slice(start, end) , curr; for (var i = 0, len = arr.length; i < len; i++) { curr = i + start + 1; ctxt += (curr == line ? ' >> ' : ' ') + curr + '| ' + arr[i] + '\n'; } err.name = e.name; err.message = 'ejs:' + line + '\n' + ctxt + e.message; throw err; }; this.compile = function () { var self = this , src; if (!this.source) { this.generateSource(); } src = 'var __output = "", __line = 1; with (locals) { try {' + this.source + '} catch (e) { rethrow(e, __line); } } return __output;'; fn = new Function('locals', src); rethrow = function (e, line) { self.handleErr(e, line); }; // Return a callable function which will execute the function // created by the source-code, with the passed data as locals return function (data, context) { var locals = utils.mixin(data, { utils: utils , rethrow: rethrow }); return fn.call(context || _GLOBAL, locals); }; }; this.process = function (params) { var self = this , params = params || {} , domNode = params.node , src , fn , rethrow; this.data = params; this.source = this.source || ''; // Cache the template source for speed if(!this.source) this.generateSource(); src = 'var __output = "", __line = 1; with (locals) { try {' + this.source + '} catch (e) { rethrow(e, __line); } } return __output;'; fn = new Function('locals', src); rethrow = function (e, line) { self.handleErr(e, line); }; this.markup = fn.call(this, utils.mixin({ utils: utils , rethrow: rethrow }, this.data)); if (domNode) { domNode.innerHTML = this.markup; } return this.markup; }; this.generateSource = function () { var matches = this.parseTemplateText() , line , i; if (matches) { i = -1 while (++i < matches.length) { line = matches[i]; if (line) { this.scanLine(line); } } } }; this.parseTemplateText = function () { var str = this.templateText , pat = _REGEX , result = pat.exec(str) , arr = [] , firstPos , lastPos; while (result) { firstPos = result.index; lastPos = pat.lastIndex; if (firstPos !== 0) { arr.push(str.substring(0, firstPos)); str = str.slice(firstPos); } arr.push(result[0]); str = str.slice(result[0].length); result = pat.exec(str); } if (str !== '') { arr.push(str); } return arr; }; this.scanLine = function (line) { var self = this , newLineCount = 0 , _addOutput; _addOutput = function () { if (self.truncate) { line = line.replace('\n', ''); } // Preserve literal slashes line = line.replace(/\\/g, '\\\\'); // Convert linebreaks line = line.replace(/\n/g, '\\n'); line = line.replace(/\r/g, '\\r'); // Escape double-quotes // - this will be the delimiter during execution line = line.replace(/"/g, '\\"'); self.source += '__output += "' + line + '";'; }; newLineCount = (line.split('\n').length - 1); switch (line) { case '<%': this.mode = this.modes.EVAL; break; case '<%=': this.mode = this.modes.ESCAPED; break; case '<%-': this.mode = this.modes.RAW; break; case '<%#': this.mode = this.modes.COMMENT; break; case '<%%': this.mode = this.modes.LITERAL; this.source += '__output += "' + line.replace('<%%', '<%') + '";'; break; case '%>': case '-%>': if (this.mode == this.modes.LITERAL) { _addOutput(); } this.mode = null; this.truncate = line.indexOf('-') == 0; break; default: // In script mode, depends on type of tag if (this.mode) { switch (this.mode) { // Just executing code case this.modes.EVAL: this.source += line; break; // Exec, esc, and output case this.modes.ESCAPED: // Add the exec'd, escaped result to the output this.source += '__output += utils.string.escapeXML(' + line.replace(/;\S*/, '') + ');'; break; // Exec and output case this.modes.RAW: // Add the exec'd result to the output this.source += '__output += ' + line + ';'; break; case this.modes.COMMENT: // Do nothing break; // Literal <%% mode, append as raw output case this.modes.LITERAL: _addOutput(); break; } } // In string mode, just add the output else _addOutput(); } if (newLineCount) { this.currentLine += newLineCount; this.source += '__line = ' + this.currentLine + ';'; } }; }; module.exports = ejs;
Avoid mixin pollution
lib/template/engines/ejs.js
Avoid mixin pollution
<ide><path>ib/template/engines/ejs.js <ide> // Return a callable function which will execute the function <ide> // created by the source-code, with the passed data as locals <ide> return function (data, context) { <del> var locals = utils.mixin(data, { <add> // Prevent mixin pollution <add> var d = utils.mixin({}, data); <add> var locals = utils.mixin(d, { <ide> utils: utils <ide> , rethrow: rethrow <ide> });
JavaScript
mit
16dc6fad36a2dad070de1376b2dcda51c2d87909
0
monomelodies/monad,monomelodies/monad
"use strict"; let isDateTime = new RegExp(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/); let isDate = new RegExp(/^(\d{4})-(\d{2})-(\d{2})/); let mapper = { Jan: '01', Feb: '02', Mar: '03', Apr: '04', May: '05', Jun: '06', Jul: '07', Aug: '08', Sep: '09', Oct: '10', Nov: '11', Dec: '12' }; function map(month) { return mapper[month]; }; /** * A data object with dirty checking and optional virtual members or other * additional logic. Implementors should generally extend this class, but this * is not required. */ export default class Model { /** * Class constructor. */ constructor() { /** * The "initial" state for this model. Used to check for pristineness. * This is automatically set when $load is called. */ this.$initial = undefined; /** * Internal data storage for this model. */ this.$data = {}; /** * Set to true if the model is scheduled for deletion. */ this.$deleted = false; } /** * Static method to create a new Model of this type, optionally specifying * default data and a class to derive from. * * @param object data Hash of key/value pairs of data. * @param class derivedClass Optional class to actually use when * instantiating (defaults to the current class). * @return mixed A new model of the desired class. */ static $create(data = {}, derivedClass = undefined) { derivedClass = derivedClass || Model; let instance = new derivedClass(); instance.$load(data); instance.$initial = undefined; return instance; } /** * Load data into this model instance. * * @param object data Hash of key/value pairs of data. * @return self */ $load(data = {}) { for (let key in data) { this.addField(key); this[key] = data[key]; } this.$initial = angular.copy(this.$data); return this; } addField(key) { if (!this.hasOwnProperty(key)) { var props = {enumerable: true, configurable: true}; props.get = () => { return this.$data[key]; }; props.set = value => { if (value != undefined) { let checkDate = isDateTime.exec(value); if (!checkDate) { checkDate = isDate.exec(value); } if (checkDate) { checkDate.shift(); // Javascript months are offset by 0 for reasons only Brendan Eich knows... checkDate[1]--; value = new Date(...checkDate); } } this.$data[key] = value; }; Object.defineProperty(this, key, props); } } /** * Virtual property to check if this model is "new". * * @return boolean True if new, false if existing. */ get $new() { return !this.$promise && this.$initial === undefined; } /** * Virtual property to check if this model is "dirty". * * @return boolean True if dirty, false if pristine. */ get $dirty() { if (this.$deleted) { return true; } for (let key in this) { if (key.substring(0, 1) == '$') { continue; } if (!(key in this.$data)) { let value = this[key]; delete this[key]; this.addField(key, value); } if (!(this.$initial && ('' + this.$data[key]) == ('' + this.$initial[key]))) { if (this.$data[key] !== null && this.$data[key] !== undefined && ('' + this.$data[key]).replace(/\s+/, '').length) { return true; } } else if (typeof this.$data[key] == 'object' && this.$data[key] != null) { if ('map' in this.$data[key]) { let dirty = false; this.$data[key].map(elem => { if (typeof elem == 'object' && elem.$dirty || elem.$deleted) { dirty = true; } }); if (dirty) { return true; } } else if (this.$data[key].$dirty || this.$data[key].$deleted) { return true; } } } return false; } };
src/classes/Model.js
"use strict"; let isDateTime = new RegExp(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/); let isDate = new RegExp(/^(\d{4})-(\d{2})-(\d{2})/); let mapper = { Jan: '01', Feb: '02', Mar: '03', Apr: '04', May: '05', Jun: '06', Jul: '07', Aug: '08', Sep: '09', Oct: '10', Nov: '11', Dec: '12' }; function map(month) { return mapper[month]; }; /** * A data object with dirty checking and optional virtual members or other * additional logic. Implementors should generally extend this class, but this * is not required. */ export default class Model { /** * Class constructor. */ constructor() { /** * The "initial" state for this model. Used to check for pristineness. * This is automatically set when $load is called. */ this.$initial = undefined; /** * Internal data storage for this model. */ this.$data = {}; /** * Set to true if the model is scheduled for deletion. */ this.$deleted = false; } /** * Static method to create a new Model of this type, optionally specifying * default data and a class to derive from. * * @param object data Hash of key/value pairs of data. * @param class derivedClass Optional class to actually use when * instantiating (defaults to the current class). * @return mixed A new model of the desired class. */ static $create(data = {}, derivedClass = undefined) { derivedClass = derivedClass || Model; let instance = new derivedClass(); instance.$load(data); instance.$initial = undefined; return instance; } /** * Load data into this model instance. * * @param object data Hash of key/value pairs of data. * @return self */ $load(data = {}) { for (let key in data) { this.addField(key); this[key] = data[key]; } this.$initial = this.$data; return this; } addField(key) { if (!this.hasOwnProperty(key)) { var props = {enumerable: true, configurable: true}; props.get = () => { return this.$data[key]; }; props.set = value => { if (value != undefined) { let checkDate = isDateTime.exec(value); if (!checkDate) { checkDate = isDate.exec(value); } if (checkDate) { checkDate.shift(); // Javascript months are offset by 0 for reasons only Brendan Eich knows... checkDate[1]--; value = new Date(...checkDate); } } this.$data[key] = value; }; Object.defineProperty(this, key, props); } } /** * Virtual property to check if this model is "new". * * @return boolean True if new, false if existing. */ get $new() { return !this.$promise && this.$initial === undefined; } /** * Virtual property to check if this model is "dirty". * * @return boolean True if dirty, false if pristine. */ get $dirty() { if (this.$deleted) { return true; } for (let key in this) { if (key.substring(0, 1) == '$') { continue; } if (!(key in this.$data)) { let value = this[key]; delete this[key]; this.addField(key, value); } if (!(this.$initial && this.$data[key] == this.$initial[key])) { if (this.$data[key] !== null && this.$data[key] !== undefined && ('' + this.$data[key]).replace(/\s+/, '').length) { return true; } } else if (typeof this.$data[key] == 'object' && this.$data[key] != null) { if ('map' in this.$data[key]) { let dirty = false; this.$data[key].map(elem => { if (typeof elem == 'object' && elem.$dirty || elem.$deleted) { dirty = true; } }); if (dirty) { return true; } } else if (this.$data[key].$dirty || this.$data[key].$deleted) { return true; } } } return false; } };
use angular.copy so we get, eh, a copy (not a reference) and toString before comparing or javascript acts weird
src/classes/Model.js
use angular.copy so we get, eh, a copy (not a reference) and toString before comparing or javascript acts weird
<ide><path>rc/classes/Model.js <ide> this.addField(key); <ide> this[key] = data[key]; <ide> } <del> this.$initial = this.$data; <add> this.$initial = angular.copy(this.$data); <ide> return this; <ide> } <ide> <ide> delete this[key]; <ide> this.addField(key, value); <ide> } <del> if (!(this.$initial && this.$data[key] == this.$initial[key])) { <add> if (!(this.$initial && ('' + this.$data[key]) == ('' + this.$initial[key]))) { <ide> if (this.$data[key] !== null && this.$data[key] !== undefined && ('' + this.$data[key]).replace(/\s+/, '').length) { <ide> return true; <ide> }
Java
mit
913970f37934a1f9c2091818641e952d900cdefa
0
aglne/Archimulator,mcai/Archimulator,aglne/Archimulator,mcai/Archimulator,mcai/Archimulator,aglne/Archimulator,aglne/Archimulator,mcai/Archimulator
/******************************************************************************* * Copyright (c) 2010-2013 by Min Cai ([email protected]). * * This file is part of the Archimulator multicore architectural simulator. * * Archimulator 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. * * Archimulator 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 Archimulator. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package archimulator.sim.uncore.cache.Interval; import archimulator.sim.common.Simulation; import archimulator.sim.common.SimulationType; import archimulator.sim.common.report.ReportNode; import archimulator.sim.common.report.Reportable; import archimulator.sim.core.Thread; import archimulator.sim.core.event.DynamicInstructionCommittedEvent; import archimulator.sim.uncore.helperThread.HelperThreadL2RequestProfilingHelper; import archimulator.sim.uncore.helperThread.HelperThreadingHelper; import archimulator.sim.uncore.mlp.BLPProfilingHelper; import archimulator.sim.uncore.mlp.MLPProfilingHelper; import java.util.ArrayList; import java.util.List; /** * Interval helper. * * @author Min Cai */ public class IntervalHelper implements Reportable { /** * Interval. */ private class Interval { private long numMainThreadDynamicInstructionsCommitted; private long numHelperThreadDynamicInstructionsCommitted; private long numMainThreadL2Hits; private long numMainThreadL2Misses; private long numHelperThreadL2Hits; private long numHelperThreadL2Misses; private long numRedundantHitToTransientTagHelperThreadL2Requests; private long numRedundantHitToCacheHelperThreadL2Requests; private long numTimelyHelperThreadL2Requests; private long numLateHelperThreadL2Requests; private long numBadHelperThreadL2Requests; private long numEarlyHelperThreadL2Requests; private long numUglyHelperThreadL2Requests; private double mainThreadIpc; private double helperThreadIpc; private double mainThreadCpi; private double helperThreadCpi; private double mainThreadMpki; private double helperThreadMpki; private double l2MissMlpCosts; private double numL2MissMlpSamples; private double dramBankAccessBlpCosts; private double numDramBankAccessBlpSamples; /** * Handle when this interval is completed. */ public void onCompleted() { mainThreadIpc = (double) numMainThreadDynamicInstructionsCommitted / numCyclesElapsedPerInterval; helperThreadIpc = (double) numHelperThreadDynamicInstructionsCommitted / numCyclesElapsedPerInterval; mainThreadCpi = (double) numCyclesElapsedPerInterval / numMainThreadDynamicInstructionsCommitted; helperThreadCpi = (double) numCyclesElapsedPerInterval / numHelperThreadDynamicInstructionsCommitted; mainThreadMpki = (double) numMainThreadL2Misses / ((double) numMainThreadDynamicInstructionsCommitted / 1000); helperThreadMpki = (double) numHelperThreadL2Misses / ((double) numHelperThreadDynamicInstructionsCommitted / 1000); } } private int numCyclesElapsedPerInterval; private int numCyclesElapsed; private List<Interval> intervals; private Interval currentInterval; /** * Create an interval helper. * * @param simulation the simulation */ public IntervalHelper(final Simulation simulation) { this.numCyclesElapsedPerInterval = 5000000; this.intervals = new ArrayList<>(); this.currentInterval = new Interval(); simulation.getCycleAccurateEventQueue().getPerCycleEvents().add(() -> { if (simulation.getType() != SimulationType.FAST_FORWARD) { numCyclesElapsed++; if (numCyclesElapsed == numCyclesElapsedPerInterval) { currentInterval.onCompleted(); intervals.add(currentInterval); numCyclesElapsed = 0; currentInterval = new Interval(); } } }); simulation.getBlockingEventDispatcher().addListener(DynamicInstructionCommittedEvent.class, event -> { Thread thread = event.getDynamicInstruction().getThread(); if (HelperThreadingHelper.isMainThread(thread)) { currentInterval.numMainThreadDynamicInstructionsCommitted++; } else if (HelperThreadingHelper.isHelperThread(thread)) { currentInterval.numHelperThreadDynamicInstructionsCommitted++; } }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.MainThreadL2HitEvent.class, event -> { currentInterval.numMainThreadL2Hits++; }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.MainThreadL2MissEvent.class, event -> { currentInterval.numMainThreadL2Misses++; }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.HelperThreadL2HitEvent.class, event -> { currentInterval.numHelperThreadL2Hits++; }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.HelperThreadL2MissEvent.class, event -> { currentInterval.numHelperThreadL2Misses++; }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.HelperThreadL2RequestEvent.class, event -> { switch (event.getQuality()) { case REDUNDANT_HIT_TO_TRANSIENT_TAG: currentInterval.numRedundantHitToTransientTagHelperThreadL2Requests++; break; case REDUNDANT_HIT_TO_CACHE: currentInterval.numRedundantHitToCacheHelperThreadL2Requests++; break; case TIMELY: currentInterval.numTimelyHelperThreadL2Requests++; break; case LATE: currentInterval.numLateHelperThreadL2Requests++; break; case BAD: currentInterval.numBadHelperThreadL2Requests++; break; case EARLY: currentInterval.numEarlyHelperThreadL2Requests++; break; case UGLY: currentInterval.numUglyHelperThreadL2Requests++; break; default: throw new IllegalArgumentException(); } }); simulation.getBlockingEventDispatcher().addListener(MLPProfilingHelper.L2MissMLPProfiledEvent.class, event -> { currentInterval.l2MissMlpCosts += event.getPendingL2Miss().getMlpCost(); currentInterval.numL2MissMlpSamples++; }); simulation.getBlockingEventDispatcher().addListener(BLPProfilingHelper.BankAccessBLPProfiledEvent.class, event -> { currentInterval.dramBankAccessBlpCosts += event.getPendingDramBankAccess().getBlpCost(); currentInterval.numDramBankAccessBlpSamples++; }); } @Override public void dumpStats(ReportNode reportNode) { reportNode.getChildren().add(new ReportNode(reportNode, "intervalHelper") {{ for (int i = 0; i < intervals.size(); i++) { Interval interval = intervals.get(i); getChildren().add(new ReportNode(this, "numMainThreadDynamicInstructionsCommitted[" + i + "]", interval.numMainThreadDynamicInstructionsCommitted + "")); getChildren().add(new ReportNode(this, "numHelperThreadDynamicInstructionsCommitted[" + i + "]", interval.numHelperThreadDynamicInstructionsCommitted + "")); getChildren().add(new ReportNode(this, "numMainThreadL2Hits[" + i + "]", interval.numMainThreadL2Hits + "")); getChildren().add(new ReportNode(this, "numMainThreadL2Misses[" + i + "]", interval.numMainThreadL2Misses + "")); getChildren().add(new ReportNode(this, "numHelperThreadL2Hits[" + i + "]", interval.numHelperThreadL2Hits + "")); getChildren().add(new ReportNode(this, "numHelperThreadL2Misses[" + i + "]", interval.numHelperThreadL2Misses + "")); getChildren().add(new ReportNode(this, "numRedundantHitToTransientTagHelperThreadL2Requests[" + i + "]", interval.numRedundantHitToTransientTagHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numRedundantHitToCacheHelperThreadL2Requests[" + i + "]", interval.numRedundantHitToCacheHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numTimelyHelperThreadL2Requests[" + i + "]", interval.numTimelyHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numLateHelperThreadL2Requests[" + i + "]", interval.numLateHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numBadHelperThreadL2Requests[" + i + "]", interval.numBadHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numEarlyHelperThreadL2Requests[" + i + "]", interval.numEarlyHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numUglyHelperThreadL2Requests[" + i + "]", interval.numUglyHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "mainThreadIpc[" + i + "]", interval.mainThreadIpc + "")); getChildren().add(new ReportNode(this, "helperThreadIpc[" + i + "]", interval.helperThreadIpc + "")); getChildren().add(new ReportNode(this, "mainThreadCpi[" + i + "]", interval.mainThreadCpi + "")); getChildren().add(new ReportNode(this, "helperThreadCpi[" + i + "]", interval.helperThreadCpi + "")); getChildren().add(new ReportNode(this, "mainThreadMpki[" + i + "]", interval.mainThreadMpki + "")); getChildren().add(new ReportNode(this, "helperThreadMpki[" + i + "]", interval.helperThreadMpki + "")); getChildren().add(new ReportNode(this, "averageL2MissMlpCost[" + i + "]", (interval.numL2MissMlpSamples == 0 ? 0 : interval.l2MissMlpCosts / interval.numL2MissMlpSamples) + "")); getChildren().add(new ReportNode(this, "numL2MissMlpSamples[" + i + "]", interval.numL2MissMlpSamples + "")); getChildren().add(new ReportNode(this, "averageDramBankAccessBlpCost[" + i + "]", (interval.numDramBankAccessBlpSamples == 0 ? 0 : interval.dramBankAccessBlpCosts / interval.numDramBankAccessBlpSamples) + "")); getChildren().add(new ReportNode(this, "numDramBankAccessBlpSamples[" + i + "]", interval.numDramBankAccessBlpSamples + "")); } }}); } }
src/main/java/archimulator/sim/uncore/cache/Interval/IntervalHelper.java
/******************************************************************************* * Copyright (c) 2010-2013 by Min Cai ([email protected]). * * This file is part of the Archimulator multicore architectural simulator. * * Archimulator 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. * * Archimulator 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 Archimulator. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package archimulator.sim.uncore.cache.Interval; import archimulator.sim.common.Simulation; import archimulator.sim.common.SimulationType; import archimulator.sim.common.report.ReportNode; import archimulator.sim.common.report.Reportable; import archimulator.sim.core.Thread; import archimulator.sim.core.event.DynamicInstructionCommittedEvent; import archimulator.sim.uncore.helperThread.HelperThreadL2RequestProfilingHelper; import archimulator.sim.uncore.helperThread.HelperThreadingHelper; import archimulator.sim.uncore.mlp.BLPProfilingHelper; import archimulator.sim.uncore.mlp.MLPProfilingHelper; import java.util.ArrayList; import java.util.List; /** * Interval helper. * * @author Min Cai */ public class IntervalHelper implements Reportable { /** * Interval. */ private class Interval { private long numMainThreadDynamicInstructionsCommitted; private long numHelperThreadDynamicInstructionsCommitted; private long numMainThreadL2Hits; private long numMainThreadL2Misses; private long numHelperThreadL2Hits; private long numHelperThreadL2Misses; private long numRedundantHitToTransientTagHelperThreadL2Requests; private long numRedundantHitToCacheHelperThreadL2Requests; private long numTimelyHelperThreadL2Requests; private long numLateHelperThreadL2Requests; private long numBadHelperThreadL2Requests; private long numEarlyHelperThreadL2Requests; private long numUglyHelperThreadL2Requests; private double helperThreadL2RequestAccuracy; private double helperThreadL2RequestRedundancy; private double helperThreadL2RequestEarliness; private double helperThreadL2RequestLateness; private double helperThreadL2RequestPollution; private double mainThreadIpc; private double helperThreadIpc; private double mainThreadCpi; private double helperThreadCpi; private double mainThreadMpki; private double helperThreadMpki; private double l2MissMlpCosts; private double numL2MissMlpSamples; private double dramBankAccessBlpCosts; private double numDramBankAccessBlpSamples; /** * Handle when this interval is completed. */ public void onCompleted() { long numTotalHelperThreadL2Requests = numHelperThreadL2Hits + numHelperThreadL2Misses; long numUsefulHelperThreadL2Requests = numTimelyHelperThreadL2Requests + numLateHelperThreadL2Requests; helperThreadL2RequestAccuracy = (double) numUsefulHelperThreadL2Requests / numTotalHelperThreadL2Requests; helperThreadL2RequestRedundancy = (double) (numRedundantHitToTransientTagHelperThreadL2Requests + numRedundantHitToCacheHelperThreadL2Requests) / numUsefulHelperThreadL2Requests; helperThreadL2RequestEarliness = (double) numUglyHelperThreadL2Requests / numUsefulHelperThreadL2Requests; helperThreadL2RequestLateness = (double) numLateHelperThreadL2Requests / numUsefulHelperThreadL2Requests; helperThreadL2RequestPollution = (double) numBadHelperThreadL2Requests / numUsefulHelperThreadL2Requests; mainThreadIpc = (double) numMainThreadDynamicInstructionsCommitted / numCyclesElapsedPerInterval; helperThreadIpc = (double) numHelperThreadDynamicInstructionsCommitted / numCyclesElapsedPerInterval; mainThreadCpi = (double) numCyclesElapsedPerInterval / numMainThreadDynamicInstructionsCommitted; helperThreadCpi = (double) numCyclesElapsedPerInterval / numHelperThreadDynamicInstructionsCommitted; mainThreadMpki = (double) numMainThreadL2Misses / ((double) numMainThreadDynamicInstructionsCommitted / 1000); helperThreadMpki = (double) numHelperThreadL2Misses / ((double) numHelperThreadDynamicInstructionsCommitted / 1000); } } private int numCyclesElapsedPerInterval; private int numCyclesElapsed; private List<Interval> intervals; private Interval currentInterval; /** * Create an interval helper. * * @param simulation the simulation */ public IntervalHelper(final Simulation simulation) { this.numCyclesElapsedPerInterval = 5000000; this.intervals = new ArrayList<>(); this.currentInterval = new Interval(); simulation.getCycleAccurateEventQueue().getPerCycleEvents().add(() -> { if (simulation.getType() != SimulationType.FAST_FORWARD) { numCyclesElapsed++; if (numCyclesElapsed == numCyclesElapsedPerInterval) { currentInterval.onCompleted(); intervals.add(currentInterval); numCyclesElapsed = 0; currentInterval = new Interval(); } } }); simulation.getBlockingEventDispatcher().addListener(DynamicInstructionCommittedEvent.class, event -> { Thread thread = event.getDynamicInstruction().getThread(); if (HelperThreadingHelper.isMainThread(thread)) { currentInterval.numMainThreadDynamicInstructionsCommitted++; } else if (HelperThreadingHelper.isHelperThread(thread)) { currentInterval.numHelperThreadDynamicInstructionsCommitted++; } }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.MainThreadL2HitEvent.class, event -> { currentInterval.numMainThreadL2Hits++; }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.MainThreadL2MissEvent.class, event -> { currentInterval.numMainThreadL2Misses++; }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.HelperThreadL2HitEvent.class, event -> { currentInterval.numHelperThreadL2Hits++; }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.HelperThreadL2MissEvent.class, event -> { currentInterval.numHelperThreadL2Misses++; }); simulation.getBlockingEventDispatcher().addListener(HelperThreadL2RequestProfilingHelper.HelperThreadL2RequestEvent.class, event -> { switch (event.getQuality()) { case REDUNDANT_HIT_TO_TRANSIENT_TAG: currentInterval.numRedundantHitToTransientTagHelperThreadL2Requests++; break; case REDUNDANT_HIT_TO_CACHE: currentInterval.numRedundantHitToCacheHelperThreadL2Requests++; break; case TIMELY: currentInterval.numTimelyHelperThreadL2Requests++; break; case LATE: currentInterval.numLateHelperThreadL2Requests++; break; case BAD: currentInterval.numBadHelperThreadL2Requests++; break; case EARLY: currentInterval.numEarlyHelperThreadL2Requests++; break; case UGLY: currentInterval.numUglyHelperThreadL2Requests++; break; default: throw new IllegalArgumentException(); } }); simulation.getBlockingEventDispatcher().addListener(MLPProfilingHelper.L2MissMLPProfiledEvent.class, event -> { currentInterval.l2MissMlpCosts += event.getPendingL2Miss().getMlpCost(); currentInterval.numL2MissMlpSamples++; }); simulation.getBlockingEventDispatcher().addListener(BLPProfilingHelper.BankAccessBLPProfiledEvent.class, event -> { currentInterval.dramBankAccessBlpCosts += event.getPendingDramBankAccess().getBlpCost(); currentInterval.numDramBankAccessBlpSamples++; }); } @Override public void dumpStats(ReportNode reportNode) { reportNode.getChildren().add(new ReportNode(reportNode, "intervalHelper") {{ for (int i = 0; i < intervals.size(); i++) { Interval interval = intervals.get(i); getChildren().add(new ReportNode(this, "numMainThreadDynamicInstructionsCommitted[" + i + "]", interval.numMainThreadDynamicInstructionsCommitted + "")); getChildren().add(new ReportNode(this, "numHelperThreadDynamicInstructionsCommitted[" + i + "]", interval.numHelperThreadDynamicInstructionsCommitted + "")); getChildren().add(new ReportNode(this, "numMainThreadL2Hits[" + i + "]", interval.numMainThreadL2Hits + "")); getChildren().add(new ReportNode(this, "numMainThreadL2Misses[" + i + "]", interval.numMainThreadL2Misses + "")); getChildren().add(new ReportNode(this, "numHelperThreadL2Hits[" + i + "]", interval.numHelperThreadL2Hits + "")); getChildren().add(new ReportNode(this, "numHelperThreadL2Misses[" + i + "]", interval.numHelperThreadL2Misses + "")); getChildren().add(new ReportNode(this, "numRedundantHitToTransientTagHelperThreadL2Requests[" + i + "]", interval.numRedundantHitToTransientTagHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numRedundantHitToCacheHelperThreadL2Requests[" + i + "]", interval.numRedundantHitToCacheHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numTimelyHelperThreadL2Requests[" + i + "]", interval.numTimelyHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numLateHelperThreadL2Requests[" + i + "]", interval.numLateHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numBadHelperThreadL2Requests[" + i + "]", interval.numBadHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numEarlyHelperThreadL2Requests[" + i + "]", interval.numEarlyHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "numUglyHelperThreadL2Requests[" + i + "]", interval.numUglyHelperThreadL2Requests + "")); getChildren().add(new ReportNode(this, "helperThreadL2RequestAccuracy[" + i + "]", interval.helperThreadL2RequestAccuracy + "")); getChildren().add(new ReportNode(this, "helperThreadL2RequestRedundancy[" + i + "]", interval.helperThreadL2RequestRedundancy + "")); getChildren().add(new ReportNode(this, "helperThreadL2RequestEarliness[" + i + "]", interval.helperThreadL2RequestEarliness + "")); getChildren().add(new ReportNode(this, "helperThreadL2RequestLateness[" + i + "]", interval.helperThreadL2RequestLateness + "")); getChildren().add(new ReportNode(this, "helperThreadL2RequestPollution[" + i + "]", interval.helperThreadL2RequestPollution + "")); getChildren().add(new ReportNode(this, "mainThreadIpc[" + i + "]", interval.mainThreadIpc + "")); getChildren().add(new ReportNode(this, "helperThreadIpc[" + i + "]", interval.helperThreadIpc + "")); getChildren().add(new ReportNode(this, "mainThreadCpi[" + i + "]", interval.mainThreadCpi + "")); getChildren().add(new ReportNode(this, "helperThreadCpi[" + i + "]", interval.helperThreadCpi + "")); getChildren().add(new ReportNode(this, "mainThreadMpki[" + i + "]", interval.mainThreadMpki + "")); getChildren().add(new ReportNode(this, "helperThreadMpki[" + i + "]", interval.helperThreadMpki + "")); getChildren().add(new ReportNode(this, "averageL2MissMlpCost[" + i + "]", (interval.numL2MissMlpSamples == 0 ? 0 : interval.l2MissMlpCosts / interval.numL2MissMlpSamples) + "")); getChildren().add(new ReportNode(this, "numL2MissMlpSamples[" + i + "]", interval.numL2MissMlpSamples + "")); getChildren().add(new ReportNode(this, "averageDramBankAccessBlpCost[" + i + "]", (interval.numDramBankAccessBlpSamples == 0 ? 0 : interval.dramBankAccessBlpCosts / interval.numDramBankAccessBlpSamples) + "")); getChildren().add(new ReportNode(this, "numDramBankAccessBlpSamples[" + i + "]", interval.numDramBankAccessBlpSamples + "")); } }}); } }
Remove unused helper thread prefetch performance indicators stuff in IntervalHelper.
src/main/java/archimulator/sim/uncore/cache/Interval/IntervalHelper.java
Remove unused helper thread prefetch performance indicators stuff in IntervalHelper.
<ide><path>rc/main/java/archimulator/sim/uncore/cache/Interval/IntervalHelper.java <ide> <ide> private long numUglyHelperThreadL2Requests; <ide> <del> private double helperThreadL2RequestAccuracy; <del> private double helperThreadL2RequestRedundancy; <del> private double helperThreadL2RequestEarliness; <del> private double helperThreadL2RequestLateness; <del> private double helperThreadL2RequestPollution; <del> <ide> private double mainThreadIpc; <ide> private double helperThreadIpc; <ide> <ide> * Handle when this interval is completed. <ide> */ <ide> public void onCompleted() { <del> long numTotalHelperThreadL2Requests = numHelperThreadL2Hits + numHelperThreadL2Misses; <del> long numUsefulHelperThreadL2Requests = numTimelyHelperThreadL2Requests + numLateHelperThreadL2Requests; <del> <del> helperThreadL2RequestAccuracy = (double) numUsefulHelperThreadL2Requests / numTotalHelperThreadL2Requests; <del> helperThreadL2RequestRedundancy = (double) (numRedundantHitToTransientTagHelperThreadL2Requests + numRedundantHitToCacheHelperThreadL2Requests) / numUsefulHelperThreadL2Requests; <del> helperThreadL2RequestEarliness = (double) numUglyHelperThreadL2Requests / numUsefulHelperThreadL2Requests; <del> helperThreadL2RequestLateness = (double) numLateHelperThreadL2Requests / numUsefulHelperThreadL2Requests; <del> helperThreadL2RequestPollution = (double) numBadHelperThreadL2Requests / numUsefulHelperThreadL2Requests; <del> <ide> mainThreadIpc = (double) numMainThreadDynamicInstructionsCommitted / numCyclesElapsedPerInterval; <ide> helperThreadIpc = (double) numHelperThreadDynamicInstructionsCommitted / numCyclesElapsedPerInterval; <ide> <ide> <ide> getChildren().add(new ReportNode(this, "numUglyHelperThreadL2Requests[" + i + "]", interval.numUglyHelperThreadL2Requests + "")); <ide> <del> getChildren().add(new ReportNode(this, "helperThreadL2RequestAccuracy[" + i + "]", interval.helperThreadL2RequestAccuracy + "")); <del> getChildren().add(new ReportNode(this, "helperThreadL2RequestRedundancy[" + i + "]", interval.helperThreadL2RequestRedundancy + "")); <del> getChildren().add(new ReportNode(this, "helperThreadL2RequestEarliness[" + i + "]", interval.helperThreadL2RequestEarliness + "")); <del> getChildren().add(new ReportNode(this, "helperThreadL2RequestLateness[" + i + "]", interval.helperThreadL2RequestLateness + "")); <del> getChildren().add(new ReportNode(this, "helperThreadL2RequestPollution[" + i + "]", interval.helperThreadL2RequestPollution + "")); <del> <ide> getChildren().add(new ReportNode(this, "mainThreadIpc[" + i + "]", interval.mainThreadIpc + "")); <ide> getChildren().add(new ReportNode(this, "helperThreadIpc[" + i + "]", interval.helperThreadIpc + "")); <ide>
Java
apache-2.0
728a52ec86da6f87b5fefbdf85b893008d171342
0
tr3vr/jena,CesarPantoja/jena,atsolakid/jena,kamir/jena,samaitra/jena,jianglili007/jena,kidaa/jena,jianglili007/jena,CesarPantoja/jena,apache/jena,atsolakid/jena,apache/jena,CesarPantoja/jena,kamir/jena,jianglili007/jena,atsolakid/jena,tr3vr/jena,samaitra/jena,tr3vr/jena,jianglili007/jena,samaitra/jena,CesarPantoja/jena,atsolakid/jena,apache/jena,tr3vr/jena,atsolakid/jena,apache/jena,jianglili007/jena,adrapereira/jena,adrapereira/jena,CesarPantoja/jena,kidaa/jena,tr3vr/jena,jianglili007/jena,kidaa/jena,kidaa/jena,apache/jena,adrapereira/jena,samaitra/jena,atsolakid/jena,kamir/jena,adrapereira/jena,kamir/jena,samaitra/jena,tr3vr/jena,kamir/jena,apache/jena,adrapereira/jena,kidaa/jena,jianglili007/jena,CesarPantoja/jena,apache/jena,kamir/jena,kidaa/jena,atsolakid/jena,CesarPantoja/jena,tr3vr/jena,adrapereira/jena,samaitra/jena,samaitra/jena,kidaa/jena,kamir/jena,adrapereira/jena,apache/jena
/* * 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 com.hp.hpl.jena.sparql.syntax; import com.hp.hpl.jena.graph.Node ; import com.hp.hpl.jena.graph.NodeFactory ; import org.apache.jena.atlas.logging.Log ; import com.hp.hpl.jena.sparql.util.NodeIsomorphismMap ; /** A SERVICE pattern - access a remote SPARQL service. */ public class ElementService extends Element { private final Node serviceNode ; private final Element element ; private final boolean silent ; public ElementService(String serviceURI, Element el) { this(NodeFactory.createURI(serviceURI), el, false) ; } public ElementService(String serviceURI, Element el, boolean silent) { this(NodeFactory.createURI(serviceURI), el, silent) ; } // Variable? public ElementService(Node n, Element el, boolean silent) { if ( ! n.isURI() && ! n.isVariable() ) Log.fatal(this, "Must be a URI (or variable which will be bound) for a service endpoint") ; this.serviceNode = n ; this.element = el ; this.silent = silent ; } public Element getElement() { return element ; } public Node getServiceNode() { return serviceNode ; } public boolean getSilent() { return silent ; } @Override public int hashCode() { return serviceNode.hashCode() ^ element.hashCode(); } @Override public boolean equalTo(Element el2, NodeIsomorphismMap isoMap) { if ( ! ( el2 instanceof ElementService ) ) return false ; ElementService service = (ElementService)el2 ; if ( ! serviceNode.equals(service.serviceNode) ) return false ; if ( service.getSilent() != getSilent() ) return false ; if ( ! this.getElement().equalTo(service.getElement(), isoMap) ) return false ; return true ; } @Override public void visit(ElementVisitor v) { v.visit(this) ; } }
jena-arq/src/main/java/com/hp/hpl/jena/sparql/syntax/ElementService.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 com.hp.hpl.jena.sparql.syntax; import com.hp.hpl.jena.graph.Node ; import com.hp.hpl.jena.graph.NodeFactory ; import org.apache.jena.atlas.logging.Log ; import com.hp.hpl.jena.sparql.util.NodeIsomorphismMap ; /** A SERVICE pattern - access a remote SPARQL service. */ public class ElementService extends Element { private final Node serviceNode ; private final Element element ; private final boolean silent ; public ElementService(String serviceURI, Element el) { this(NodeFactory.createURI(serviceURI), el, false) ; } public ElementService(String serviceURI, Element el, boolean silent) { this(NodeFactory.createURI(serviceURI), el, silent) ; } // Variable? public ElementService(Node n, Element el, boolean silent) { if ( ! n.isURI() && ! n.isVariable() ) Log.fatal(this, "Must be a URI (or variable which will be bound) for a service endpoint") ; this.serviceNode = n ; this.element = el ; this.silent = silent ; } public Element getElement() { return element ; } public Node getServiceNode() { return serviceNode ; } public String getServiceURI() { return serviceNode.getURI(); } public boolean getSilent() { return silent ; } @Override public int hashCode() { return serviceNode.hashCode() ^ element.hashCode(); } @Override public boolean equalTo(Element el2, NodeIsomorphismMap isoMap) { if ( ! ( el2 instanceof ElementService ) ) return false ; ElementService service = (ElementService)el2 ; if ( ! serviceNode.equals(service.serviceNode) ) return false ; if ( service.getSilent() != getSilent() ) return false ; if ( ! this.getElement().equalTo(service.getElement(), isoMap) ) return false ; return true ; } @Override public void visit(ElementVisitor v) { v.visit(this) ; } }
Remove unnecessary method. git-svn-id: bc509ec38c1227b3e85ea1246fda136342965d36@1459506 13f79535-47bb-0310-9956-ffa450edef68
jena-arq/src/main/java/com/hp/hpl/jena/sparql/syntax/ElementService.java
Remove unnecessary method.
<ide><path>ena-arq/src/main/java/com/hp/hpl/jena/sparql/syntax/ElementService.java <ide> <ide> public Element getElement() { return element ; } <ide> public Node getServiceNode() { return serviceNode ; } <del> public String getServiceURI() { return serviceNode.getURI(); } <ide> public boolean getSilent() { return silent ; } <ide> <ide> @Override
Java
apache-2.0
091538752b3b6b177de538ec5fbe4cb928f7b195
0
m2049r/xmrwallet,m2049r/xmrwallet,m2049r/xmrwallet
/* * Copyright (c) 2017 m2049r * * 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.m2049r.xmrwallet; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.m2049r.xmrwallet.layout.WalletInfoAdapter; import com.m2049r.xmrwallet.model.NetworkType; import com.m2049r.xmrwallet.model.WalletManager; import com.m2049r.xmrwallet.util.Helper; import com.m2049r.xmrwallet.util.KeyStoreHelper; import com.m2049r.xmrwallet.util.NodeList; import com.m2049r.xmrwallet.util.Notice; import com.m2049r.xmrwallet.widget.DropDownEditText; import com.m2049r.xmrwallet.widget.Toolbar; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Set; import timber.log.Timber; public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInteractionListener, View.OnClickListener { private WalletInfoAdapter adapter; private List<WalletManager.WalletInfo> walletList = new ArrayList<>(); private List<WalletManager.WalletInfo> displayedList = new ArrayList<>(); private EditText etDummy; private ImageView ivGunther; private DropDownEditText etDaemonAddress; private ArrayAdapter<String> nodeAdapter; private Listener activityCallback; // Container Activity must implement this interface public interface Listener { SharedPreferences getPrefs(); File getStorageRoot(); boolean onWalletSelected(String wallet, String daemon); void onWalletDetails(String wallet); void onWalletReceive(String wallet); void onWalletRename(String name); void onWalletBackup(String name); void onWalletArchive(String walletName); void onAddWallet(String type); void showNet(); void setToolbarButton(int type); void setTitle(String title); void setNetworkType(NetworkType networkType); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof Listener) { this.activityCallback = (Listener) context; } else { throw new ClassCastException(context.toString() + " must implement Listener"); } } @Override public void onPause() { Timber.d("onPause()"); savePrefs(); super.onPause(); } @Override public void onResume() { super.onResume(); Timber.d("onResume()"); activityCallback.setTitle(null); activityCallback.setToolbarButton(Toolbar.BUTTON_CREDITS); activityCallback.showNet(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Timber.d("onCreateView"); View view = inflater.inflate(R.layout.fragment_login, container, false); ivGunther = (ImageView) view.findViewById(R.id.ivGunther); fabScreen = (FrameLayout) view.findViewById(R.id.fabScreen); fab = (FloatingActionButton) view.findViewById(R.id.fab); fabNew = (FloatingActionButton) view.findViewById(R.id.fabNew); fabView = (FloatingActionButton) view.findViewById(R.id.fabView); fabKey = (FloatingActionButton) view.findViewById(R.id.fabKey); fabSeed = (FloatingActionButton) view.findViewById(R.id.fabSeed); fabNewL = (RelativeLayout) view.findViewById(R.id.fabNewL); fabViewL = (RelativeLayout) view.findViewById(R.id.fabViewL); fabKeyL = (RelativeLayout) view.findViewById(R.id.fabKeyL); fabSeedL = (RelativeLayout) view.findViewById(R.id.fabSeedL); fab_pulse = AnimationUtils.loadAnimation(getContext(), R.anim.fab_pulse); fab_open_screen = AnimationUtils.loadAnimation(getContext(), R.anim.fab_open_screen); fab_close_screen = AnimationUtils.loadAnimation(getContext(), R.anim.fab_close_screen); fab_open = AnimationUtils.loadAnimation(getContext(), R.anim.fab_open); fab_close = AnimationUtils.loadAnimation(getContext(), R.anim.fab_close); rotate_forward = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_forward); rotate_backward = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_backward); fab.setOnClickListener(this); fabNew.setOnClickListener(this); fabView.setOnClickListener(this); fabKey.setOnClickListener(this); fabSeed.setOnClickListener(this); fabScreen.setOnClickListener(this); RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list); registerForContextMenu(recyclerView); this.adapter = new WalletInfoAdapter(getActivity(), this); recyclerView.setAdapter(adapter); etDummy = (EditText) view.findViewById(R.id.etDummy); ViewGroup llNotice = (ViewGroup) view.findViewById(R.id.llNotice); Notice.showAll(llNotice,".*_login"); etDaemonAddress = (DropDownEditText) view.findViewById(R.id.etDaemonAddress); nodeAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line); etDaemonAddress.setAdapter(nodeAdapter); Helper.hideKeyboard(getActivity()); etDaemonAddress.setThreshold(0); etDaemonAddress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etDaemonAddress.showDropDown(); Helper.showKeyboard(getActivity()); } }); etDaemonAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && !getActivity().isFinishing() && etDaemonAddress.isLaidOut()) { etDaemonAddress.showDropDown(); Helper.showKeyboard(getActivity()); } } }); etDaemonAddress.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { Helper.hideKeyboard(getActivity()); etDummy.requestFocus(); return true; } return false; } }); etDaemonAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) { Helper.hideKeyboard(getActivity()); etDummy.requestFocus(); } }); loadPrefs(); return view; } // Callbacks from WalletInfoAdapter @Override public void onInteraction(final View view, final WalletManager.WalletInfo infoItem) { String addressPrefix = addressPrefix(); if (addressPrefix.indexOf(infoItem.address.charAt(0)) < 0) { Toast.makeText(getActivity(), getString(R.string.prompt_wrong_net), Toast.LENGTH_LONG).show(); return; } if (activityCallback.onWalletSelected(infoItem.name, getDaemon())) { savePrefs(); } } @Override public boolean onContextInteraction(MenuItem item, WalletManager.WalletInfo listItem) { switch (item.getItemId()) { case R.id.action_info: showInfo(listItem.name); break; case R.id.action_receive: showReceive(listItem.name); break; case R.id.action_rename: activityCallback.onWalletRename(listItem.name); break; case R.id.action_backup: activityCallback.onWalletBackup(listItem.name); break; case R.id.action_archive: activityCallback.onWalletArchive(listItem.name); break; default: return super.onContextItemSelected(item); } return true; } private String addressPrefix() { switch (WalletManager.getInstance().getNetworkType()) { case NetworkType_Testnet: return "9A-"; case NetworkType_Mainnet: return "4-"; case NetworkType_Stagenet: return "5-"; default: throw new IllegalStateException("Unsupported Network: " + WalletManager.getInstance().getNetworkType()); } } private void filterList() { displayedList.clear(); String addressPrefix = addressPrefix(); for (WalletManager.WalletInfo s : walletList) { if (addressPrefix.indexOf(s.address.charAt(0)) >= 0) displayedList.add(s); } } public void loadList() { Timber.d("loadList()"); WalletManager mgr = WalletManager.getInstance(); List<WalletManager.WalletInfo> walletInfos = mgr.findWallets(activityCallback.getStorageRoot()); walletList.clear(); walletList.addAll(walletInfos); filterList(); adapter.setInfos(displayedList); adapter.notifyDataSetChanged(); // deal with Gunther & FAB animation if (displayedList.isEmpty()) { fab.startAnimation(fab_pulse); if (ivGunther.getDrawable() == null) { ivGunther.setImageResource(R.drawable.gunther_desaturated); } } else { fab.clearAnimation(); if (ivGunther.getDrawable() != null) { ivGunther.setImageDrawable(null); } } // remove information of non-existent wallet Set<String> removedWallets = getActivity() .getSharedPreferences(KeyStoreHelper.SecurityConstants.WALLET_PASS_PREFS_NAME, Context.MODE_PRIVATE) .getAll().keySet(); for (WalletManager.WalletInfo s : walletList) { removedWallets.remove(s.name); } for (String name : removedWallets) { KeyStoreHelper.removeWalletUserPass(getActivity(), name); } } private void showInfo(@NonNull String name) { activityCallback.onWalletDetails(name); } private void showReceive(@NonNull String name) { activityCallback.onWalletReceive(name); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.list_menu, menu); menu.findItem(R.id.action_stagenet).setChecked(stagenetCheckMenu); super.onCreateOptionsMenu(menu, inflater); } private boolean stagenetCheckMenu = BuildConfig.DEBUG; public boolean onStagenetMenuItem() { boolean lastState = stagenetCheckMenu; setNet(!lastState, true); // set and save return !lastState; } public void setNet(boolean stagenetChecked, boolean save) { this.stagenetCheckMenu = stagenetChecked; NetworkType net = stagenetChecked ? NetworkType.NetworkType_Stagenet : NetworkType.NetworkType_Mainnet; activityCallback.setNetworkType(net); activityCallback.showNet(); if (save) { savePrefs(true); // use previous state as we just clicked it } if (stagenetChecked) { setDaemon(daemonStageNet); } else { setDaemon(daemonMainNet); } loadList(); } private static final String PREF_DAEMON_STAGENET = "daemon_stagenet"; private static final String PREF_DAEMON_MAINNET = "daemon_mainnet"; private static final String PREF_DAEMONLIST_MAINNET = "node.moneroworld.com:18089;node.xmrbackb.one;node.xmr.be"; private static final String PREF_DAEMONLIST_STAGENET = "stagenet.monerujo.io;stagenet.xmr-tw.org"; private NodeList daemonStageNet; private NodeList daemonMainNet; void loadPrefs() { SharedPreferences sharedPref = activityCallback.getPrefs(); daemonMainNet = new NodeList(sharedPref.getString(PREF_DAEMON_MAINNET, PREF_DAEMONLIST_MAINNET)); daemonStageNet = new NodeList(sharedPref.getString(PREF_DAEMON_STAGENET, PREF_DAEMONLIST_STAGENET)); setNet(stagenetCheckMenu, false); } void savePrefs() { savePrefs(false); } void savePrefs(boolean usePreviousNetState) { Timber.d("SAVE / %s", usePreviousNetState); // save the daemon address for the net boolean stagenet = stagenetCheckMenu ^ usePreviousNetState; String daemon = getDaemon(); if (stagenet) { daemonStageNet.setRecent(daemon); } else { daemonMainNet.setRecent(daemon); } SharedPreferences sharedPref = activityCallback.getPrefs(); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(PREF_DAEMON_MAINNET, daemonMainNet.toString()); editor.putString(PREF_DAEMON_STAGENET, daemonStageNet.toString()); editor.apply(); } String getDaemon() { return etDaemonAddress.getText().toString().trim(); } void setDaemon(NodeList nodeList) { Timber.d("setDaemon() %s", nodeList.toString()); String[] nodes = nodeList.getNodes().toArray(new String[0]); nodeAdapter.clear(); nodeAdapter.addAll(nodes); etDaemonAddress.getText().clear(); if (nodes.length > 0) { etDaemonAddress.setText(nodes[0]); } etDaemonAddress.dismissDropDown(); etDummy.requestFocus(); Helper.hideKeyboard(getActivity()); } private boolean isFabOpen = false; private FloatingActionButton fab, fabNew, fabView, fabKey, fabSeed; private FrameLayout fabScreen; private RelativeLayout fabNewL, fabViewL, fabKeyL, fabSeedL; private Animation fab_open, fab_close, rotate_forward, rotate_backward, fab_open_screen, fab_close_screen; private Animation fab_pulse; public boolean isFabOpen() { return isFabOpen; } public void animateFAB() { if (isFabOpen) { fabScreen.setVisibility(View.INVISIBLE); fabScreen.setClickable(false); fabScreen.startAnimation(fab_close_screen); fab.startAnimation(rotate_backward); fabNewL.startAnimation(fab_close); fabNew.setClickable(false); fabViewL.startAnimation(fab_close); fabView.setClickable(false); fabKeyL.startAnimation(fab_close); fabKey.setClickable(false); fabSeedL.startAnimation(fab_close); fabSeed.setClickable(false); isFabOpen = false; } else { fabScreen.setClickable(true); fabScreen.startAnimation(fab_open_screen); fab.startAnimation(rotate_forward); fabNewL.startAnimation(fab_open); fabNew.setClickable(true); fabViewL.startAnimation(fab_open); fabView.setClickable(true); fabKeyL.startAnimation(fab_open); fabKey.setClickable(true); fabSeedL.startAnimation(fab_open); fabSeed.setClickable(true); isFabOpen = true; } } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.fab: animateFAB(); break; case R.id.fabNew: fabScreen.setVisibility(View.INVISIBLE); isFabOpen = false; activityCallback.onAddWallet(GenerateFragment.TYPE_NEW); break; case R.id.fabView: animateFAB(); activityCallback.onAddWallet(GenerateFragment.TYPE_VIEWONLY); break; case R.id.fabKey: animateFAB(); activityCallback.onAddWallet(GenerateFragment.TYPE_KEY); break; case R.id.fabSeed: animateFAB(); activityCallback.onAddWallet(GenerateFragment.TYPE_SEED); break; case R.id.fabScreen: animateFAB(); break; } } }
app/src/main/java/com/m2049r/xmrwallet/LoginFragment.java
/* * Copyright (c) 2017 m2049r * * 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.m2049r.xmrwallet; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.m2049r.xmrwallet.layout.WalletInfoAdapter; import com.m2049r.xmrwallet.model.NetworkType; import com.m2049r.xmrwallet.model.WalletManager; import com.m2049r.xmrwallet.util.Helper; import com.m2049r.xmrwallet.util.KeyStoreHelper; import com.m2049r.xmrwallet.util.NodeList; import com.m2049r.xmrwallet.util.Notice; import com.m2049r.xmrwallet.widget.DropDownEditText; import com.m2049r.xmrwallet.widget.Toolbar; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Set; import timber.log.Timber; public class LoginFragment extends Fragment implements WalletInfoAdapter.OnInteractionListener, View.OnClickListener { private WalletInfoAdapter adapter; private List<WalletManager.WalletInfo> walletList = new ArrayList<>(); private List<WalletManager.WalletInfo> displayedList = new ArrayList<>(); private EditText etDummy; private ImageView ivGunther; private DropDownEditText etDaemonAddress; private ArrayAdapter<String> nodeAdapter; private Listener activityCallback; // Container Activity must implement this interface public interface Listener { SharedPreferences getPrefs(); File getStorageRoot(); boolean onWalletSelected(String wallet, String daemon); void onWalletDetails(String wallet); void onWalletReceive(String wallet); void onWalletRename(String name); void onWalletBackup(String name); void onWalletArchive(String walletName); void onAddWallet(String type); void showNet(); void setToolbarButton(int type); void setTitle(String title); void setNetworkType(NetworkType networkType); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof Listener) { this.activityCallback = (Listener) context; } else { throw new ClassCastException(context.toString() + " must implement Listener"); } } @Override public void onPause() { Timber.d("onPause()"); savePrefs(); super.onPause(); } @Override public void onResume() { super.onResume(); Timber.d("onResume()"); activityCallback.setTitle(null); activityCallback.setToolbarButton(Toolbar.BUTTON_CREDITS); activityCallback.showNet(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Timber.d("onCreateView"); View view = inflater.inflate(R.layout.fragment_login, container, false); ivGunther = (ImageView) view.findViewById(R.id.ivGunther); fabScreen = (FrameLayout) view.findViewById(R.id.fabScreen); fab = (FloatingActionButton) view.findViewById(R.id.fab); fabNew = (FloatingActionButton) view.findViewById(R.id.fabNew); fabView = (FloatingActionButton) view.findViewById(R.id.fabView); fabKey = (FloatingActionButton) view.findViewById(R.id.fabKey); fabSeed = (FloatingActionButton) view.findViewById(R.id.fabSeed); fabNewL = (RelativeLayout) view.findViewById(R.id.fabNewL); fabViewL = (RelativeLayout) view.findViewById(R.id.fabViewL); fabKeyL = (RelativeLayout) view.findViewById(R.id.fabKeyL); fabSeedL = (RelativeLayout) view.findViewById(R.id.fabSeedL); fab_pulse = AnimationUtils.loadAnimation(getContext(), R.anim.fab_pulse); fab_open_screen = AnimationUtils.loadAnimation(getContext(), R.anim.fab_open_screen); fab_close_screen = AnimationUtils.loadAnimation(getContext(), R.anim.fab_close_screen); fab_open = AnimationUtils.loadAnimation(getContext(), R.anim.fab_open); fab_close = AnimationUtils.loadAnimation(getContext(), R.anim.fab_close); rotate_forward = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_forward); rotate_backward = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_backward); fab.setOnClickListener(this); fabNew.setOnClickListener(this); fabView.setOnClickListener(this); fabKey.setOnClickListener(this); fabSeed.setOnClickListener(this); fabScreen.setOnClickListener(this); RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list); registerForContextMenu(recyclerView); this.adapter = new WalletInfoAdapter(getActivity(), this); recyclerView.setAdapter(adapter); etDummy = (EditText) view.findViewById(R.id.etDummy); ViewGroup llNotice = (ViewGroup) view.findViewById(R.id.llNotice); Notice.showAll(llNotice,".*_login"); etDaemonAddress = (DropDownEditText) view.findViewById(R.id.etDaemonAddress); nodeAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line); etDaemonAddress.setAdapter(nodeAdapter); Helper.hideKeyboard(getActivity()); etDaemonAddress.setThreshold(0); etDaemonAddress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etDaemonAddress.showDropDown(); Helper.showKeyboard(getActivity()); } }); etDaemonAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && !getActivity().isFinishing() && etDaemonAddress.isLaidOut()) { etDaemonAddress.showDropDown(); Helper.showKeyboard(getActivity()); } } }); etDaemonAddress.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { Helper.hideKeyboard(getActivity()); etDummy.requestFocus(); return true; } return false; } }); etDaemonAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) { Helper.hideKeyboard(getActivity()); etDummy.requestFocus(); } }); loadPrefs(); return view; } // Callbacks from WalletInfoAdapter @Override public void onInteraction(final View view, final WalletManager.WalletInfo infoItem) { String addressPrefix = addressPrefix(); if (addressPrefix.indexOf(infoItem.address.charAt(0)) < 0) { Toast.makeText(getActivity(), getString(R.string.prompt_wrong_net), Toast.LENGTH_LONG).show(); return; } if (activityCallback.onWalletSelected(infoItem.name, getDaemon())) { savePrefs(); } } @Override public boolean onContextInteraction(MenuItem item, WalletManager.WalletInfo listItem) { switch (item.getItemId()) { case R.id.action_info: showInfo(listItem.name); break; case R.id.action_receive: showReceive(listItem.name); break; case R.id.action_rename: activityCallback.onWalletRename(listItem.name); break; case R.id.action_backup: activityCallback.onWalletBackup(listItem.name); break; case R.id.action_archive: activityCallback.onWalletArchive(listItem.name); break; default: return super.onContextItemSelected(item); } return true; } private String addressPrefix() { switch (WalletManager.getInstance().getNetworkType()) { case NetworkType_Testnet: return "9A-"; case NetworkType_Mainnet: return "4-"; case NetworkType_Stagenet: return "5-"; default: throw new IllegalStateException("Unsupported Network: " + WalletManager.getInstance().getNetworkType()); } } private void filterList() { displayedList.clear(); String addressPrefix = addressPrefix(); for (WalletManager.WalletInfo s : walletList) { if (addressPrefix.indexOf(s.address.charAt(0)) >= 0) displayedList.add(s); } } public void loadList() { Timber.d("loadList()"); WalletManager mgr = WalletManager.getInstance(); List<WalletManager.WalletInfo> walletInfos = mgr.findWallets(activityCallback.getStorageRoot()); walletList.clear(); walletList.addAll(walletInfos); filterList(); adapter.setInfos(displayedList); adapter.notifyDataSetChanged(); // deal with Gunther & FAB animation if (displayedList.isEmpty()) { fab.startAnimation(fab_pulse); if (ivGunther.getDrawable() == null) { ivGunther.setImageResource(R.drawable.gunther_desaturated); } } else { fab.clearAnimation(); if (ivGunther.getDrawable() != null) { ivGunther.setImageDrawable(null); } } // remove information of non-existent wallet Set<String> removedWallets = getActivity() .getSharedPreferences(KeyStoreHelper.SecurityConstants.WALLET_PASS_PREFS_NAME, Context.MODE_PRIVATE) .getAll().keySet(); for (WalletManager.WalletInfo s : walletList) { removedWallets.remove(s.name); } for (String name : removedWallets) { KeyStoreHelper.removeWalletUserPass(getActivity(), name); } } private void showInfo(@NonNull String name) { activityCallback.onWalletDetails(name); } private void showReceive(@NonNull String name) { activityCallback.onWalletReceive(name); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.list_menu, menu); menu.findItem(R.id.action_stagenet).setChecked(stagenetCheckMenu); super.onCreateOptionsMenu(menu, inflater); } private boolean stagenetCheckMenu = BuildConfig.DEBUG; public boolean onStagenetMenuItem() { boolean lastState = stagenetCheckMenu; setNet(!lastState, true); // set and save return !lastState; } public void setNet(boolean stagenetChecked, boolean save) { this.stagenetCheckMenu = stagenetChecked; NetworkType net = stagenetChecked ? NetworkType.NetworkType_Stagenet : NetworkType.NetworkType_Mainnet; activityCallback.setNetworkType(net); activityCallback.showNet(); if (save) { savePrefs(true); // use previous state as we just clicked it } if (stagenetChecked) { setDaemon(daemonStageNet); } else { setDaemon(daemonMainNet); } loadList(); } private static final String PREF_DAEMON_STAGENET = "daemon_stagenet"; private static final String PREF_DAEMON_MAINNET = "daemon_mainnet"; private static final String PREF_DAEMONLIST_MAINNET = "node.moneroworld.com:18089;node.xmrbackb.one;node.xmr.be"; private static final String PREF_DAEMONLIST_STAGENET = "stagenet.xmr-tw.org"; private NodeList daemonStageNet; private NodeList daemonMainNet; void loadPrefs() { SharedPreferences sharedPref = activityCallback.getPrefs(); daemonMainNet = new NodeList(sharedPref.getString(PREF_DAEMON_MAINNET, PREF_DAEMONLIST_MAINNET)); daemonStageNet = new NodeList(sharedPref.getString(PREF_DAEMON_STAGENET, PREF_DAEMONLIST_STAGENET)); setNet(stagenetCheckMenu, false); } void savePrefs() { savePrefs(false); } void savePrefs(boolean usePreviousNetState) { Timber.d("SAVE / %s", usePreviousNetState); // save the daemon address for the net boolean stagenet = stagenetCheckMenu ^ usePreviousNetState; String daemon = getDaemon(); if (stagenet) { daemonStageNet.setRecent(daemon); } else { daemonMainNet.setRecent(daemon); } SharedPreferences sharedPref = activityCallback.getPrefs(); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(PREF_DAEMON_MAINNET, daemonMainNet.toString()); editor.putString(PREF_DAEMON_STAGENET, daemonStageNet.toString()); editor.apply(); } String getDaemon() { return etDaemonAddress.getText().toString().trim(); } void setDaemon(NodeList nodeList) { Timber.d("setDaemon() %s", nodeList.toString()); String[] nodes = nodeList.getNodes().toArray(new String[0]); nodeAdapter.clear(); nodeAdapter.addAll(nodes); etDaemonAddress.getText().clear(); if (nodes.length > 0) { etDaemonAddress.setText(nodes[0]); } etDaemonAddress.dismissDropDown(); etDummy.requestFocus(); Helper.hideKeyboard(getActivity()); } private boolean isFabOpen = false; private FloatingActionButton fab, fabNew, fabView, fabKey, fabSeed; private FrameLayout fabScreen; private RelativeLayout fabNewL, fabViewL, fabKeyL, fabSeedL; private Animation fab_open, fab_close, rotate_forward, rotate_backward, fab_open_screen, fab_close_screen; private Animation fab_pulse; public boolean isFabOpen() { return isFabOpen; } public void animateFAB() { if (isFabOpen) { fabScreen.setVisibility(View.INVISIBLE); fabScreen.setClickable(false); fabScreen.startAnimation(fab_close_screen); fab.startAnimation(rotate_backward); fabNewL.startAnimation(fab_close); fabNew.setClickable(false); fabViewL.startAnimation(fab_close); fabView.setClickable(false); fabKeyL.startAnimation(fab_close); fabKey.setClickable(false); fabSeedL.startAnimation(fab_close); fabSeed.setClickable(false); isFabOpen = false; } else { fabScreen.setClickable(true); fabScreen.startAnimation(fab_open_screen); fab.startAnimation(rotate_forward); fabNewL.startAnimation(fab_open); fabNew.setClickable(true); fabViewL.startAnimation(fab_open); fabView.setClickable(true); fabKeyL.startAnimation(fab_open); fabKey.setClickable(true); fabSeedL.startAnimation(fab_open); fabSeed.setClickable(true); isFabOpen = true; } } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.fab: animateFAB(); break; case R.id.fabNew: fabScreen.setVisibility(View.INVISIBLE); isFabOpen = false; activityCallback.onAddWallet(GenerateFragment.TYPE_NEW); break; case R.id.fabView: animateFAB(); activityCallback.onAddWallet(GenerateFragment.TYPE_VIEWONLY); break; case R.id.fabKey: animateFAB(); activityCallback.onAddWallet(GenerateFragment.TYPE_KEY); break; case R.id.fabSeed: animateFAB(); activityCallback.onAddWallet(GenerateFragment.TYPE_SEED); break; case R.id.fabScreen: animateFAB(); break; } } }
add our stagenet server to defaults (#321)
app/src/main/java/com/m2049r/xmrwallet/LoginFragment.java
add our stagenet server to defaults (#321)
<ide><path>pp/src/main/java/com/m2049r/xmrwallet/LoginFragment.java <ide> "node.moneroworld.com:18089;node.xmrbackb.one;node.xmr.be"; <ide> <ide> private static final String PREF_DAEMONLIST_STAGENET = <del> "stagenet.xmr-tw.org"; <add> "stagenet.monerujo.io;stagenet.xmr-tw.org"; <ide> <ide> private NodeList daemonStageNet; <ide> private NodeList daemonMainNet;
JavaScript
mit
b2cd42ea88f960ddad0957d664a5eca8a7a16869
0
auth0/auth0-sandbox-ext
var Boom = require('boom'); var Bluebird = require('bluebird'); var Cron = require('cron-parser'); var Express = require('express'); var Jwt = require('jsonwebtoken'); var Webtask = require('webtask-tools'); var _ = require('lodash'); var app = Express(); var router = Express.Router(); var mongo; // Check for required configuration parameters app.use(function (req, res, next) { var data = req.webtaskContext.data; var required = ['JOB_COLLECTION', 'MONGO_URL', 'cluster_url']; for (var i in required) { var key = required[i]; if (!data[key]) { var err = Boom.badGateway('Cron webtask needs to be configured ' + 'with the parameter: `' + key + '`.', data); return next(err); } } next(); }); // Set up connection to mongodb app.use(function (req, res, next) { // Short-cut if mongo is already setup if (mongo) { req.mongo = mongo; return next(); } var MongoClient = require('mongodb').MongoClient; var connect = Bluebird.promisify(MongoClient.connect, MongoClient); var data = req.webtaskContext.data; return connect(data.MONGO_URL) .then(function (db) { // Store the settled promise resolving to the db object mongo = req.mongo = db; }) .catch(function (err) { throw Boom.wrap(err, 503, 'Database unreachable.'); }) .nodeify(next); }); // Parse incoming json bodies app.use(require('body-parser').json()); app.use(router); app.use(function(err, req, res, next) { console.log(err.message); console.log(err.stack); if (!err.isBoom) err = Boom.wrap(err); res .set(err.output.headers) .status(err.output.statusCode) .json(err.output.payload); }); router.post('/reserve', ensure('query', ['count', 'ttl']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var count = Math.max(0, Math.min(100, parseInt(req.query.count, 10))); var now = new Date(); var nextAvailableAt = new Date(now.valueOf() + (parseInt(data.ttl, 10) * 1000)); console.log('attempting to reserve ' + count + ' jobs.'); Bluebird.map(_.range(count), function (n) { var filter = { cluster_url: data.cluster_url, next_available_at: { $lte: now }, state: 'active', }; var update = { $set: { next_available_at: nextAvailableAt } }; var options = { projection: { results: { $slice: 10 }, // Limit to the 10 last results }, returnOriginal: false, // Return modified }; return Bluebird.promisify(jobs.findOneAndUpdate, jobs)(filter, update, options) .get('value'); // Only pull out the value }) // Don't prevent one failure from blocking the entire // reservation (that would mean extra waiting on those that // didn't fail) .settle() // Log errors and continue with safe fallback .map(function (result) { if (result.isRejected()) { console.log('error reserving job: ' + result.value().message); return null; } else { return result.value(); } }) // Elminate error queries and queries that did not match // (this is the case when there are fewer than N jobs // available for running now) .filter(Boolean) .tap(function (jobs) { console.log('successfully reserved ' + jobs.length + ' job(s).'); }) .map(stripMongoId) .then(res.json.bind(res), next); }); router.get('/:container?', function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = { cluster_url: data.cluster_url, }; // Both admin and user will hit this endpoint. When admin, container can be unset if (req.params.container) query.container = req.params.container; var limit = req.query.limit ? Math.max(0, Math.min(20, parseInt(req.query.limit, 10))) : 10; var skip = req.query.offset ? Math.max(0, parseInt(req.query.offset, 10)) : 0; var cursor = jobs.find(query) .skip(skip) .limit(limit); Bluebird.promisify(cursor.toArray, cursor)() .catch(function (err) { throw Boom.wrap(err, 503, 'Error querying database.'); }) .map(stripMongoId) .then(res.json.bind(res), next); }); // Internal handler for updating a job's state router.post('/:container/:name', ensure('params', ['container', 'name']), ensure('body', ['criteria', 'updates']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = canonicalizeDates(_.defaults(req.body.criteria, { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, })); var updates = { $set: canonicalizeDates(req.body.updates) }; Bluebird.promisify(jobs.findOneAndUpdate, jobs)(query, updates, { returnOriginal: false, }) .catch(function (err) { throw Boom.wrap(err, 503, 'Error updating database'); }) .get('value') .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .then(stripMongoId) .then(res.json.bind(res), next); }); // Create or update an existing cron job (idempotent) router.put('/:container/:name', ensure('params', ['container', 'name']), ensure('body', ['token', 'schedule']), function (req, res, next) { var data = req.webtaskContext.data; var maxJobsPerContainer = parseInt(data.max_jobs_per_container, 10) || 100; var jobs = req.mongo.collection(data.JOB_COLLECTION); var now = new Date(); var tokenData = Jwt.decode(req.body.token, {complete: true}); var intervalOptions = {}; var nextAvailableAt; if (tokenData.payload.exp) { intervalOptions.endDate = new Date(tokenData.payload.exp * 1000); } if (tokenData.payload.nbf) { intervalOptions.currentDate = new Date(tokenData.payload.nbf * 1000); } try { var interval = Cron.parseExpression(req.body.schedule, intervalOptions); nextAvailableAt = interval.next(); } catch (e) { return next(Boom.badRequest('Invalid cron expression `' + req.body.schedule + '`.', req.body)); } if (!nextAvailableAt) { return next(Boom.badRequest('The provided token\'s `nbf` and `exp` ' + 'claims are such that the job would never run with the ' + 'schedule `' + req.body.schedule + '`.')); } var update = { $set: { state: 'active', schedule: req.body.schedule, token: req.body.token, cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, expires_at: intervalOptions.endDate || null, last_scheduled_at: null, next_available_at: nextAvailableAt, token_data: tokenData.payload, }, $setOnInsert: { results: [], run_count: 0, error_count: 0, } }; var countExistingCursor = jobs.find({ cluster_url: data.cluster_url, container: req.params.container, }); var countExisting = Bluebird.promisify(countExistingCursor.count, countExistingCursor)(); var alreadyExistsCursor = jobs.find({ cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }); var alreadyExists = Bluebird.promisify(alreadyExistsCursor.count, alreadyExistsCursor)(); Bluebird.all([countExisting, alreadyExists]) .catch(function (err) { throw Boom.wrap(err, 503, 'Error querying database'); }) .spread(function (sameContainerCount, exists) { if (!exists && sameContainerCount >= maxJobsPerContainer) { throw Boom.badRequest('Unable to schedule more than ' + maxJobsPerContainer + ' jobs per container.'); } return Bluebird.promisify(jobs.findOneAndUpdate, jobs)({ cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }, update, { returnOriginal: false, upsert: true, }) .catch(function (err) { throw Boom.wrap(err, 503, 'Error updating database'); }) .get('value'); }) .then(stripMongoId) .then(res.json.bind(res), next); }); router.get('/:container/:name', ensure('params', ['container', 'name']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }; var projection = { results: { $slice: 1 }, }; Bluebird.promisify(jobs.findOne, jobs)(query, projection) .catch(function (err) { throw Boom.wrap(err, 503, 'Error querying database.'); }) .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .then(stripMongoId) .then(res.json.bind(res), next); }); router.delete('/:container/:name', ensure('params', ['container', 'name']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }; var sort = { cluster_url: 1, container: 1, name: 1, }; Bluebird.promisify(jobs.findAndRemove, jobs)(query, sort, {}) .catch(function (err) { console.log(err); throw Boom.wrap(err, 503, 'Error querying database'); }) .get('value') .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .then(respondWith204(res), next); }); router.get('/:container/:name/history', ensure('params', ['container', 'name']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }; var limit = req.query.limit ? Math.max(0, Math.min(20, parseInt(req.query.limit, 10))) : 10; var skip = req.query.offset ? Math.max(0, parseInt(req.query.offset, 10)) : 0; var projection = { results: { $slice: [skip, limit] }, }; Bluebird.promisify(jobs.findOne, jobs)(query, projection) .catch(function (err) { throw Boom.wrap(err, 503, 'Error querying database'); }) .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .get('results') .map(stripMongoId) .then(res.json.bind(res), next); }); router.post('/:container/:name/history', ensure('params', ['container', 'name']), ensure('body', ['created_at', 'type', 'body']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var result = canonicalizeDates(req.body); var query = { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }; var update = { $push: { results: { $each: [result], $position: 0, // Push to head of array $slice: 100, // Maximum 100 history entries } }, $inc: { run_count: +(result.type === 'success'), error_count: +(result.type === 'error'), } }; Bluebird.promisify(jobs.findOneAndUpdate, jobs)(query, update, { returnOriginal: false, }) .catch(function (err) { throw Boom.wrap(err, 503, 'Error updating database'); }) .get('value') .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .then(stripMongoId) .then(respondWith204(res), next); }); module.exports = Webtask.fromConnect(app); // Helper methods function ensure (source, fields) { return function (req, res, next) { var data = req[source]; for (var i in fields) { if (!data[fields[i]]) { return next(Boom.badRequest('Missing ' + source + 'parameter ' + '`' + fields[i] + '`.')); } } next(); }; } function canonicalizeDates (obj) { if (_.isArray(obj)) return _.map(obj, canonicalizeDates); if (_.isObject(obj)) { if (obj['$date']) return new Date(obj['$date']); else return _.mapValues(obj, canonicalizeDates); } return obj; } function stripMongoId (doc) { if (doc) { if (doc._id) delete doc._id; if (doc.results) doc.results = _.map(doc.results, stripMongoId); } return doc; } function respondWith204 (res) { return function () { res.status(204).send(); }; }
webtasks/cron_backend_mongodb.js
var Boom = require('boom'); var Bluebird = require('bluebird'); var Cron = require('cron-parser'); var Express = require('express'); var Jwt = require('jsonwebtoken'); var Webtask = require('webtask-tools'); var _ = require('lodash'); var app = Express(); var router = Express.Router(); var mongo; // Check for required configuration parameters app.use(function (req, res, next) { var data = req.webtaskContext.data; var required = ['JOB_COLLECTION', 'MONGO_URL', 'cluster_url']; for (var i in required) { var key = required[i]; if (!data[key]) { var err = Boom.badGateway('Cron webtask needs to be configured ' + 'with the parameter: `' + key + '`.', data); return next(err); } } next(); }); // Set up connection to mongodb app.use(function (req, res, next) { // Short-cut if mongo is already setup if (mongo) { req.mongo = mongo; return next(); } var MongoClient = require('mongodb').MongoClient; var connect = Bluebird.promisify(MongoClient.connect, MongoClient); var data = req.webtaskContext.data; return connect(data.MONGO_URL) .then(function (db) { // Store the settled promise resolving to the db object mongo = req.mongo = db; }) .catch(function (err) { throw Boom.wrap(err, 503, 'Database unreachable.'); }) .nodeify(next); }); // Parse incoming json bodies app.use(require('body-parser').json()); app.use(router); app.use(function(err, req, res, next) { console.log(err.message); console.log(err.stack); if (!err.isBoom) err = Boom.wrap(err); res .set(err.output.headers) .status(err.output.statusCode) .json(err.output.payload); }); router.post('/reserve', ensure('query', ['count', 'ttl']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var count = Math.max(0, Math.min(100, parseInt(req.query.count, 10))); var now = new Date(); var nextAvailableAt = new Date(now.valueOf() + (parseInt(data.ttl, 10) * 1000)); console.log('attempting to reserve ' + count + ' jobs.'); Bluebird.map(_.range(count), function (n) { var filter = { cluster_url: data.cluster_url, next_available_at: { $lte: now }, state: 'active', }; var update = { $set: { next_available_at: nextAvailableAt } }; var options = { projection: { results: { $slice: 10 }, // Limit to the 10 last results }, returnOriginal: false, // Return modified }; return Bluebird.promisify(jobs.findOneAndUpdate, jobs)(filter, update, options) .get('value'); // Only pull out the value }) // Don't prevent one failure from blocking the entire // reservation (that would mean extra waiting on those that // didn't fail) .settle() // Log errors and continue with safe fallback .map(function (result) { if (result.isRejected()) { console.log('error reserving job: ' + result.value().message); return null; } else { return result.value(); } }) // Elminate error queries and queries that did not match // (this is the case when there are fewer than N jobs // available for running now) .filter(Boolean) .tap(function (jobs) { console.log('successfully reserved ' + jobs.length + ' job(s).'); }) .map(stripMongoId) .then(res.json.bind(res), next); }); router.get('/:container?', function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = { cluster_url: data.cluster_url, }; // Both admin and user will hit this endpoint. When admin, container can be unset if (req.params.container) query.container = req.params.container; var limit = req.query.limit ? Math.max(0, Math.min(20, parseInt(req.query.limit, 10))) : 10; var skip = req.query.offset ? Math.max(0, parseInt(req.query.offset, 10)) : 0; var cursor = jobs.find(query) .skip(skip) .limit(limit); Bluebird.promisify(cursor.toArray, cursor)() .catch(function (err) { throw Boom.wrap(err, 503, 'Error querying database.'); }) .map(stripMongoId) .then(res.json.bind(res), next); }); // Internal handler for updating a job's state router.post('/:container/:name', ensure('params', ['container', 'name']), ensure('body', ['criteria', 'updates']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = canonicalizeDates(_.defaults(req.body.criteria, { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, })); var updates = { $set: canonicalizeDates(req.body.updates) }; Bluebird.promisify(jobs.findOneAndUpdate, jobs)(query, updates, { returnOriginal: false, upsert: true, }) .catch(function (err) { throw Boom.wrap(err, 503, 'Error updating database.'); }) .get('value') .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .then(stripMongoId) .then(res.json.bind(res), next); }); // Create or update an existing cron job (idempotent) router.put('/:container/:name', ensure('params', ['container', 'name']), ensure('body', ['token', 'schedule']), function (req, res, next) { var data = req.webtaskContext.data; var maxJobsPerContainer = parseInt(data.max_jobs_per_container, 10) || 100; var jobs = req.mongo.collection(data.JOB_COLLECTION); var now = new Date(); var tokenData = Jwt.decode(req.body.token, {complete: true}); var intervalOptions = {}; var nextAvailableAt; if (tokenData.payload.exp) { intervalOptions.endDate = new Date(tokenData.payload.exp * 1000); } if (tokenData.payload.nbf) { intervalOptions.currentDate = new Date(tokenData.payload.nbf * 1000); } try { var interval = Cron.parseExpression(req.body.schedule, intervalOptions); nextAvailableAt = interval.next(); } catch (e) { return next(Boom.badRequest('Invalid cron expression `' + req.body.schedule + '`.', req.body)); } if (!nextAvailableAt) { return next(Boom.badRequest('The provided token\'s `nbf` and `exp` ' + 'claims are such that the job would never run with the ' + 'schedule `' + req.body.schedule + '`.')); } var update = { $set: { state: 'active', schedule: req.body.schedule, token: req.body.token, cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, expires_at: intervalOptions.endDate || null, last_scheduled_at: null, next_available_at: nextAvailableAt, token_data: tokenData.payload, }, $setOnInsert: { results: [], run_count: 0, error_count: 0, } }; var countExistingCursor = jobs.find({ cluster_url: data.cluster_url, container: req.params.container, }); var countExisting = Bluebird.promisify(countExistingCursor.count, countExistingCursor)(); var alreadyExistsCursor = jobs.find({ cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }); var alreadyExists = Bluebird.promisify(alreadyExistsCursor.count, alreadyExistsCursor)(); Bluebird.all([countExisting, alreadyExists]) .catch(function (err) { throw Boom.wrap(err, 503, 'Error querying database.'); }) .then(function (counts) { var sameContainerCount = counts[0]; var exists = !!counts[1]; if (!exists && sameContainerCount >= maxJobsPerContainer) { throw Boom.badRequest('Unable to schedule more than ' + maxJobsPerContainer + ' jobs per container.'); } return Bluebird.promisify(jobs.findOneAndUpdate, jobs)({ cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }, update, { returnOriginal: false, upsert: true, }) .catch(function (err) { throw Boom.wrap(err, 503, 'Error updating database.'); }) .get('value'); }) .then(stripMongoId) .then(res.json.bind(res), next); }); router.get('/:container/:name', ensure('params', ['container', 'name']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }; var projection = { results: { $slice: 1 }, }; Bluebird.promisify(jobs.findOne, jobs)(query, projection) .catch(function (err) { throw Boom.wrap(err, 503, 'Error querying database.'); }) .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .then(stripMongoId) .then(res.json.bind(res), next); }); router.delete('/:container/:name', ensure('params', ['container', 'name']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }; var sort = { cluster_url: 1, container: 1, name: 1, }; Bluebird.promisify(jobs.findAndRemove, jobs)(query, sort, {}) .catch(function (err) { console.log(err); throw Boom.wrap(err, 503, 'Error querying database.'); }) .get('value') .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .then(respondWith204(res), next); }); router.get('/:container/:name/history', ensure('params', ['container', 'name']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var query = { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }; var limit = req.query.limit ? Math.max(0, Math.min(20, parseInt(req.query.limit, 10))) : 10; var skip = req.query.offset ? Math.max(0, parseInt(req.query.offset, 10)) : 0; var projection = { results: { $slice: [skip, limit] }, }; Bluebird.promisify(jobs.findOne, jobs)(query, projection) .catch(function (err) { throw Boom.wrap(err, 503, 'Error querying database.'); }) .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .get('results') .map(stripMongoId) .then(res.json.bind(res), next); }); router.post('/:container/:name/history', ensure('params', ['container', 'name']), ensure('body', ['created_at', 'type', 'headers', 'statusCode', 'body']), function (req, res, next) { var data = req.webtaskContext.data; var jobs = req.mongo.collection(data.JOB_COLLECTION); var result = canonicalizeDates(req.body); var query = { cluster_url: data.cluster_url, container: req.params.container, name: req.params.name, }; var update = { $push: { results: { $each: [result], $position: 0, // Push to head of array $slice: 100, // Maximum 100 history entries } }, $inc: { run_count: +(result.type === 'success'), error_count: +(result.type === 'error'), } } Bluebird.promisify(jobs.findOneAndUpdate, jobs)(query, update, { returnOriginal: false, upsert: true, }) .catch(function (err) { throw Boom.wrap(err, 503, 'Error updating database.'); }) .get('value') .then(function (job) { if (!job) { throw Boom.notFound('No such job `' + req.params.name + '`.'); } return job; }) .then(stripMongoId) .then(respondWith204(res), next); }); module.exports = Webtask.fromConnect(app); // Helper methods function ensure (source, fields) { return function (req, res, next) { var data = req[source]; for (var i in fields) { if (!data[fields[i]]) { return next(Boom.badRequest('Missing ' + source + 'parameter ' + '`' + fields[i] + '`.')); } } next(); }; } function canonicalizeDates (obj) { if (_.isArray(obj)) return _.map(obj, canonicalizeDates); if (_.isObject(obj)) { if (obj['$date']) return new Date(obj['$date']); else return _.mapValues(obj, canonicalizeDates); } return obj; } function stripMongoId (doc) { if (doc) { if (doc._id) delete doc._id; if (doc.results) doc.results = _.map(doc.results, stripMongoId); } return doc; } function respondWith204 (res) { return function () { res.status(204).send(); }; }
Minor fixes to cron mongodb backend
webtasks/cron_backend_mongodb.js
Minor fixes to cron mongodb backend
<ide><path>ebtasks/cron_backend_mongodb.js <ide> <ide> Bluebird.promisify(jobs.findOneAndUpdate, jobs)(query, updates, { <ide> returnOriginal: false, <del> upsert: true, <del> }) <del> .catch(function (err) { <del> throw Boom.wrap(err, 503, 'Error updating database.'); <add> }) <add> .catch(function (err) { <add> throw Boom.wrap(err, 503, 'Error updating database'); <ide> }) <ide> .get('value') <ide> .then(function (job) { <ide> <ide> Bluebird.all([countExisting, alreadyExists]) <ide> .catch(function (err) { <del> throw Boom.wrap(err, 503, 'Error querying database.'); <del> }) <del> .then(function (counts) { <del> var sameContainerCount = counts[0]; <del> var exists = !!counts[1]; <del> <add> throw Boom.wrap(err, 503, 'Error querying database'); <add> }) <add> .spread(function (sameContainerCount, exists) { <ide> if (!exists && sameContainerCount >= maxJobsPerContainer) { <ide> throw Boom.badRequest('Unable to schedule more than ' <ide> + maxJobsPerContainer <ide> upsert: true, <ide> }) <ide> .catch(function (err) { <del> throw Boom.wrap(err, 503, 'Error updating database.'); <add> throw Boom.wrap(err, 503, 'Error updating database'); <ide> }) <ide> .get('value'); <ide> }) <ide> Bluebird.promisify(jobs.findAndRemove, jobs)(query, sort, {}) <ide> .catch(function (err) { <ide> console.log(err); <del> throw Boom.wrap(err, 503, 'Error querying database.'); <add> throw Boom.wrap(err, 503, 'Error querying database'); <ide> }) <ide> .get('value') <ide> .then(function (job) { <ide> <ide> Bluebird.promisify(jobs.findOne, jobs)(query, projection) <ide> .catch(function (err) { <del> throw Boom.wrap(err, 503, 'Error querying database.'); <add> throw Boom.wrap(err, 503, 'Error querying database'); <ide> }) <ide> .then(function (job) { <ide> if (!job) { <ide> <ide> router.post('/:container/:name/history', <ide> ensure('params', ['container', 'name']), <del> ensure('body', ['created_at', 'type', 'headers', 'statusCode', 'body']), <add> ensure('body', ['created_at', 'type', 'body']), <ide> function (req, res, next) { <ide> var data = req.webtaskContext.data; <ide> var jobs = req.mongo.collection(data.JOB_COLLECTION); <ide> run_count: +(result.type === 'success'), <ide> error_count: +(result.type === 'error'), <ide> } <del> } <add> }; <ide> <ide> Bluebird.promisify(jobs.findOneAndUpdate, jobs)(query, update, { <ide> returnOriginal: false, <del> upsert: true, <del> }) <del> .catch(function (err) { <del> throw Boom.wrap(err, 503, 'Error updating database.'); <add> }) <add> .catch(function (err) { <add> throw Boom.wrap(err, 503, 'Error updating database'); <ide> }) <ide> .get('value') <ide> .then(function (job) {
Java
agpl-3.0
1b0fc6b2cfb79a8b41f93dce993df2aa42566d7c
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
d99a768a-2e61-11e5-9284-b827eb9e62be
hello.java
d9950de4-2e61-11e5-9284-b827eb9e62be
d99a768a-2e61-11e5-9284-b827eb9e62be
hello.java
d99a768a-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>d9950de4-2e61-11e5-9284-b827eb9e62be <add>d99a768a-2e61-11e5-9284-b827eb9e62be
Java
epl-1.0
6deb35efd6e80722f1e66c411930b8add2aa4fd8
0
debrief/debrief,theanuradha/debrief,debrief/debrief,debrief/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * 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. */ package com.planetmayo.debrief.satc.util; import java.util.ArrayList; import com.planetmayo.debrief.satc.model.GeoPoint; import com.planetmayo.debrief.satc.model.states.LocationRange; import com.planetmayo.debrief.satc.util.calculator.GeoCalculatorType; import com.planetmayo.debrief.satc.util.calculator.GeodeticCalculator; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.PrecisionModel; /** * utility class providing geospatial support * * @author ian * */ public class GeoSupport { private static volatile GeoCalculatorType _calculatorType = GeoCalculatorType.FAST; private static final GeometryFactory _factory = new GeometryFactory(new PrecisionModel(1000000)); // private static final GeometryFactory _factory = new GeometryFactory(); public static double[][] getCoordsFor(LocationRange loc) { Geometry geometry = loc.getGeometry(); Coordinate[] coords = geometry.getCoordinates(); double[][] res = new double[coords.length][2]; for (int i = 0; i < coords.length; i++) { Coordinate thisC = coords[i]; res[i][0] = thisC.x; res[i][1] = thisC.y; } return res; } public static void setCalculatorType(GeoCalculatorType type) { _calculatorType = type; } /** * get our geometry factory * * @return */ public static GeometryFactory getFactory() { return _factory; } public static Point createPoint(double lon, double lat) { return getFactory().createPoint(new Coordinate(lon, lat)); } /** * creates a ring with center in specified point (lon, lat) and specified radius in meters (range) * @param center * @param range * @param polygon * @return */ public static LinearRing geoRing(Point center, double range) { return (LinearRing) geoRingOrPolygon(center, range, false); } /** * creates a circle with center in specified point (lon, lat) and specified radius in meters (range) * @param center * @param range * @param polygon * @return */ public static Polygon geoCircle(Point center, double range) { return (Polygon) geoRingOrPolygon(center, range, true); } public static Geometry geoRingOrPolygon(Point center, double range, boolean polygon) { GeodeticCalculator calculator = createCalculator(); calculator.setStartingGeographicPoint(center.getX(), center.getY()); calculator.setDirection(0, range); double yRadius = Math.abs(calculator.getDestinationGeographicPoint().getY() - center.getY()); calculator.setDirection(90, range); double xRadius = Math.abs(calculator.getDestinationGeographicPoint().getX() - center.getX()); Coordinate[] coords = new Coordinate[37]; double current = 0; double delta = Math.PI / 18.0; for (int i = 0; i < 36; i++, current += delta) { coords[i] = new Coordinate( center.getX() + Math.cos(current) * xRadius, center.getY() + Math.sin(current) * yRadius ); } coords[36] = coords[0]; return polygon ? _factory.createPolygon(coords) : _factory.createLinearRing(coords); } public static double kts2MSec(double kts) { return kts * 0.514444444; } // /** convert a turn rate of degrees per second to radians per millisecond // * // * @param rads_milli // * @return // */ // public static double degsSec2radsMilli(double degs_sec) // { // // first convert to millis // double res = degs_sec / 1000; // // // and now to rads // return Math.toRadians(res); // } // // /** convert a turn rate of radians per millisecond to degrees per second to // radians per millisecond // * // * @param rads_milli // * @return // */ // public static double radsMilli2degSec(double rads_milli) // { // // first convert to seconds // double res = rads_milli * 1000d; // // // now to degrees // return Math.toDegrees(res); // } public static double MSec2kts(double m_sec) { return m_sec / 0.514444444; } public static double yds2m(double yds) { return yds * 0.91444; } public static double convertToCompassAngle(double angle) { return MathUtils.normalizeAngle(Math.PI / 2 - angle); } public static GeodeticCalculator createCalculator() { return _calculatorType.create(); } public static String formatGeoPoint(GeoPoint geoPoint) { double _lat = geoPoint.getLat(); double _lon = geoPoint.getLon(); String latitudeStr = decimalToDMS(Math.abs(_lat)) + (_lat < 0 ? "S" : "N"); String longitudeStr = decimalToDMS(Math.abs(_lon)) + (_lon < 0 ? "W" : "E"); return latitudeStr + "\n" + longitudeStr; } public static String decimalToDMS(double coord) { String output, degrees, minutes, seconds; double mod = coord % 1; int intPart = (int) coord; degrees = String.valueOf((int) intPart); coord = mod * 60; mod = coord % 1; intPart = (int) coord; minutes = String.valueOf((int) intPart); coord = mod * 60; intPart = (int) coord; seconds = String.valueOf(Math.round(coord * 100.0) / 100.0); output = degrees + "\u00B0 " + minutes + "' " + seconds + "\" "; return output; } public static GeoPoint getGeoPointFromString(String latlong) { String[] _latlong = latlong.split("[NEWS]"); String lat = _latlong[0]; String lon = _latlong[1]; double _lat = parseDMSString(lat); double _lon = parseDMSString(lon); if (latlong.indexOf("S") > 0) { _lat *= -1; } if (latlong.indexOf("W") > 0) { _lon *= -1; } return new GeoPoint(_lat, _lon); } private static double parseDMSString(String lat) { double deg = Double.parseDouble(lat.substring(0, lat.indexOf("\u00B0 "))); double min = Double.parseDouble(lat.substring(lat.indexOf("\u00B0 ") + 1, lat.indexOf("' "))); double sec = Double.parseDouble(lat.substring(lat.indexOf("' ") + 1, lat.indexOf("\" "))); return dmsToDecimal(deg, min, sec); } public static double dmsToDecimal(double degree, double minutes, double seconds) { return degree + ((seconds / 60) + minutes) / 60; } /** * generate a grid of points across the polygon (see implementation for more * detail) */ public static ArrayList<Point> ST_Tile(final Geometry p_geom, final int numPoints, final int p_precision) { return MakeGrid.ST_Tile(p_geom, numPoints, p_precision); } }
org.mwc.debrief.satc.core/src/com/planetmayo/debrief/satc/util/GeoSupport.java
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * 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. */ package com.planetmayo.debrief.satc.util; import java.util.ArrayList; import com.planetmayo.debrief.satc.model.GeoPoint; import com.planetmayo.debrief.satc.model.states.LocationRange; import com.planetmayo.debrief.satc.util.calculator.GeoCalculatorType; import com.planetmayo.debrief.satc.util.calculator.GeodeticCalculator; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * utility class providing geospatial support * * @author ian * */ public class GeoSupport { private static volatile GeoCalculatorType _calculatorType = GeoCalculatorType.FAST; private static final GeometryFactory _factory = new GeometryFactory(); public static double[][] getCoordsFor(LocationRange loc) { Geometry geometry = loc.getGeometry(); Coordinate[] coords = geometry.getCoordinates(); double[][] res = new double[coords.length][2]; for (int i = 0; i < coords.length; i++) { Coordinate thisC = coords[i]; res[i][0] = thisC.x; res[i][1] = thisC.y; } return res; } public static void setCalculatorType(GeoCalculatorType type) { _calculatorType = type; } /** * get our geometry factory * * @return */ public static GeometryFactory getFactory() { return _factory; } public static Point createPoint(double lon, double lat) { return getFactory().createPoint(new Coordinate(lon, lat)); } /** * creates a ring with center in specified point (lon, lat) and specified radius in meters (range) * @param center * @param range * @param polygon * @return */ public static LinearRing geoRing(Point center, double range) { return (LinearRing) geoRingOrPolygon(center, range, false); } /** * creates a circle with center in specified point (lon, lat) and specified radius in meters (range) * @param center * @param range * @param polygon * @return */ public static Polygon geoCircle(Point center, double range) { return (Polygon) geoRingOrPolygon(center, range, true); } public static Geometry geoRingOrPolygon(Point center, double range, boolean polygon) { GeodeticCalculator calculator = createCalculator(); calculator.setStartingGeographicPoint(center.getX(), center.getY()); calculator.setDirection(0, range); double yRadius = Math.abs(calculator.getDestinationGeographicPoint().getY() - center.getY()); calculator.setDirection(90, range); double xRadius = Math.abs(calculator.getDestinationGeographicPoint().getX() - center.getX()); Coordinate[] coords = new Coordinate[37]; double current = 0; double delta = Math.PI / 18.0; for (int i = 0; i < 36; i++, current += delta) { coords[i] = new Coordinate( center.getX() + Math.cos(current) * xRadius, center.getY() + Math.sin(current) * yRadius ); } coords[36] = coords[0]; return polygon ? _factory.createPolygon(coords) : _factory.createLinearRing(coords); } public static double kts2MSec(double kts) { return kts * 0.514444444; } // /** convert a turn rate of degrees per second to radians per millisecond // * // * @param rads_milli // * @return // */ // public static double degsSec2radsMilli(double degs_sec) // { // // first convert to millis // double res = degs_sec / 1000; // // // and now to rads // return Math.toRadians(res); // } // // /** convert a turn rate of radians per millisecond to degrees per second to // radians per millisecond // * // * @param rads_milli // * @return // */ // public static double radsMilli2degSec(double rads_milli) // { // // first convert to seconds // double res = rads_milli * 1000d; // // // now to degrees // return Math.toDegrees(res); // } public static double MSec2kts(double m_sec) { return m_sec / 0.514444444; } public static double yds2m(double yds) { return yds * 0.91444; } public static double convertToCompassAngle(double angle) { return MathUtils.normalizeAngle(Math.PI / 2 - angle); } public static GeodeticCalculator createCalculator() { return _calculatorType.create(); } public static String formatGeoPoint(GeoPoint geoPoint) { double _lat = geoPoint.getLat(); double _lon = geoPoint.getLon(); String latitudeStr = decimalToDMS(Math.abs(_lat)) + (_lat < 0 ? "S" : "N"); String longitudeStr = decimalToDMS(Math.abs(_lon)) + (_lon < 0 ? "W" : "E"); return latitudeStr + "\n" + longitudeStr; } public static String decimalToDMS(double coord) { String output, degrees, minutes, seconds; double mod = coord % 1; int intPart = (int) coord; degrees = String.valueOf((int) intPart); coord = mod * 60; mod = coord % 1; intPart = (int) coord; minutes = String.valueOf((int) intPart); coord = mod * 60; intPart = (int) coord; seconds = String.valueOf(Math.round(coord * 100.0) / 100.0); output = degrees + "\u00B0 " + minutes + "' " + seconds + "\" "; return output; } public static GeoPoint getGeoPointFromString(String latlong) { String[] _latlong = latlong.split("[NEWS]"); String lat = _latlong[0]; String lon = _latlong[1]; double _lat = parseDMSString(lat); double _lon = parseDMSString(lon); if (latlong.indexOf("S") > 0) { _lat *= -1; } if (latlong.indexOf("W") > 0) { _lon *= -1; } return new GeoPoint(_lat, _lon); } private static double parseDMSString(String lat) { double deg = Double.parseDouble(lat.substring(0, lat.indexOf("\u00B0 "))); double min = Double.parseDouble(lat.substring(lat.indexOf("\u00B0 ") + 1, lat.indexOf("' "))); double sec = Double.parseDouble(lat.substring(lat.indexOf("' ") + 1, lat.indexOf("\" "))); return dmsToDecimal(deg, min, sec); } public static double dmsToDecimal(double degree, double minutes, double seconds) { return degree + ((seconds / 60) + minutes) / 60; } /** * generate a grid of points across the polygon (see implementation for more * detail) */ public static ArrayList<Point> ST_Tile(final Geometry p_geom, final int numPoints, final int p_precision) { return MakeGrid.ST_Tile(p_geom, numPoints, p_precision); } }
Relax the PrecisionModel precision, to avoid "found non-noded intersection" JTS issue
org.mwc.debrief.satc.core/src/com/planetmayo/debrief/satc/util/GeoSupport.java
Relax the PrecisionModel precision, to avoid "found non-noded intersection" JTS issue
<ide><path>rg.mwc.debrief.satc.core/src/com/planetmayo/debrief/satc/util/GeoSupport.java <ide> import com.vividsolutions.jts.geom.LinearRing; <ide> import com.vividsolutions.jts.geom.Point; <ide> import com.vividsolutions.jts.geom.Polygon; <add>import com.vividsolutions.jts.geom.PrecisionModel; <ide> <ide> /** <ide> * utility class providing geospatial support <ide> { <ide> private static volatile GeoCalculatorType _calculatorType = GeoCalculatorType.FAST; <ide> <del> private static final GeometryFactory _factory = new GeometryFactory(); <add> private static final GeometryFactory _factory = new GeometryFactory(new PrecisionModel(1000000)); <add>// private static final GeometryFactory _factory = new GeometryFactory(); <ide> <ide> public static double[][] getCoordsFor(LocationRange loc) <ide> {
Java
cc0-1.0
e1235d2688bdfa9b7d57c7fc506d3c0323c5036c
0
C4K3/Misc
package net.simpvp.Misc; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.server.ServerCommandEvent; public class DisableCmd implements Listener { /* Disables all commands in the disabled.txt file * Adapted from PlgDisableCmd by Plague */ private static List<String> disabledCmds; private static List<String> opOnlyCmds; private Player player; @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { String[] split = event.getMessage().split(" "); if (split.length < 1) return; String cmd = split[0].trim().substring(1).toLowerCase(); player = event.getPlayer(); if (Collections.binarySearch(disabledCmds, cmd) >= 0 ) { disable_event(event, "Blocked command found in disabledCmds.txt"); } else if (Collections.binarySearch(opOnlyCmds, cmd) >= 0 && !player.isOp()) { disable_event(event, "Blocked command found in opOnlyCmds.txt"); } else if (cmd.contains(":")) { disable_event(event, "Blocked command that contained :"); } } @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void onServerCommandEvent(ServerCommandEvent event) { if (event.getSender() instanceof ConsoleCommandSender) { return; } String[] split = event.getCommand().split(" "); if (split.length < 1) { return; } String cmd = split[0].trim().toLowerCase(); if (Collections.binarySearch(disabledCmds, cmd) >= 0) { event.getSender().sendMessage("You do not have permission to use this command."); Misc.instance.getLogger().info("Blocked commanad '" + cmd + "' found in disabledCmds.txt"); event.setCancelled(true); } else if (cmd.contains(":")) { event.getSender().sendMessage("You do not have permission to use this command."); Misc.instance.getLogger().info("Blocked commanad '" + cmd + "' that contained :"); event.setCancelled(true); } } private void disable_event(PlayerCommandPreprocessEvent event, String blocked_message) { event.getPlayer().sendMessage("Unknown command. Type \"/help\" for help."); Misc.instance.getLogger().info(blocked_message); event.setCancelled(true); } public static void loadDisabledCmds() { /* Adds disabled cmds to disabledCmds array * Reads from plugins/Misc/disabledCmds.txt file */ try { disabledCmds = new ArrayList<String>(); File f = new File(Misc.instance.getDataFolder(), "disabledCmds.txt"); if (!f.exists()) { Misc.instance.getLogger().info("No items found in disabledCmds.txt"); } else { BufferedReader rdr = new BufferedReader(new FileReader(f)); String line; while ((line = rdr.readLine()) != null) { line = line.trim(); if (line.length() < 1) continue; disabledCmds.add(line.trim().toLowerCase()); } rdr.close(); Collections.sort(disabledCmds); Misc.instance.getLogger().info("Disabling " + disabledCmds.size() + " commands from disabledCmds.txt"); } } catch (Exception e) { Misc.instance.getLogger().info("Unexpected error: " + e.getMessage()); } /* Adding commands that are disabled for everybody but OPs to the opOnlyCmds array * Reads from plugins/Misc/opOnlyCmds.txt */ try { opOnlyCmds = new ArrayList<String>(); File f = new File(Misc.instance.getDataFolder(), "opOnlyCmds.txt"); if (!f.exists()) { Bukkit.getLogger().info("No items found in opOnlyCmds.txt"); } else { BufferedReader rdr = new BufferedReader(new FileReader(f)); String line; while ((line = rdr.readLine()) != null) { line = line.trim(); if (line.length() < 1) continue; opOnlyCmds.add(line.trim().toLowerCase()); } rdr.close(); Collections.sort(opOnlyCmds); Misc.instance.getLogger().info("Disabling " + opOnlyCmds.size() + " commands from opOnlyCmds.txt"); } } catch (Exception e) { Misc.instance.getLogger().info("Unexpected error: " + e.getMessage()); } } }
src/main/java/net/simpvp/Misc/DisableCmd.java
package net.simpvp.Misc; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.server.ServerCommandEvent; public class DisableCmd implements Listener { /* Disables all commands in the disabled.txt file * Adapted from PlgDisableCmd by Plague */ private static List<String> disabledCmds; private static List<String> opOnlyCmds; private Player player; @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { String[] split = event.getMessage().split(" "); if (split.length < 1) return; String cmd = split[0].trim().substring(1).toLowerCase(); player = event.getPlayer(); if (Collections.binarySearch(disabledCmds, cmd) >= 0 ) { disable_event(event, "Blocked command found in disabledCmds.txt"); } else if (Collections.binarySearch(opOnlyCmds, cmd) >= 0 && !player.isOp()) { disable_event(event, "Blocked command found in opOnlyCmds.txt"); } else if (cmd.contains(":")) { disable_event(event, "Blocked command that contained :"); } } @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void onServerCommandEvent(ServerCommandEvent event) { if (event.getSender() instanceof ConsoleCommandSender) { Misc.instance.getLogger().info("console"); return; } String[] split = event.getCommand().split(" "); if (split.length < 1) { return; } String cmd = split[0].trim().toLowerCase(); if (Collections.binarySearch(disabledCmds, cmd) >= 0) { event.getSender().sendMessage("You do not have permission to use this command."); Misc.instance.getLogger().info("Blocked commanad '" + cmd + "' found in disabledCmds.txt"); event.setCancelled(true); } else if (cmd.contains(":")) { event.getSender().sendMessage("You do not have permission to use this command."); Misc.instance.getLogger().info("Blocked commanad '" + cmd + "' that contained :"); event.setCancelled(true); } } private void disable_event(PlayerCommandPreprocessEvent event, String blocked_message) { event.getPlayer().sendMessage("Unknown command. Type \"/help\" for help."); Misc.instance.getLogger().info(blocked_message); event.setCancelled(true); } public static void loadDisabledCmds() { /* Adds disabled cmds to disabledCmds array * Reads from plugins/Misc/disabledCmds.txt file */ try { disabledCmds = new ArrayList<String>(); File f = new File(Misc.instance.getDataFolder(), "disabledCmds.txt"); if (!f.exists()) { Misc.instance.getLogger().info("No items found in disabledCmds.txt"); } else { BufferedReader rdr = new BufferedReader(new FileReader(f)); String line; while ((line = rdr.readLine()) != null) { line = line.trim(); if (line.length() < 1) continue; disabledCmds.add(line.trim().toLowerCase()); } rdr.close(); Collections.sort(disabledCmds); Misc.instance.getLogger().info("Disabling " + disabledCmds.size() + " commands from disabledCmds.txt"); } } catch (Exception e) { Misc.instance.getLogger().info("Unexpected error: " + e.getMessage()); } /* Adding commands that are disabled for everybody but OPs to the opOnlyCmds array * Reads from plugins/Misc/opOnlyCmds.txt */ try { opOnlyCmds = new ArrayList<String>(); File f = new File(Misc.instance.getDataFolder(), "opOnlyCmds.txt"); if (!f.exists()) { Bukkit.getLogger().info("No items found in opOnlyCmds.txt"); } else { BufferedReader rdr = new BufferedReader(new FileReader(f)); String line; while ((line = rdr.readLine()) != null) { line = line.trim(); if (line.length() < 1) continue; opOnlyCmds.add(line.trim().toLowerCase()); } rdr.close(); Collections.sort(opOnlyCmds); Misc.instance.getLogger().info("Disabling " + opOnlyCmds.size() + " commands from opOnlyCmds.txt"); } } catch (Exception e) { Misc.instance.getLogger().info("Unexpected error: " + e.getMessage()); } } }
Remove stray debug log
src/main/java/net/simpvp/Misc/DisableCmd.java
Remove stray debug log
<ide><path>rc/main/java/net/simpvp/Misc/DisableCmd.java <ide> @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) <ide> public void onServerCommandEvent(ServerCommandEvent event) { <ide> if (event.getSender() instanceof ConsoleCommandSender) { <del> Misc.instance.getLogger().info("console"); <ide> return; <ide> } <ide>
JavaScript
apache-2.0
c5c35a56e1c749d8a5225bad49ddda8978ebd0dd
0
apigee/apigeelint
/* Copyright 2019-2022 Google LLC 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. */ const ruleId = require("../myUtil.js").getRuleId(), debug = require("debug")("apigeelint:" + ruleId), xpath = require("xpath"); const plugin = { ruleId, name: "Check for commonly misplaced elements", message: "For example, a Flow element should be a child of Flows parent.", fatal: false, severity: 2, // error nodeType: "Endpoint", enabled: true }; const onProxyEndpoint = function(endpoint, cb) { debug('onProxyEndpoint'); let checker = new EndpointChecker(endpoint, true); let flagged = checker.check(); if (typeof(cb) == 'function') { cb(null, flagged); } }; const onTargetEndpoint = function(endpoint, cb) { debug('onTargetEndpoint'); let checker = new EndpointChecker(endpoint, false); let flagged = checker.check(); if (typeof(cb) == 'function') { cb(null, flagged); } }; const _markEndpoint = (endpoint, message, line, column) => { var result = { ruleId: plugin.ruleId, severity: plugin.severity, nodeType: plugin.nodeType, message, line, column, }; // discard duplicates if ( !line || !column || !endpoint.report.messages.find(m => m.line == line && m.column == column)) { endpoint.addMessage(result); } }; const allowedParents = { Step: ['Request', 'Response', 'FaultRule', 'DefaultFaultRule'], Request: ['PreFlow', 'PostFlow', 'Flow', 'PostClientFlow', 'HTTPMonitor'], Response: ['PreFlow', 'PostFlow', 'Flow', 'PostClientFlow'], Flows: ['ProxyEndpoint', 'TargetEndpoint'], Flow: ['Flows'], RouteRule: ['ProxyEndpoint'], DefaultFaultRule: ['ProxyEndpoint', 'TargetEndpoint'], HTTPTargetConnection: ['TargetEndpoint'], LoadBalancer: ['HTTPTargetConnection'], HealthMonitor: ['HTTPTargetConnection'], HTTPMonitor: ['HealthMonitor'], TCPMonitor: ['HealthMonitor'], SuccessResponse: ['HTTPMonitor'] }; const allowedChildren = { Step: ['Name', 'Condition'], Request: ['Step'], 'Request-child-of-HTTPMonitor': ['ConnectTimeoutInSec', 'SocketReadTimeoutInSec', 'Payload', 'IsSSL', 'TrustAllSSL', 'Port', 'Verb', 'Path', 'Header', 'IncludeHealthCheckIdHeader'], Response: ['Step'], Flows: ['Flow'], Flow: ['Description', 'Request', 'Response', 'Condition'], RouteRule: ['Condition', 'TargetEndpoint'], DefaultFaultRule: ['Step', 'AlwaysEnforce'], HTTPTargetConnection: ['LoadBalancer', 'Properties', 'Path', 'HealthMonitor', 'URL'], LoadBalancer: ['Algorithm', 'Server', 'MaxFailures', 'ServerUnhealthyResponse', 'RetryEnabled', 'TargetDisableSecs'], HealthMonitor: ['IsEnabled', 'IntervalInSec', 'HTTPMonitor', 'TCPMonitor'], HTTPMonitor: ['Request', 'SuccessResponse'], TCPMonitor: ['ConnectTimeoutInSec', 'Port'], SuccessResponse: ['ResponseCode', 'Header'], ProxyEndpoint: ['PreFlow', 'PostFlow', 'Flows', 'RouteRule', 'PostClientFlow', 'Description', 'FaultRules', 'DefaultFaultRule', 'HTTPProxyConnection'], TargetEndpoint: ['PreFlow', 'PostFlow', 'Flows', 'Description', 'FaultRules', 'DefaultFaultRule', 'LocalTargetConnection', 'HTTPTargetConnection'] }; class EndpointChecker { constructor(endpoint, isProxyEndpoint) { debug('EndpointChecker ctor (%s)', endpoint.getName()); this.endpoint = endpoint; this.isProxyEndpoint = isProxyEndpoint; this.flagged = false; } check() { try { const self = this; let ep = self.isProxyEndpoint ? 'ProxyEndpoint': 'TargetEndpoint'; let topLevelChildren = xpath.select("*", self.endpoint.element); topLevelChildren.forEach(child => { if (allowedChildren[ep].indexOf(child.tagName)< 0) { self.flagged = true; _markEndpoint(self.endpoint, `Invalid ${child.tagName} element`, child.lineNumber, child.columnNumber); } }); // 1st level children that must have at most one instance: Flows, DFR ['Flows', 'DefaultFaultRule', 'FaultRules'].forEach( elementName => { let elements = xpath.select(`${elementName}`, self.endpoint.element); if (elements.length != 0 && elements.length != 1) { self.flagged = true; elements.slice(1) .forEach(element => _markEndpoint(self.endpoint, `Extra ${elementName} element`, element.lineNumber, element.columnNumber)); } }); // Request, Response, Step, Flow, DefaultFaultRule, RouteRule let condition = Object.keys(allowedParents).map(n => `self::${n}`).join(' or '); let elements = xpath.select(`//*[${condition}]`, self.endpoint.element); elements.forEach(element => { let tagName = element.tagName; // misplaced children of toplevel elements are covered above if (element.parentNode.tagName != 'ProxyEndpoint' && element.parentNode.tagName != 'TargetEndpoint') { if (allowedParents[tagName].indexOf(element.parentNode.tagName)<0) { self.flagged = true; _markEndpoint(self.endpoint, `Misplaced ${tagName} element child of ${element.parentNode.tagName}`, element.lineNumber, element.columnNumber); } } let children = xpath.select("*", element); children.forEach(child => { // special case Request, there are two of them let t = (tagName == 'Request' && element.parentNode.tagName == 'HTTPMonitor') ? 'Request-child-of-HTTPMonitor' : tagName; if (allowedChildren[t].indexOf(child.tagName)<0) { self.flagged = true; _markEndpoint(self.endpoint, `Misplaced '${child.tagName}' element child of ${tagName}`, child.lineNumber, child.columnNumber); } }); }); // exactly one of LocalTarget and HTTPTarget is required if (! self.isProxyEndpoint) { let condition = ['LocalTargetConnection', 'HTTPTargetConnection'].map(n => `self::${n}`).join(' or '); let targetChildren = xpath.select(`*[${condition}]`, self.endpoint.element); if (targetChildren.length == 0) { self.flagged = true; _markEndpoint(self.endpoint, `Missing a required *TargetConnection`, 1, 2); } else if (targetChildren.length != 1) { self.flagged = true; targetChildren.slice(1) .forEach(configElement => _markEndpoint(self.endpoint, `${configElement.tagName} element conflicts with ${targetChildren[0].tagName} on line ${targetChildren[0].lineNumber}`, configElement.lineNumber, configElement.columnNumber)); } } // in HealthMonitor, exactly one of HTTPMonitor or TCPMonitor is required if (! self.isProxyEndpoint) { let healthMonitors = xpath.select(`HTTPTargetConnection/HealthMonitor`, self.endpoint.element); if (healthMonitors.length > 1) { self.flagged = true; healthMonitors.slice(1) .forEach(elt => _markEndpoint(self.endpoint, `Redundant HealthMonitor element`, elt.lineNumber, elt.columnNumber)); } if (healthMonitors.length > 0) { let condition = ['HTTP', 'TCP'].map(n => `self::${n}Monitor`).join(' or '); let monitors = xpath.select(`*[${condition}]`, healthMonitors[0]); if (monitors.length != 1) { self.flagged = true; monitors.slice(1) .forEach(configElement => _markEndpoint(self.endpoint, `${configElement.tagName} element conflicts with ${monitors[0].tagName} on line ${monitors[0].lineNumber}`, configElement.lineNumber, configElement.columnNumber)); } } } // future: add other checks here. return this.flagged; } catch(e) { console.log(e); return false; } } } module.exports = { plugin, onProxyEndpoint, onTargetEndpoint };
lib/package/plugins/EP002-misplacedElements.js
/* Copyright 2019-2022 Google LLC 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. */ const ruleId = require("../myUtil.js").getRuleId(), debug = require("debug")("apigeelint:" + ruleId), xpath = require("xpath"); const plugin = { ruleId, name: "Check for commonly misplaced elements", message: "For example, a Flow element should be a child of Flows parent.", fatal: false, severity: 2, // error nodeType: "Endpoint", enabled: true }; const onProxyEndpoint = function(endpoint, cb) { debug('onProxyEndpoint'); let checker = new EndpointChecker(endpoint, true); let flagged = checker.check(); if (typeof(cb) == 'function') { cb(null, flagged); } }; const onTargetEndpoint = function(endpoint, cb) { debug('onTargetEndpoint'); let checker = new EndpointChecker(endpoint, false); let flagged = checker.check(); if (typeof(cb) == 'function') { cb(null, flagged); } }; const _markEndpoint = (endpoint, message, line, column) => { var result = { ruleId: plugin.ruleId, severity: plugin.severity, nodeType: plugin.nodeType, message, line, column, }; // discard duplicates if ( !line || !column || !endpoint.report.messages.find(m => m.line == line && m.column == column)) { endpoint.addMessage(result); } }; const allowedParents = { Step: ['Request', 'Response', 'FaultRule', 'DefaultFaultRule'], Request: ['PreFlow', 'PostFlow', 'Flow', 'PostClientFlow', 'HTTPMonitor'], Response: ['PreFlow', 'PostFlow', 'Flow', 'PostClientFlow'], Flows: ['ProxyEndpoint', 'TargetEndpoint'], Flow: ['Flows'], RouteRule: ['ProxyEndpoint'], DefaultFaultRule: ['ProxyEndpoint', 'TargetEndpoint'], HTTPTargetConnection: ['TargetEndpoint'], LoadBalancer: ['HTTPTargetConnection'], HealthMonitor: ['HTTPTargetConnection'], HTTPMonitor: ['HealthMonitor'], TCPMonitor: ['HealthMonitor'], SuccessResponse: ['HTTPMonitor'] }; const allowedChildren = { Step: ['Name', 'Condition'], Request: ['Step'], 'Request-child-of-HTTPMonitor': ['ConnectTimeoutInSec', 'SocketReadTimeoutInSec', 'Payload', 'IsSSL', 'TrustAllSSL', 'Port', 'Verb', 'Path', 'Header', 'IncludeHealthCheckIdHeader'], Response: ['Step'], Flows: ['Flow'], Flow: ['Description', 'Request', 'Response', 'Condition'], RouteRule: ['Condition', 'TargetEndpoint'], DefaultFaultRule: ['Step', 'AlwaysEnforce'], HTTPTargetConnection: ['LoadBalancer', 'Properties', 'Path', 'HealthMonitor'], LoadBalancer: ['Algorithm', 'Server', 'MaxFailures', 'ServerUnhealthyResponse', 'RetryEnabled', 'TargetDisableSecs'], HealthMonitor: ['IsEnabled', 'IntervalInSec', 'HTTPMonitor', 'TCPMonitor'], HTTPMonitor: ['Request', 'SuccessResponse'], TCPMonitor: ['ConnectTimeoutInSec', 'Port'], SuccessResponse: ['ResponseCode', 'Header'], ProxyEndpoint: ['PreFlow', 'PostFlow', 'Flows', 'RouteRule', 'PostClientFlow', 'Description', 'FaultRules', 'DefaultFaultRule', 'HTTPProxyConnection'], TargetEndpoint: ['PreFlow', 'PostFlow', 'Flows', 'Description', 'FaultRules', 'DefaultFaultRule', 'LocalTargetConnection', 'HTTPTargetConnection'] }; class EndpointChecker { constructor(endpoint, isProxyEndpoint) { debug('EndpointChecker ctor (%s)', endpoint.getName()); this.endpoint = endpoint; this.isProxyEndpoint = isProxyEndpoint; this.flagged = false; } check() { try { const self = this; let ep = self.isProxyEndpoint ? 'ProxyEndpoint': 'TargetEndpoint'; let topLevelChildren = xpath.select("*", self.endpoint.element); topLevelChildren.forEach(child => { if (allowedChildren[ep].indexOf(child.tagName)< 0) { self.flagged = true; _markEndpoint(self.endpoint, `Invalid ${child.tagName} element`, child.lineNumber, child.columnNumber); } }); // 1st level children that must have at most one instance: Flows, DFR ['Flows', 'DefaultFaultRule', 'FaultRules'].forEach( elementName => { let elements = xpath.select(`${elementName}`, self.endpoint.element); if (elements.length != 0 && elements.length != 1) { self.flagged = true; elements.slice(1) .forEach(element => _markEndpoint(self.endpoint, `Extra ${elementName} element`, element.lineNumber, element.columnNumber)); } }); // Request, Response, Step, Flow, DefaultFaultRule, RouteRule let condition = Object.keys(allowedParents).map(n => `self::${n}`).join(' or '); let elements = xpath.select(`//*[${condition}]`, self.endpoint.element); elements.forEach(element => { let tagName = element.tagName; // misplaced children of toplevel elements are covered above if (element.parentNode.tagName != 'ProxyEndpoint' && element.parentNode.tagName != 'TargetEndpoint') { if (allowedParents[tagName].indexOf(element.parentNode.tagName)<0) { self.flagged = true; _markEndpoint(self.endpoint, `Misplaced ${tagName} element child of ${element.parentNode.tagName}`, element.lineNumber, element.columnNumber); } } let children = xpath.select("*", element); children.forEach(child => { // special case Request, there are two of them let t = (tagName == 'Request' && element.parentNode.tagName == 'HTTPMonitor') ? 'Request-child-of-HTTPMonitor' : tagName; if (allowedChildren[t].indexOf(child.tagName)<0) { self.flagged = true; _markEndpoint(self.endpoint, `Misplaced '${child.tagName}' element child of ${tagName}`, child.lineNumber, child.columnNumber); } }); }); // exactly one of LocalTarget and HTTPTarget is required if (! self.isProxyEndpoint) { let condition = ['LocalTargetConnection', 'HTTPTargetConnection'].map(n => `self::${n}`).join(' or '); let targetChildren = xpath.select(`*[${condition}]`, self.endpoint.element); if (targetChildren.length == 0) { self.flagged = true; _markEndpoint(self.endpoint, `Missing a required *TargetConnection`, 1, 2); } else if (targetChildren.length != 1) { self.flagged = true; targetChildren.slice(1) .forEach(configElement => _markEndpoint(self.endpoint, `${configElement.tagName} element conflicts with ${targetChildren[0].tagName} on line ${targetChildren[0].lineNumber}`, configElement.lineNumber, configElement.columnNumber)); } } // in HealthMonitor, exactly one of HTTPMonitor or TCPMonitor is required if (! self.isProxyEndpoint) { let healthMonitors = xpath.select(`HTTPTargetConnection/HealthMonitor`, self.endpoint.element); if (healthMonitors.length > 1) { self.flagged = true; healthMonitors.slice(1) .forEach(elt => _markEndpoint(self.endpoint, `Redundant HealthMonitor element`, elt.lineNumber, elt.columnNumber)); } if (healthMonitors.length > 0) { let condition = ['HTTP', 'TCP'].map(n => `self::${n}Monitor`).join(' or '); let monitors = xpath.select(`*[${condition}]`, healthMonitors[0]); if (monitors.length != 1) { self.flagged = true; monitors.slice(1) .forEach(configElement => _markEndpoint(self.endpoint, `${configElement.tagName} element conflicts with ${monitors[0].tagName} on line ${monitors[0].lineNumber}`, configElement.lineNumber, configElement.columnNumber)); } } } // future: add other checks here. return this.flagged; } catch(e) { console.log(e); return false; } } } module.exports = { plugin, onProxyEndpoint, onTargetEndpoint };
Fix for #323
lib/package/plugins/EP002-misplacedElements.js
Fix for #323
<ide><path>ib/package/plugins/EP002-misplacedElements.js <ide> Flow: ['Description', 'Request', 'Response', 'Condition'], <ide> RouteRule: ['Condition', 'TargetEndpoint'], <ide> DefaultFaultRule: ['Step', 'AlwaysEnforce'], <del> HTTPTargetConnection: ['LoadBalancer', 'Properties', 'Path', 'HealthMonitor'], <add> HTTPTargetConnection: ['LoadBalancer', 'Properties', 'Path', 'HealthMonitor', 'URL'], <ide> LoadBalancer: ['Algorithm', 'Server', 'MaxFailures', 'ServerUnhealthyResponse', 'RetryEnabled', 'TargetDisableSecs'], <ide> HealthMonitor: ['IsEnabled', 'IntervalInSec', 'HTTPMonitor', 'TCPMonitor'], <ide> HTTPMonitor: ['Request', 'SuccessResponse'],
Java
apache-2.0
2b3dcc22185b4d2b20651654b0a998c50de53822
0
b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl
/* * Copyright 2017-2020 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.index.es.admin; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Maps.newHashMapWithExpectedSize; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newHashSetWithExpectedSize; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.regex.Pattern; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest.Level; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest; import org.elasticsearch.action.bulk.BulkItemResponse.Failure; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.cluster.metadata.MappingMetadata; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.reindex.BulkByScrollResponse; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.script.ScriptType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.b2international.commons.ClassUtils; import com.b2international.commons.CompareUtils; import com.b2international.commons.ReflectionUtils; import com.b2international.index.*; import com.b2international.index.admin.IndexAdmin; import com.b2international.index.es.client.EsClient; import com.b2international.index.es.query.EsQueryBuilder; import com.b2international.index.mapping.DocumentMapping; import com.b2international.index.mapping.Mappings; import com.b2international.index.query.Expressions; import com.b2international.index.util.NumericClassUtils; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.flipkart.zjsonpatch.DiffFlags; import com.flipkart.zjsonpatch.JsonDiff; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.common.primitives.Primitives; /** * @since 5.10 */ public final class EsIndexAdmin implements IndexAdmin { private static final Set<String> DYNAMIC_SETTINGS = Set.of(IndexClientFactory.RESULT_WINDOW_KEY); /** * Important DIFF flags required to produce the JSON patch needed for proper compare and branch merge operation behavior, for proper index schema migration, and so on. * Should be used by default when using jsonpatch. */ public static final EnumSet<DiffFlags> DIFF_FLAGS = EnumSet.of(DiffFlags.ADD_ORIGINAL_VALUE_ON_REPLACE, DiffFlags.OMIT_COPY_OPERATION, DiffFlags.OMIT_MOVE_OPERATION); private static final int DEFAULT_MAX_NUMBER_OF_VERSION_CONFLICT_RETRIES = 5; private final Random random = new Random(); private final EsClient client; private final ObjectMapper mapper; private final String name; private final Map<String, Object> settings; private Mappings mappings; private final Logger log; private final String prefix; public EsIndexAdmin(EsClient client, ObjectMapper mapper, String name, Mappings mappings, Map<String, Object> settings) { this.client = client; this.mapper = mapper; this.name = name.toLowerCase(); this.mappings = mappings; this.settings = newHashMap(settings); this.log = LoggerFactory.getLogger(String.format("index.%s", this.name)); this.settings.putIfAbsent(IndexClientFactory.COMMIT_CONCURRENCY_LEVEL, IndexClientFactory.DEFAULT_COMMIT_CONCURRENCY_LEVEL); this.settings.putIfAbsent(IndexClientFactory.RESULT_WINDOW_KEY, ""+IndexClientFactory.DEFAULT_RESULT_WINDOW); this.settings.putIfAbsent(IndexClientFactory.MAX_TERMS_COUNT_KEY, ""+IndexClientFactory.DEFAULT_MAX_TERMS_COUNT); this.settings.putIfAbsent(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, IndexClientFactory.DEFAULT_TRANSLOG_SYNC_INTERVAL); this.settings.putIfAbsent(IndexClientFactory.BULK_ACTIONS_SIZE, IndexClientFactory.DEFAULT_BULK_ACTIONS_SIZE); this.settings.putIfAbsent(IndexClientFactory.BULK_ACTIONS_SIZE_IN_MB, IndexClientFactory.DEFAULT_BULK_ACTIONS_SIZE_IN_MB); final String prefix = (String) settings.getOrDefault(IndexClientFactory.INDEX_PREFIX, IndexClientFactory.DEFAULT_INDEX_PREFIX); this.prefix = prefix.isEmpty() ? "" : prefix + "."; } @Override public Logger log() { return log; } @Override public boolean exists() { try { return client().indices().exists(indices()); } catch (Exception e) { throw new IndexException("Couldn't check the existence of all ES indices.", e); } } private boolean exists(DocumentMapping mapping) { final String index = getTypeIndex(mapping); try { return client().indices().exists(index); } catch (Exception e) { throw new IndexException("Couldn't check the existence of ES index '" + index + "'.", e); } } @Override public void create() { log.info("Preparing '{}' indexes...", name); // create number of indexes based on number of types for (DocumentMapping mapping : mappings.getMappings()) { final String index = getTypeIndex(mapping); final String type = mapping.typeAsString(); final Map<String, Object> typeMapping = ImmutableMap.<String, Object>builder() .put("date_detection", false) .put("numeric_detection", false) .putAll(toProperties(mapping)) .build(); if (exists(mapping)) { // update mapping if required ImmutableOpenMap<String, MappingMetadata> currentIndexMapping; try { currentIndexMapping = client.indices().getMapping(new GetMappingsRequest().types(type).indices(index)).mappings().get(index); } catch (Exception e) { throw new IndexException(String.format("Failed to get mapping of '%s' for type '%s'", name, mapping.typeAsString()), e); } try { final ObjectNode newTypeMapping = mapper.valueToTree(typeMapping); final ObjectNode currentTypeMapping = mapper.valueToTree(currentIndexMapping.get(type).getSourceAsMap()); final JsonNode diff = JsonDiff.asJson(currentTypeMapping, newTypeMapping, DIFF_FLAGS); final ArrayNode diffNode = ClassUtils.checkAndCast(diff, ArrayNode.class); Set<String> compatibleChanges = newHashSet(); Set<String> uncompatibleChanges = newHashSet(); for (ObjectNode change : Iterables.filter(diffNode, ObjectNode.class)) { String prop = change.get("path").asText().substring(1); switch (change.get("op").asText()) { case "add": compatibleChanges.add(prop); break; case "move": case "replace": uncompatibleChanges.add(prop); break; default: break; } } if (!uncompatibleChanges.isEmpty()) { log.warn("Cannot migrate index '{}' to new mapping with breaking changes on properties '{}'. Run repository reindex to migrate to new mapping schema or drop that index manually using the Elasticsearch API.", index, uncompatibleChanges); } else if (!compatibleChanges.isEmpty()) { compatibleChanges.forEach(prop -> { log.info("Applying mapping changes on property {} in index {}", prop, index); }); AcknowledgedResponse response = client.indices().updateMapping(new PutMappingRequest(index).type(type).source(typeMapping)); checkState(response.isAcknowledged(), "Failed to update mapping '%s' for type '%s'", name, mapping.typeAsString()); } } catch (IOException e) { throw new IndexException(String.format("Failed to update mapping '%s' for type '%s'", name, mapping.typeAsString()), e); } } else { // create index final Map<String, Object> indexSettings; try { indexSettings = createIndexSettings(); log.info("Configuring '{}' index with settings: {}", index, indexSettings); } catch (IOException e) { throw new IndexException("Couldn't prepare settings for index " + index, e); } final CreateIndexRequest createIndexRequest = new CreateIndexRequest(index); createIndexRequest.mapping(type, typeMapping); createIndexRequest.settings(indexSettings); try { final CreateIndexResponse response = client.indices().create(createIndexRequest); checkState(response.isAcknowledged(), "Failed to create index '%s' for type '%s'", name, mapping.typeAsString()); } catch (Exception e) { throw new IndexException(String.format("Failed to create index '%s' for type '%s'", name, mapping.typeAsString()), e); } } } // wait until the cluster processes each index create request waitForYellowHealth(indices()); log.info("'{}' indexes are ready.", name); } private Map<String, Object> createIndexSettings() throws IOException { InputStream analysisStream = getClass().getResourceAsStream("analysis.json"); Settings analysisSettings = Settings.builder() .loadFromStream("analysis.json", analysisStream, true) .build(); // FIXME: Is XContent a good alternative to a Map? getAsStructureMap is now private Map<String, Object> analysisMap = ReflectionUtils.callMethod(Settings.class, analysisSettings, "getAsStructuredMap"); return ImmutableMap.<String, Object>builder() .put("analysis", analysisMap) .put("number_of_shards", String.valueOf(settings().getOrDefault(IndexClientFactory.NUMBER_OF_SHARDS, "1"))) .put("number_of_replicas", "0") // disable es refresh, we will do it manually on each commit .put("refresh_interval", "-1") // use async durability for the translog .put("translog.durability", "async") // wait all shards during writes .put("write.wait_for_active_shards", "all") .put(IndexClientFactory.RESULT_WINDOW_KEY, settings().get(IndexClientFactory.RESULT_WINDOW_KEY)) .put(IndexClientFactory.MAX_TERMS_COUNT_KEY, settings().get(IndexClientFactory.MAX_TERMS_COUNT_KEY)) .put(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, settings().get(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY)) .build(); } private void waitForYellowHealth(String... indices) { if (!CompareUtils.isEmpty(indices)) { /* * See https://www.elastic.co/guide/en/elasticsearch/reference/6.3/cluster-health.html * for the low-level structure of the cluster health request. */ final Object clusterTimeoutSetting = settings.getOrDefault(IndexClientFactory.CLUSTER_HEALTH_TIMEOUT, IndexClientFactory.DEFAULT_CLUSTER_HEALTH_TIMEOUT); final Object socketTimeoutSetting = settings.getOrDefault(IndexClientFactory.SOCKET_TIMEOUT, IndexClientFactory.DEFAULT_SOCKET_TIMEOUT); final int clusterTimeout = clusterTimeoutSetting instanceof Integer ? (int) clusterTimeoutSetting : Integer.parseInt((String) clusterTimeoutSetting); final int socketTimeout = socketTimeoutSetting instanceof Integer ? (int) socketTimeoutSetting : Integer.parseInt((String) socketTimeoutSetting); final int pollTimeout = socketTimeout / 2; final ClusterHealthRequest req = new ClusterHealthRequest(indices) .waitForYellowStatus() // Wait until yellow status is reached .timeout(String.format("%sms", pollTimeout)); // Poll interval is half the socket timeout req.level(Level.INDICES); // Detail level should be concerned with the indices in the path final long startTime = System.currentTimeMillis(); final long endTime = startTime + clusterTimeout; // Polling finishes when the cluster timeout is reached long currentTime = startTime; ClusterHealthResponse response = null; do { try { response = client().cluster().health(req); currentTime = System.currentTimeMillis(); if (response != null && !response.isTimedOut()) { break; } } catch (Exception e) { throw new IndexException("Couldn't retrieve cluster health for index " + name, e); } } while (currentTime < endTime); if (response == null || response.isTimedOut()) { throw new IndexException(String.format("Cluster health did not reach yellow status for '%s' indexes after %s ms.", name, currentTime - startTime), null); } else { log.info("Cluster health for '{}' indexes reported as '{}' after {} ms.", name, response.getStatus(), currentTime - startTime); } } } private Map<String, Object> toProperties(DocumentMapping mapping) { Map<String, Object> properties = newHashMap(); for (Field field : mapping.getFields()) { // skip transient fields if (Modifier.isTransient(field.getModifiers())) { continue; } final String property = field.getName(); if (DocumentMapping._ID.equals(property)) continue; final Class<?> fieldType = NumericClassUtils.unwrapCollectionType(field); if (Map.class.isAssignableFrom(fieldType)) { // allow dynamic mappings for dynamic objects like field using Map final Map<String, Object> prop = newHashMap(); prop.put("type", "object"); prop.put("dynamic", "true"); properties.put(property, prop); continue; } else if (fieldType.isAnnotationPresent(Doc.class)) { Doc annotation = fieldType.getAnnotation(Doc.class); // this is a nested document type create a nested mapping final Map<String, Object> prop = newHashMap(); // XXX type: object is the default for nested objects, ES won't store it in the mapping and will default to object even if explicitly set, which would cause unnecessary mapping update during boot if (annotation.nested()) { prop.put("type", "nested"); } // XXX enabled: true is the default, ES won't store it in the mapping and will default to true even if explicitly set, which would cause unnecessary mapping update during boot if (!annotation.index()) { prop.put("enabled", false); } prop.putAll(toProperties(new DocumentMapping(fieldType))); properties.put(property, prop); } else { final Map<String, Object> prop = newHashMap(); if (!mapping.isText(property) && !mapping.isKeyword(property)) { addFieldProperties(prop, fieldType); properties.put(property, prop); } else { checkState(String.class.isAssignableFrom(fieldType), "Only String fields can have Text and Keyword annotation. Found them on '%s'", property); final Map<String, Text> textFields = mapping.getTextFields(property); final Map<String, Keyword> keywordFields = mapping.getKeywordFields(property); final Text textMapping = textFields.get(property); final Keyword keywordMapping = keywordFields.get(property); checkState(textMapping == null || keywordMapping == null, "Cannot declare both Text and Keyword annotation on same field '%s'", property); if (textMapping != null) { prop.put("type", "text"); prop.put("analyzer", textMapping.analyzer().getAnalyzer()); if (textMapping.searchAnalyzer() != Analyzers.INDEX) { prop.put("search_analyzer", textMapping.searchAnalyzer().getAnalyzer()); } } if (keywordMapping != null) { prop.put("type", "keyword"); String normalizer = keywordMapping.normalizer().getNormalizer(); if (!Strings.isNullOrEmpty(normalizer)) { prop.put("normalizer", normalizer); } // XXX index: true is the default, ES won't store it in the mapping and will default to true even if explicitly set, which would cause unnecessary mapping update during boot if (!keywordMapping.index()) { prop.put("index", false); } prop.put("doc_values", keywordMapping.index()); } // put extra text fields into fields object final Map<String, Object> fields = newHashMapWithExpectedSize(textFields.size() + keywordFields.size()); for (Entry<String, Text> analyzer : textFields.entrySet()) { final String extraField = analyzer.getKey(); final String[] extraFieldParts = extraField.split(Pattern.quote(DocumentMapping.DELIMITER)); if (extraFieldParts.length > 1) { final Text analyzed = analyzer.getValue(); final Map<String, Object> fieldProps = newHashMap(); fieldProps.put("type", "text"); fieldProps.put("analyzer", analyzed.analyzer().getAnalyzer()); if (analyzed.searchAnalyzer() != Analyzers.INDEX) { fieldProps.put("search_analyzer", analyzed.searchAnalyzer().getAnalyzer()); } fields.put(extraFieldParts[1], fieldProps); } } // put extra keyword fields into fields object for (Entry<String, Keyword> analyzer : keywordFields.entrySet()) { final String extraField = analyzer.getKey(); final String[] extraFieldParts = extraField.split(Pattern.quote(DocumentMapping.DELIMITER)); if (extraFieldParts.length > 1) { final Keyword analyzed = analyzer.getValue(); final Map<String, Object> fieldProps = newHashMap(); fieldProps.put("type", "keyword"); String normalizer = analyzed.normalizer().getNormalizer(); if (!Strings.isNullOrEmpty(normalizer)) { fieldProps.put("normalizer", normalizer); } if (!analyzed.index()) { fieldProps.put("index", false); } fields.put(extraFieldParts[1], fieldProps); } } if (!fields.isEmpty()) { prop.put("fields", fields); } properties.put(property, prop); } } } return ImmutableMap.of("properties", properties); } private void addFieldProperties(Map<String, Object> fieldProperties, Class<?> fieldType) { if (Enum.class.isAssignableFrom(fieldType) || NumericClassUtils.isBigDecimal(fieldType) || String.class.isAssignableFrom(fieldType)) { fieldProperties.put("type", "keyword"); } else if (NumericClassUtils.isFloat(fieldType)) { fieldProperties.put("type", "float"); } else if (NumericClassUtils.isInt(fieldType)) { fieldProperties.put("type", "integer"); } else if (NumericClassUtils.isShort(fieldType)) { fieldProperties.put("type", "short"); } else if (NumericClassUtils.isDate(fieldType) || NumericClassUtils.isLong(fieldType)) { fieldProperties.put("type", "long"); } else if (Boolean.class.isAssignableFrom(Primitives.wrap(fieldType))) { fieldProperties.put("type", "boolean"); } else if (fieldType.isAnnotationPresent(IP.class)) { fieldProperties.put("type", "ip"); } else if (hasJsonValue(fieldType)) { fieldProperties.put("type", "keyword"); // FIXME for now consider only String based @JsonValue annotations } else { // Any other type will result in a sub-object that only appears in _source fieldProperties.put("type", "object"); fieldProperties.put("enabled", false); } } // returns true if one of the methods of the type has the @JsonValue annotation private boolean hasJsonValue(Class<?> fieldType) { for (Method method : fieldType.getMethods()) { if (method.isAnnotationPresent(JsonValue.class) && String.class == method.getReturnType()) { return true; } } return false; } @Override public void delete() { if (exists()) { final DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(name + "*"); try { final AcknowledgedResponse deleteIndexResponse = client() .indices() .delete(deleteIndexRequest); checkState(deleteIndexResponse.isAcknowledged(), "Failed to delete all ES indices for '%s'.", name); } catch (Exception e) { throw new IndexException(String.format("Failed to delete all ES indices for '%s'.", name), e); } } } @Override public void clear(Collection<Class<?>> types) { if (CompareUtils.isEmpty(types)) { return; } final Set<DocumentMapping> typesToRefresh = Collections.synchronizedSet(newHashSetWithExpectedSize(types.size())); for (Class<?> type : types) { bulkDelete(new BulkDelete<>(type, Expressions.matchAll()), typesToRefresh); } refresh(typesToRefresh); } @Override public Map<String, Object> settings() { return settings; } @Override public void updateSettings(Map<String, Object> newSettings) { if (CompareUtils.isEmpty(newSettings)) { return; } final Set<String> unsupportedDynamicSettings = Sets.difference(newSettings.keySet(), DYNAMIC_SETTINGS); if (!unsupportedDynamicSettings.isEmpty()) { throw new IndexException(String.format("Settings [%s] are not dynamically updateable settings.", unsupportedDynamicSettings), null); } boolean shouldUpdate = false; for (String settingKey : newSettings.keySet()) { Object currentValue = settings.get(settingKey); Object newValue = newSettings.get(settingKey); if (!Objects.equals(currentValue, newValue)) { shouldUpdate = true; } } if (!shouldUpdate) { return; } for (DocumentMapping mapping : mappings.getMappings()) { final String index = getTypeIndex(mapping); // if any index exists, then update the settings based on the new settings if (exists(mapping)) { try { log.info("Applying settings '{}' changes in index {}...", newSettings, index); AcknowledgedResponse response = client.indices().updateSettings(new UpdateSettingsRequest().indices(index).settings(newSettings)); checkState(response.isAcknowledged(), "Failed to update index settings '%s'.", index); } catch (IOException e) { throw new IndexException(String.format("Couldn't update settings of index '%s'", index), e); } } } settings.putAll(newSettings); } @Override public Mappings mappings() { return mappings; } @Override public void updateMappings(Mappings mappings) { this.mappings = mappings; } @Override public String name() { return name; } @Override public void close() {} @Override public void optimize(int maxSegments) { // client().admin().indices().prepareForceMerge(name).setMaxNumSegments(maxSegments).get(); // waitForYellowHealth(); } @Override public String getTypeIndex(DocumentMapping mapping) { if (mapping.getParent() != null) { return String.format("%s%s-%s", prefix, name, mapping.getParent().typeAsString()); } else { return String.format("%s%s-%s", prefix, name, mapping.typeAsString()); } } @Override public EsClient client() { return client; } public void refresh(Set<DocumentMapping> typesToRefresh) { if (!CompareUtils.isEmpty(typesToRefresh)) { final String[] indicesToRefresh; synchronized (typesToRefresh) { indicesToRefresh = typesToRefresh.stream() .map(this::getTypeIndex) .distinct() .toArray(String[]::new); } if (log.isTraceEnabled()) { log.trace("Refreshing indexes '{}'", Arrays.toString(indicesToRefresh)); } try { final RefreshRequest refreshRequest = new RefreshRequest(indicesToRefresh); final RefreshResponse refreshResponse = client() .indices() .refresh(refreshRequest); if (RestStatus.OK != refreshResponse.getStatus() && log.isErrorEnabled()) { log.error("Index refresh request of '{}' returned with status {}", Arrays.toString(indicesToRefresh), refreshResponse.getStatus()); } } catch (Exception e) { throw new IndexException(String.format("Failed to refresh ES indexes '%s'.", Arrays.toString(indicesToRefresh)), e); } } } public void bulkUpdate(final BulkUpdate<?> update, Set<DocumentMapping> mappingsToRefresh) { final DocumentMapping mapping = mappings().getMapping(update.getType()); final String rawScript = mapping.getScript(update.getScript()).script(); org.elasticsearch.script.Script script = new org.elasticsearch.script.Script(ScriptType.INLINE, "painless", rawScript, ImmutableMap.copyOf(update.getParams())); bulkIndexByScroll(client, update, "update", script, mappingsToRefresh); } public void bulkDelete(final BulkDelete<?> delete, Set<DocumentMapping> mappingsToRefresh) { bulkIndexByScroll(client, delete, "delete", null, mappingsToRefresh); } private void bulkIndexByScroll(final EsClient client, final BulkOperation<?> op, final String command, final org.elasticsearch.script.Script script, final Set<DocumentMapping> mappingsToRefresh) { final DocumentMapping mapping = mappings().getMapping(op.getType()); final QueryBuilder query = new EsQueryBuilder(mapping, settings).build(op.getFilter()); long versionConflicts = 0; int attempts = DEFAULT_MAX_NUMBER_OF_VERSION_CONFLICT_RETRIES; do { try { final BulkByScrollResponse response; if ("update".equals(command)) { response = client.updateByQuery(getTypeIndex(mapping), (int) settings.get(IndexClientFactory.BULK_ACTIONS_SIZE), script, getConcurrencyLevel(), query); } else if ("delete".equals(command)) { response = client.deleteByQuery(getTypeIndex(mapping), (int) settings.get(IndexClientFactory.BULK_ACTIONS_SIZE), getConcurrencyLevel(), query); } else { throw new UnsupportedOperationException("Not implemented command: " + command); } final long updateCount = response.getUpdated(); final long deleteCount = response.getDeleted(); final long noops = response.getNoops(); final List<Failure> failures = response.getBulkFailures(); versionConflicts = response.getVersionConflicts(); boolean updated = updateCount > 0; if (updated) { mappingsToRefresh.add(mapping); log().info("Updated {} {} documents with bulk {}", updateCount, mapping.typeAsString(), op); } boolean deleted = deleteCount > 0; if (deleted) { mappingsToRefresh.add(mapping); log().info("Deleted {} {} documents with bulk {}", deleteCount, mapping.typeAsString(), op); } if (!updated && !deleted) { log().warn("Bulk {} could not be applied to {} documents, no-ops ({}), conflicts ({})", op, mapping.typeAsString(), noops, versionConflicts); } if (failures.size() > 0) { boolean versionConflictsOnly = true; for (Failure failure : failures) { final String failureMessage = failure.getCause().getMessage(); final int failureStatus = failure.getStatus().getStatus(); if (failureStatus != RestStatus.CONFLICT.getStatus()) { versionConflictsOnly = false; log().error("Index failure during bulk update: {}", failureMessage); } else { log().warn("Version conflict reason: {}", failureMessage); } } if (!versionConflictsOnly) { throw new IllegalStateException("There were indexing failures during bulk updates. See logs for all failures."); } } if (attempts <= 0) { throw new IndexException("There were indexing failures during bulk updates. See logs for all failures.", null); } if (versionConflicts > 0) { --attempts; try { Thread.sleep(100 + random.nextInt(900)); refresh(Collections.singleton(mapping)); } catch (InterruptedException e) { throw new IndexException("Interrupted", e); } } } catch (IOException e) { throw new IndexException("Could not execute bulk update.", e); } } while (versionConflicts > 0); } public int getConcurrencyLevel() { return (int) settings().get(IndexClientFactory.COMMIT_CONCURRENCY_LEVEL); } }
commons/com.b2international.index/src/com/b2international/index/es/admin/EsIndexAdmin.java
/* * Copyright 2017-2020 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.index.es.admin; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Maps.newHashMapWithExpectedSize; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newHashSetWithExpectedSize; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.regex.Pattern; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest.Level; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest; import org.elasticsearch.action.bulk.BulkItemResponse.Failure; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.cluster.metadata.MappingMetadata; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.reindex.BulkByScrollResponse; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.script.ScriptType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.b2international.commons.ClassUtils; import com.b2international.commons.CompareUtils; import com.b2international.commons.ReflectionUtils; import com.b2international.index.*; import com.b2international.index.admin.IndexAdmin; import com.b2international.index.es.client.EsClient; import com.b2international.index.es.query.EsQueryBuilder; import com.b2international.index.mapping.DocumentMapping; import com.b2international.index.mapping.Mappings; import com.b2international.index.query.Expressions; import com.b2international.index.util.NumericClassUtils; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.flipkart.zjsonpatch.DiffFlags; import com.flipkart.zjsonpatch.JsonDiff; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.common.primitives.Primitives; /** * @since 5.10 */ public final class EsIndexAdmin implements IndexAdmin { private static final Set<String> DYNAMIC_SETTINGS = Set.of(IndexClientFactory.RESULT_WINDOW_KEY); /** * Important DIFF flags required to produce the JSON patch needed for proper compare and branch merge operation behavior, for proper index schema migration, and so on. * Should be used by default when using jsonpatch. */ public static final EnumSet<DiffFlags> DIFF_FLAGS = EnumSet.of(DiffFlags.ADD_ORIGINAL_VALUE_ON_REPLACE, DiffFlags.OMIT_COPY_OPERATION, DiffFlags.OMIT_MOVE_OPERATION); private static final int DEFAULT_MAX_NUMBER_OF_VERSION_CONFLICT_RETRIES = 5; private final Random random = new Random(); private final EsClient client; private final ObjectMapper mapper; private final String name; private final Map<String, Object> settings; private Mappings mappings; private final Logger log; private final String prefix; public EsIndexAdmin(EsClient client, ObjectMapper mapper, String name, Mappings mappings, Map<String, Object> settings) { this.client = client; this.mapper = mapper; this.name = name.toLowerCase(); this.mappings = mappings; this.settings = newHashMap(settings); this.log = LoggerFactory.getLogger(String.format("index.%s", this.name)); this.settings.putIfAbsent(IndexClientFactory.COMMIT_CONCURRENCY_LEVEL, IndexClientFactory.DEFAULT_COMMIT_CONCURRENCY_LEVEL); this.settings.putIfAbsent(IndexClientFactory.RESULT_WINDOW_KEY, ""+IndexClientFactory.DEFAULT_RESULT_WINDOW); this.settings.putIfAbsent(IndexClientFactory.MAX_TERMS_COUNT_KEY, ""+IndexClientFactory.DEFAULT_MAX_TERMS_COUNT); this.settings.putIfAbsent(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, IndexClientFactory.DEFAULT_TRANSLOG_SYNC_INTERVAL); this.settings.putIfAbsent(IndexClientFactory.BULK_ACTIONS_SIZE, IndexClientFactory.DEFAULT_BULK_ACTIONS_SIZE); this.settings.putIfAbsent(IndexClientFactory.BULK_ACTIONS_SIZE_IN_MB, IndexClientFactory.DEFAULT_BULK_ACTIONS_SIZE_IN_MB); final String prefix = (String) settings.getOrDefault(IndexClientFactory.INDEX_PREFIX, IndexClientFactory.DEFAULT_INDEX_PREFIX); this.prefix = prefix.isEmpty() ? "" : prefix + "."; } @Override public Logger log() { return log; } @Override public boolean exists() { try { return client().indices().exists(indices()); } catch (Exception e) { throw new IndexException("Couldn't check the existence of all ES indices.", e); } } private boolean exists(DocumentMapping mapping) { final String index = getTypeIndex(mapping); try { return client().indices().exists(index); } catch (Exception e) { throw new IndexException("Couldn't check the existence of ES index '" + index + "'.", e); } } @Override public void create() { log.info("Preparing '{}' indexes...", name); // create number of indexes based on number of types for (DocumentMapping mapping : mappings.getMappings()) { final String index = getTypeIndex(mapping); final String type = mapping.typeAsString(); final Map<String, Object> typeMapping = ImmutableMap.<String, Object>builder() .put("date_detection", false) .put("numeric_detection", false) .putAll(toProperties(mapping)) .build(); if (exists(mapping)) { // update mapping if required ImmutableOpenMap<String, MappingMetadata> currentIndexMapping; try { currentIndexMapping = client.indices().getMapping(new GetMappingsRequest().types(type).indices(index)).mappings().get(index); } catch (Exception e) { throw new IndexException(String.format("Failed to get mapping of '%s' for type '%s'", name, mapping.typeAsString()), e); } try { final ObjectNode newTypeMapping = mapper.valueToTree(typeMapping); final ObjectNode currentTypeMapping = mapper.valueToTree(currentIndexMapping.get(type).getSourceAsMap()); final JsonNode diff = JsonDiff.asJson(currentTypeMapping, newTypeMapping, DIFF_FLAGS); final ArrayNode diffNode = ClassUtils.checkAndCast(diff, ArrayNode.class); Set<String> compatibleChanges = newHashSet(); Set<String> uncompatibleChanges = newHashSet(); for (ObjectNode change : Iterables.filter(diffNode, ObjectNode.class)) { String prop = change.get("path").asText().substring(1); switch (change.get("op").asText()) { case "add": compatibleChanges.add(prop); break; case "move": case "replace": uncompatibleChanges.add(prop); break; default: break; } } if (!uncompatibleChanges.isEmpty()) { log.warn("Cannot migrate index '{}' to new mapping with breaking changes on properties '{}'. Run repository reindex to migrate to new mapping schema or drop that index manually using the Elasticsearch API.", index, uncompatibleChanges); } else if (!compatibleChanges.isEmpty()) { compatibleChanges.forEach(prop -> { log.info("Applying mapping changes on property {} in index {}", prop, index); }); AcknowledgedResponse response = client.indices().updateMapping(new PutMappingRequest(index).type(type).source(typeMapping)); checkState(response.isAcknowledged(), "Failed to update mapping '%s' for type '%s'", name, mapping.typeAsString()); } } catch (IOException e) { throw new IndexException(String.format("Failed to update mapping '%s' for type '%s'", name, mapping.typeAsString()), e); } } else { // create index final Map<String, Object> indexSettings; try { indexSettings = createIndexSettings(); log.info("Configuring '{}' index with settings: {}", index, indexSettings); } catch (IOException e) { throw new IndexException("Couldn't prepare settings for index " + index, e); } final CreateIndexRequest createIndexRequest = new CreateIndexRequest(index); createIndexRequest.mapping(type, typeMapping); createIndexRequest.settings(indexSettings); try { final CreateIndexResponse response = client.indices().create(createIndexRequest); checkState(response.isAcknowledged(), "Failed to create index '%s' for type '%s'", name, mapping.typeAsString()); } catch (Exception e) { throw new IndexException(String.format("Failed to create index '%s' for type '%s'", name, mapping.typeAsString()), e); } } } // wait until the cluster processes each index create request waitForYellowHealth(indices()); log.info("'{}' indexes are ready.", name); } private Map<String, Object> createIndexSettings() throws IOException { InputStream analysisStream = getClass().getResourceAsStream("analysis.json"); Settings analysisSettings = Settings.builder() .loadFromStream("analysis.json", analysisStream, true) .build(); // FIXME: Is XContent a good alternative to a Map? getAsStructureMap is now private Map<String, Object> analysisMap = ReflectionUtils.callMethod(Settings.class, analysisSettings, "getAsStructuredMap"); return ImmutableMap.<String, Object>builder() .put("analysis", analysisMap) .put("number_of_shards", String.valueOf(settings().getOrDefault(IndexClientFactory.NUMBER_OF_SHARDS, "1"))) .put("number_of_replicas", "0") // disable es refresh, we will do it manually on each commit .put("refresh_interval", "-1") // use async durability for the translog .put("translog.durability", "async") // wait all shards during writes .put("write.wait_for_active_shards", "all") .put(IndexClientFactory.RESULT_WINDOW_KEY, settings().get(IndexClientFactory.RESULT_WINDOW_KEY)) .put(IndexClientFactory.MAX_TERMS_COUNT_KEY, settings().get(IndexClientFactory.MAX_TERMS_COUNT_KEY)) .put(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, settings().get(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY)) .build(); } private void waitForYellowHealth(String... indices) { if (!CompareUtils.isEmpty(indices)) { /* * See https://www.elastic.co/guide/en/elasticsearch/reference/6.3/cluster-health.html * for the low-level structure of the cluster health request. */ final Object clusterTimeoutSetting = settings.getOrDefault(IndexClientFactory.CLUSTER_HEALTH_TIMEOUT, IndexClientFactory.DEFAULT_CLUSTER_HEALTH_TIMEOUT); final Object socketTimeoutSetting = settings.getOrDefault(IndexClientFactory.SOCKET_TIMEOUT, IndexClientFactory.DEFAULT_SOCKET_TIMEOUT); final int clusterTimeout = clusterTimeoutSetting instanceof Integer ? (int) clusterTimeoutSetting : Integer.parseInt((String) clusterTimeoutSetting); final int socketTimeout = socketTimeoutSetting instanceof Integer ? (int) socketTimeoutSetting : Integer.parseInt((String) socketTimeoutSetting); final int pollTimeout = socketTimeout / 2; final ClusterHealthRequest req = new ClusterHealthRequest(indices) .waitForYellowStatus() // Wait until yellow status is reached .timeout(String.format("%sms", pollTimeout)); // Poll interval is half the socket timeout req.level(Level.INDICES); // Detail level should be concerned with the indices in the path final long startTime = System.currentTimeMillis(); final long endTime = startTime + clusterTimeout; // Polling finishes when the cluster timeout is reached long currentTime = startTime; ClusterHealthResponse response = null; do { try { response = client().cluster().health(req); currentTime = System.currentTimeMillis(); if (response != null && !response.isTimedOut()) { break; } } catch (Exception e) { throw new IndexException("Couldn't retrieve cluster health for index " + name, e); } } while (currentTime < endTime); if (response == null || response.isTimedOut()) { throw new IndexException(String.format("Cluster health did not reach yellow status for '%s' indexes after %s ms.", name, currentTime - startTime), null); } else { log.info("Cluster health for '{}' indexes reported as '{}' after {} ms.", name, response.getStatus(), currentTime - startTime); } } } private Map<String, Object> toProperties(DocumentMapping mapping) { Map<String, Object> properties = newHashMap(); for (Field field : mapping.getFields()) { // skip transient fields if (Modifier.isTransient(field.getModifiers())) { continue; } final String property = field.getName(); if (DocumentMapping._ID.equals(property)) continue; final Class<?> fieldType = NumericClassUtils.unwrapCollectionType(field); if (Map.class.isAssignableFrom(fieldType)) { // allow dynamic mappings for dynamic objects like field using Map final Map<String, Object> prop = newHashMap(); prop.put("type", "object"); prop.put("dynamic", "true"); properties.put(property, prop); continue; } else if (fieldType.isAnnotationPresent(Doc.class)) { Doc annotation = fieldType.getAnnotation(Doc.class); // this is a nested document type create a nested mapping final Map<String, Object> prop = newHashMap(); // XXX type: object is the default for nested objects, ES won't store it in the mapping and will default to object even if explicitly set, which would cause unnecessary mapping update during boot if (annotation.nested()) { prop.put("type", "nested"); } // XXX enabled: true is the default, ES won't store it in the mapping and will default to true even if explicitly set, which would cause unnecessary mapping update during boot if (!annotation.index()) { prop.put("enabled", false); } prop.putAll(toProperties(new DocumentMapping(fieldType))); properties.put(property, prop); } else { final Map<String, Object> prop = newHashMap(); if (!mapping.isText(property) && !mapping.isKeyword(property)) { addFieldProperties(prop, fieldType); properties.put(property, prop); } else { checkState(String.class.isAssignableFrom(fieldType), "Only String fields can have Text and Keyword annotation. Found them on '%s'", property); final Map<String, Text> textFields = mapping.getTextFields(property); final Map<String, Keyword> keywordFields = mapping.getKeywordFields(property); final Text textMapping = textFields.get(property); final Keyword keywordMapping = keywordFields.get(property); checkState(textMapping == null || keywordMapping == null, "Cannot declare both Text and Keyword annotation on same field '%s'", property); if (textMapping != null) { prop.put("type", "text"); prop.put("analyzer", textMapping.analyzer().getAnalyzer()); if (textMapping.searchAnalyzer() != Analyzers.INDEX) { prop.put("search_analyzer", textMapping.searchAnalyzer().getAnalyzer()); } } if (keywordMapping != null) { prop.put("type", "keyword"); String normalizer = keywordMapping.normalizer().getNormalizer(); if (!Strings.isNullOrEmpty(normalizer)) { prop.put("normalizer", normalizer); } // XXX index: true is the default, ES won't store it in the mapping and will default to true even if explicitly set, which would cause unnecessary mapping update during boot if (!keywordMapping.index()) { prop.put("index", false); } prop.put("doc_values", keywordMapping.index()); } // put extra text fields into fields object final Map<String, Object> fields = newHashMapWithExpectedSize(textFields.size() + keywordFields.size()); for (Entry<String, Text> analyzer : textFields.entrySet()) { final String extraField = analyzer.getKey(); final String[] extraFieldParts = extraField.split(Pattern.quote(DocumentMapping.DELIMITER)); if (extraFieldParts.length > 1) { final Text analyzed = analyzer.getValue(); final Map<String, Object> fieldProps = newHashMap(); fieldProps.put("type", "text"); fieldProps.put("analyzer", analyzed.analyzer().getAnalyzer()); if (analyzed.searchAnalyzer() != Analyzers.INDEX) { fieldProps.put("search_analyzer", analyzed.searchAnalyzer().getAnalyzer()); } fields.put(extraFieldParts[1], fieldProps); } } // put extra keyword fields into fields object for (Entry<String, Keyword> analyzer : keywordFields.entrySet()) { final String extraField = analyzer.getKey(); final String[] extraFieldParts = extraField.split(Pattern.quote(DocumentMapping.DELIMITER)); if (extraFieldParts.length > 1) { final Keyword analyzed = analyzer.getValue(); final Map<String, Object> fieldProps = newHashMap(); fieldProps.put("type", "keyword"); String normalizer = analyzed.normalizer().getNormalizer(); if (!Strings.isNullOrEmpty(normalizer)) { fieldProps.put("normalizer", normalizer); } if (!analyzed.index()) { fieldProps.put("index", false); } fields.put(extraFieldParts[1], fieldProps); } } if (!fields.isEmpty()) { prop.put("fields", fields); } properties.put(property, prop); } } } return ImmutableMap.of("properties", properties); } private void addFieldProperties(Map<String, Object> fieldProperties, Class<?> fieldType) { if (Enum.class.isAssignableFrom(fieldType) || NumericClassUtils.isBigDecimal(fieldType) || String.class.isAssignableFrom(fieldType)) { fieldProperties.put("type", "keyword"); } else if (NumericClassUtils.isFloat(fieldType)) { fieldProperties.put("type", "float"); } else if (NumericClassUtils.isInt(fieldType)) { fieldProperties.put("type", "integer"); } else if (NumericClassUtils.isShort(fieldType)) { fieldProperties.put("type", "short"); } else if (NumericClassUtils.isDate(fieldType) || NumericClassUtils.isLong(fieldType)) { fieldProperties.put("type", "long"); } else if (Boolean.class.isAssignableFrom(Primitives.wrap(fieldType))) { fieldProperties.put("type", "boolean"); } else if (fieldType.isAnnotationPresent(IP.class)) { fieldProperties.put("type", "ip"); } else if (hasJsonValue(fieldType)) { fieldProperties.put("type", "keyword"); // FIXME for now consider only String based @JsonValue annotations } else { // Any other type will result in a sub-object that only appears in _source fieldProperties.put("type", "object"); fieldProperties.put("enabled", false); } } // returns true if one of the methods of the type has the @JsonValue annotation private boolean hasJsonValue(Class<?> fieldType) { for (Method method : fieldType.getMethods()) { if (method.isAnnotationPresent(JsonValue.class) && String.class == method.getReturnType()) { return true; } } return false; } @Override public void delete() { if (exists()) { final DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(name + "*"); try { final AcknowledgedResponse deleteIndexResponse = client() .indices() .delete(deleteIndexRequest); checkState(deleteIndexResponse.isAcknowledged(), "Failed to delete all ES indices for '%s'.", name); } catch (Exception e) { throw new IndexException(String.format("Failed to delete all ES indices for '%s'.", name), e); } } } @Override public void clear(Collection<Class<?>> types) { if (CompareUtils.isEmpty(types)) { return; } final Set<DocumentMapping> typesToRefresh = Collections.synchronizedSet(newHashSetWithExpectedSize(types.size())); for (Class<?> type : types) { bulkDelete(new BulkDelete<>(type, Expressions.matchAll()), typesToRefresh); } refresh(typesToRefresh); } @Override public Map<String, Object> settings() { return settings; } @Override public void updateSettings(Map<String, Object> newSettings) { if (CompareUtils.isEmpty(newSettings)) { return; } final Set<String> unsupportedDynamicSettings = Sets.difference(newSettings.keySet(), DYNAMIC_SETTINGS); if (!unsupportedDynamicSettings.isEmpty()) { throw new IndexException(String.format("Settings [%s] are not dynamically updateable settings.", unsupportedDynamicSettings), null); } for (DocumentMapping mapping : mappings.getMappings()) { final String index = getTypeIndex(mapping); // if any index exists, then update the settings based on the new settings if (exists(mapping)) { try { AcknowledgedResponse response = client.indices().updateSettings(new UpdateSettingsRequest().indices(index).settings(newSettings)); checkState(response.isAcknowledged(), "Failed to update index settings '%s'.", index); } catch (IOException e) { throw new IndexException(String.format("Couldn't update settings of index '%s'", index), e); } } } settings.putAll(newSettings); } @Override public Mappings mappings() { return mappings; } @Override public void updateMappings(Mappings mappings) { this.mappings = mappings; } @Override public String name() { return name; } @Override public void close() {} @Override public void optimize(int maxSegments) { // client().admin().indices().prepareForceMerge(name).setMaxNumSegments(maxSegments).get(); // waitForYellowHealth(); } @Override public String getTypeIndex(DocumentMapping mapping) { if (mapping.getParent() != null) { return String.format("%s%s-%s", prefix, name, mapping.getParent().typeAsString()); } else { return String.format("%s%s-%s", prefix, name, mapping.typeAsString()); } } @Override public EsClient client() { return client; } public void refresh(Set<DocumentMapping> typesToRefresh) { if (!CompareUtils.isEmpty(typesToRefresh)) { final String[] indicesToRefresh; synchronized (typesToRefresh) { indicesToRefresh = typesToRefresh.stream() .map(this::getTypeIndex) .distinct() .toArray(String[]::new); } if (log.isTraceEnabled()) { log.trace("Refreshing indexes '{}'", Arrays.toString(indicesToRefresh)); } try { final RefreshRequest refreshRequest = new RefreshRequest(indicesToRefresh); final RefreshResponse refreshResponse = client() .indices() .refresh(refreshRequest); if (RestStatus.OK != refreshResponse.getStatus() && log.isErrorEnabled()) { log.error("Index refresh request of '{}' returned with status {}", Arrays.toString(indicesToRefresh), refreshResponse.getStatus()); } } catch (Exception e) { throw new IndexException(String.format("Failed to refresh ES indexes '%s'.", Arrays.toString(indicesToRefresh)), e); } } } public void bulkUpdate(final BulkUpdate<?> update, Set<DocumentMapping> mappingsToRefresh) { final DocumentMapping mapping = mappings().getMapping(update.getType()); final String rawScript = mapping.getScript(update.getScript()).script(); org.elasticsearch.script.Script script = new org.elasticsearch.script.Script(ScriptType.INLINE, "painless", rawScript, ImmutableMap.copyOf(update.getParams())); bulkIndexByScroll(client, update, "update", script, mappingsToRefresh); } public void bulkDelete(final BulkDelete<?> delete, Set<DocumentMapping> mappingsToRefresh) { bulkIndexByScroll(client, delete, "delete", null, mappingsToRefresh); } private void bulkIndexByScroll(final EsClient client, final BulkOperation<?> op, final String command, final org.elasticsearch.script.Script script, final Set<DocumentMapping> mappingsToRefresh) { final DocumentMapping mapping = mappings().getMapping(op.getType()); final QueryBuilder query = new EsQueryBuilder(mapping, settings).build(op.getFilter()); long versionConflicts = 0; int attempts = DEFAULT_MAX_NUMBER_OF_VERSION_CONFLICT_RETRIES; do { try { final BulkByScrollResponse response; if ("update".equals(command)) { response = client.updateByQuery(getTypeIndex(mapping), (int) settings.get(IndexClientFactory.BULK_ACTIONS_SIZE), script, getConcurrencyLevel(), query); } else if ("delete".equals(command)) { response = client.deleteByQuery(getTypeIndex(mapping), (int) settings.get(IndexClientFactory.BULK_ACTIONS_SIZE), getConcurrencyLevel(), query); } else { throw new UnsupportedOperationException("Not implemented command: " + command); } final long updateCount = response.getUpdated(); final long deleteCount = response.getDeleted(); final long noops = response.getNoops(); final List<Failure> failures = response.getBulkFailures(); versionConflicts = response.getVersionConflicts(); boolean updated = updateCount > 0; if (updated) { mappingsToRefresh.add(mapping); log().info("Updated {} {} documents with bulk {}", updateCount, mapping.typeAsString(), op); } boolean deleted = deleteCount > 0; if (deleted) { mappingsToRefresh.add(mapping); log().info("Deleted {} {} documents with bulk {}", deleteCount, mapping.typeAsString(), op); } if (!updated && !deleted) { log().warn("Bulk {} could not be applied to {} documents, no-ops ({}), conflicts ({})", op, mapping.typeAsString(), noops, versionConflicts); } if (failures.size() > 0) { boolean versionConflictsOnly = true; for (Failure failure : failures) { final String failureMessage = failure.getCause().getMessage(); final int failureStatus = failure.getStatus().getStatus(); if (failureStatus != RestStatus.CONFLICT.getStatus()) { versionConflictsOnly = false; log().error("Index failure during bulk update: {}", failureMessage); } else { log().warn("Version conflict reason: {}", failureMessage); } } if (!versionConflictsOnly) { throw new IllegalStateException("There were indexing failures during bulk updates. See logs for all failures."); } } if (attempts <= 0) { throw new IndexException("There were indexing failures during bulk updates. See logs for all failures.", null); } if (versionConflicts > 0) { --attempts; try { Thread.sleep(100 + random.nextInt(900)); refresh(Collections.singleton(mapping)); } catch (InterruptedException e) { throw new IndexException("Interrupted", e); } } } catch (IOException e) { throw new IndexException("Could not execute bulk update.", e); } } while (versionConflicts > 0); } public int getConcurrencyLevel() { return (int) settings().get(IndexClientFactory.COMMIT_CONCURRENCY_LEVEL); } }
[index] update settings only when they have changed
commons/com.b2international.index/src/com/b2international/index/es/admin/EsIndexAdmin.java
[index] update settings only when they have changed
<ide><path>ommons/com.b2international.index/src/com/b2international/index/es/admin/EsIndexAdmin.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Map.Entry; <add>import java.util.Objects; <ide> import java.util.Random; <ide> import java.util.Set; <ide> import java.util.regex.Pattern; <ide> throw new IndexException(String.format("Settings [%s] are not dynamically updateable settings.", unsupportedDynamicSettings), null); <ide> } <ide> <add> boolean shouldUpdate = false; <add> for (String settingKey : newSettings.keySet()) { <add> Object currentValue = settings.get(settingKey); <add> Object newValue = newSettings.get(settingKey); <add> if (!Objects.equals(currentValue, newValue)) { <add> shouldUpdate = true; <add> } <add> } <add> <add> if (!shouldUpdate) { <add> return; <add> } <add> <ide> for (DocumentMapping mapping : mappings.getMappings()) { <ide> final String index = getTypeIndex(mapping); <ide> // if any index exists, then update the settings based on the new settings <ide> if (exists(mapping)) { <ide> try { <add> log.info("Applying settings '{}' changes in index {}...", newSettings, index); <ide> AcknowledgedResponse response = client.indices().updateSettings(new UpdateSettingsRequest().indices(index).settings(newSettings)); <ide> checkState(response.isAcknowledged(), "Failed to update index settings '%s'.", index); <ide> } catch (IOException e) {
JavaScript
mit
09a296fc0ecd928381f594991c3f237ec5a56b06
0
bolinfest/atom,bolinfest/atom,bsmr-x-script/atom,Mokolea/atom,sotayamashita/atom,sotayamashita/atom,Ingramz/atom,atom/atom,Arcanemagus/atom,Ingramz/atom,stinsonga/atom,CraZySacX/atom,ardeshirj/atom,AlexxNica/atom,Arcanemagus/atom,AdrianVovk/substance-ide,bolinfest/atom,FIT-CSE2410-A-Bombs/atom,bsmr-x-script/atom,AlexxNica/atom,AdrianVovk/substance-ide,decaffeinate-examples/atom,brettle/atom,ardeshirj/atom,kevinrenaers/atom,kevinrenaers/atom,decaffeinate-examples/atom,Mokolea/atom,tjkr/atom,liuderchi/atom,stinsonga/atom,bsmr-x-script/atom,liuderchi/atom,decaffeinate-examples/atom,xream/atom,xream/atom,tjkr/atom,me-benni/atom,CraZySacX/atom,ardeshirj/atom,andrewleverette/atom,AlexxNica/atom,stinsonga/atom,FIT-CSE2410-A-Bombs/atom,liuderchi/atom,andrewleverette/atom,xream/atom,atom/atom,rlugojr/atom,t9md/atom,decaffeinate-examples/atom,rlugojr/atom,PKRoma/atom,t9md/atom,kevinrenaers/atom,andrewleverette/atom,t9md/atom,PKRoma/atom,me-benni/atom,tjkr/atom,atom/atom,sotayamashita/atom,Arcanemagus/atom,PKRoma/atom,me-benni/atom,Mokolea/atom,liuderchi/atom,Ingramz/atom,brettle/atom,brettle/atom,CraZySacX/atom,FIT-CSE2410-A-Bombs/atom,stinsonga/atom,rlugojr/atom,AdrianVovk/substance-ide
/** @babel */ import TextBuffer, {Point, Range} from 'text-buffer' import {File, Directory} from 'pathwatcher' import {Emitter, Disposable, CompositeDisposable} from 'event-kit' import Grim from 'grim' import dedent from 'dedent' import BufferedNodeProcess from '../src/buffered-node-process' import BufferedProcess from '../src/buffered-process' import GitRepository from '../src/git-repository' import Notification from '../src/notification' const atomExport = { BufferedNodeProcess, BufferedProcess, GitRepository, Notification, TextBuffer, Point, Range, File, Directory, Emitter, Disposable, CompositeDisposable } // Shell integration is required by both Squirrel and Settings-View if (process.platform === 'win32') { Object.defineProperty(atomExport, 'WinShell', { enumerable: true, get () { return require('../src/main-process/win-shell') } }) } // The following classes can't be used from a Task handler and should therefore // only be exported when not running as a child node process if (process.type === 'renderer') { atomExport.Task = require('../src/task') const TextEditor = (params) => { return atom.workspace.buildTextEditor(params) } TextEditor.prototype = require('../src/text-editor').prototype Object.defineProperty(atomExport, 'TextEditor', { enumerable: true, get () { Grim.deprecate(dedent` The \`TextEditor\` constructor is no longer public. To construct a text editor, use \`atom.workspace.buildTextEditor()\`. To check if an object is a text editor, use \`atom.workspace.isTextEditor(object)\`. `) return TextEditor } }) } export default atomExport
exports/atom.js
/** @babel */ import TextBuffer, {Point, Range} from 'text-buffer' import {File, Directory} from 'pathwatcher' import {Emitter, Disposable, CompositeDisposable} from 'event-kit' import Grim from 'grim' import dedent from 'dedent' import BufferedNodeProcess from '../src/buffered-node-process' import BufferedProcess from '../src/buffered-process' import GitRepository from '../src/git-repository' import Notification from '../src/notification' const atomExport = { BufferedNodeProcess, BufferedProcess, GitRepository, Notification, TextBuffer, Point, Range, File, Directory, Emitter, Disposable, CompositeDisposable } // Shell integration is required by both Squirrel and Settings-View if (process.platform === 'win32') { Object.defineProperty(atomExport, 'WinShell', { enumerable: true, get () { return require('../src/main-process/win-shell') } }) } // The following classes can't be used from a Task handler and should therefore // only be exported when not running as a child node process if (!process.env.ATOM_SHELL_INTERNAL_RUN_AS_NODE) { atomExport.Task = require('../src/task') const TextEditor = (params) => { return atom.workspace.buildTextEditor(params) } TextEditor.prototype = require('../src/text-editor').prototype Object.defineProperty(atomExport, 'TextEditor', { enumerable: true, get () { Grim.deprecate(dedent` The \`TextEditor\` constructor is no longer public. To construct a text editor, use \`atom.workspace.buildTextEditor()\`. To check if an object is a text editor, use \`atom.workspace.isTextEditor(object)\`. `) return TextEditor } }) } export default atomExport
Detect headless environment using process.type Signed-off-by: Nathan Sobo <[email protected]>
exports/atom.js
Detect headless environment using process.type
<ide><path>xports/atom.js <ide> <ide> // The following classes can't be used from a Task handler and should therefore <ide> // only be exported when not running as a child node process <del>if (!process.env.ATOM_SHELL_INTERNAL_RUN_AS_NODE) { <add>if (process.type === 'renderer') { <ide> atomExport.Task = require('../src/task') <ide> <ide> const TextEditor = (params) => {
Java
apache-2.0
42a4805d93c8ca9bfbc80e58793706c92981b380
0
abhinavmishra14/alfresco-sdk,abhinavmishra14/alfresco-sdk,Alfresco/alfresco-sdk,abhinavmishra14/alfresco-sdk,Alfresco/alfresco-sdk,abhinavmishra14/alfresco-sdk,Alfresco/alfresco-sdk,Alfresco/alfresco-sdk
/** * Copyright (C) 2017 Alfresco Software Limited. * <p/> * This file is part of the Alfresco SDK project. * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.alfresco.rad.test; import org.alfresco.rad.SpringContextHolder; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Ignore; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; /** * This is a JUnit test runner that is designed to work with an Alfresco repository. * It detects if it's executing a test inside of a running Alfresco instance. If that * is the case the tests are all run normally. If however the test is being run from * outside the repository, from the maven command line or from an IDE * such as IntelliJ or STS/Eclipse for example, then instead of running the actual * test an HTTP request is made to a Web Script in a running Alfresco instance. This * Web Script runs the test and returns enough information to this class so we can * emulate having run the test locally. * <p/> * By doing this, we are able to create Integration Tests (IT) using standard JUnit * capabilities. These can then be run from our IDEs with the associated visualizations, * support for re-running failed tests, etc. * <p/> * Integration testing framework donated by Zia Consulting * * @author Bindu Wavell <[email protected]> * @author [email protected] (some editing) * @since 3.0 */ public class AlfrescoTestRunner extends BlockJUnit4ClassRunner { private static final String ACS_ENDPOINT_PROP = "acs.endpoint.path"; private static final String ACS_DEFAULT_ENDPOINT = "http://localhost:8080/alfresco"; public static final String SUCCESS = "SUCCESS"; public static final String FAILURE = "FAILURE"; public AlfrescoTestRunner(Class<?> klass) throws InitializationError { super(klass); } public static String serializableToString(Serializable serializable) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(serializable); oos.close(); String string = Base64.encodeBase64URLSafeString(baos.toByteArray()); return string; } @Override protected void runChild(FrameworkMethod method, RunNotifier notifier) { if (areWeRunningInAlfresco()) { // Just run the test as normally super.runChild(method, notifier); } else { // We are not running in an Alfresco Server, we need to call one and have it execute the test... Description desc = describeChild(method); if (method.getAnnotation(Ignore.class) != null) { notifier.fireTestIgnored(desc); } else { callProxiedChild(method, notifier, desc); } } } /** * Call a remote Alfresco server and have the test run there. * * @param method the test method to run * @param notifier * @param desc */ protected void callProxiedChild(FrameworkMethod method, RunNotifier notifier, Description desc) { notifier.fireTestStarted(desc); String className = method.getMethod().getDeclaringClass().getCanonicalName(); String methodName = method.getName(); if (null != methodName) { className += "#" + methodName; } // Login credentials for Alfresco Repo // TODO: Maybe configure credentials in props... CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin"); provider.setCredentials(AuthScope.ANY, credentials); // Create HTTP Client with credentials CloseableHttpClient httpclient = HttpClientBuilder.create() .setDefaultCredentialsProvider(provider) .build(); // Create the GET Request for the Web Script that will run the test String testWebScriptUrl = "/service/testing/test.xml?clazz=" + className.replace("#", "%23"); //System.out.println("AlfrescoTestRunner: Invoking Web Script for test execution: " + testWebScriptUrl); HttpGet get = new HttpGet(getContextRoot(method) + testWebScriptUrl); try { // Send proxied request and read response HttpResponse resp = httpclient.execute(get); InputStream is = resp.getEntity().getContent(); InputStreamReader ir = new InputStreamReader(is); BufferedReader br = new BufferedReader(ir); String body = ""; String line; while ((line = br.readLine()) != null) { body += line + "\n"; } // Process response if (body.length() > 0) { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new InputSource(new StringReader(body))); Element root = doc.getDocumentElement(); NodeList results = root.getElementsByTagName("result"); if (null != results && results.getLength() > 0) { String result = results.item(0).getFirstChild().getNodeValue(); if (SUCCESS.equals(result)) { notifier.fireTestFinished(desc); } else { boolean failureFired = false; NodeList throwableNodes = root.getElementsByTagName("throwable"); for (int tid = 0; tid < throwableNodes.getLength(); tid++) { String throwableBody = null; Object object = null; Throwable throwable = null; throwableBody = throwableNodes.item(tid).getFirstChild().getNodeValue(); if (null != throwableBody) { try { object = objectFromString(throwableBody); } catch (ClassNotFoundException e) { } if (null != object && object instanceof Throwable) { throwable = (Throwable) object; } } if (null == throwable) { throwable = new Throwable("Unable to process exception body: " + throwableBody); } notifier.fireTestFailure(new Failure(desc, throwable)); failureFired = true; } if (!failureFired) { notifier.fireTestFailure(new Failure(desc, new Throwable( "There was an error but we can't figure out what it was, sorry!"))); } } } else { notifier.fireTestFailure(new Failure(desc, new Throwable( "Unable to process response for proxied test request: " + body))); } } else { notifier.fireTestFailure(new Failure(desc, new Throwable( "Attempt to proxy test into running Alfresco instance failed, no response received"))); } } catch (IOException e) { notifier.fireTestFailure(new Failure(desc, e)); } catch (ParserConfigurationException e) { notifier.fireTestFailure(new Failure(desc, e)); } catch (SAXException e) { notifier.fireTestFailure(new Failure(desc, e)); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } protected static Object objectFromString(String string) throws IOException, ClassNotFoundException { byte[] buffer = Base64.decodeBase64(string); ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream(buffer)); Object object = ois.readObject(); ois.close(); return object; } /** * Check if we are running this test in an Alfresco server instance. * * @return true if we are running in an Alfresco server */ protected boolean areWeRunningInAlfresco() { Object contextHolder = SpringContextHolder.Instance(); return (contextHolder != null); } /** * Check the @Remote config on the test class to see where the * Alfresco Repo is running. If it is not present, check the * ACS_ENDPOINT_PROP system property as an alternative location. * If none of them has a value, then return the default location. * * @param method * @return */ protected String getContextRoot(FrameworkMethod method) { Class<?> declaringClass = method.getMethod().getDeclaringClass(); boolean annotationPresent = declaringClass.isAnnotationPresent(Remote.class); if (annotationPresent) { Remote annotation = declaringClass.getAnnotation(Remote.class); return annotation.endpoint(); } final String platformEndpoint = System.getProperty(ACS_ENDPOINT_PROP); return StringUtils.isNotBlank(platformEndpoint) ? platformEndpoint : ACS_DEFAULT_ENDPOINT; } }
modules/alfresco-rad/src/main/java/org/alfresco/rad/test/AlfrescoTestRunner.java
/** * Copyright (C) 2017 Alfresco Software Limited. * <p/> * This file is part of the Alfresco SDK project. * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.alfresco.rad.test; import org.alfresco.rad.SpringContextHolder; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Ignore; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; /** * This is a JUnit test runner that is designed to work with an Alfresco repository. * It detects if it's executing a test inside of a running Alfresco instance. If that * is the case the tests are all run normally. If however the test is being run from * outside the repository, from the maven command line or from an IDE * such as IntelliJ or STS/Eclipse for example, then instead of running the actual * test an HTTP request is made to a Web Script in a running Alfresco instance. This * Web Script runs the test and returns enough information to this class so we can * emulate having run the test locally. * <p/> * By doing this, we are able to create Integration Tests (IT) using standard JUnit * capabilities. These can then be run from our IDEs with the associated visualizations, * support for re-running failed tests, etc. * <p/> * Integration testing framework donated by Zia Consulting * * @author Bindu Wavell <[email protected]> * @author [email protected] (some editing) * @since 3.0 */ public class AlfrescoTestRunner extends BlockJUnit4ClassRunner { public static final String SUCCESS = "SUCCESS"; public static final String FAILURE = "FAILURE"; public AlfrescoTestRunner(Class<?> klass) throws InitializationError { super(klass); } public static String serializableToString(Serializable serializable) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(serializable); oos.close(); String string = Base64.encodeBase64URLSafeString(baos.toByteArray()); return string; } @Override protected void runChild(FrameworkMethod method, RunNotifier notifier) { if (areWeRunningInAlfresco()) { // Just run the test as normally super.runChild(method, notifier); } else { // We are not running in an Alfresco Server, we need to call one and have it execute the test... Description desc = describeChild(method); if (method.getAnnotation(Ignore.class) != null) { notifier.fireTestIgnored(desc); } else { callProxiedChild(method, notifier, desc); } } } /** * Call a remote Alfresco server and have the test run there. * * @param method the test method to run * @param notifier * @param desc */ protected void callProxiedChild(FrameworkMethod method, RunNotifier notifier, Description desc) { notifier.fireTestStarted(desc); String className = method.getMethod().getDeclaringClass().getCanonicalName(); String methodName = method.getName(); if (null != methodName) { className += "#" + methodName; } // Login credentials for Alfresco Repo // TODO: Maybe configure credentials in props... CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin"); provider.setCredentials(AuthScope.ANY, credentials); // Create HTTP Client with credentials CloseableHttpClient httpclient = HttpClientBuilder.create() .setDefaultCredentialsProvider(provider) .build(); // Create the GET Request for the Web Script that will run the test String testWebScriptUrl = "/service/testing/test.xml?clazz=" + className.replace("#", "%23"); //System.out.println("AlfrescoTestRunner: Invoking Web Script for test execution: " + testWebScriptUrl); HttpGet get = new HttpGet(getContextRoot(method) + testWebScriptUrl); try { // Send proxied request and read response HttpResponse resp = httpclient.execute(get); InputStream is = resp.getEntity().getContent(); InputStreamReader ir = new InputStreamReader(is); BufferedReader br = new BufferedReader(ir); String body = ""; String line; while ((line = br.readLine()) != null) { body += line + "\n"; } // Process response if (body.length() > 0) { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new InputSource(new StringReader(body))); Element root = doc.getDocumentElement(); NodeList results = root.getElementsByTagName("result"); if (null != results && results.getLength() > 0) { String result = results.item(0).getFirstChild().getNodeValue(); if (SUCCESS.equals(result)) { notifier.fireTestFinished(desc); } else { boolean failureFired = false; NodeList throwableNodes = root.getElementsByTagName("throwable"); for (int tid = 0; tid < throwableNodes.getLength(); tid++) { String throwableBody = null; Object object = null; Throwable throwable = null; throwableBody = throwableNodes.item(tid).getFirstChild().getNodeValue(); if (null != throwableBody) { try { object = objectFromString(throwableBody); } catch (ClassNotFoundException e) { } if (null != object && object instanceof Throwable) { throwable = (Throwable) object; } } if (null == throwable) { throwable = new Throwable("Unable to process exception body: " + throwableBody); } notifier.fireTestFailure(new Failure(desc, throwable)); failureFired = true; } if (!failureFired) { notifier.fireTestFailure(new Failure(desc, new Throwable( "There was an error but we can't figure out what it was, sorry!"))); } } } else { notifier.fireTestFailure(new Failure(desc, new Throwable( "Unable to process response for proxied test request: " + body))); } } else { notifier.fireTestFailure(new Failure(desc, new Throwable( "Attempt to proxy test into running Alfresco instance failed, no response received"))); } } catch (IOException e) { notifier.fireTestFailure(new Failure(desc, e)); } catch (ParserConfigurationException e) { notifier.fireTestFailure(new Failure(desc, e)); } catch (SAXException e) { notifier.fireTestFailure(new Failure(desc, e)); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } protected static Object objectFromString(String string) throws IOException, ClassNotFoundException { byte[] buffer = Base64.decodeBase64(string); ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream(buffer)); Object object = ois.readObject(); ois.close(); return object; } /** * Check if we are running this test in an Alfresco server instance. * * @return true if we are running in an Alfresco server */ protected boolean areWeRunningInAlfresco() { Object contextHolder = SpringContextHolder.Instance(); return (contextHolder != null); } /** * Check the @Remote config on the test class to see where the * Alfresco Repo is running * * @param method * @return */ protected String getContextRoot(FrameworkMethod method) { Class<?> declaringClass = method.getMethod().getDeclaringClass(); boolean annotationPresent = declaringClass.isAnnotationPresent(Remote.class); if (annotationPresent) { Remote annotation = declaringClass.getAnnotation(Remote.class); return annotation.endpoint(); } return "http://localhost:8080/alfresco"; } }
Look for custom java system property for alfresco location Modify the Alfresco RAD module to check for the java system property acs.endpoint.path as an alternative for the default location of alfresco which is http://localhost:8080/alfresco. This is useful to avoid connection refuse when starting ACS 6 as a container in a windows machine with Docker Toolbox, which exposes the containers through a custom IP instead of localhost.
modules/alfresco-rad/src/main/java/org/alfresco/rad/test/AlfrescoTestRunner.java
Look for custom java system property for alfresco location
<ide><path>odules/alfresco-rad/src/main/java/org/alfresco/rad/test/AlfrescoTestRunner.java <ide> <ide> import org.alfresco.rad.SpringContextHolder; <ide> import org.apache.commons.codec.binary.Base64; <add>import org.apache.commons.lang3.StringUtils; <ide> import org.apache.http.HttpResponse; <ide> import org.apache.http.auth.AuthScope; <ide> import org.apache.http.auth.UsernamePasswordCredentials; <ide> * @since 3.0 <ide> */ <ide> public class AlfrescoTestRunner extends BlockJUnit4ClassRunner { <add> private static final String ACS_ENDPOINT_PROP = "acs.endpoint.path"; <add> private static final String ACS_DEFAULT_ENDPOINT = "http://localhost:8080/alfresco"; <add> <ide> public static final String SUCCESS = "SUCCESS"; <ide> public static final String FAILURE = "FAILURE"; <ide> <ide> <ide> /** <ide> * Check the @Remote config on the test class to see where the <del> * Alfresco Repo is running <add> * Alfresco Repo is running. If it is not present, check the <add> * ACS_ENDPOINT_PROP system property as an alternative location. <add> * If none of them has a value, then return the default location. <ide> * <ide> * @param method <ide> * @return <ide> return annotation.endpoint(); <ide> } <ide> <del> return "http://localhost:8080/alfresco"; <add> final String platformEndpoint = System.getProperty(ACS_ENDPOINT_PROP); <add> return StringUtils.isNotBlank(platformEndpoint) ? platformEndpoint : ACS_DEFAULT_ENDPOINT; <ide> } <ide> <ide> }
Java
apache-2.0
589e8d9698a135499c2e0597a96cbfcd77d9deaa
0
phax/ph-commons
/** * Copyright (C) 2014-2017 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.security.keystore; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStore.PasswordProtection; import java.security.KeyStore.ProtectionParameter; import java.security.KeyStoreException; import java.security.UnrecoverableKeyException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.PresentForCodeCoverage; import com.helger.commons.concurrent.SimpleReadWriteLock; import com.helger.commons.io.resourceprovider.ClassPathResourceProvider; import com.helger.commons.io.resourceprovider.FileSystemResourceProvider; import com.helger.commons.io.resourceprovider.IReadableResourceProvider; import com.helger.commons.io.resourceprovider.ReadableResourceProviderChain; import com.helger.commons.io.stream.StreamHelper; import com.helger.commons.lang.ClassHelper; import com.helger.commons.string.StringHelper; /** * Helper methods to access Java key stores of type JKS (Java KeyStore). * * @author PEPPOL.AT, BRZ, Philip Helger */ @ThreadSafe public final class KeyStoreHelper { public static final String KEYSTORE_TYPE_JKS = "JKS"; public static final String KEYSTORE_TYPE_PKCS12 = "PKCS12"; private static final Logger s_aLogger = LoggerFactory.getLogger (KeyStoreHelper.class); private static final SimpleReadWriteLock s_aRWLock = new SimpleReadWriteLock (); @GuardedBy ("s_aRWLock") private static IReadableResourceProvider s_aResourceProvider = new ReadableResourceProviderChain (new FileSystemResourceProvider ().setCanReadRelativePaths (true), new ClassPathResourceProvider ()); @PresentForCodeCoverage private static final KeyStoreHelper s_aInstance = new KeyStoreHelper (); private KeyStoreHelper () {} @Nonnull public static IReadableResourceProvider getResourceProvider () { return s_aRWLock.readLocked ( () -> s_aResourceProvider); } public static void setResourceProvider (@Nonnull final IReadableResourceProvider aResourceProvider) { ValueEnforcer.notNull (aResourceProvider, "ResourceProvider"); s_aRWLock.writeLocked ( () -> s_aResourceProvider = aResourceProvider); } @Nonnull public static KeyStore getJKSKeyStore () throws KeyStoreException { return KeyStore.getInstance (KEYSTORE_TYPE_JKS); } @Nonnull public static KeyStore getSimiliarKeyStore (@Nonnull final KeyStore aOther) throws KeyStoreException { return KeyStore.getInstance (aOther.getType (), aOther.getProvider ()); } /** * Load a key store from a resource. * * @param sKeyStorePath * The path pointing to the key store. May not be <code>null</code>. * @param sKeyStorePassword * The key store password. May be <code>null</code> to indicate that no * password is required. * @return The Java key-store object. * @see KeyStore#load(InputStream, char[]) * @throws GeneralSecurityException * In case of a key store error * @throws IOException * In case key store loading fails * @throws IllegalArgumentException * If the keystore path is invalid */ @Nonnull public static KeyStore loadKeyStoreDirect (@Nonnull final String sKeyStorePath, @Nullable final String sKeyStorePassword) throws GeneralSecurityException, IOException { return loadKeyStoreDirect (sKeyStorePath, sKeyStorePassword == null ? null : sKeyStorePassword.toCharArray ()); } /** * Load a key store from a resource. * * @param sKeyStorePath * The path pointing to the key store. May not be <code>null</code>. * @param aKeyStorePassword * The key store password. May be <code>null</code> to indicate that no * password is required. * @return The Java key-store object. * @see KeyStore#load(InputStream, char[]) * @throws GeneralSecurityException * In case of a key store error * @throws IOException * In case key store loading fails * @throws IllegalArgumentException * If the keystore path is invalid */ @Nonnull public static KeyStore loadKeyStoreDirect (@Nonnull final String sKeyStorePath, @Nullable final char [] aKeyStorePassword) throws GeneralSecurityException, IOException { ValueEnforcer.notNull (sKeyStorePath, "KeyStorePath"); // Open the resource stream final InputStream aIS = getResourceProvider ().getInputStream (sKeyStorePath); if (aIS == null) throw new IllegalArgumentException ("Failed to open key store '" + sKeyStorePath + "'"); try { final KeyStore aKeyStore = getJKSKeyStore (); aKeyStore.load (aIS, aKeyStorePassword); return aKeyStore; } catch (final KeyStoreException ex) { throw new IllegalStateException ("No provider can handle JKS key stores! Very weird!", ex); } finally { StreamHelper.close (aIS); } } /** * Create a new key store based on an existing key store * * @param aBaseKeyStore * The source key store. May not be <code>null</code> * @param sAliasToCopy * The name of the alias in the source key store that should be put in * the new key store * @param aAliasPassword * The optional password to access the alias in the source key store. * If it is not <code>null</code> the same password will be used in the * created key store * @return The created in-memory key store * @throws GeneralSecurityException * In case of a key store error * @throws IOException * In case key store loading fails */ @Nonnull public static KeyStore createKeyStoreWithOnlyOneItem (@Nonnull final KeyStore aBaseKeyStore, @Nonnull final String sAliasToCopy, @Nullable final char [] aAliasPassword) throws GeneralSecurityException, IOException { ValueEnforcer.notNull (aBaseKeyStore, "BaseKeyStore"); ValueEnforcer.notNull (sAliasToCopy, "AliasToCopy"); final KeyStore aKeyStore = getSimiliarKeyStore (aBaseKeyStore); // null stream means: create new key store aKeyStore.load (null, null); // Do we need a password? ProtectionParameter aPP = null; if (aAliasPassword != null) aPP = new PasswordProtection (aAliasPassword); aKeyStore.setEntry (sAliasToCopy, aBaseKeyStore.getEntry (sAliasToCopy, aPP), aPP); return aKeyStore; } /** * Load the provided keystore in a safe manner. * * @param sKeyStorePath * Path to the keystore. May not be <code>null</code> to succeed. * @param sKeyStorePassword * Password for the keystore. May not be <code>null</code> to succeed. * @return The keystore loading result. Never <code>null</code>. */ @Nonnull public static LoadedKeyStore loadKeyStore (@Nullable final String sKeyStorePath, @Nullable final String sKeyStorePassword) { // Get the parameters for the key store if (StringHelper.hasNoText (sKeyStorePath)) return new LoadedKeyStore (null, EKeyStoreLoadError.KEYSTORE_NO_PATH); KeyStore aKeyStore = null; // Try to load key store try { aKeyStore = loadKeyStoreDirect (sKeyStorePath, sKeyStorePassword); } catch (final IllegalArgumentException ex) { s_aLogger.warn ("No such key store '" + sKeyStorePath + "': " + ex.getMessage (), ex.getCause ()); return new LoadedKeyStore (null, EKeyStoreLoadError.KEYSTORE_LOAD_ERROR_NON_EXISTING, sKeyStorePath, ex.getMessage ()); } catch (final Exception ex) { s_aLogger.warn ("Failed to load key store '" + sKeyStorePath + "': " + ex.getMessage (), ex.getCause ()); final boolean bInvalidPW = ex instanceof IOException && ex.getCause () instanceof UnrecoverableKeyException; return new LoadedKeyStore (null, bInvalidPW ? EKeyStoreLoadError.KEYSTORE_INVALID_PASSWORD : EKeyStoreLoadError.KEYSTORE_LOAD_ERROR_FORMAT_ERROR, sKeyStorePath, ex.getMessage ()); } // Finally success return new LoadedKeyStore (aKeyStore, null); } @Nonnull private static <T extends KeyStore.Entry> LoadedKey <T> _loadKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword, @Nonnull final Class <T> aTargetClass) { ValueEnforcer.notNull (aKeyStore, "KeyStore"); ValueEnforcer.notNull (sKeyStorePath, "KeyStorePath"); if (StringHelper.hasNoText (sKeyStoreKeyAlias)) return new LoadedKey <> (null, EKeyStoreLoadError.KEY_NO_ALIAS, sKeyStorePath); if (aKeyStoreKeyPassword == null) return new LoadedKey <> (null, EKeyStoreLoadError.KEY_NO_PASSWORD, sKeyStoreKeyAlias, sKeyStorePath); // Try to load the key. T aKeyEntry = null; try { final KeyStore.ProtectionParameter aProtection = new KeyStore.PasswordProtection (aKeyStoreKeyPassword); final KeyStore.Entry aEntry = aKeyStore.getEntry (sKeyStoreKeyAlias, aProtection); if (aEntry == null) { // No such entry return new LoadedKey <> (null, EKeyStoreLoadError.KEY_INVALID_ALIAS, sKeyStoreKeyAlias, sKeyStorePath); } if (!aTargetClass.isAssignableFrom (aEntry.getClass ())) { // Not a matching return new LoadedKey <> (null, EKeyStoreLoadError.KEY_INVALID_TYPE, sKeyStoreKeyAlias, sKeyStorePath, ClassHelper.getClassName (aEntry)); } aKeyEntry = aTargetClass.cast (aEntry); } catch (final UnrecoverableKeyException ex) { return new LoadedKey <> (null, EKeyStoreLoadError.KEY_INVALID_PASSWORD, sKeyStoreKeyAlias, sKeyStorePath, ex.getMessage ()); } catch (final GeneralSecurityException ex) { return new LoadedKey <> (null, EKeyStoreLoadError.KEY_LOAD_ERROR, sKeyStoreKeyAlias, sKeyStorePath, ex.getMessage ()); } // Finally success return new LoadedKey <> (aKeyEntry, null); } /** * Load the specified private key entry from the provided keystore. * * @param aKeyStore * The keystore to load the key from. May not be <code>null</code>. * @param sKeyStorePath * Keystore path. For nice error messages only. May be * <code>null</code>. * @param sKeyStoreKeyAlias * The alias to be resolved in the keystore. Must be non- * <code>null</code> to succeed. * @param aKeyStoreKeyPassword * The key password for the keystore. Must be non-<code>null</code> to * succeed. * @return The key loading result. Never <code>null</code>. */ @Nonnull public static LoadedKey <KeyStore.PrivateKeyEntry> loadPrivateKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword) { return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.PrivateKeyEntry.class); } /** * Load the specified secret key entry from the provided keystore. * * @param aKeyStore * The keystore to load the key from. May not be <code>null</code>. * @param sKeyStorePath * Keystore path. For nice error messages only. May be * <code>null</code>. * @param sKeyStoreKeyAlias * The alias to be resolved in the keystore. Must be non- * <code>null</code> to succeed. * @param aKeyStoreKeyPassword * The key password for the keystore. Must be non-<code>null</code> to * succeed. * @return The key loading result. Never <code>null</code>. */ @Nonnull public static LoadedKey <KeyStore.SecretKeyEntry> loadSecretKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword) { return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.SecretKeyEntry.class); } /** * Load the specified private key entry from the provided keystore. * * @param aKeyStore * The keystore to load the key from. May not be <code>null</code>. * @param sKeyStorePath * Keystore path. For nice error messages only. May be * <code>null</code>. * @param sKeyStoreKeyAlias * The alias to be resolved in the keystore. Must be non- * <code>null</code> to succeed. * @param aKeyStoreKeyPassword * The key password for the keystore. Must be non-<code>null</code> to * succeed. * @return The key loading result. Never <code>null</code>. */ @Nonnull public static LoadedKey <KeyStore.TrustedCertificateEntry> loadTrustedCertificateKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword) { return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.TrustedCertificateEntry.class); } }
ph-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java
/** * Copyright (C) 2014-2017 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.security.keystore; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStore.PasswordProtection; import java.security.KeyStore.ProtectionParameter; import java.security.KeyStoreException; import java.security.UnrecoverableKeyException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.PresentForCodeCoverage; import com.helger.commons.concurrent.SimpleReadWriteLock; import com.helger.commons.io.resourceprovider.ClassPathResourceProvider; import com.helger.commons.io.resourceprovider.FileSystemResourceProvider; import com.helger.commons.io.resourceprovider.IReadableResourceProvider; import com.helger.commons.io.resourceprovider.ReadableResourceProviderChain; import com.helger.commons.io.stream.StreamHelper; import com.helger.commons.lang.ClassHelper; import com.helger.commons.string.StringHelper; /** * Helper methods to access Java key stores of type JKS (Java KeyStore). * * @author PEPPOL.AT, BRZ, Philip Helger */ @ThreadSafe public final class KeyStoreHelper { public static final String KEYSTORE_TYPE_JKS = "JKS"; public static final String KEYSTORE_TYPE_PKCS12 = "PKCS12"; private static final SimpleReadWriteLock s_aRWLock = new SimpleReadWriteLock (); @GuardedBy ("s_aRWLock") private static IReadableResourceProvider s_aResourceProvider = new ReadableResourceProviderChain (new FileSystemResourceProvider ().setCanReadRelativePaths (true), new ClassPathResourceProvider ()); @PresentForCodeCoverage private static final KeyStoreHelper s_aInstance = new KeyStoreHelper (); private KeyStoreHelper () {} @Nonnull public static IReadableResourceProvider getResourceProvider () { return s_aRWLock.readLocked ( () -> s_aResourceProvider); } public static void setResourceProvider (@Nonnull final IReadableResourceProvider aResourceProvider) { ValueEnforcer.notNull (aResourceProvider, "ResourceProvider"); s_aRWLock.writeLocked ( () -> s_aResourceProvider = aResourceProvider); } @Nonnull public static KeyStore getJKSKeyStore () throws KeyStoreException { return KeyStore.getInstance (KEYSTORE_TYPE_JKS); } @Nonnull public static KeyStore getSimiliarKeyStore (@Nonnull final KeyStore aOther) throws KeyStoreException { return KeyStore.getInstance (aOther.getType (), aOther.getProvider ()); } /** * Load a key store from a resource. * * @param sKeyStorePath * The path pointing to the key store. May not be <code>null</code>. * @param sKeyStorePassword * The key store password. May be <code>null</code> to indicate that no * password is required. * @return The Java key-store object. * @see KeyStore#load(InputStream, char[]) * @throws GeneralSecurityException * In case of a key store error * @throws IOException * In case key store loading fails * @throws IllegalArgumentException * If the keystore path is invalid */ @Nonnull public static KeyStore loadKeyStoreDirect (@Nonnull final String sKeyStorePath, @Nullable final String sKeyStorePassword) throws GeneralSecurityException, IOException { return loadKeyStoreDirect (sKeyStorePath, sKeyStorePassword == null ? null : sKeyStorePassword.toCharArray ()); } /** * Load a key store from a resource. * * @param sKeyStorePath * The path pointing to the key store. May not be <code>null</code>. * @param aKeyStorePassword * The key store password. May be <code>null</code> to indicate that no * password is required. * @return The Java key-store object. * @see KeyStore#load(InputStream, char[]) * @throws GeneralSecurityException * In case of a key store error * @throws IOException * In case key store loading fails * @throws IllegalArgumentException * If the keystore path is invalid */ @Nonnull public static KeyStore loadKeyStoreDirect (@Nonnull final String sKeyStorePath, @Nullable final char [] aKeyStorePassword) throws GeneralSecurityException, IOException { ValueEnforcer.notNull (sKeyStorePath, "KeyStorePath"); // Open the resource stream final InputStream aIS = getResourceProvider ().getInputStream (sKeyStorePath); if (aIS == null) throw new IllegalArgumentException ("Failed to open key store '" + sKeyStorePath + "'"); try { final KeyStore aKeyStore = getJKSKeyStore (); aKeyStore.load (aIS, aKeyStorePassword); return aKeyStore; } catch (final KeyStoreException ex) { throw new IllegalStateException ("No provider can handle JKS key stores! Very weird!", ex); } finally { StreamHelper.close (aIS); } } /** * Create a new key store based on an existing key store * * @param aBaseKeyStore * The source key store. May not be <code>null</code> * @param sAliasToCopy * The name of the alias in the source key store that should be put in * the new key store * @param aAliasPassword * The optional password to access the alias in the source key store. * If it is not <code>null</code> the same password will be used in the * created key store * @return The created in-memory key store * @throws GeneralSecurityException * In case of a key store error * @throws IOException * In case key store loading fails */ @Nonnull public static KeyStore createKeyStoreWithOnlyOneItem (@Nonnull final KeyStore aBaseKeyStore, @Nonnull final String sAliasToCopy, @Nullable final char [] aAliasPassword) throws GeneralSecurityException, IOException { ValueEnforcer.notNull (aBaseKeyStore, "BaseKeyStore"); ValueEnforcer.notNull (sAliasToCopy, "AliasToCopy"); final KeyStore aKeyStore = getSimiliarKeyStore (aBaseKeyStore); // null stream means: create new key store aKeyStore.load (null, null); // Do we need a password? ProtectionParameter aPP = null; if (aAliasPassword != null) aPP = new PasswordProtection (aAliasPassword); aKeyStore.setEntry (sAliasToCopy, aBaseKeyStore.getEntry (sAliasToCopy, aPP), aPP); return aKeyStore; } /** * Load the provided keystore in a safe manner. * * @param sKeyStorePath * Path to the keystore. May not be <code>null</code> to succeed. * @param sKeyStorePassword * Password for the keystore. May not be <code>null</code> to succeed. * @return The keystore loading result. Never <code>null</code>. */ @Nonnull public static LoadedKeyStore loadKeyStore (@Nullable final String sKeyStorePath, @Nullable final String sKeyStorePassword) { // Get the parameters for the key store if (StringHelper.hasNoText (sKeyStorePath)) return new LoadedKeyStore (null, EKeyStoreLoadError.KEYSTORE_NO_PATH); KeyStore aKeyStore = null; // Try to load key store try { aKeyStore = loadKeyStoreDirect (sKeyStorePath, sKeyStorePassword); } catch (final IllegalArgumentException ex) { return new LoadedKeyStore (null, EKeyStoreLoadError.KEYSTORE_LOAD_ERROR_NON_EXISTING, sKeyStorePath, ex.getMessage ()); } catch (final Exception ex) { final boolean bInvalidPW = ex instanceof IOException && ex.getCause () instanceof UnrecoverableKeyException; return new LoadedKeyStore (null, bInvalidPW ? EKeyStoreLoadError.KEYSTORE_INVALID_PASSWORD : EKeyStoreLoadError.KEYSTORE_LOAD_ERROR_FORMAT_ERROR, sKeyStorePath, ex.getMessage ()); } // Finally success return new LoadedKeyStore (aKeyStore, null); } @Nonnull private static <T extends KeyStore.Entry> LoadedKey <T> _loadKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword, @Nonnull final Class <T> aTargetClass) { ValueEnforcer.notNull (aKeyStore, "KeyStore"); ValueEnforcer.notNull (sKeyStorePath, "KeyStorePath"); if (StringHelper.hasNoText (sKeyStoreKeyAlias)) return new LoadedKey<> (null, EKeyStoreLoadError.KEY_NO_ALIAS, sKeyStorePath); if (aKeyStoreKeyPassword == null) return new LoadedKey<> (null, EKeyStoreLoadError.KEY_NO_PASSWORD, sKeyStoreKeyAlias, sKeyStorePath); // Try to load the key. T aKeyEntry = null; try { final KeyStore.ProtectionParameter aProtection = new KeyStore.PasswordProtection (aKeyStoreKeyPassword); final KeyStore.Entry aEntry = aKeyStore.getEntry (sKeyStoreKeyAlias, aProtection); if (aEntry == null) { // No such entry return new LoadedKey<> (null, EKeyStoreLoadError.KEY_INVALID_ALIAS, sKeyStoreKeyAlias, sKeyStorePath); } if (!aTargetClass.isAssignableFrom (aEntry.getClass ())) { // Not a matching return new LoadedKey<> (null, EKeyStoreLoadError.KEY_INVALID_TYPE, sKeyStoreKeyAlias, sKeyStorePath, ClassHelper.getClassName (aEntry)); } aKeyEntry = aTargetClass.cast (aEntry); } catch (final UnrecoverableKeyException ex) { return new LoadedKey<> (null, EKeyStoreLoadError.KEY_INVALID_PASSWORD, sKeyStoreKeyAlias, sKeyStorePath, ex.getMessage ()); } catch (final GeneralSecurityException ex) { return new LoadedKey<> (null, EKeyStoreLoadError.KEY_LOAD_ERROR, sKeyStoreKeyAlias, sKeyStorePath, ex.getMessage ()); } // Finally success return new LoadedKey<> (aKeyEntry, null); } /** * Load the specified private key entry from the provided keystore. * * @param aKeyStore * The keystore to load the key from. May not be <code>null</code>. * @param sKeyStorePath * Keystore path. For nice error messages only. May be * <code>null</code>. * @param sKeyStoreKeyAlias * The alias to be resolved in the keystore. Must be non- * <code>null</code> to succeed. * @param aKeyStoreKeyPassword * The key password for the keystore. Must be non-<code>null</code> to * succeed. * @return The key loading result. Never <code>null</code>. */ @Nonnull public static LoadedKey <KeyStore.PrivateKeyEntry> loadPrivateKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword) { return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.PrivateKeyEntry.class); } /** * Load the specified secret key entry from the provided keystore. * * @param aKeyStore * The keystore to load the key from. May not be <code>null</code>. * @param sKeyStorePath * Keystore path. For nice error messages only. May be * <code>null</code>. * @param sKeyStoreKeyAlias * The alias to be resolved in the keystore. Must be non- * <code>null</code> to succeed. * @param aKeyStoreKeyPassword * The key password for the keystore. Must be non-<code>null</code> to * succeed. * @return The key loading result. Never <code>null</code>. */ @Nonnull public static LoadedKey <KeyStore.SecretKeyEntry> loadSecretKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword) { return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.SecretKeyEntry.class); } /** * Load the specified private key entry from the provided keystore. * * @param aKeyStore * The keystore to load the key from. May not be <code>null</code>. * @param sKeyStorePath * Keystore path. For nice error messages only. May be * <code>null</code>. * @param sKeyStoreKeyAlias * The alias to be resolved in the keystore. Must be non- * <code>null</code> to succeed. * @param aKeyStoreKeyPassword * The key password for the keystore. Must be non-<code>null</code> to * succeed. * @return The key loading result. Never <code>null</code>. */ @Nonnull public static LoadedKey <KeyStore.TrustedCertificateEntry> loadTrustedCertificateKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword) { return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.TrustedCertificateEntry.class); } }
Improved logging
ph-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java
Improved logging
<ide><path>h-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java <ide> import javax.annotation.concurrent.GuardedBy; <ide> import javax.annotation.concurrent.ThreadSafe; <ide> <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add> <ide> import com.helger.commons.ValueEnforcer; <ide> import com.helger.commons.annotation.PresentForCodeCoverage; <ide> import com.helger.commons.concurrent.SimpleReadWriteLock; <ide> public static final String KEYSTORE_TYPE_JKS = "JKS"; <ide> public static final String KEYSTORE_TYPE_PKCS12 = "PKCS12"; <ide> <add> private static final Logger s_aLogger = LoggerFactory.getLogger (KeyStoreHelper.class); <ide> private static final SimpleReadWriteLock s_aRWLock = new SimpleReadWriteLock (); <ide> @GuardedBy ("s_aRWLock") <ide> private static IReadableResourceProvider s_aResourceProvider = new ReadableResourceProviderChain (new FileSystemResourceProvider ().setCanReadRelativePaths (true), <ide> } <ide> catch (final IllegalArgumentException ex) <ide> { <add> s_aLogger.warn ("No such key store '" + sKeyStorePath + "': " + ex.getMessage (), ex.getCause ()); <ide> return new LoadedKeyStore (null, <ide> EKeyStoreLoadError.KEYSTORE_LOAD_ERROR_NON_EXISTING, <ide> sKeyStorePath, <ide> } <ide> catch (final Exception ex) <ide> { <add> s_aLogger.warn ("Failed to load key store '" + sKeyStorePath + "': " + ex.getMessage (), ex.getCause ()); <add> <ide> final boolean bInvalidPW = ex instanceof IOException && ex.getCause () instanceof UnrecoverableKeyException; <ide> <ide> return new LoadedKeyStore (null, <ide> ValueEnforcer.notNull (sKeyStorePath, "KeyStorePath"); <ide> <ide> if (StringHelper.hasNoText (sKeyStoreKeyAlias)) <del> return new LoadedKey<> (null, EKeyStoreLoadError.KEY_NO_ALIAS, sKeyStorePath); <add> return new LoadedKey <> (null, EKeyStoreLoadError.KEY_NO_ALIAS, sKeyStorePath); <ide> <ide> if (aKeyStoreKeyPassword == null) <del> return new LoadedKey<> (null, EKeyStoreLoadError.KEY_NO_PASSWORD, sKeyStoreKeyAlias, sKeyStorePath); <add> return new LoadedKey <> (null, EKeyStoreLoadError.KEY_NO_PASSWORD, sKeyStoreKeyAlias, sKeyStorePath); <ide> <ide> // Try to load the key. <ide> T aKeyEntry = null; <ide> if (aEntry == null) <ide> { <ide> // No such entry <del> return new LoadedKey<> (null, EKeyStoreLoadError.KEY_INVALID_ALIAS, sKeyStoreKeyAlias, sKeyStorePath); <add> return new LoadedKey <> (null, EKeyStoreLoadError.KEY_INVALID_ALIAS, sKeyStoreKeyAlias, sKeyStorePath); <ide> } <ide> if (!aTargetClass.isAssignableFrom (aEntry.getClass ())) <ide> { <ide> // Not a matching <del> return new LoadedKey<> (null, <del> EKeyStoreLoadError.KEY_INVALID_TYPE, <del> sKeyStoreKeyAlias, <del> sKeyStorePath, <del> ClassHelper.getClassName (aEntry)); <add> return new LoadedKey <> (null, <add> EKeyStoreLoadError.KEY_INVALID_TYPE, <add> sKeyStoreKeyAlias, <add> sKeyStorePath, <add> ClassHelper.getClassName (aEntry)); <ide> } <ide> aKeyEntry = aTargetClass.cast (aEntry); <ide> } <ide> catch (final UnrecoverableKeyException ex) <ide> { <del> return new LoadedKey<> (null, <del> EKeyStoreLoadError.KEY_INVALID_PASSWORD, <del> sKeyStoreKeyAlias, <del> sKeyStorePath, <del> ex.getMessage ()); <add> return new LoadedKey <> (null, <add> EKeyStoreLoadError.KEY_INVALID_PASSWORD, <add> sKeyStoreKeyAlias, <add> sKeyStorePath, <add> ex.getMessage ()); <ide> } <ide> catch (final GeneralSecurityException ex) <ide> { <del> return new LoadedKey<> (null, <del> EKeyStoreLoadError.KEY_LOAD_ERROR, <del> sKeyStoreKeyAlias, <del> sKeyStorePath, <del> ex.getMessage ()); <add> return new LoadedKey <> (null, <add> EKeyStoreLoadError.KEY_LOAD_ERROR, <add> sKeyStoreKeyAlias, <add> sKeyStorePath, <add> ex.getMessage ()); <ide> } <ide> <ide> // Finally success <del> return new LoadedKey<> (aKeyEntry, null); <add> return new LoadedKey <> (aKeyEntry, null); <ide> } <ide> <ide> /**
Java
apache-2.0
6ddafaf40da60d15078fc42d5657e2803861b599
0
googleinterns/step1-2020,googleinterns/step1-2020
// Copyright 2020 Google LLC // // 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. package com.google.step.snippet.servlets; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.step.snippet.data.Card; import com.google.step.snippet.external.GeeksForGeeksClient; import com.google.step.snippet.external.StackOverflowClient; import com.google.step.snippet.external.W3SchoolClient; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException import java.util.concurrent.ExecutionException import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; /** Servlet that handles searches. */ @WebServlet("/search") public class SearchServlet extends HttpServlet { private static final String W3_CSE_ID = "INSERT_W3SCHOOL_CSE_ID"; private static final String STACK_CSE_ID = "INSERT_STACKOVERFLOW_CSE_ID"; private static final String GEEKS_CSE_ID = "INSERT_GEEKSFORGEEKS_CSE_ID"; private static final String API_KEY = "INSERT_API_KEY"; private static final String CSE_URL = "https://www.googleapis.com/customsearch/v1"; private static final String CSE_ITEMS = "items"; private static final String CSE_LINK = "link"; private static final String CARD_LIST_LABEL = "cardList"; private static String encodeValue(String value) { try { return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException ex) { return null; } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String param = request.getParameter("q"); if (param == null || encodeValue(param) == null) { response.setContentType("text/html;"); response.getWriter().println("Invalid Query"); return; } String query = encodeValue(param); List<Card> allCards = new ArrayList<>(); ExecutorService executor = Executors.newFixedThreadPool(3); List<Callable<Card>> cardCallbacks = Arrays.asList( () -> { String w3Link = getLink(W3_CSE_ID, query); if (w3Link != null) { W3SchoolClient w3client = new W3SchoolClient(); return w3client.search(w3Link); } return null; }, () -> { String stackLink = getLink(STACK_CSE_ID, query); if (stackLink != null) { StackOverflowClient stackClient = new StackOverflowClient(); return stackClient.search(stackLink); } return null; }, () -> { String geeksLink = getLink(GEEKS_CSE_ID, query); if (geeksLink != null) { GeeksForGeeksClient geeksClient = new GeeksForGeeksClient(); return geeksClient.search(geeksLink); } return null; }); try { executor.invokeAll(cardCallbacks).stream() .map( future -> { try { return future.get(); } catch (CancellationException | ExecutionException | InterruptedException e) { return null; } }) .forEach( (c) -> { if (c != null) { allCards.add(c); } }); } catch (InterruptedException | NullPointerException | RejectedExecutionException e) { return; } request.setAttribute(CARD_LIST_LABEL, allCards); request.getRequestDispatcher("WEB-INF/templates/search.jsp").forward(request, response); } private String getLink(String id, String query) { String url = CSE_URL + "?key=" + API_KEY + "&cx=" + id + "&q=" + query; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpResponse response = httpClient.execute(new HttpGet(url))) { if (response.getStatusLine().getStatusCode() != 200) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } JsonObject obj; try { obj = JsonParser.parseReader(new InputStreamReader(entity.getContent())).getAsJsonObject(); } catch (JsonParseException | IllegalStateException | UnsupportedOperationException | IOException e) { return null; } if (obj.has(CSE_ITEMS) && obj.getAsJsonArray(CSE_ITEMS).size() > 0) { JsonObject topResult = obj.getAsJsonArray(CSE_ITEMS).get(0).getAsJsonObject(); if (topResult.has(CSE_LINK)) { return topResult.get(CSE_LINK).getAsString(); } } } catch (IOException | IllegalStateException | ClassCastException e) { return null; } } catch (IOException e) { return null; } return null; } }
src/main/java/com/google/step/snippet/servlets/SearchServlet.java
// Copyright 2020 Google LLC // // 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. package com.google.step.snippet.servlets; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.step.snippet.data.Card; import com.google.step.snippet.external.GeeksForGeeksClient; import com.google.step.snippet.external.StackOverflowClient; import com.google.step.snippet.external.W3SchoolClient; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; /** Servlet that handles searches. */ @WebServlet("/search") public class SearchServlet extends HttpServlet { private static final String W3_CSE_ID = "INSERT_W3SCHOOL_CSE_ID"; private static final String STACK_CSE_ID = "INSERT_STACKOVERFLOW_CSE_ID"; private static final String GEEKS_CSE_ID = "INSERT_GEEKSFORGEEKS_CSE_ID"; private static final String API_KEY = "INSERT_API_KEY"; private static final String CSE_URL = "https://www.googleapis.com/customsearch/v1"; private static final String CSE_ITEMS = "items"; private static final String CSE_LINK = "link"; private static final String CARD_LIST_LABEL = "cardList"; private static String encodeValue(String value) { try { return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException ex) { return null; } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String param = request.getParameter("q"); if (param == null || encodeValue(param) == null) { response.setContentType("text/html;"); response.getWriter().println("Invalid Query"); return; } String query = encodeValue(param); List<Card> allCards = new ArrayList<>(); ExecutorService executor = Executors.newFixedThreadPool(3); List<Callable<Card>> cardCallbacks = Arrays.asList( () -> { String w3Link = getLink(W3_CSE_ID, query); if (w3Link != null) { W3SchoolClient w3client = new W3SchoolClient(); return w3client.search(w3Link); } return null; }, () -> { String stackLink = getLink(STACK_CSE_ID, query); if (stackLink != null) { StackOverflowClient stackClient = new StackOverflowClient(); return stackClient.search(stackLink); } return null; }, () -> { String geeksLink = getLink(GEEKS_CSE_ID, query); if (geeksLink != null) { GeeksForGeeksClient geeksClient = new GeeksForGeeksClient(); return geeksClient.search(geeksLink); } return null; }); try { executor.invokeAll(cardCallbacks).stream() .map( future -> { try { return future.get(); } catch (Exception e) { throw new IllegalStateException(e); } }) .forEach( (c) -> { if (c != null) { allCards.add(c); } }); } catch (InterruptedException | NullPointerException | RejectedExecutionException e) { return; } request.setAttribute(CARD_LIST_LABEL, allCards); request.getRequestDispatcher("WEB-INF/templates/search.jsp").forward(request, response); } private String getLink(String id, String query) { String url = CSE_URL + "?key=" + API_KEY + "&cx=" + id + "&q=" + query; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpResponse response = httpClient.execute(new HttpGet(url))) { if (response.getStatusLine().getStatusCode() != 200) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } JsonObject obj; try { obj = JsonParser.parseReader(new InputStreamReader(entity.getContent())).getAsJsonObject(); } catch (JsonParseException | IllegalStateException | UnsupportedOperationException | IOException e) { return null; } if (obj.has(CSE_ITEMS) && obj.getAsJsonArray(CSE_ITEMS).size() > 0) { JsonObject topResult = obj.getAsJsonArray(CSE_ITEMS).get(0).getAsJsonObject(); if (topResult.has(CSE_LINK)) { return topResult.get(CSE_LINK).getAsString(); } } } catch (IOException | IllegalStateException | ClassCastException e) { return null; } } catch (IOException e) { return null; } return null; } }
catch specific exceptions
src/main/java/com/google/step/snippet/servlets/SearchServlet.java
catch specific exceptions
<ide><path>rc/main/java/com/google/step/snippet/servlets/SearchServlet.java <ide> import java.util.Arrays; <ide> import java.util.List; <ide> import java.util.concurrent.Callable; <add>import java.util.concurrent.CancellationException <add>import java.util.concurrent.ExecutionException <ide> import java.util.concurrent.ExecutorService; <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.RejectedExecutionException; <ide> future -> { <ide> try { <ide> return future.get(); <del> } catch (Exception e) { <del> throw new IllegalStateException(e); <add> } catch (CancellationException | ExecutionException | InterruptedException e) { <add> return null; <ide> } <ide> }) <ide> .forEach(
Java
apache-2.0
8b4d4d277f17d0b399a7f9ddca37d7339883fda7
0
wmixvideo/nfe,danieldhp/nfe,eldevanjr/nfe
package com.fincatto.documentofiscal.utils; import com.fincatto.documentofiscal.DFConfig; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; import javax.xml.crypto.dsig.keyinfo.X509Data; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Signature; import java.security.UnrecoverableEntryException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; import java.util.Enumeration; import java.util.List; public class DFAssinaturaDigital { private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; private static final String[] ELEMENTOS_ASSINAVEIS = new String[]{"infEvento", "infCanc", "infNFe", "infInut", "infMDFe", "infCte"}; private final DFConfig config; public DFAssinaturaDigital(final DFConfig config) { this.config = config; } public boolean isValida(final InputStream xmlStream) throws Exception { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); final Document document = dbf.newDocumentBuilder().parse(xmlStream); final NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nodeList.getLength() == 0) { throw new IllegalStateException("Nao foi encontrada a assinatura do XML."); } final String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).getDeclaredConstructor().newInstance()); final DOMValidateContext validateContext = new DOMValidateContext(new DFKeySelector(), nodeList.item(0)); for (final String tag : DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS) { final NodeList elements = document.getElementsByTagName(tag); if (elements.getLength() > 0) { validateContext.setIdAttributeNS((Element) elements.item(0), null, "Id"); } } return signatureFactory.unmarshalXMLSignature(validateContext).validate(validateContext); } public String assinarDocumento(final String conteudoXml) throws Exception { return this.assinarDocumento(conteudoXml, DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS); } public String assinarDocumento(final String conteudoXml, final String... elementosAssinaveis) throws Exception { try (StringReader reader = new StringReader(conteudoXml)) { try (StringWriter writer = new StringWriter()) { this.assinarDocumento(reader, writer, elementosAssinaveis); return writer.toString(); } } } public void assinarDocumento(Reader xmlReader, Writer xmlAssinado, final String... elementosAssinaveis) throws Exception { final KeyStore.PrivateKeyEntry keyEntry = getPrivateKeyEntry(); //Adiciona System.out p/ verificação do certificado que assina o documento try { String dn = ((X509Certificate)keyEntry.getCertificate()).getSubjectX500Principal().getName(); LdapName ldapDN = null; ldapDN = new LdapName(dn); String commonName = ldapDN.getRdns().stream() .filter(rdn -> StringUtils.equalsIgnoreCase(rdn.getType(), "CN")).map(val -> val.getValue() + "").findFirst() .orElse(""); System.out.println("CERTIFICADO ASSINANDO(CNPJ):" + commonName ); } catch (InvalidNameException e) { } final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); final List<Transform> transforms = new ArrayList<>(2); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(signatureFactory.newTransform(DFAssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate())); final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(xmlReader)); for (final String elementoAssinavel : elementosAssinaveis) { final NodeList elements = document.getElementsByTagName(elementoAssinavel); for (int i = 0; i < elements.getLength(); i++) { final Element element = (Element) elements.item(i); final String id = element.getAttribute("Id"); element.setIdAttribute("Id", true); final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode())); } } final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(document), new StreamResult(xmlAssinado)); } private KeyStore.PrivateKeyEntry getPrivateKeyEntry() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray()); if(StringUtils.isNotEmpty(config.getCertificadoAlias())){ final String certificateAlias = config.getCertificadoAlias() != null ? config.getCertificadoAlias() : config.getCertificadoKeyStore().aliases().nextElement(); return (KeyStore.PrivateKeyEntry) config.getCertificadoKeyStore().getEntry(certificateAlias, passwordProtection); }else{ KeyStore ks = config.getCertificadoKeyStore(); for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); if (ks.isKeyEntry(alias)) { return (KeyStore.PrivateKeyEntry) ks.getEntry(alias, passwordProtection); } } throw new RuntimeException("Não foi possível encontrar a chave privada do certificado"); } } public String assinarString(String _string) throws Exception { byte[] buffer = _string.getBytes(); Signature signatureProvider = Signature.getInstance("SHA1withRSA"); signatureProvider.initSign(getPrivateKeyEntry().getPrivateKey()); signatureProvider.update(buffer, 0, buffer.length); byte[] signature = signatureProvider.sign(); System.out.println(getPrivateKeyEntry().getPrivateKey().getFormat()); return Base64.getEncoder().encodeToString(signature); } static class DFKeySelector extends KeySelector { @Override public KeySelectorResult select(final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context) throws KeySelectorException { for (final Object object : keyInfo.getContent()) { final XMLStructure info = (XMLStructure) object; if (info instanceof X509Data) { final X509Data x509Data = (X509Data) info; for (final Object certificado : x509Data.getContent()) { if (certificado instanceof X509Certificate) { final X509Certificate x509Certificate = (X509Certificate) certificado; if (this.algEquals(method.getAlgorithm(), x509Certificate.getPublicKey().getAlgorithm())) { return x509Certificate::getPublicKey; } } } } } throw new KeySelectorException("Nao foi localizada a chave do certificado."); } private boolean algEquals(final String algURI, final String algName) { return ((algName.equalsIgnoreCase("DSA") && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) || (algName.equalsIgnoreCase("RSA") && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1))); } } }
src/main/java/com/fincatto/documentofiscal/utils/DFAssinaturaDigital.java
package com.fincatto.documentofiscal.utils; import com.fincatto.documentofiscal.DFConfig; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; import javax.xml.crypto.dsig.keyinfo.X509Data; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Signature; import java.security.UnrecoverableEntryException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; import java.util.Enumeration; import java.util.List; public class DFAssinaturaDigital { private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; private static final String[] ELEMENTOS_ASSINAVEIS = new String[]{"infEvento", "infCanc", "infNFe", "infInut", "infMDFe", "infCte"}; private final DFConfig config; public DFAssinaturaDigital(final DFConfig config) { this.config = config; } public boolean isValida(final InputStream xmlStream) throws Exception { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); final Document document = dbf.newDocumentBuilder().parse(xmlStream); final NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nodeList.getLength() == 0) { throw new IllegalStateException("Nao foi encontrada a assinatura do XML."); } final String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).getDeclaredConstructor().newInstance()); final DOMValidateContext validateContext = new DOMValidateContext(new DFKeySelector(), nodeList.item(0)); for (final String tag : DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS) { final NodeList elements = document.getElementsByTagName(tag); if (elements.getLength() > 0) { validateContext.setIdAttributeNS((Element) elements.item(0), null, "Id"); } } return signatureFactory.unmarshalXMLSignature(validateContext).validate(validateContext); } public String assinarDocumento(final String conteudoXml) throws Exception { return this.assinarDocumento(conteudoXml, DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS); } public String assinarDocumento(final String conteudoXml, final String... elementosAssinaveis) throws Exception { try (StringReader reader = new StringReader(conteudoXml)) { try (StringWriter writer = new StringWriter()) { this.assinarDocumento(reader, writer, elementosAssinaveis); return writer.toString(); } } } public void assinarDocumento(Reader xmlReader, Writer xmlAssinado, final String... elementosAssinaveis) throws Exception { final KeyStore.PrivateKeyEntry keyEntry = getPrivateKeyEntry(); //Adiciona System.out p/ verificação do certificado que assina o documento try { String dn = ((X509Certificate)keyEntry.getCertificate()).getSubjectX500Principal().getName(); LdapName ldapDN = null; ldapDN = new LdapName(dn); String commonName = ldapDN.getRdns().stream() .filter(rdn -> StringUtils.equalsIgnoreCase(rdn.getType(), "CN")).map(val -> val.getValue() + "").findFirst() .orElse(""); System.out.println("CERTIFICADO ASSINANDO(CNPJ):" + commonName ); } catch (InvalidNameException e) { } final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); final List<Transform> transforms = new ArrayList<>(2); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(signatureFactory.newTransform(DFAssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate())); final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(xmlReader)); for (final String elementoAssinavel : elementosAssinaveis) { final NodeList elements = document.getElementsByTagName(elementoAssinavel); for (int i = 0; i < elements.getLength(); i++) { final Element element = (Element) elements.item(i); final String id = element.getAttribute("Id"); element.setIdAttribute("Id", true); final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode())); } } final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(document), new StreamResult(xmlAssinado)); } private KeyStore.PrivateKeyEntry getPrivateKeyEntry() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { // final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray()); // // KeyStore ks = config.getCertificadoKeyStore(); // for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { // String alias = e.nextElement(); // if (ks.isKeyEntry(alias)) { // return (KeyStore.PrivateKeyEntry) ks.getEntry(alias, passwordProtection); // } // } // // throw new RuntimeException("Não foi possível encontrar a chave privada do certificado"); final String certificateAlias = config.getCertificadoAlias() != null ? config.getCertificadoAlias() : config.getCertificadoKeyStore().aliases().nextElement(); final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray()); return (KeyStore.PrivateKeyEntry) config.getCertificadoKeyStore().getEntry(certificateAlias, passwordProtection); } public String assinarString(String _string) throws Exception { byte[] buffer = _string.getBytes(); Signature signatureProvider = Signature.getInstance("SHA1withRSA"); signatureProvider.initSign(getPrivateKeyEntry().getPrivateKey()); signatureProvider.update(buffer, 0, buffer.length); byte[] signature = signatureProvider.sign(); System.out.println(getPrivateKeyEntry().getPrivateKey().getFormat()); return Base64.getEncoder().encodeToString(signature); } static class DFKeySelector extends KeySelector { @Override public KeySelectorResult select(final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context) throws KeySelectorException { for (final Object object : keyInfo.getContent()) { final XMLStructure info = (XMLStructure) object; if (info instanceof X509Data) { final X509Data x509Data = (X509Data) info; for (final Object certificado : x509Data.getContent()) { if (certificado instanceof X509Certificate) { final X509Certificate x509Certificate = (X509Certificate) certificado; if (this.algEquals(method.getAlgorithm(), x509Certificate.getPublicKey().getAlgorithm())) { return x509Certificate::getPublicKey; } } } } } throw new KeySelectorException("Nao foi localizada a chave do certificado."); } private boolean algEquals(final String algURI, final String algName) { return ((algName.equalsIgnoreCase("DSA") && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) || (algName.equalsIgnoreCase("RSA") && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1))); } } }
Corrige código que desconsidera o ALIAS escolhido na configuração.
src/main/java/com/fincatto/documentofiscal/utils/DFAssinaturaDigital.java
Corrige código que desconsidera o ALIAS escolhido na configuração.
<ide><path>rc/main/java/com/fincatto/documentofiscal/utils/DFAssinaturaDigital.java <ide> private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; <ide> private static final String[] ELEMENTOS_ASSINAVEIS = new String[]{"infEvento", "infCanc", "infNFe", "infInut", "infMDFe", "infCte"}; <ide> private final DFConfig config; <del> <add> <ide> public DFAssinaturaDigital(final DFConfig config) { <ide> this.config = config; <ide> } <del> <add> <ide> public boolean isValida(final InputStream xmlStream) throws Exception { <ide> final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); <ide> dbf.setNamespaceAware(true); <ide> } <ide> return signatureFactory.unmarshalXMLSignature(validateContext).validate(validateContext); <ide> } <del> <add> <ide> public String assinarDocumento(final String conteudoXml) throws Exception { <ide> return this.assinarDocumento(conteudoXml, DFAssinaturaDigital.ELEMENTOS_ASSINAVEIS); <ide> } <del> <add> <ide> public String assinarDocumento(final String conteudoXml, final String... elementosAssinaveis) throws Exception { <ide> try (StringReader reader = new StringReader(conteudoXml)) { <ide> try (StringWriter writer = new StringWriter()) { <ide> } <ide> } <ide> } <del> <add> <ide> public void assinarDocumento(Reader xmlReader, Writer xmlAssinado, final String... elementosAssinaveis) throws Exception { <ide> final KeyStore.PrivateKeyEntry keyEntry = getPrivateKeyEntry(); <ide> //Adiciona System.out p/ verificação do certificado que assina o documento <ide> } <ide> <ide> private KeyStore.PrivateKeyEntry getPrivateKeyEntry() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { <del>// final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray()); <del>// <del>// KeyStore ks = config.getCertificadoKeyStore(); <del>// for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { <del>// String alias = e.nextElement(); <del>// if (ks.isKeyEntry(alias)) { <del>// return (KeyStore.PrivateKeyEntry) ks.getEntry(alias, passwordProtection); <del>// } <del>// } <del>// <del>// throw new RuntimeException("Não foi possível encontrar a chave privada do certificado"); <del> <del> final String certificateAlias = config.getCertificadoAlias() != null ? config.getCertificadoAlias() <del> : config.getCertificadoKeyStore().aliases().nextElement(); <ide> final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray()); <del> return (KeyStore.PrivateKeyEntry) config.getCertificadoKeyStore().getEntry(certificateAlias, passwordProtection); <del> <add> if(StringUtils.isNotEmpty(config.getCertificadoAlias())){ <add> final String certificateAlias = config.getCertificadoAlias() != null ? config.getCertificadoAlias() <add> : config.getCertificadoKeyStore().aliases().nextElement(); <add> return (KeyStore.PrivateKeyEntry) config.getCertificadoKeyStore().getEntry(certificateAlias, passwordProtection); <add> }else{ <add> KeyStore ks = config.getCertificadoKeyStore(); <add> for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { <add> String alias = e.nextElement(); <add> if (ks.isKeyEntry(alias)) { <add> return (KeyStore.PrivateKeyEntry) ks.getEntry(alias, passwordProtection); <add> } <add> } <add> throw new RuntimeException("Não foi possível encontrar a chave privada do certificado"); <add> } <ide> } <ide> <ide> public String assinarString(String _string) throws Exception { <ide> } <ide> throw new KeySelectorException("Nao foi localizada a chave do certificado."); <ide> } <del> <add> <ide> private boolean algEquals(final String algURI, final String algName) { <ide> return ((algName.equalsIgnoreCase("DSA") && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) || (algName.equalsIgnoreCase("RSA") && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1))); <ide> }
Java
apache-2.0
7ef5c3ddee7e60800dd462986f56f0dce9b6bad4
0
adligo/i_util.adligo.org
package org.adligo.i.util.client; /** * * Note Hash Code and Equals not implemented * on purpose in this class * * it is used in the GWT SystemEventController * class and the HashMap would fail the I_Invoker * lookups if HashCode and Equals were implemened * * @author scott * */ public class Event implements I_Disposable { /** * this represents the GUI (view) component that * created the event */ private Object source = null; private Throwable exception = null; private Object value = null; public void dispose() { source = null; exception = null; value = null; } public Object clone() { Event e = new Event(); e.source = source; e.exception = exception; e. value = value; return e; } public Event copy() { return (Event) this.clone(); } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public boolean threwException() { if (exception == null) { return false; } return true; } public Throwable getException() { return exception; } public void setException(Throwable exception) { this.exception = exception; } public Object getSource() { return source; } public void setSource(Object source) { this.source = source; } }
src/org/adligo/i/util/client/Event.java
package org.adligo.i.util.client; /** * * Note Hash Code and Equals not implemented * on purpose in this class * * it is used in the GWT SystemEventController * class and the HashMap would fail the I_Invoker * lookups if HashCode and Equals were implemened * * @author scott * */ public class Event implements I_Disposable { private Throwable exception = null; private Object value = null; public void dispose() { exception = null; value = null; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public boolean threwException() { if (exception == null) { return false; } return true; } public Throwable getException() { return exception; } public void setException(Throwable exception) { this.exception = exception; } }
adding event source to clean up some event code
src/org/adligo/i/util/client/Event.java
adding event source to clean up some event code
<ide><path>rc/org/adligo/i/util/client/Event.java <ide> * <ide> */ <ide> public class Event implements I_Disposable { <del> <add> /** <add> * this represents the GUI (view) component that <add> * created the event <add> */ <add> private Object source = null; <ide> private Throwable exception = null; <ide> private Object value = null; <ide> <ide> public void dispose() { <add> source = null; <ide> exception = null; <ide> value = null; <add> } <add> <add> public Object clone() { <add> Event e = new Event(); <add> e.source = source; <add> e.exception = exception; <add> e. value = value; <add> return e; <add> } <add> <add> public Event copy() { <add> return (Event) this.clone(); <ide> } <ide> <ide> public Object getValue() { <ide> public void setException(Throwable exception) { <ide> this.exception = exception; <ide> } <add> <add> public Object getSource() { <add> return source; <add> } <add> <add> public void setSource(Object source) { <add> this.source = source; <add> } <ide> <ide> }
Java
mit
43b2c43177e6fa021c31a65525d879698a4a60ce
0
Nunnery/MythicDrops
package net.nunnerycode.bukkit.mythicdrops.commands; import net.nunnerycode.bukkit.mythicdrops.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import se.ranzdo.bukkit.methodcommand.Arg; import se.ranzdo.bukkit.methodcommand.Command; import se.ranzdo.bukkit.methodcommand.CommandHandler; import se.ranzdo.bukkit.methodcommand.FlagArg; import se.ranzdo.bukkit.methodcommand.Flags; public class MythicDropsCommand { private final MythicDrops plugin; private final CommandHandler commandHandler; public MythicDropsCommand(MythicDrops plugin) { this.plugin = plugin; commandHandler = new CommandHandler(this.plugin); commandHandler.registerCommands(this); } @Command(identifier = "mythicdrops save", description = "Saves the configuration files", permissions = "mythicdrops.command.save") public void saveSubcommand(CommandSender sender) { getPlugin().getSettingsSaver().save(); getPlugin().getLanguageSaver().save(); getPlugin().getCustomItemSaver().save(); getPlugin().getTierSaver().save(); getPlugin().getLanguageManager().sendMessage(sender, "command.save-config"); } public MythicDrops getPlugin() { return plugin; } @Command(identifier = "mythicdrops load", description = "Reloads the configuration files", permissions = "mythicdrops.command.load") public void loadSubcommand(CommandSender sender) { getPlugin().getSettingsLoader().load(); getPlugin().getLanguageLoader().load(); getPlugin().getCustomItemLoader().load(); getPlugin().getTierLoader().load(); getPlugin().getLanguageManager().sendMessage(sender, "command.reload-config"); } @Command(identifier = "mythicdrops reload", description = "Reloads the entire plugin", permissions = "mythicdrops.command.reload") public void reloadSubcommand(CommandSender sender) { getPlugin().reload(); getPlugin().getLanguageManager().sendMessage(sender, "command.reload-plugin"); } @Command(identifier = "mythicdrops give", description = "Gives MythicDrops items", permissions = "mythicdrops.command.give") @Flags(identifier = {"a", "t", "mind", "maxd"}, description = {"Amount to spawn", "Tier to spawn", "Minimum durability", "Maximum durability"}) public void giveSubcommand(CommandSender sender, @Arg(name = "player") Player player, @Arg(name = "amount", def = "1") @FlagArg("a") int amount, @Arg(name = "tier", def = "*") @FlagArg("t") String tierName, @Arg(name = "mindurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("mind") double minDura, @Arg(name = "maxdurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("maxd") double maxDura) { if (tierName.equalsIgnoreCase("*") && !sender.hasPermission("mythicdrops.command.give.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } Tier tier; try { if (tierName.equalsIgnoreCase("*")) { tier = null; } else { tier = plugin.getTierManager().getTierFromName(tierName); if (tier == null) { tier = plugin.getTierManager().getTierFromDisplayName(tierName); } } } catch (NullPointerException e) { getPlugin().getLanguageManager().sendMessage(player, "command.tier-does-not-exist"); return; } if (tier == null) { if (!player.hasPermission("mythicdrops.command.give.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } } else { if (!player.hasPermission("mythicdrops.command.give." + tier.getTierName().toLowerCase()) && !player .hasPermission("mythicdrops.command.give.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } } int amountGiven = 0; for (int i = 0; i < amount; i++) { try { ItemStack itemStack; if (tier == null) { itemStack = getPlugin().getDropManager().constructItemStackFromTier(getPlugin().getTierManager() .getRandomTierWithChance(), ItemGenerationReason.COMMAND); } else { itemStack = getPlugin().getDropManager().constructItemStackFromTier(tier, ItemGenerationReason.COMMAND); } itemStack.setDurability(ItemStackUtils.getDurabilityForMaterial(itemStack.getType(), minDura, maxDura)); player.getInventory().addItem(itemStack); amountGiven++; } catch (Exception ignored) { ignored.printStackTrace(); } } getPlugin().getLanguageManager().sendMessage(player, "command.give-random-receiver", new String[][]{{"%amount%", String.valueOf(amountGiven)}}); getPlugin().getLanguageManager().sendMessage(sender, "command.give-random-sender", new String[][]{{"%amount%", String.valueOf(amountGiven)}, {"%receiver%", player.getName()}}); } @Command(identifier = "mythicdrops custom", description = "Gives custom MythicDrops items", permissions = "mythicdrops.command.give") @Flags(identifier = {"a", "c", "mind", "maxd"}, description = {"Amount to spawn", "Custom Item to spawn", "Minimum durability", "Maximum durability"}) public void customSubcommand(CommandSender sender, @Arg(name = "player", def = "self") String playerName, @Arg(name = "amount", def = "1") @FlagArg("a") int amount, @Arg(name = "item", def = "*") @FlagArg("c") String itemName, @Arg(name = "mindurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("mind") double minDura, @Arg(name = "maxdurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("maxd") double maxDura) { if (!sender.hasPermission("mythicdrops.command.custom")) { getPlugin().getLanguageManager().sendMessage(sender, "command.no-access"); return; } Player player; if (playerName.equalsIgnoreCase("self")) { if (sender instanceof Player) { player = (Player) sender; } else { getPlugin().getLanguageManager().sendMessage(sender, "command.no-access"); return; } } else { player = Bukkit.getPlayer(playerName); } if (player == null) { getPlugin().getLanguageManager().sendMessage(sender, "command.player-does-not-exist"); return; } CustomItem customItem = null; if (!itemName.equalsIgnoreCase("*")) { try { customItem = getPlugin().getCustomItemManager().getCustomItemFromName(itemName); if (customItem == null) { customItem = getPlugin().getCustomItemManager().getCustomItemFromDisplayName(itemName); } } catch (NullPointerException e) { getPlugin().getLanguageManager().sendMessage(sender, "command.custom-item-does-not-exist"); return; } } int amountGiven = 0; for (int i = 0; i < amount; i++) { try { ItemStack itemStack; if (customItem == null) { itemStack = getPlugin().getDropManager().generateItemStackFromCustomItem(getPlugin() .getCustomItemManager().getRandomCustomItemWithChance(), ItemGenerationReason.COMMAND); } else { itemStack = getPlugin().getDropManager().generateItemStackFromCustomItem(customItem, ItemGenerationReason.COMMAND); } itemStack.setDurability(ItemStackUtils.getDurabilityForMaterial(itemStack.getType(), minDura, maxDura)); player.getInventory().addItem(itemStack); amountGiven++; } catch (Exception ignored) { ignored.printStackTrace(); } } getPlugin().getLanguageManager().sendMessage(player, "command.give-custom-receiver", new String[][]{{"%amount%", String.valueOf(amountGiven)}}); getPlugin().getLanguageManager().sendMessage(sender, "command.give-custom-sender", new String[][]{{"%amount%", String.valueOf(amountGiven)}, {"%receiver%", player.getName()}}); } @Command(identifier = "mythicdrops spawn", description = "Spawns in MythicDrops items", permissions = "mythicdrops.command.spawn") @Flags(identifier = {"a", "t", "mind", "maxd"}, description = {"Amount to spawn", "Tier to spawn", "Minimum durability", "Maximum durability"}) public void spawnSubcommand(CommandSender sender, @Arg(name = "amount", def = "1") @FlagArg("a") int amount, @Arg(name = "tier", def = "*") @FlagArg("t") String tierName, @Arg(name = "mindurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("mind") double minDura, @Arg(name = "maxdurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("maxd") double maxDura) { if (!(sender instanceof Player)) { getPlugin().getLanguageManager().sendMessage(sender, "command.no-access"); return; } Player player = (Player) sender; if (tierName.equalsIgnoreCase("*") && !sender.hasPermission("mythicdrops.command.give.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } Tier tier; try { if (tierName.equalsIgnoreCase("*")) { tier = null; } else { tier = plugin.getTierManager().getTierFromName(tierName); if (tier == null) { tier = plugin.getTierManager().getTierFromDisplayName(tierName); } } } catch (NullPointerException e) { getPlugin().getLanguageManager().sendMessage(player, "command.tier-does-not-exist"); return; } if (tier == null) { if (!player.hasPermission("mythicdrops.command.spawn.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } } else { if (!player.hasPermission("mythicdrops.command.spawn." + tier.getTierName().toLowerCase()) && !player .hasPermission("mythicdrops.command.spawn.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } } int amountGiven = 0; for (int i = 0; i < amount; i++) { try { ItemStack itemStack; if (tier == null) { itemStack = getPlugin().getDropManager().constructItemStackFromTier(getPlugin().getTierManager() .getRandomTierWithChance(), ItemGenerationReason.COMMAND); } else { itemStack = getPlugin().getDropManager().constructItemStackFromTier(tier, ItemGenerationReason.COMMAND); } itemStack.setDurability(ItemStackUtils.getDurabilityForMaterial(itemStack.getType(), minDura, maxDura)); player.getInventory().addItem(itemStack); amountGiven++; } catch (Exception ignored) { ignored.printStackTrace(); } } getPlugin().getLanguageManager().sendMessage(player, "command.spawn-random", new String[][]{{"%amount%", String.valueOf(amountGiven)}}); } @Command(identifier = "mythicdrops", description = "Basic MythicDrops command") public void baseCommand(CommandSender sender) { sender.sendMessage(ChatColor.GOLD + "<=-=-=-=-=-=-=-=-=-=-=-=-=-=-=>"); sender.sendMessage(ChatColor.GOLD + getPlugin().getName() + " " + ChatColor.GRAY + "v" + getPlugin() .getDescription().getVersion()); sender.sendMessage(ChatColor.GRAY + "Written by ToppleTheNun, Designed by pur3pow3r"); if (sender.hasPermission("mythicdrops.command.spawn")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops spawn (-a [amount]) (-t [tier]) (-mind [mindurability])" + " (-maxd [maxdurability])"}, {"%help%", "Spawns an amount of MythicDrops items (default " + "1) of a tier (* spawns random tiers) with durability between mindurability (default 1.0)" + " and maxdurability (default 1.0)"}}); } if (sender.hasPermission("mythicdrops.command.give")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops give [player] (-a [amount]) (-t [tier]) (-mind " + "[mindurability]) (-maxd [maxdurability])"}, {"%help%", "Gives an amount of MythicDrops" + " items (default 1) of a tier (* spawns random tiers) with durability between " + "mindurability (default 1.0) and maxdurability (default 1.0) to a player"}}); } if (sender.hasPermission("mythicdrops.command.custom")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops custom [player] (-a [amount]) (-c [item]) (-mind " + "[mindurability]) (-maxd [maxdurability])"}, {"%help%", "Gives an amount of MythicDrops" + " items (default 1) of a custom item (* spawns random items) with durability between " + "mindurability (default 1.0) and maxdurability (default 1.0) to a player (self is " + "command sender)"}}); } if (sender.hasPermission("mythicdrops.command.save")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops save"}, {"%help%", "Saves the configuration files"}}); } if (sender.hasPermission("mythicdrops.command.load")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops load"}, {"%help%", "Loads the configuration files"}}); } sender.sendMessage(ChatColor.GOLD + "<=-=-=-=-=-=-=-=-=-=-=-=-=-=-=>"); } }
src/main/java/net/nunnerycode/bukkit/mythicdrops/commands/MythicDropsCommand.java
package net.nunnerycode.bukkit.mythicdrops.commands; import net.nunnerycode.bukkit.mythicdrops.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import se.ranzdo.bukkit.methodcommand.Arg; import se.ranzdo.bukkit.methodcommand.Command; import se.ranzdo.bukkit.methodcommand.CommandHandler; import se.ranzdo.bukkit.methodcommand.FlagArg; import se.ranzdo.bukkit.methodcommand.Flags; public class MythicDropsCommand { private final MythicDrops plugin; private final CommandHandler commandHandler; public MythicDropsCommand(MythicDrops plugin) { this.plugin = plugin; commandHandler = new CommandHandler(this.plugin); commandHandler.registerCommands(this); } @Command(identifier = "mythicdrops save", description = "Saves the configuration files", permissions = "mythicdrops.command.save") public void saveSubcommand(CommandSender sender) { getPlugin().getSettingsSaver().save(); getPlugin().getLanguageSaver().save(); getPlugin().getCustomItemSaver().save(); getPlugin().getTierSaver().save(); getPlugin().getLanguageManager().sendMessage(sender, "command.save-config"); } public MythicDrops getPlugin() { return plugin; } @Command(identifier = "mythicdrops load", description = "Reloads the configuration files", permissions = "mythicdrops.command.load") public void loadSubcommand(CommandSender sender) { getPlugin().getSettingsLoader().load(); getPlugin().getLanguageLoader().load(); getPlugin().getCustomItemLoader().load(); getPlugin().getTierLoader().load(); getPlugin().getLanguageManager().sendMessage(sender, "command.reload-config"); } @Command(identifier = "mythicdrops reload", description = "Reloads the entire plugin", permissions = "mythicdrops.command.reload") public void reloadSubcommand(CommandSender sender) { getPlugin().reload(); getPlugin().getLanguageManager().sendMessage(sender, "command.reload-plugin"); } @Command(identifier = "mythicdrops give", description = "Gives MythicDrops items", permissions = "mythicdrops.command.give") @Flags(identifier = {"a", "t", "mind", "maxd"}, description = {"Amount to spawn", "Tier to spawn", "Minimum durability", "Maximum durability"}) public void giveSubcommand(CommandSender sender, @Arg(name = "player") Player player, @Arg(name = "amount", def = "1") @FlagArg("a") int amount, @Arg(name = "tier", def = "*") @FlagArg("t") String tierName, @Arg(name = "mindurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("mind") double minDura, @Arg(name = "maxdurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("maxd") double maxDura) { if (tierName.equalsIgnoreCase("*") && !sender.hasPermission("mythicdrops.command.give.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } Tier tier; try { if (tierName.equalsIgnoreCase("*")) { tier = null; } else { tier = plugin.getTierManager().getTierFromName(tierName); if (tier == null) { tier = plugin.getTierManager().getTierFromDisplayName(tierName); } } } catch (NullPointerException e) { getPlugin().getLanguageManager().sendMessage(player, "command.tier-does-not-exist"); return; } if (tier == null) { if (!player.hasPermission("mythicdrops.command.give.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } } else { if (!player.hasPermission("mythicdrops.command.give." + tier.getTierName().toLowerCase()) && !player .hasPermission("mythicdrops.command.give.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } } int amountGiven = 0; for (int i = 0; i < amount; i++) { try { ItemStack itemStack; if (tier == null) { itemStack = getPlugin().getDropManager().constructItemStackFromTier(getPlugin().getTierManager() .getRandomTierWithChance(), ItemGenerationReason.COMMAND); } else { itemStack = getPlugin().getDropManager().constructItemStackFromTier(tier, ItemGenerationReason.COMMAND); } itemStack.setDurability(ItemStackUtils.getDurabilityForMaterial(itemStack.getType(), minDura, maxDura)); player.getInventory().addItem(itemStack); amountGiven++; } catch (Exception ignored) { } } getPlugin().getLanguageManager().sendMessage(player, "command.give-random-receiver", new String[][]{{"%amount%", String.valueOf(amountGiven)}}); getPlugin().getLanguageManager().sendMessage(sender, "command.give-random-sender", new String[][]{{"%amount%", String.valueOf(amountGiven)}, {"%receiver%", player.getName()}}); } @Command(identifier = "mythicdrops custom", description = "Gives custom MythicDrops items", permissions = "mythicdrops.command.give") @Flags(identifier = {"a", "c", "mind", "maxd"}, description = {"Amount to spawn", "Custom Item to spawn", "Minimum durability", "Maximum durability"}) public void customSubcommand(CommandSender sender, @Arg(name = "player", def = "self") String playerName, @Arg(name = "amount", def = "1") @FlagArg("a") int amount, @Arg(name = "item", def = "*") @FlagArg("c") String itemName, @Arg(name = "mindurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("mind") double minDura, @Arg(name = "maxdurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("maxd") double maxDura) { if (!sender.hasPermission("mythicdrops.command.custom")) { getPlugin().getLanguageManager().sendMessage(sender, "command.no-access"); return; } Player player; if (playerName.equalsIgnoreCase("self")) { if (sender instanceof Player) { player = (Player) sender; } else { getPlugin().getLanguageManager().sendMessage(sender, "command.no-access"); return; } } else { player = Bukkit.getPlayer(playerName); } if (player == null) { getPlugin().getLanguageManager().sendMessage(sender, "command.player-does-not-exist"); return; } CustomItem customItem = null; if (!itemName.equalsIgnoreCase("*")) { try { customItem = getPlugin().getCustomItemManager().getCustomItemFromName(itemName); if (customItem == null) { customItem = getPlugin().getCustomItemManager().getCustomItemFromDisplayName(itemName); } } catch (NullPointerException e) { getPlugin().getLanguageManager().sendMessage(sender, "command.custom-item-does-not-exist"); return; } } int amountGiven = 0; for (int i = 0; i < amount; i++) { try { ItemStack itemStack; if (customItem == null) { itemStack = getPlugin().getDropManager().generateItemStackFromCustomItem(getPlugin() .getCustomItemManager().getRandomCustomItemWithChance(), ItemGenerationReason.COMMAND); } else { itemStack = getPlugin().getDropManager().generateItemStackFromCustomItem(customItem, ItemGenerationReason.COMMAND); } itemStack.setDurability(ItemStackUtils.getDurabilityForMaterial(itemStack.getType(), minDura, maxDura)); player.getInventory().addItem(itemStack); amountGiven++; } catch (Exception ignored) { } } getPlugin().getLanguageManager().sendMessage(player, "command.give-custom-receiver", new String[][]{{"%amount%", String.valueOf(amountGiven)}}); getPlugin().getLanguageManager().sendMessage(sender, "command.give-custom-sender", new String[][]{{"%amount%", String.valueOf(amountGiven)}, {"%receiver%", player.getName()}}); } @Command(identifier = "mythicdrops spawn", description = "Spawns in MythicDrops items", permissions = "mythicdrops.command.spawn") @Flags(identifier = {"a", "t", "mind", "maxd"}, description = {"Amount to spawn", "Tier to spawn", "Minimum durability", "Maximum durability"}) public void spawnSubcommand(CommandSender sender, @Arg(name = "amount", def = "1") @FlagArg("a") int amount, @Arg(name = "tier", def = "*") @FlagArg("t") String tierName, @Arg(name = "mindurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("mind") double minDura, @Arg(name = "maxdurability", def = "1.0", verifiers = "min[0.0]|max[1.0]") @FlagArg ("maxd") double maxDura) { if (!(sender instanceof Player)) { getPlugin().getLanguageManager().sendMessage(sender, "command.no-access"); return; } Player player = (Player) sender; if (tierName.equalsIgnoreCase("*") && !sender.hasPermission("mythicdrops.command.give.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } Tier tier; try { if (tierName.equalsIgnoreCase("*")) { tier = null; } else { tier = plugin.getTierManager().getTierFromName(tierName); if (tier == null) { tier = plugin.getTierManager().getTierFromDisplayName(tierName); } } } catch (NullPointerException e) { getPlugin().getLanguageManager().sendMessage(player, "command.tier-does-not-exist"); return; } if (tier == null) { if (!player.hasPermission("mythicdrops.command.spawn.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } } else { if (!player.hasPermission("mythicdrops.command.spawn." + tier.getTierName().toLowerCase()) && !player .hasPermission("mythicdrops.command.spawn.wildcard")) { getPlugin().getLanguageManager().sendMessage(player, "command.no-access"); return; } } int amountGiven = 0; for (int i = 0; i < amount; i++) { try { ItemStack itemStack; if (tier == null) { itemStack = getPlugin().getDropManager().constructItemStackFromTier(getPlugin().getTierManager() .getRandomTierWithChance(), ItemGenerationReason.COMMAND); } else { itemStack = getPlugin().getDropManager().constructItemStackFromTier(tier, ItemGenerationReason.COMMAND); } itemStack.setDurability(ItemStackUtils.getDurabilityForMaterial(itemStack.getType(), minDura, maxDura)); player.getInventory().addItem(itemStack); amountGiven++; } catch (Exception ignored) { } } getPlugin().getLanguageManager().sendMessage(player, "command.spawn-random", new String[][]{{"%amount%", String.valueOf(amountGiven)}}); } @Command(identifier = "mythicdrops", description = "Basic MythicDrops command") public void baseCommand(CommandSender sender) { sender.sendMessage(ChatColor.GOLD + "<=-=-=-=-=-=-=-=-=-=-=-=-=-=-=>"); sender.sendMessage(ChatColor.GOLD + getPlugin().getName() + " " + ChatColor.GRAY + "v" + getPlugin() .getDescription().getVersion()); sender.sendMessage(ChatColor.GRAY + "Written by ToppleTheNun, Designed by pur3pow3r"); if (sender.hasPermission("mythicdrops.command.spawn")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops spawn (-a [amount]) (-t [tier]) (-mind [mindurability])" + " (-maxd [maxdurability])"}, {"%help%", "Spawns an amount of MythicDrops items (default " + "1) of a tier (* spawns random tiers) with durability between mindurability (default 1.0)" + " and maxdurability (default 1.0)"}}); } if (sender.hasPermission("mythicdrops.command.give")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops give [player] (-a [amount]) (-t [tier]) (-mind " + "[mindurability]) (-maxd [maxdurability])"}, {"%help%", "Gives an amount of MythicDrops" + " items (default 1) of a tier (* spawns random tiers) with durability between " + "mindurability (default 1.0) and maxdurability (default 1.0) to a player"}}); } if (sender.hasPermission("mythicdrops.command.custom")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops custom [player] (-a [amount]) (-c [item]) (-mind " + "[mindurability]) (-maxd [maxdurability])"}, {"%help%", "Gives an amount of MythicDrops" + " items (default 1) of a custom item (* spawns random items) with durability between " + "mindurability (default 1.0) and maxdurability (default 1.0) to a player (self is " + "command sender)"}}); } if (sender.hasPermission("mythicdrops.command.save")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops save"}, {"%help%", "Saves the configuration files"}}); } if (sender.hasPermission("mythicdrops.command.load")) { getPlugin().getLanguageManager().sendMessage(sender, "command.command-help", new String[][]{{"%command%", "mythicdrops load"}, {"%help%", "Loads the configuration files"}}); } sender.sendMessage(ChatColor.GOLD + "<=-=-=-=-=-=-=-=-=-=-=-=-=-=-=>"); } }
build for Faceguy to do test with
src/main/java/net/nunnerycode/bukkit/mythicdrops/commands/MythicDropsCommand.java
build for Faceguy to do test with
<ide><path>rc/main/java/net/nunnerycode/bukkit/mythicdrops/commands/MythicDropsCommand.java <ide> player.getInventory().addItem(itemStack); <ide> amountGiven++; <ide> } catch (Exception ignored) { <add> ignored.printStackTrace(); <ide> } <ide> } <ide> getPlugin().getLanguageManager().sendMessage(player, "command.give-random-receiver", <ide> player.getInventory().addItem(itemStack); <ide> amountGiven++; <ide> } catch (Exception ignored) { <add> ignored.printStackTrace(); <ide> } <ide> } <ide> getPlugin().getLanguageManager().sendMessage(player, "command.give-custom-receiver", <ide> player.getInventory().addItem(itemStack); <ide> amountGiven++; <ide> } catch (Exception ignored) { <add> ignored.printStackTrace(); <ide> } <ide> } <ide> getPlugin().getLanguageManager().sendMessage(player, "command.spawn-random",
Java
bsd-3-clause
error: pathspec 'src/main/java/skadistats/clarity/examples/allchat/AllChatProcessor.java' did not match any file(s) known to git
cdeb415f87b988863867d5a06620441377922f1e
1
skadistats/clarity-examples
package skadistats.clarity.examples.allchat; import skadistats.clarity.processor.reader.OnMessage; import skadistats.clarity.processor.runner.Context; import skadistats.clarity.processor.runner.SimpleRunner; import skadistats.clarity.source.MappedFileSource; import skadistats.clarity.source.Source; import skadistats.clarity.wire.s2.proto.S2UserMessages; public class AllChatProcessor { @OnMessage(S2UserMessages.CUserMessageSayText2.class) public void onMessage(Context ctx, S2UserMessages.CUserMessageSayText2 message) { System.out.format("%s: %s\n", message.getParam1(), message.getParam2()); } public static void main(String[] args) throws Exception { // 1) create an input source from the replay Source source = new MappedFileSource("replay.dem"); // 2) create a simple runner that will read the replay once SimpleRunner runner = new SimpleRunner(source); // 3) create an instance of your processor AllChatProcessor processor = new AllChatProcessor(); // 4) and hand it over to the runner runner.runWith(processor); } }
src/main/java/skadistats/clarity/examples/allchat/AllChatProcessor.java
add readme example processor as real source
src/main/java/skadistats/clarity/examples/allchat/AllChatProcessor.java
add readme example processor as real source
<ide><path>rc/main/java/skadistats/clarity/examples/allchat/AllChatProcessor.java <add>package skadistats.clarity.examples.allchat; <add> <add>import skadistats.clarity.processor.reader.OnMessage; <add>import skadistats.clarity.processor.runner.Context; <add>import skadistats.clarity.processor.runner.SimpleRunner; <add>import skadistats.clarity.source.MappedFileSource; <add>import skadistats.clarity.source.Source; <add>import skadistats.clarity.wire.s2.proto.S2UserMessages; <add> <add>public class AllChatProcessor { <add> @OnMessage(S2UserMessages.CUserMessageSayText2.class) <add> public void onMessage(Context ctx, S2UserMessages.CUserMessageSayText2 message) { <add> System.out.format("%s: %s\n", message.getParam1(), message.getParam2()); <add> } <add> public static void main(String[] args) throws Exception { <add> // 1) create an input source from the replay <add> Source source = new MappedFileSource("replay.dem"); <add> // 2) create a simple runner that will read the replay once <add> SimpleRunner runner = new SimpleRunner(source); <add> // 3) create an instance of your processor <add> AllChatProcessor processor = new AllChatProcessor(); <add> // 4) and hand it over to the runner <add> runner.runWith(processor); <add> } <add> <add>}
JavaScript
apache-2.0
0201655538d44c05e0135e6db92caf060ee166e7
0
matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk
/* Copyright 2018, 2019 New Vector Ltd Copyright 2020 The Matrix.org Foundation C.I.C. 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. */ import React from 'react'; import PropTypes from 'prop-types'; import * as sdk from '../../../../index'; import {MatrixClientPeg} from '../../../../MatrixClientPeg'; import { MatrixClient } from 'matrix-js-sdk'; import Modal from '../../../../Modal'; import { _t } from '../../../../languageHandler'; import { accessSecretStorage } from '../../../../CrossSigningManager'; import SettingsStore from "../../../../settings/SettingsStore"; const RESTORE_TYPE_PASSPHRASE = 0; const RESTORE_TYPE_RECOVERYKEY = 1; const RESTORE_TYPE_SECRET_STORAGE = 2; /* * Dialog for restoring e2e keys from a backup and the user's recovery key */ export default class RestoreKeyBackupDialog extends React.PureComponent { static propTypes = { // if false, will close the dialog as soon as the restore completes succesfully // default: true showSummary: PropTypes.bool, // If specified, gather the key from the user but then call the function with the backup // key rather than actually (necessarily) restoring the backup. keyCallback: PropTypes.func, }; static defaultProps = { showSummary: true, }; constructor(props) { super(props); this.state = { backupInfo: null, backupKeyStored: null, loading: false, loadError: null, restoreError: null, recoveryKey: "", recoverInfo: null, recoveryKeyValid: false, forceRecoveryKey: false, passPhrase: '', restoreType: null, progress: { stage: "prefetch" }, }; } componentDidMount() { this._loadBackupStatus(); } _onCancel = () => { this.props.onFinished(false); } _onDone = () => { this.props.onFinished(true); } _onUseRecoveryKeyClick = () => { this.setState({ forceRecoveryKey: true, }); } _progressCallback = (data) => { this.setState({ progress: data, }); } _onResetRecoveryClick = () => { this.props.onFinished(false); if (SettingsStore.getValue("feature_cross_signing")) { // If cross-signing is enabled, we reset the SSSS recovery passphrase (and cross-signing keys) this.props.onFinished(false); accessSecretStorage(() => {}, /* forceReset = */ true); } else { Modal.createTrackedDialogAsync('Key Backup', 'Key Backup', import('../../../../async-components/views/dialogs/keybackup/CreateKeyBackupDialog'), { onFinished: () => { this._loadBackupStatus(); }, }, null, /* priority = */ false, /* static = */ true, ); } } _onRecoveryKeyChange = (e) => { this.setState({ recoveryKey: e.target.value, recoveryKeyValid: MatrixClientPeg.get().isValidRecoveryKey(e.target.value), }); } _onPassPhraseNext = async () => { this.setState({ loading: true, restoreError: null, restoreType: RESTORE_TYPE_PASSPHRASE, }); try { // We do still restore the key backup: we must ensure that the key backup key // is the right one and restoring it is currently the only way we can do this. const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithPassword( this.state.passPhrase, undefined, undefined, this.state.backupInfo, { progressCallback: this._progressCallback }, ); if (this.props.keyCallback) { const key = await MatrixClientPeg.get().keyBackupKeyFromPassword( this.state.passPhrase, this.state.backupInfo, ); this.props.keyCallback(key); } if (!this.props.showSummary) { this.props.onFinished(true); return; } this.setState({ loading: false, recoverInfo, }); } catch (e) { console.log("Error restoring backup", e); this.setState({ loading: false, restoreError: e, }); } } _onRecoveryKeyNext = async () => { if (!this.state.recoveryKeyValid) return; this.setState({ loading: true, restoreError: null, restoreType: RESTORE_TYPE_RECOVERYKEY, }); try { const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithRecoveryKey( this.state.recoveryKey, undefined, undefined, this.state.backupInfo, { progressCallback: this._progressCallback }, ); if (this.props.keyCallback) { const key = MatrixClientPeg.get().keyBackupKeyFromRecoveryKey(this.state.recoveryKey); this.props.keyCallback(key); } if (!this.props.showSummary) { this.props.onFinished(true); return; } this.setState({ loading: false, recoverInfo, }); } catch (e) { console.log("Error restoring backup", e); this.setState({ loading: false, restoreError: e, }); } } _onPassPhraseChange = (e) => { this.setState({ passPhrase: e.target.value, }); } async _restoreWithSecretStorage() { this.setState({ loading: true, restoreError: null, restoreType: RESTORE_TYPE_SECRET_STORAGE, }); try { // `accessSecretStorage` may prompt for storage access as needed. const recoverInfo = await accessSecretStorage(async () => { return MatrixClientPeg.get().restoreKeyBackupWithSecretStorage( this.state.backupInfo, undefined, undefined, { progressCallback: this._progressCallback }, ); }); this.setState({ loading: false, recoverInfo, }); } catch (e) { console.log("Error restoring backup", e); this.setState({ restoreError: e, loading: false, }); } } async _restoreWithCachedKey(backupInfo) { if (!backupInfo) return false; try { const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithCache( undefined, /* targetRoomId */ undefined, /* targetSessionId */ backupInfo, { progressCallback: this._progressCallback }, ); this.setState({ recoverInfo, }); return true; } catch (e) { console.log("restoreWithCachedKey failed:", e); return false; } } async _loadBackupStatus() { this.setState({ loading: true, loadError: null, }); try { const backupInfo = await MatrixClientPeg.get().getKeyBackupVersion(); const backupKeyStored = await MatrixClientPeg.get().isKeyBackupKeyStored(); this.setState({ backupInfo, backupKeyStored, }); const gotCache = await this._restoreWithCachedKey(backupInfo); if (gotCache) { console.log("RestoreKeyBackupDialog: found cached backup key"); this.setState({ loading: false, }); return; } // If the backup key is stored, we can proceed directly to restore. if (backupKeyStored) { return this._restoreWithSecretStorage(); } this.setState({ loadError: null, loading: false, }); } catch (e) { console.log("Error loading backup status", e); this.setState({ loadError: e, loading: false, }); } } render() { const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog'); const Spinner = sdk.getComponent("elements.Spinner"); const backupHasPassphrase = ( this.state.backupInfo && this.state.backupInfo.auth_data && this.state.backupInfo.auth_data.private_key_salt && this.state.backupInfo.auth_data.private_key_iterations ); let content; let title; if (this.state.loading) { title = _t("Restoring keys from backup"); let details; if (this.state.progress.stage === "fetch") { details = _t("Fetching keys from server..."); } else if (this.state.progress.stage === "load_keys") { const { total, successes, failures } = this.state.progress; details = _t("%(completed)s of %(total)s keys restored", { total, completed: successes + failures }); } else if (this.state.progress.stage === "prefetch") { details = _t("Fetching keys from server..."); } content = <div> <div>{details}</div> <Spinner /> </div>; } else if (this.state.loadError) { title = _t("Error"); content = _t("Unable to load backup status"); } else if (this.state.restoreError) { if (this.state.restoreError.errcode === MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY) { if (this.state.restoreType === RESTORE_TYPE_RECOVERYKEY) { title = _t("Recovery key mismatch"); content = <div> <p>{_t( "Backup could not be decrypted with this recovery key: " + "please verify that you entered the correct recovery key.", )}</p> </div>; } else { title = _t("Incorrect recovery passphrase"); content = <div> <p>{_t( "Backup could not be decrypted with this recovery passphrase: " + "please verify that you entered the correct recovery passphrase.", )}</p> </div>; } } else { title = _t("Error"); content = _t("Unable to restore backup"); } } else if (this.state.backupInfo === null) { title = _t("Error"); content = _t("No backup found!"); } else if (this.state.recoverInfo) { const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); title = _t("Keys restored"); let failedToDecrypt; if (this.state.recoverInfo.total > this.state.recoverInfo.imported) { failedToDecrypt = <p>{_t( "Failed to decrypt %(failedCount)s sessions!", {failedCount: this.state.recoverInfo.total - this.state.recoverInfo.imported}, )}</p>; } content = <div> <p>{_t("Successfully restored %(sessionCount)s keys", {sessionCount: this.state.recoverInfo.imported})}</p> {failedToDecrypt} <DialogButtons primaryButton={_t('OK')} onPrimaryButtonClick={this._onDone} hasCancel={false} focus={true} /> </div>; } else if (backupHasPassphrase && !this.state.forceRecoveryKey) { const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); title = _t("Enter recovery passphrase"); content = <div> <p>{_t( "<b>Warning</b>: you should only set up key backup " + "from a trusted computer.", {}, { b: sub => <b>{sub}</b> }, )}</p> <p>{_t( "Access your secure message history and set up secure " + "messaging by entering your recovery passphrase.", )}</p> <form className="mx_RestoreKeyBackupDialog_primaryContainer"> <input type="password" className="mx_RestoreKeyBackupDialog_passPhraseInput" onChange={this._onPassPhraseChange} value={this.state.passPhrase} autoFocus={true} /> <DialogButtons primaryButton={_t('Next')} onPrimaryButtonClick={this._onPassPhraseNext} primaryIsSubmit={true} hasCancel={true} onCancel={this._onCancel} focus={false} /> </form> {_t( "If you've forgotten your recovery passphrase you can "+ "<button1>use your recovery key</button1> or " + "<button2>set up new recovery options</button2>" , {}, { button1: s => <AccessibleButton className="mx_linkButton" element="span" onClick={this._onUseRecoveryKeyClick} > {s} </AccessibleButton>, button2: s => <AccessibleButton className="mx_linkButton" element="span" onClick={this._onResetRecoveryClick} > {s} </AccessibleButton>, })} </div>; } else { title = _t("Enter recovery key"); const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); let keyStatus; if (this.state.recoveryKey.length === 0) { keyStatus = <div className="mx_RestoreKeyBackupDialog_keyStatus"></div>; } else if (this.state.recoveryKeyValid) { keyStatus = <div className="mx_RestoreKeyBackupDialog_keyStatus"> {"\uD83D\uDC4D "}{_t("This looks like a valid recovery key!")} </div>; } else { keyStatus = <div className="mx_RestoreKeyBackupDialog_keyStatus"> {"\uD83D\uDC4E "}{_t("Not a valid recovery key")} </div>; } content = <div> <p>{_t( "<b>Warning</b>: You should only set up key backup " + "from a trusted computer.", {}, { b: sub => <b>{sub}</b> }, )}</p> <p>{_t( "Access your secure message history and set up secure " + "messaging by entering your recovery key.", )}</p> <div className="mx_RestoreKeyBackupDialog_primaryContainer"> <input className="mx_RestoreKeyBackupDialog_recoveryKeyInput" onChange={this._onRecoveryKeyChange} value={this.state.recoveryKey} autoFocus={true} /> {keyStatus} <DialogButtons primaryButton={_t('Next')} onPrimaryButtonClick={this._onRecoveryKeyNext} hasCancel={true} onCancel={this._onCancel} focus={false} primaryDisabled={!this.state.recoveryKeyValid} /> </div> {_t( "If you've forgotten your recovery key you can "+ "<button>set up new recovery options</button>" , {}, { button: s => <AccessibleButton className="mx_linkButton" element="span" onClick={this._onResetRecoveryClick} > {s} </AccessibleButton>, })} </div>; } return ( <BaseDialog className='mx_RestoreKeyBackupDialog' onFinished={this.props.onFinished} title={title} > <div className='mx_RestoreKeyBackupDialog_content'> {content} </div> </BaseDialog> ); } }
src/components/views/dialogs/keybackup/RestoreKeyBackupDialog.js
/* Copyright 2018, 2019 New Vector Ltd Copyright 2020 The Matrix.org Foundation C.I.C. 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. */ import React from 'react'; import PropTypes from 'prop-types'; import * as sdk from '../../../../index'; import {MatrixClientPeg} from '../../../../MatrixClientPeg'; import { MatrixClient } from 'matrix-js-sdk'; import Modal from '../../../../Modal'; import { _t } from '../../../../languageHandler'; import { accessSecretStorage } from '../../../../CrossSigningManager'; import SettingsStore from "../../../../settings/SettingsStore"; const RESTORE_TYPE_PASSPHRASE = 0; const RESTORE_TYPE_RECOVERYKEY = 1; const RESTORE_TYPE_SECRET_STORAGE = 2; /* * Dialog for restoring e2e keys from a backup and the user's recovery key */ export default class RestoreKeyBackupDialog extends React.PureComponent { static propTypes = { // if false, will close the dialog as soon as the restore completes succesfully // default: true showSummary: PropTypes.bool, // If specified, gather the key from the user but then call the function with the backup // key rather than actually (necessarily) restoring the backup. keyCallback: PropTypes.func, }; static defaultProps = { showSummary: true, }; constructor(props) { super(props); this.state = { backupInfo: null, backupKeyStored: null, loading: false, loadError: null, restoreError: null, recoveryKey: "", recoverInfo: null, recoveryKeyValid: false, forceRecoveryKey: false, passPhrase: '', restoreType: null, progress: { stage: "prefetch" }, }; } componentDidMount() { this._loadBackupStatus(); } _onCancel = () => { this.props.onFinished(false); } _onDone = () => { this.props.onFinished(true); } _onUseRecoveryKeyClick = () => { this.setState({ forceRecoveryKey: true, }); } _progressCallback = (data) => { this.setState({ progress: data, }); } _onResetRecoveryClick = () => { this.props.onFinished(false); if (SettingsStore.getValue("feature_cross_signing")) { // If cross-signing is enabled, we reset the SSSS recovery passphrase (and cross-signing keys) this.props.onFinished(false); accessSecretStorage(() => {}, /* forceReset = */ true); } else { Modal.createTrackedDialogAsync('Key Backup', 'Key Backup', import('../../../../async-components/views/dialogs/keybackup/CreateKeyBackupDialog'), { onFinished: () => { this._loadBackupStatus(); }, }, null, /* priority = */ false, /* static = */ true, ); } } _onRecoveryKeyChange = (e) => { this.setState({ recoveryKey: e.target.value, recoveryKeyValid: MatrixClientPeg.get().isValidRecoveryKey(e.target.value), }); } _onPassPhraseNext = async () => { this.setState({ loading: true, restoreError: null, restoreType: RESTORE_TYPE_PASSPHRASE, }); try { // We do still restore the key backup: we must ensure that the key backup key // is the right one and restoring it is currently the only way we can do this. const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithPassword( this.state.passPhrase, undefined, undefined, this.state.backupInfo, { progressCallback: this._progressCallback }, ); if (this.props.keyCallback) { const key = await MatrixClientPeg.get().keyBackupKeyFromPassword( this.state.passPhrase, this.state.backupInfo, ); this.props.keyCallback(key); } if (!this.props.showSummary) { this.props.onFinished(true); return; } this.setState({ loading: false, recoverInfo, }); } catch (e) { console.log("Error restoring backup", e); this.setState({ loading: false, restoreError: e, }); } } _onRecoveryKeyNext = async () => { if (!this.state.recoveryKeyValid) return; this.setState({ loading: true, restoreError: null, restoreType: RESTORE_TYPE_RECOVERYKEY, }); try { const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithRecoveryKey( this.state.recoveryKey, undefined, undefined, this.state.backupInfo, { progressCallback: this._progressCallback }, ); if (this.props.keyCallback) { const key = MatrixClientPeg.get().keyBackupKeyFromRecoveryKey(this.state.recoveryKey); this.props.keyCallback(key); } if (!this.props.showSummary) { this.props.onFinished(true); return; } this.setState({ loading: false, recoverInfo, }); } catch (e) { console.log("Error restoring backup", e); this.setState({ loading: false, restoreError: e, }); } } _onPassPhraseChange = (e) => { this.setState({ passPhrase: e.target.value, }); } async _restoreWithSecretStorage() { this.setState({ loading: true, restoreError: null, restoreType: RESTORE_TYPE_SECRET_STORAGE, }); try { // `accessSecretStorage` may prompt for storage access as needed. const recoverInfo = await accessSecretStorage(async () => { return MatrixClientPeg.get().restoreKeyBackupWithSecretStorage( this.state.backupInfo, { progressCallback: this._progressCallback }, ); }); this.setState({ loading: false, recoverInfo, }); } catch (e) { console.log("Error restoring backup", e); this.setState({ restoreError: e, loading: false, }); } } async _restoreWithCachedKey(backupInfo) { if (!backupInfo) return false; try { const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithCache( undefined, /* targetRoomId */ undefined, /* targetSessionId */ backupInfo, { progressCallback: this._progressCallback }, ); this.setState({ recoverInfo, }); return true; } catch (e) { console.log("restoreWithCachedKey failed:", e); return false; } } async _loadBackupStatus() { this.setState({ loading: true, loadError: null, }); try { const backupInfo = await MatrixClientPeg.get().getKeyBackupVersion(); const backupKeyStored = await MatrixClientPeg.get().isKeyBackupKeyStored(); this.setState({ backupInfo, backupKeyStored, }); const gotCache = await this._restoreWithCachedKey(backupInfo); if (gotCache) { console.log("RestoreKeyBackupDialog: found cached backup key"); this.setState({ loading: false, }); return; } // If the backup key is stored, we can proceed directly to restore. if (backupKeyStored) { return this._restoreWithSecretStorage(); } this.setState({ loadError: null, loading: false, }); } catch (e) { console.log("Error loading backup status", e); this.setState({ loadError: e, loading: false, }); } } render() { const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog'); const Spinner = sdk.getComponent("elements.Spinner"); const backupHasPassphrase = ( this.state.backupInfo && this.state.backupInfo.auth_data && this.state.backupInfo.auth_data.private_key_salt && this.state.backupInfo.auth_data.private_key_iterations ); let content; let title; if (this.state.loading) { title = _t("Restoring keys from backup"); let details; if (this.state.progress.stage === "fetch") { details = _t("Fetching keys from server..."); } else if (this.state.progress.stage === "load_keys") { const { total, successes, failures } = this.state.progress; details = _t("%(completed)s of %(total)s keys restored", { total, completed: successes + failures }); } else if (this.state.progress.stage === "prefetch") { details = _t("Fetching keys from server..."); } content = <div> <div>{details}</div> <Spinner /> </div>; } else if (this.state.loadError) { title = _t("Error"); content = _t("Unable to load backup status"); } else if (this.state.restoreError) { if (this.state.restoreError.errcode === MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY) { if (this.state.restoreType === RESTORE_TYPE_RECOVERYKEY) { title = _t("Recovery key mismatch"); content = <div> <p>{_t( "Backup could not be decrypted with this recovery key: " + "please verify that you entered the correct recovery key.", )}</p> </div>; } else { title = _t("Incorrect recovery passphrase"); content = <div> <p>{_t( "Backup could not be decrypted with this recovery passphrase: " + "please verify that you entered the correct recovery passphrase.", )}</p> </div>; } } else { title = _t("Error"); content = _t("Unable to restore backup"); } } else if (this.state.backupInfo === null) { title = _t("Error"); content = _t("No backup found!"); } else if (this.state.recoverInfo) { const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); title = _t("Keys restored"); let failedToDecrypt; if (this.state.recoverInfo.total > this.state.recoverInfo.imported) { failedToDecrypt = <p>{_t( "Failed to decrypt %(failedCount)s sessions!", {failedCount: this.state.recoverInfo.total - this.state.recoverInfo.imported}, )}</p>; } content = <div> <p>{_t("Successfully restored %(sessionCount)s keys", {sessionCount: this.state.recoverInfo.imported})}</p> {failedToDecrypt} <DialogButtons primaryButton={_t('OK')} onPrimaryButtonClick={this._onDone} hasCancel={false} focus={true} /> </div>; } else if (backupHasPassphrase && !this.state.forceRecoveryKey) { const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); title = _t("Enter recovery passphrase"); content = <div> <p>{_t( "<b>Warning</b>: you should only set up key backup " + "from a trusted computer.", {}, { b: sub => <b>{sub}</b> }, )}</p> <p>{_t( "Access your secure message history and set up secure " + "messaging by entering your recovery passphrase.", )}</p> <form className="mx_RestoreKeyBackupDialog_primaryContainer"> <input type="password" className="mx_RestoreKeyBackupDialog_passPhraseInput" onChange={this._onPassPhraseChange} value={this.state.passPhrase} autoFocus={true} /> <DialogButtons primaryButton={_t('Next')} onPrimaryButtonClick={this._onPassPhraseNext} primaryIsSubmit={true} hasCancel={true} onCancel={this._onCancel} focus={false} /> </form> {_t( "If you've forgotten your recovery passphrase you can "+ "<button1>use your recovery key</button1> or " + "<button2>set up new recovery options</button2>" , {}, { button1: s => <AccessibleButton className="mx_linkButton" element="span" onClick={this._onUseRecoveryKeyClick} > {s} </AccessibleButton>, button2: s => <AccessibleButton className="mx_linkButton" element="span" onClick={this._onResetRecoveryClick} > {s} </AccessibleButton>, })} </div>; } else { title = _t("Enter recovery key"); const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); let keyStatus; if (this.state.recoveryKey.length === 0) { keyStatus = <div className="mx_RestoreKeyBackupDialog_keyStatus"></div>; } else if (this.state.recoveryKeyValid) { keyStatus = <div className="mx_RestoreKeyBackupDialog_keyStatus"> {"\uD83D\uDC4D "}{_t("This looks like a valid recovery key!")} </div>; } else { keyStatus = <div className="mx_RestoreKeyBackupDialog_keyStatus"> {"\uD83D\uDC4E "}{_t("Not a valid recovery key")} </div>; } content = <div> <p>{_t( "<b>Warning</b>: You should only set up key backup " + "from a trusted computer.", {}, { b: sub => <b>{sub}</b> }, )}</p> <p>{_t( "Access your secure message history and set up secure " + "messaging by entering your recovery key.", )}</p> <div className="mx_RestoreKeyBackupDialog_primaryContainer"> <input className="mx_RestoreKeyBackupDialog_recoveryKeyInput" onChange={this._onRecoveryKeyChange} value={this.state.recoveryKey} autoFocus={true} /> {keyStatus} <DialogButtons primaryButton={_t('Next')} onPrimaryButtonClick={this._onRecoveryKeyNext} hasCancel={true} onCancel={this._onCancel} focus={false} primaryDisabled={!this.state.recoveryKeyValid} /> </div> {_t( "If you've forgotten your recovery key you can "+ "<button>set up new recovery options</button>" , {}, { button: s => <AccessibleButton className="mx_linkButton" element="span" onClick={this._onResetRecoveryClick} > {s} </AccessibleButton>, })} </div>; } return ( <BaseDialog className='mx_RestoreKeyBackupDialog' onFinished={this.props.onFinished} title={title} > <div className='mx_RestoreKeyBackupDialog_content'> {content} </div> </BaseDialog> ); } }
Fix key backup restore with SSSS The room / session ID params come after the backupInfo for restoring from SSSS so the options object was being passed into the wrong param. Roll on TypeScript. This meant restoring backups worked fine when the key was cached but failed when it wasn't. Regressed in https://github.com/matrix-org/matrix-react-sdk/pull/4507
src/components/views/dialogs/keybackup/RestoreKeyBackupDialog.js
Fix key backup restore with SSSS
<ide><path>rc/components/views/dialogs/keybackup/RestoreKeyBackupDialog.js <ide> // `accessSecretStorage` may prompt for storage access as needed. <ide> const recoverInfo = await accessSecretStorage(async () => { <ide> return MatrixClientPeg.get().restoreKeyBackupWithSecretStorage( <del> this.state.backupInfo, <add> this.state.backupInfo, undefined, undefined, <ide> { progressCallback: this._progressCallback }, <ide> ); <ide> });
Java
apache-2.0
52150847151e67129c4ae282d29ab2c770c38dd8
0
DBCG/cql_engine,DBCG/cql_engine
package org.opencds.cqf.cql.elm.execution; import org.opencds.cqf.cql.data.DataProvider; import org.opencds.cqf.cql.execution.Context; import org.opencds.cqf.cql.runtime.Code; import org.opencds.cqf.cql.runtime.Concept; import org.opencds.cqf.cql.runtime.Interval; import org.cqframework.cql.elm.execution.ValueSetRef; import org.cqframework.cql.elm.execution.ValueSetDef; import java.util.ArrayList; import java.util.List; /** * Created by Bryn on 5/25/2016. */ public class RetrieveEvaluator extends org.cqframework.cql.elm.execution.Retrieve { public Object evaluate(Context context) { DataProvider dataProvider = context.resolveDataProvider(this.dataType); Iterable<Code> codes = null; String valueSet = null; if (this.getCodes() != null) { if (this.getCodes() instanceof ValueSetRef) { ValueSetRef valueSetRef = (ValueSetRef)this.getCodes(); ValueSetDef valueSetDef = context.resolveValueSetRef(valueSetRef.getLibraryName(), valueSetRef.getName()); // TODO: Handle value set versions..... valueSet = valueSetDef.getId(); } else { Object codesResult = this.getCodes().evaluate(context); if (codesResult instanceof Code) { ArrayList<Code> codesList = new ArrayList<>(); codesList.add((Code)codesResult); codes = codesList; } else if (codesResult instanceof Concept) { ArrayList<Code> codesList = new ArrayList<>(); for (Code conceptCode : ((Concept)codesResult).getCodes()) { codesList.add(conceptCode); } codes = codesList; } else { codes = (Iterable<Code>) this.getCodes().evaluate(context); } } } Interval dateRange = null; if (this.getDateRange() != null) { dateRange = (Interval)this.getDateRange().evaluate(context); } Object result = dataProvider.retrieve(context.getCurrentContext(), context.getCurrentContextValue(), getDataType().getLocalPart(), getTemplateId(), getCodeProperty(), codes, valueSet, getDateProperty(), getDateLowProperty(), getDateHighProperty(), dateRange); //append list results to evaluatedResources list if (result instanceof List) { for (Object element : (List)result) { context.getEvaluatedResources().add(element); } } else { context.getEvaluatedResources().add(result); } return result; } }
cql-engine/src/main/java/org/opencds/cqf/cql/elm/execution/RetrieveEvaluator.java
package org.opencds.cqf.cql.elm.execution; import org.opencds.cqf.cql.data.DataProvider; import org.opencds.cqf.cql.execution.Context; import org.opencds.cqf.cql.runtime.Code; import org.opencds.cqf.cql.runtime.Concept; import org.opencds.cqf.cql.runtime.Interval; import org.cqframework.cql.elm.execution.ValueSetRef; import org.cqframework.cql.elm.execution.ValueSetDef; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Created by Bryn on 5/25/2016. */ public class RetrieveEvaluator extends org.cqframework.cql.elm.execution.Retrieve { public Object evaluate(Context context) { DataProvider dataProvider = context.resolveDataProvider(this.dataType); Iterable<Code> codes = null; String valueSet = null; if (this.getCodes() != null) { if (this.getCodes() instanceof ValueSetRef) { ValueSetRef valueSetRef = (ValueSetRef)this.getCodes(); ValueSetDef valueSetDef = context.resolveValueSetRef(valueSetRef.getLibraryName(), valueSetRef.getName()); // TODO: Handle value set versions..... valueSet = valueSetDef.getId(); } else { Object codesResult = this.getCodes().evaluate(context); if (codesResult instanceof Code) { ArrayList<Code> codesList = new ArrayList<>(); codesList.add((Code)codesResult); codes = codesList; } else if (codesResult instanceof Concept) { ArrayList<Code> codesList = new ArrayList<>(); for (Code conceptCode : ((Concept)codesResult).getCodes()) { codesList.add(conceptCode); } codes = codesList; } else { codes = (Iterable<Code>) this.getCodes().evaluate(context); } } } Interval dateRange = null; if (this.getDateRange() != null) { dateRange = (Interval)this.getDateRange().evaluate(context); } Object result = dataProvider.retrieve(context.getCurrentContext(), context.getCurrentContextValue(), getDataType().getLocalPart(), getTemplateId(), getCodeProperty(), codes, valueSet, getDateProperty(), getDateLowProperty(), getDateHighProperty(), dateRange); //append list results to evaluatedResources list if (result instanceof List) { for (Object element : (List)result) { context.getEvaluatedResources().add(element); } } else { context.getEvaluatedResources().add(result); } return result; } }
Removed unneeded imports
cql-engine/src/main/java/org/opencds/cqf/cql/elm/execution/RetrieveEvaluator.java
Removed unneeded imports
<ide><path>ql-engine/src/main/java/org/opencds/cqf/cql/elm/execution/RetrieveEvaluator.java <ide> import org.cqframework.cql.elm.execution.ValueSetRef; <ide> import org.cqframework.cql.elm.execution.ValueSetDef; <ide> <del>import java.lang.reflect.Method; <add> <ide> import java.util.ArrayList; <ide> import java.util.List; <del>import java.util.Locale; <ide> <ide> /** <ide> * Created by Bryn on 5/25/2016.
Java
apache-2.0
2e12e8cbcdfc127c3936936b82e8e0b61ec1c944
0
whitesource/fs-agent,whitesource/fs-agent,whitesource/fs-agent,whitesource/fs-agent,whitesource/fs-agent,whitesource/fs-agent
package org.whitesource.agent.dependency.resolver.python; import org.apache.commons.lang.StringUtils; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whitesource.agent.api.model.AgentProjectInfo; import org.whitesource.agent.api.model.DependencyInfo; import org.whitesource.agent.api.model.DependencyType; import org.whitesource.agent.dependency.resolver.DependencyCollector; import org.whitesource.agent.hash.ChecksumUtils; import org.whitesource.agent.utils.CommandLineProcess; import org.whitesource.agent.utils.FilesUtils; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; /** * @author raz.nitzan */ public class PythonDependencyCollector extends DependencyCollector { /* -- Members -- */ private boolean installVirtualEnv; private boolean resolveHierarchyTree; private boolean ignorePipInstallErrors; private String requirementsTxtPath; private String pythonPath; private String pipPath; private String tempDirPackages; private String tempDirVirtualenv; private String topLevelFolder; private AtomicInteger counterFolders = new AtomicInteger(0); private final Logger logger = LoggerFactory.getLogger(org.whitesource.agent.dependency.resolver.python.PythonDependencyResolver.class); /* --- Static members --- */ private static final String VIRTUALENV = "virtualenv"; private static final String USER = "--user"; private static final String SOURCE = "source"; private static final String BIN_ACTIVATE = "/env/bin/activate"; private static final String SCRIPTS_ACTIVATE = "\\env\\Scripts\\activate.bat"; private static final String AND = "&&"; private static final String PIPDEPTREE = "pipdeptree"; private static final String M = "-m"; private static final String ENV = "/env"; private static final String JSON_TREE = "--json-tree"; private static final String HIERARCHY_TREE_TXT = "/HierarchyTree.txt"; private static final String PACKAGE_NAME = "package_name"; private static final String INSTALLED_VERSION = "installed_version"; private static final String DEPENDENCIES = "dependencies"; private static final String LOWER_COMMA = "_"; private static final String F = "-f"; private static final String COMMA = "-"; private static final String EMPTY_STRING = ""; private static final String DOWNLOAD = "download"; private static final String INSTALL = "install"; private static final String R_PARAMETER = "-r"; private static final String D_PARAMETER = "-d"; private static final String COMMENT_SIGN_PYTHON = "#"; private static final int NUM_THREADS = 8; private static final String FORWARD_SLASH = "/"; private static final String SCRIPT_SH = "/script.sh"; /* --- Constructors --- */ public PythonDependencyCollector(String pythonPath, String pipPath, boolean installVirtualEnv, boolean resolveHierarchyTree, boolean ignorePipInstallErrors, String requirementsTxtPath, String tempDirPackages, String tempDirVirtualEnv) { super(); this.pythonPath = pythonPath; this.pipPath = pipPath; this.installVirtualEnv = installVirtualEnv; this.resolveHierarchyTree = resolveHierarchyTree; this.requirementsTxtPath = requirementsTxtPath; this.tempDirPackages = tempDirPackages; this.tempDirVirtualenv = tempDirVirtualEnv; this.ignorePipInstallErrors = ignorePipInstallErrors; } @Override public Collection<AgentProjectInfo> collectDependencies(String topLevelFolder) { this.topLevelFolder = topLevelFolder; List<DependencyInfo> dependencies = new LinkedList<>(); boolean virtualEnvInstalled = true; if (this.installVirtualEnv && this.resolveHierarchyTree) { try { // install virtualEnv package virtualEnvInstalled = !processCommand(new String[]{pythonPath, M, pipPath, INSTALL, USER, VIRTUALENV}, true); } catch (IOException e) { virtualEnvInstalled = false; } } // FSA will run 'pip download -r requirements.txt -d TEMP_FOLDER_PATH' if (virtualEnvInstalled) { try { logger.debug("Collecting python dependencies. It might take a few minutes."); boolean failedGetTree; boolean failed = processCommand(new String[]{pipPath, DOWNLOAD, R_PARAMETER, this.requirementsTxtPath, D_PARAMETER, tempDirPackages}, true); // if process failed, download each package line by line if (failed) { String error = "Fail to run 'pip install -r " + this.requirementsTxtPath + "'"; logger.warn(error + ". To see the full error, re-run the plugin with this parameter in the config file: log.level=debug"); } else if (!failed && !this.resolveHierarchyTree) { dependencies = collectDependencies(new File(tempDirPackages), this.requirementsTxtPath); } else if (!failed && this.resolveHierarchyTree) { failedGetTree = getTree(this.requirementsTxtPath); if (!failedGetTree) { dependencies = collectDependenciesWithTree(this.tempDirVirtualenv + HIERARCHY_TREE_TXT, requirementsTxtPath); } else { // collect flat list if hierarchy tree failed dependencies = collectDependencies(new File(tempDirPackages), this.requirementsTxtPath); } } if (failed && this.ignorePipInstallErrors) { logger.info("Try to download each dependency in the requirements.txt file one by one. It might take a few minutes."); FilesUtils.deleteDirectory(new File(tempDirPackages)); this.tempDirPackages = new FilesUtils().createTmpFolder(false); if (this.tempDirPackages != null) { downloadLineByLine(this.requirementsTxtPath); dependencies = collectDependencies(new File(tempDirPackages), this.requirementsTxtPath); FilesUtils.deleteDirectory(new File(tempDirPackages)); } } } catch (IOException e) { logger.warn("Cannot read the requirements.txt file"); } } else { logger.warn("Virutalenv package installation failed"); } return getSingleProjectList(dependencies); } private List<DependencyInfo> collectDependenciesWithTree(String treeFile, String requirementsTxtPath) { List<DependencyInfo> dependencies = new LinkedList<>(); try { // read json dependency tree from cmd tmp file String allTreeFile = new String(Files.readAllBytes(Paths.get(treeFile)), StandardCharsets.UTF_8); JSONArray treeArray = new JSONArray(allTreeFile); File[] files = (new File(this.tempDirPackages)).listFiles(); dependencies = collectDependenciesReq(treeArray, files, requirementsTxtPath); } catch (IOException e) { logger.warn("Cannot read the hierarchy tree file"); } return dependencies; } private List<DependencyInfo> collectDependenciesReq(JSONArray dependenciesArray, File[] files, String requirementsTxtPath) { List<DependencyInfo> dependencies = new LinkedList<>(); for (int i = 0; i < dependenciesArray.length(); i++) { JSONObject packageObject = dependenciesArray.getJSONObject(i); DependencyInfo dependency = getDependencyByName(files, packageObject.getString(PACKAGE_NAME), packageObject.getString(INSTALLED_VERSION), requirementsTxtPath); if (dependency != null) { dependencies.add(dependency); dependency.setChildren(collectDependenciesReq(packageObject.getJSONArray(DEPENDENCIES), files, requirementsTxtPath)); } } return dependencies; } private DependencyInfo getDependencyByName(File[] files, String name, String version, String requirementsTxtPath) { String nameAndVersion1 = name + COMMA + version; String nameAndVersion2 = name.replace(COMMA, LOWER_COMMA) + COMMA + version; nameAndVersion1 = nameAndVersion1.toLowerCase(); nameAndVersion2 = nameAndVersion2.toLowerCase(); for (File file : files) { String fileNameLowerCase = file.getName().toLowerCase(); if (fileNameLowerCase.startsWith(nameAndVersion1) || fileNameLowerCase.startsWith(nameAndVersion2)) { return getDependencyFromFile(file, requirementsTxtPath); } } return null; } private boolean getTree(String requirementsTxtPath) { boolean failed; try { // Create the virtual environment failed = processCommand(new String[]{pythonPath, M, VIRTUALENV, this.tempDirVirtualenv + ENV}, true); if (!failed) { if (isWindows()) { failed = processCommand(getFullCmdInstallation(requirementsTxtPath), true); } else { String scriptPath = createScript(requirementsTxtPath); if (scriptPath != null) { failed = processCommand(new String[] {scriptPath}, true); } else { failed = true; } } } } catch (IOException e) { logger.warn("Cannot install requirements.txt in the virtual environment."); failed = true; } return failed; } private List<DependencyInfo> collectDependencies(File folder, String requirementsTxtPath) { List<DependencyInfo> result = new LinkedList<>(); for (File file : folder.listFiles()) { if (file.isDirectory()) { for (File regFile : file.listFiles()) { addDependencyInfoData(regFile, requirementsTxtPath, result); } } else { addDependencyInfoData(file, requirementsTxtPath, result); } } return result; } private void addDependencyInfoData(File file, String requirementsTxtPath, List<DependencyInfo> dependencies) { DependencyInfo dependency = getDependencyFromFile(file, requirementsTxtPath); if (dependency != null) { dependencies.add(dependency); } } private DependencyInfo getDependencyFromFile(File file, String requirementsTxtPath) { DependencyInfo dependency = new DependencyInfo(); String fileName = file.getName(); // ignore name and version and use only the sha1 // int firstIndexOfComma = fileName.indexOf(COMMA); // String name = fileName.substring(0, firstIndexOfComma); // int indexOfExtension = fileName.indexOf(TAR_GZ); // String version; // if (indexOfExtension < 0) { // indexOfExtension = fileName.lastIndexOf(DOT); // version = fileName.substring(firstIndexOfComma + 1, indexOfExtension); // int indexOfComma = version.indexOf(COMMA); // if (indexOfComma >= 0) { // version = version.substring(0, indexOfComma); // } // } else { // version = fileName.substring(firstIndexOfComma + 1, indexOfExtension); // } String sha1 = getSha1(file); if (StringUtils.isEmpty(sha1)) { return null; } // dependency.setGroupId(name); dependency.setArtifactId(fileName); // dependency.setVersion(version); dependency.setSha1(sha1); dependency.setSystemPath(requirementsTxtPath); dependency.setDependencyType(DependencyType.PYTHON); return dependency; } private String getSha1(File file) { try { return ChecksumUtils.calculateSHA1(file); } catch (IOException e) { logger.warn("Failed getting " + file + ". File will not be send to WhiteSource server."); return EMPTY_STRING; } } private String[] getFullCmdInstallation(String requirementsTxtPath) { // TODO add comment String[] forWindows = new String[]{this.tempDirVirtualenv + SCRIPTS_ACTIVATE, AND, pipPath, INSTALL, R_PARAMETER, requirementsTxtPath, F, this.tempDirPackages, AND, pipPath, INSTALL, PIPDEPTREE, AND, PIPDEPTREE, JSON_TREE, ">", this.tempDirVirtualenv + HIERARCHY_TREE_TXT}; return forWindows; } private boolean processCommand(String[] args, boolean withOutput) throws IOException { CommandLineProcess commandLineProcess = new CommandLineProcess(this.topLevelFolder, args); if (withOutput) { commandLineProcess.executeProcess(); } else { commandLineProcess.executeProcessWithoutOutput(); } return commandLineProcess.isErrorInProcess(); } private void downloadLineByLine(String requirementsTxtPath) { try { ExecutorService executorService = Executors.newWorkStealingPool(NUM_THREADS); Collection<DownloadDependency> threadsCollection = new LinkedList<>(); BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(requirementsTxtPath))); String line; while ((line = bufferedReader.readLine()) != null) { if (StringUtils.isNotEmpty(line)) { int commentIndex = line.indexOf(COMMENT_SIGN_PYTHON); if (commentIndex < 0) { commentIndex = line.length(); } String packageNameToDownload = line.substring(0, commentIndex); if (StringUtils.isNotEmpty(packageNameToDownload)) { threadsCollection.add(new DownloadDependency(packageNameToDownload)); } } } if (bufferedReader != null) { bufferedReader.close(); } runThreadCollection(executorService, threadsCollection); } catch (IOException e) { logger.warn("Cannot read the requirements.txt file: {}", e.getMessage()); } } private void runThreadCollection(ExecutorService executorService, Collection<DownloadDependency> threadsCollection) { try { executorService.invokeAll(threadsCollection); executorService.shutdown(); } catch (InterruptedException e) { logger.warn("One of the threads was interrupted, please try to scan again the project. Error: {}", e.getMessage()); logger.debug("One of the threads was interrupted, please try to scan again the project. Error: {}", e.getStackTrace()); } } private void downloadOneDependency(String packageName) { int currentCounter = this.counterFolders.incrementAndGet(); String message = "Failed to download the transitive dependencies of '"; try { if (processCommand(new String[]{pipPath, DOWNLOAD, packageName, D_PARAMETER, tempDirPackages + FORWARD_SLASH + currentCounter}, false)) { logger.warn(message + packageName + "'"); } } catch (IOException e) { logger.warn("Cannot read the requirements.txt file"); } } private String createScript(String requirementsTxtPath) { FilesUtils filesUtils = new FilesUtils(); String path = filesUtils.createTmpFolder(false); String pathOfScript = null; if (path != null) { pathOfScript = path + SCRIPT_SH; try { File file = new File(pathOfScript); FileOutputStream fos = new FileOutputStream(file); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fos)); bufferedWriter.write("#!/bin/bash"); bufferedWriter.newLine(); bufferedWriter.write(SOURCE + " " + this.tempDirVirtualenv + BIN_ACTIVATE); bufferedWriter.newLine(); bufferedWriter.write(pipPath + " " + INSTALL + " " + R_PARAMETER + " " + requirementsTxtPath + " " + F + " " + this.tempDirPackages); bufferedWriter.newLine(); bufferedWriter.write(pipPath + " " + INSTALL + " " + PIPDEPTREE); bufferedWriter.newLine(); bufferedWriter.write(PIPDEPTREE + " " + JSON_TREE + " " + ">" + " " + this.tempDirVirtualenv + HIERARCHY_TREE_TXT); bufferedWriter.close(); fos.close(); file.setExecutable(true); } catch (IOException e) { return null; } } return pathOfScript; } /* --- Nested classes --- */ class DownloadDependency implements Callable<Void> { /* --- Members --- */ private String packageName; /* --- Constructors --- */ public DownloadDependency(String packageName) { this.packageName = packageName; } /* --- Overridden methods --- */ @Override public Void call() { downloadOneDependency(this.packageName); return null; } } }
src/main/java/org/whitesource/agent/dependency/resolver/python/PythonDependencyCollector.java
package org.whitesource.agent.dependency.resolver.python; import org.apache.commons.lang.StringUtils; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whitesource.agent.api.model.AgentProjectInfo; import org.whitesource.agent.api.model.DependencyInfo; import org.whitesource.agent.api.model.DependencyType; import org.whitesource.agent.dependency.resolver.DependencyCollector; import org.whitesource.agent.hash.ChecksumUtils; import org.whitesource.agent.utils.CommandLineProcess; import org.whitesource.agent.utils.FilesUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; /** * @author raz.nitzan */ public class PythonDependencyCollector extends DependencyCollector { /* -- Members -- */ private boolean installVirtualEnv; private boolean resolveHierarchyTree; private boolean ignorePipInstallErrors; private String requirementsTxtPath; private String pythonPath; private String pipPath; private String tempDirPackages; private String tempDirVirtualenv; private String topLevelFolder; private AtomicInteger counterFolders = new AtomicInteger(0); private final Logger logger = LoggerFactory.getLogger(org.whitesource.agent.dependency.resolver.python.PythonDependencyResolver.class); /* --- Static members --- */ private static final String VIRTUALENV = "virtualenv"; private static final String USER = "--user"; private static final String SOURCE = "source"; private static final String BIN_ACTIVATE = "/env/bin/activate"; private static final String SCRIPTS_ACTIVATE = "\\env\\Scripts\\activate.bat"; private static final String AND = "&&"; private static final String PIPDEPTREE = "pipdeptree"; private static final String M = "-m"; private static final String ENV = "/env"; private static final String JSON_TREE = "--json-tree"; private static final String HIERARCHY_TREE_TXT = "/HierarchyTree.txt"; private static final String PACKAGE_NAME = "package_name"; private static final String INSTALLED_VERSION = "installed_version"; private static final String DEPENDENCIES = "dependencies"; private static final String LOWER_COMMA = "_"; private static final String F = "-f"; private static final String COMMA = "-"; private static final String EMPTY_STRING = ""; private static final String DOWNLOAD = "download"; private static final String INSTALL = "install"; private static final String R_PARAMETER = "-r"; private static final String D_PARAMETER = "-d"; private static final String COMMENT_SIGN_PYTHON = "#"; private static final int NUM_THREADS = 8; private static final String FORWARD_SLASH = "/"; /* --- Constructors --- */ public PythonDependencyCollector(String pythonPath, String pipPath, boolean installVirtualEnv, boolean resolveHierarchyTree, boolean ignorePipInstallErrors, String requirementsTxtPath, String tempDirPackages, String tempDirVirtualEnv) { super(); this.pythonPath = pythonPath; this.pipPath = pipPath; this.installVirtualEnv = installVirtualEnv; this.resolveHierarchyTree = resolveHierarchyTree; this.requirementsTxtPath = requirementsTxtPath; this.tempDirPackages = tempDirPackages; this.tempDirVirtualenv = tempDirVirtualEnv; this.ignorePipInstallErrors = ignorePipInstallErrors; } @Override public Collection<AgentProjectInfo> collectDependencies(String topLevelFolder) { this.topLevelFolder = topLevelFolder; List<DependencyInfo> dependencies = new LinkedList<>(); boolean virtualEnvInstalled = true; if (this.installVirtualEnv && this.resolveHierarchyTree) { try { // install virtualEnv package virtualEnvInstalled = !processCommand(new String[]{pythonPath, M, pipPath, INSTALL, USER, VIRTUALENV}, true); } catch (IOException e) { virtualEnvInstalled = false; } } // FSA will run 'pip download -r requirements.txt -d TEMP_FOLDER_PATH' if (virtualEnvInstalled) { try { logger.debug("Collecting python dependencies. It might take a few minutes."); boolean failedGetTree; boolean failed = processCommand(new String[]{pipPath, DOWNLOAD, R_PARAMETER, this.requirementsTxtPath, D_PARAMETER, tempDirPackages}, true); // if process failed, download each package line by line if (failed) { String error = "Fail to run 'pip install -r " + this.requirementsTxtPath + "'"; logger.warn(error + ". To see the full error, re-run the plugin with this parameter in the config file: log.level=debug"); } else if (!failed && !this.resolveHierarchyTree) { dependencies = collectDependencies(new File(tempDirPackages), this.requirementsTxtPath); } else if (!failed && this.resolveHierarchyTree) { failedGetTree = getTree(this.requirementsTxtPath); if (!failedGetTree) { dependencies = collectDependenciesWithTree(this.tempDirVirtualenv + HIERARCHY_TREE_TXT, requirementsTxtPath); } else { // collect flat list if hierarchy tree failed dependencies = collectDependencies(new File(tempDirPackages), this.requirementsTxtPath); } } if (failed && this.ignorePipInstallErrors) { logger.info("Try to download each dependency in the requirements.txt file one by one. It might take a few minutes."); FilesUtils.deleteDirectory(new File(tempDirPackages)); this.tempDirPackages = new FilesUtils().createTmpFolder(false); if (this.tempDirPackages != null) { downloadLineByLine(this.requirementsTxtPath); dependencies = collectDependencies(new File(tempDirPackages), this.requirementsTxtPath); FilesUtils.deleteDirectory(new File(tempDirPackages)); } } } catch (IOException e) { logger.warn("Cannot read the requirements.txt file"); } } else { logger.warn("Virutalenv package installation failed"); } return getSingleProjectList(dependencies); } private List<DependencyInfo> collectDependenciesWithTree(String treeFile, String requirementsTxtPath) { List<DependencyInfo> dependencies = new LinkedList<>(); try { // read json dependency tree from cmd tmp file String allTreeFile = new String(Files.readAllBytes(Paths.get(treeFile)), StandardCharsets.UTF_8); JSONArray treeArray = new JSONArray(allTreeFile); File[] files = (new File(this.tempDirPackages)).listFiles(); dependencies = collectDependenciesReq(treeArray, files, requirementsTxtPath); } catch (IOException e) { logger.warn("Cannot read the hierarchy tree file"); } return dependencies; } private List<DependencyInfo> collectDependenciesReq(JSONArray dependenciesArray, File[] files, String requirementsTxtPath) { List<DependencyInfo> dependencies = new LinkedList<>(); for (int i = 0; i < dependenciesArray.length(); i++) { JSONObject packageObject = dependenciesArray.getJSONObject(i); DependencyInfo dependency = getDependencyByName(files, packageObject.getString(PACKAGE_NAME), packageObject.getString(INSTALLED_VERSION), requirementsTxtPath); if (dependency != null) { dependencies.add(dependency); dependency.setChildren(collectDependenciesReq(packageObject.getJSONArray(DEPENDENCIES), files, requirementsTxtPath)); } } return dependencies; } private DependencyInfo getDependencyByName(File[] files, String name, String version, String requirementsTxtPath) { String nameAndVersion1 = name + COMMA + version; String nameAndVersion2 = name.replace(COMMA, LOWER_COMMA) + COMMA + version; nameAndVersion1 = nameAndVersion1.toLowerCase(); nameAndVersion2 = nameAndVersion2.toLowerCase(); for (File file : files) { String fileNameLowerCase = file.getName().toLowerCase(); if (fileNameLowerCase.startsWith(nameAndVersion1) || fileNameLowerCase.startsWith(nameAndVersion2)) { return getDependencyFromFile(file, requirementsTxtPath); } } return null; } private boolean getTree(String requirementsTxtPath) { boolean failed; try { // Create the virtual environment failed = processCommand(new String[]{pythonPath, M, VIRTUALENV, this.tempDirVirtualenv + ENV}, true); if (!failed) { // Install the dependencies in the virtual environment and get the full tree of dependencies in a file failed = processCommand(getFullCmdInstallation(requirementsTxtPath), true); } } catch (IOException e) { logger.warn("Cannot install requirements.txt in the virtual environment."); failed = true; } return failed; } private List<DependencyInfo> collectDependencies(File folder, String requirementsTxtPath) { List<DependencyInfo> result = new LinkedList<>(); for (File file : folder.listFiles()) { if (file.isDirectory()) { for (File regFile : file.listFiles()) { addDependencyInfoData(regFile, requirementsTxtPath, result); } } else { addDependencyInfoData(file, requirementsTxtPath, result); } } return result; } private void addDependencyInfoData(File file, String requirementsTxtPath, List<DependencyInfo> dependencies) { DependencyInfo dependency = getDependencyFromFile(file, requirementsTxtPath); if (dependency != null) { dependencies.add(dependency); } } private DependencyInfo getDependencyFromFile(File file, String requirementsTxtPath) { DependencyInfo dependency = new DependencyInfo(); String fileName = file.getName(); // ignore name and version and use only the sha1 // int firstIndexOfComma = fileName.indexOf(COMMA); // String name = fileName.substring(0, firstIndexOfComma); // int indexOfExtension = fileName.indexOf(TAR_GZ); // String version; // if (indexOfExtension < 0) { // indexOfExtension = fileName.lastIndexOf(DOT); // version = fileName.substring(firstIndexOfComma + 1, indexOfExtension); // int indexOfComma = version.indexOf(COMMA); // if (indexOfComma >= 0) { // version = version.substring(0, indexOfComma); // } // } else { // version = fileName.substring(firstIndexOfComma + 1, indexOfExtension); // } String sha1 = getSha1(file); if (StringUtils.isEmpty(sha1)) { return null; } // dependency.setGroupId(name); dependency.setArtifactId(fileName); // dependency.setVersion(version); dependency.setSha1(sha1); dependency.setSystemPath(requirementsTxtPath); dependency.setDependencyType(DependencyType.PYTHON); return dependency; } private String getSha1(File file) { try { return ChecksumUtils.calculateSHA1(file); } catch (IOException e) { logger.warn("Failed getting " + file + ". File will not be send to WhiteSource server."); return EMPTY_STRING; } } private String[] getFullCmdInstallation(String requirementsTxtPath) { // TODO add comment String[] result; String[] forWindows = new String[]{this.tempDirVirtualenv + SCRIPTS_ACTIVATE, AND, pipPath, INSTALL, R_PARAMETER, requirementsTxtPath, F, this.tempDirPackages, AND, pipPath, INSTALL, PIPDEPTREE, AND, PIPDEPTREE, JSON_TREE, ">", this.tempDirVirtualenv + HIERARCHY_TREE_TXT}; if(!isWindows()) { forWindows[0] = this.tempDirVirtualenv + BIN_ACTIVATE; String[] forLinux = new String[forWindows.length + 1]; forLinux[0] = SOURCE; System.arraycopy(forWindows, 0, forLinux, 1, forWindows.length); result = forLinux; } else { result = forWindows; } return result; } private boolean processCommand(String[] args, boolean withOutput) throws IOException { CommandLineProcess commandLineProcess = new CommandLineProcess(this.topLevelFolder, args); if (withOutput) { commandLineProcess.executeProcess(); } else { commandLineProcess.executeProcessWithoutOutput(); } return commandLineProcess.isErrorInProcess(); } private void downloadLineByLine(String requirementsTxtPath) { try { ExecutorService executorService = Executors.newWorkStealingPool(NUM_THREADS); Collection<DownloadDependency> threadsCollection = new LinkedList<>(); BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(requirementsTxtPath))); String line; while ((line = bufferedReader.readLine()) != null) { if (StringUtils.isNotEmpty(line)) { int commentIndex = line.indexOf(COMMENT_SIGN_PYTHON); if (commentIndex < 0) { commentIndex = line.length(); } String packageNameToDownload = line.substring(0, commentIndex); if (StringUtils.isNotEmpty(packageNameToDownload)) { threadsCollection.add(new DownloadDependency(packageNameToDownload)); } } } if (bufferedReader != null) { bufferedReader.close(); } runThreadCollection(executorService, threadsCollection); } catch (IOException e) { logger.warn("Cannot read the requirements.txt file: {}", e.getMessage()); } } private void runThreadCollection(ExecutorService executorService, Collection<DownloadDependency> threadsCollection) { try { executorService.invokeAll(threadsCollection); executorService.shutdown(); } catch (InterruptedException e) { logger.warn("One of the threads was interrupted, please try to scan again the project. Error: {}", e.getMessage()); logger.debug("One of the threads was interrupted, please try to scan again the project. Error: {}", e.getStackTrace()); } } private void downloadOneDependency(String packageName) { int currentCounter = this.counterFolders.incrementAndGet(); String message = "Failed to download the transitive dependencies of '"; try { if (processCommand(new String[]{pipPath, DOWNLOAD, packageName, D_PARAMETER, tempDirPackages + FORWARD_SLASH + currentCounter}, false)) { logger.warn(message + packageName + "'"); } } catch (IOException e) { logger.warn("Cannot read the requirements.txt file"); } } /* --- Nested classes --- */ class DownloadDependency implements Callable<Void> { /* --- Members --- */ private String packageName; /* --- Constructors --- */ public DownloadDependency(String packageName) { this.packageName = packageName; } /* --- Overridden methods --- */ @Override public Void call() { downloadOneDependency(this.packageName); return null; } } }
WSE-502 - fix linux problem
src/main/java/org/whitesource/agent/dependency/resolver/python/PythonDependencyCollector.java
WSE-502 - fix linux problem
<ide><path>rc/main/java/org/whitesource/agent/dependency/resolver/python/PythonDependencyCollector.java <ide> import org.whitesource.agent.utils.CommandLineProcess; <ide> import org.whitesource.agent.utils.FilesUtils; <ide> <del>import java.io.BufferedReader; <del>import java.io.File; <del>import java.io.FileReader; <del>import java.io.IOException; <add>import java.io.*; <ide> import java.nio.charset.StandardCharsets; <ide> import java.nio.file.Files; <ide> import java.nio.file.Paths; <ide> private static final String COMMENT_SIGN_PYTHON = "#"; <ide> private static final int NUM_THREADS = 8; <ide> private static final String FORWARD_SLASH = "/"; <add> private static final String SCRIPT_SH = "/script.sh"; <ide> <ide> /* --- Constructors --- */ <ide> <ide> // Create the virtual environment <ide> failed = processCommand(new String[]{pythonPath, M, VIRTUALENV, this.tempDirVirtualenv + ENV}, true); <ide> if (!failed) { <del> // Install the dependencies in the virtual environment and get the full tree of dependencies in a file <del> failed = processCommand(getFullCmdInstallation(requirementsTxtPath), true); <add> if (isWindows()) { <add> failed = processCommand(getFullCmdInstallation(requirementsTxtPath), true); <add> } else { <add> String scriptPath = createScript(requirementsTxtPath); <add> if (scriptPath != null) { <add> failed = processCommand(new String[] {scriptPath}, true); <add> } else { <add> failed = true; <add> } <add> } <ide> } <ide> } catch (IOException e) { <ide> logger.warn("Cannot install requirements.txt in the virtual environment."); <ide> <ide> private String[] getFullCmdInstallation(String requirementsTxtPath) { <ide> // TODO add comment <del> String[] result; <ide> String[] forWindows = new String[]{this.tempDirVirtualenv + SCRIPTS_ACTIVATE, AND, pipPath, INSTALL, R_PARAMETER, <ide> requirementsTxtPath, F, this.tempDirPackages, AND, pipPath, INSTALL, PIPDEPTREE, AND, PIPDEPTREE, <ide> JSON_TREE, ">", this.tempDirVirtualenv + HIERARCHY_TREE_TXT}; <del> if(!isWindows()) { <del> forWindows[0] = this.tempDirVirtualenv + BIN_ACTIVATE; <del> String[] forLinux = new String[forWindows.length + 1]; <del> forLinux[0] = SOURCE; <del> System.arraycopy(forWindows, 0, forLinux, 1, forWindows.length); <del> result = forLinux; <del> } else { <del> result = forWindows; <del> } <del> return result; <add> return forWindows; <ide> } <ide> <ide> private boolean processCommand(String[] args, boolean withOutput) throws IOException { <ide> } <ide> } <ide> <add> private String createScript(String requirementsTxtPath) { <add> FilesUtils filesUtils = new FilesUtils(); <add> String path = filesUtils.createTmpFolder(false); <add> String pathOfScript = null; <add> if (path != null) { <add> pathOfScript = path + SCRIPT_SH; <add> try { <add> File file = new File(pathOfScript); <add> FileOutputStream fos = new FileOutputStream(file); <add> BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fos)); <add> bufferedWriter.write("#!/bin/bash"); <add> bufferedWriter.newLine(); <add> bufferedWriter.write(SOURCE + " " + this.tempDirVirtualenv + BIN_ACTIVATE); <add> bufferedWriter.newLine(); <add> bufferedWriter.write(pipPath + " " + INSTALL + " " + R_PARAMETER + " " + requirementsTxtPath + " " + F + " " + this.tempDirPackages); <add> bufferedWriter.newLine(); <add> bufferedWriter.write(pipPath + " " + INSTALL + " " + PIPDEPTREE); <add> bufferedWriter.newLine(); <add> bufferedWriter.write(PIPDEPTREE + " " + JSON_TREE + " " + ">" + " " + this.tempDirVirtualenv + HIERARCHY_TREE_TXT); <add> bufferedWriter.close(); <add> fos.close(); <add> file.setExecutable(true); <add> } catch (IOException e) { <add> return null; <add> } <add> } <add> return pathOfScript; <add> } <add> <ide> /* --- Nested classes --- */ <ide> <ide> class DownloadDependency implements Callable<Void> {
Java
apache-2.0
8839b7367c17483b5f69e1f8b2c7d25b363f0d95
0
realityforge/replicant,realityforge/replicant
package replicant; import java.lang.reflect.Field; import javax.annotation.Nonnull; import org.realityforge.anodoc.TestOnly; /** * Utility class for interacting with Replicant config settings in tests. */ @SuppressWarnings( "WeakerAccess" ) @TestOnly @GwtIncompatible public final class ReplicantTestUtil { private ReplicantTestUtil() { } /** * Reset the state of Arez config to either production or development state. * * @param productionMode true to set it to production mode configuration, false to set it to development mode config. */ public static void resetConfig( final boolean productionMode ) { if ( ReplicantConfig.isProductionMode() ) { /* * This should really never happen but if it does add assertion (so code stops in debugger) or * failing that throw an exception. */ assert !ReplicantConfig.isProductionMode(); throw new IllegalStateException( "Unable to reset config as Replicant is in production mode" ); } if ( productionMode ) { noRecordRequestKey(); noValidateRepositoryOnLoad(); noRequestDebugOutputEnabled(); noSubscriptionsDebugOutputEnabled(); noCheckInvariants(); noCheckApiInvariants(); } else { recordRequestKey(); validateRepositoryOnLoad(); requestDebugOutputEnabled(); subscriptionsDebugOutputEnabled(); checkInvariants(); checkApiInvariants(); } disableZones(); ReplicantZoneHolder.reset(); } /** * Set `replicant.recordRequestKey` setting to true. */ public static void recordRequestKey() { setShouldRecordRequestKey( true ); } /** * Set `replicant.recordRequestKey` setting to false. */ public static void noRecordRequestKey() { setShouldRecordRequestKey( false ); } /** * Configure the `replicant.enable_names` setting. * * @param value the setting. */ private static void setShouldRecordRequestKey( final boolean value ) { setConstant( "RECORD_REQUEST_KEY", value ); } /** * Set `replicant.validateRepositoryOnLoad` setting to true. */ public static void validateRepositoryOnLoad() { setValidateRepositoryOnLoad( true ); } /** * Set `replicant.validateRepositoryOnLoad` setting to false. */ public static void noValidateRepositoryOnLoad() { setValidateRepositoryOnLoad( false ); } /** * Configure the `replicant.validateRepositoryOnLoad` setting. * * @param value the setting. */ private static void setValidateRepositoryOnLoad( final boolean value ) { setConstant( "VALIDATE_REPOSITORY_ON_LOAD", value ); } /** * Set `replicant.requestDebugOutputEnabled` setting to true. */ public static void requestDebugOutputEnabled() { setRequestDebugOutputEnabled( true ); } /** * Set `replicant.requestDebugOutputEnabled` setting to false. */ public static void noRequestDebugOutputEnabled() { setRequestDebugOutputEnabled( false ); } /** * Configure the `replicant.requestDebugOutputEnabled` setting. * * @param value the setting. */ private static void setRequestDebugOutputEnabled( final boolean value ) { setConstant( "REQUEST_DEBUG_OUTPUT_ENABLED", value ); } /** * Set `replicant.subscriptionsDebugOutputEnabled` setting to true. */ public static void subscriptionsDebugOutputEnabled() { setSubscriptionsDebugOutputEnabled( true ); } /** * Set `replicant.subscriptionsDebugOutputEnabled` setting to false. */ public static void noSubscriptionsDebugOutputEnabled() { setSubscriptionsDebugOutputEnabled( false ); } /** * Configure the `replicant.subscriptionsDebugOutputEnabled` setting. * * @param value the setting. */ private static void setSubscriptionsDebugOutputEnabled( final boolean value ) { setConstant( "SUBSCRIPTION_DEBUG_OUTPUT_ENABLED", value ); } /** * Set `replicant.check_invariants` setting to true. */ public static void checkInvariants() { setCheckInvariants( true ); } /** * Set the `replicant.check_invariants` setting to false. */ public static void noCheckInvariants() { setCheckInvariants( false ); } /** * Configure the `replicant.check_invariants` setting. * * @param checkInvariants the "check invariants" setting. */ private static void setCheckInvariants( final boolean checkInvariants ) { setConstant( "CHECK_INVARIANTS", checkInvariants ); } /** * Set `replicant.check_api_invariants` setting to true. */ public static void checkApiInvariants() { setCheckApiInvariants( true ); } /** * Set the `replicant.check_api_invariants` setting to false. */ public static void noCheckApiInvariants() { setCheckApiInvariants( false ); } /** * Configure the `replicant.check_api_invariants` setting. * * @param checkApiInvariants the "check invariants" setting. */ private static void setCheckApiInvariants( final boolean checkApiInvariants ) { setConstant( "CHECK_API_INVARIANTS", checkApiInvariants ); } /** * Set `replicant.enable_zones` setting to true. */ public static void enableZones() { setEnableZones( true ); } /** * Set `replicant.enable_zones` setting to false. */ public static void disableZones() { setEnableZones( false ); } /** * Configure the `replicant.enable_zones` setting. * * @param value the setting. */ private static void setEnableZones( final boolean value ) { setConstant( "ENABLE_ZONES", value ); } /** * Set the specified field name on ReplicantConfig. */ @SuppressWarnings( "NonJREEmulationClassesInClientCode" ) private static void setConstant( @Nonnull final String fieldName, final boolean value ) { if ( !ReplicantConfig.isProductionMode() ) { try { final Field field = ReplicantConfig.class.getDeclaredField( fieldName ); field.setAccessible( true ); field.set( null, value ); } catch ( final NoSuchFieldException | IllegalAccessException e ) { throw new IllegalStateException( "Unable to change constant " + fieldName, e ); } } else { /* * This should not happen but if it does then just fail with an assertion or error. */ assert !ReplicantConfig.isProductionMode(); throw new IllegalStateException( "Unable to change constant " + fieldName + " as Replicant is in production mode" ); } } }
client/src/main/java/replicant/ReplicantTestUtil.java
package replicant; import java.lang.reflect.Field; import javax.annotation.Nonnull; import org.realityforge.anodoc.TestOnly; /** * Utility class for interacting with Replicant config settings in tests. */ @SuppressWarnings( "WeakerAccess" ) @TestOnly @GwtIncompatible public final class ReplicantTestUtil { private ReplicantTestUtil() { } /** * Reset the state of Arez config to either production or development state. * * @param productionMode true to set it to production mode configuration, false to set it to development mode config. */ public static void resetConfig( final boolean productionMode ) { if ( ReplicantConfig.isProductionMode() ) { /* * This should really never happen but if it does add assertion (so code stops in debugger) or * failing that throw an exception. */ assert !ReplicantConfig.isProductionMode(); throw new IllegalStateException( "Unable to reset config as Replicant is in production mode" ); } if ( productionMode ) { noRecordRequestKey(); noCheckInvariants(); noCheckApiInvariants(); } else { recordRequestKey(); checkInvariants(); checkApiInvariants(); } disableZones(); ReplicantZoneHolder.reset(); } /** * Set `replicant.recordRequestKey` setting to true. */ public static void recordRequestKey() { setShouldRecordRequestKey( true ); } /** * Set `replicant.recordRequestKey` setting to false. */ public static void noRecordRequestKey() { setShouldRecordRequestKey( false ); } /** * Configure the `replicant.enable_names` setting. * * @param value the setting. */ private static void setShouldRecordRequestKey( final boolean value ) { setConstant( "RECORD_REQUEST_KEY", value ); } /** * Set `replicant.validateRepositoryOnLoad` setting to true. */ public static void validateRepositoryOnLoad() { setValidateRepositoryOnLoad( true ); } /** * Set `replicant.validateRepositoryOnLoad` setting to false. */ public static void noValidateRepositoryOnLoad() { setValidateRepositoryOnLoad( false ); } /** * Configure the `replicant.validateRepositoryOnLoad` setting. * * @param value the setting. */ private static void setValidateRepositoryOnLoad( final boolean value ) { setConstant( "VALIDATE_REPOSITORY_ON_LOAD", value ); } /** * Set `replicant.requestDebugOutputEnabled` setting to true. */ public static void requestDebugOutputEnabled() { setRequestDebugOutputEnabled( true ); } /** * Set `replicant.requestDebugOutputEnabled` setting to false. */ public static void noRequestDebugOutputEnabled() { setRequestDebugOutputEnabled( false ); } /** * Configure the `replicant.requestDebugOutputEnabled` setting. * * @param value the setting. */ private static void setRequestDebugOutputEnabled( final boolean value ) { setConstant( "REQUEST_DEBUG_OUTPUT_ENABLED", value ); } /** * Set `replicant.subscriptionsDebugOutputEnabled` setting to true. */ public static void subscriptionsDebugOutputEnabled() { setSubscriptionsDebugOutputEnabled( true ); } /** * Set `replicant.subscriptionsDebugOutputEnabled` setting to false. */ public static void noSubscriptionsDebugOutputEnabled() { setSubscriptionsDebugOutputEnabled( false ); } /** * Configure the `replicant.subscriptionsDebugOutputEnabled` setting. * * @param value the setting. */ private static void setSubscriptionsDebugOutputEnabled( final boolean value ) { setConstant( "SUBSCRIPTION_DEBUG_OUTPUT_ENABLED", value ); } /** * Set `replicant.check_invariants` setting to true. */ public static void checkInvariants() { setCheckInvariants( true ); } /** * Set the `replicant.check_invariants` setting to false. */ public static void noCheckInvariants() { setCheckInvariants( false ); } /** * Configure the `replicant.check_invariants` setting. * * @param checkInvariants the "check invariants" setting. */ private static void setCheckInvariants( final boolean checkInvariants ) { setConstant( "CHECK_INVARIANTS", checkInvariants ); } /** * Set `replicant.check_api_invariants` setting to true. */ public static void checkApiInvariants() { setCheckApiInvariants( true ); } /** * Set the `replicant.check_api_invariants` setting to false. */ public static void noCheckApiInvariants() { setCheckApiInvariants( false ); } /** * Configure the `replicant.check_api_invariants` setting. * * @param checkApiInvariants the "check invariants" setting. */ private static void setCheckApiInvariants( final boolean checkApiInvariants ) { setConstant( "CHECK_API_INVARIANTS", checkApiInvariants ); } /** * Set `replicant.enable_zones` setting to true. */ public static void enableZones() { setEnableZones( true ); } /** * Set `replicant.enable_zones` setting to false. */ public static void disableZones() { setEnableZones( false ); } /** * Configure the `replicant.enable_zones` setting. * * @param value the setting. */ private static void setEnableZones( final boolean value ) { setConstant( "ENABLE_ZONES", value ); } /** * Set the specified field name on ReplicantConfig. */ @SuppressWarnings( "NonJREEmulationClassesInClientCode" ) private static void setConstant( @Nonnull final String fieldName, final boolean value ) { if ( !ReplicantConfig.isProductionMode() ) { try { final Field field = ReplicantConfig.class.getDeclaredField( fieldName ); field.setAccessible( true ); field.set( null, value ); } catch ( final NoSuchFieldException | IllegalAccessException e ) { throw new IllegalStateException( "Unable to change constant " + fieldName, e ); } } else { /* * This should not happen but if it does then just fail with an assertion or error. */ assert !ReplicantConfig.isProductionMode(); throw new IllegalStateException( "Unable to change constant " + fieldName + " as Replicant is in production mode" ); } } }
Make sure tests reset "compile time" settings
client/src/main/java/replicant/ReplicantTestUtil.java
Make sure tests reset "compile time" settings
<ide><path>lient/src/main/java/replicant/ReplicantTestUtil.java <ide> if ( productionMode ) <ide> { <ide> noRecordRequestKey(); <add> noValidateRepositoryOnLoad(); <add> noRequestDebugOutputEnabled(); <add> noSubscriptionsDebugOutputEnabled(); <ide> noCheckInvariants(); <ide> noCheckApiInvariants(); <ide> } <ide> else <ide> { <ide> recordRequestKey(); <add> validateRepositoryOnLoad(); <add> requestDebugOutputEnabled(); <add> subscriptionsDebugOutputEnabled(); <ide> checkInvariants(); <ide> checkApiInvariants(); <ide> }
Java
apache-2.0
df6ad406ed5cfb8be316ded5c16a5e143ca6f567
0
daidong/DominoHBase,daidong/DominoHBase,daidong/DominoHBase,daidong/DominoHBase,daidong/DominoHBase,daidong/DominoHBase,daidong/DominoHBase,daidong/DominoHBase,daidong/DominoHBase
/** * * 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.hbase.mapreduce; import java.io.IOException; import java.math.BigDecimal; import java.math.MathContext; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; /** * There are two tables in WordCount MapReduce: 'items', 'central'. * 'items' contains 'vec:value(K1:K2:..)' column * 'central' contains 'central:k1-k50' column * * @author daidong * */ public class KMeans { public static class KMeansMapper extends TableMapper<ImmutableBytesWritable, Text> { private HTable centrals = null; @SuppressWarnings("resource") @Override public void setup(Context context){ Configuration conf = HBaseConfiguration.create(); try { HTable centrals = new HTable(conf, "central".getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void map(ImmutableBytesWritable row, Result value, Context context) throws InterruptedException, IOException{ byte[] vector = value.getValue("vec".getBytes(), "value".getBytes()); String[] v = Bytes.toString(vector).split(":"); double least = Double.MAX_VALUE; int belongto = -1; for (int i = 0; i < 120; i++){ Get g = new Get(Bytes.toBytes(i)); Result t = centrals.get(g); byte[] r = t.getValue("central".getBytes(), "value".getBytes()); String[] rs = Bytes.toString(r).split(":"); double distance = 0.0; for (int j = 0; j < v.length; j++){ double v1 = Double.parseDouble(v[j]); double v2 = Double.parseDouble(rs[j]); distance += Math.abs(v1 - v2); } if (distance < least){ least = distance; belongto = i; } } byte[] clustering = Bytes.toBytes(belongto); context.write(new ImmutableBytesWritable(clustering), new Text(vector)); } } public static class KMeansReducer extends TableReducer<ImmutableBytesWritable, Text, ImmutableBytesWritable>{ public void reduce(ImmutableBytesWritable key, Iterable<Text> value, Context context) throws InterruptedException, IOException{ double[] avg = new double[50]; for (int i = 0; i < 50; i++){ avg[i] = 0.0; } int num = 0; for (Text v : value){ num ++; byte[] vec = v.getBytes(); int i = 0; for (String vi : Bytes.toString(vec).split(":")){ avg[i++] += Double.parseDouble(vi); } } for (int i = 0; i < 50; i++){ avg[i] = avg[i]/num; } String central = ""; for (int i = 0; i < 49; i++){ central = central + avg[i] + ":"; } central = central + avg[49]; Put p = new Put(key.get()); p.add("central".getBytes(), "value".getBytes(), central.getBytes()); context.write(key, p); } } /** * @param args * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { long start = System.currentTimeMillis(); for (int i = 0; i < 1; i++){ Configuration config = HBaseConfiguration.create(); Job job = new Job(config,"KMeans"+i); job.setJarByClass(WordCount.class); Scan scan = new Scan(); scan.setCaching(500); // 1 is the default in Scan, which will be bad for MapReduce jobs scan.setCacheBlocks(false); // don't set to true for MR jobs // set other scan attrs TableMapReduceUtil.initTableMapperJob( "items", // input table scan, // Scan instance to control CF and attribute selection KMeansMapper.class, // mapper class ImmutableBytesWritable.class, // mapper output key Text.class, // mapper output value job); TableMapReduceUtil.initTableReducerJob( "central", // output table KMeansReducer.class, // reducer class job); boolean b = job.waitForCompletion(true); if (!b) { throw new IOException("error with job!"); } } long end = System.currentTimeMillis(); System.out.println("One Round Time: " + (end - start)); } }
hbase-examples/src/main/java/org/apache/hadoop/hbase/mapreduce/KMeans.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.hbase.mapreduce; import java.io.IOException; import java.math.BigDecimal; import java.math.MathContext; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; /** * There are two tables in WordCount MapReduce: 'items', 'cluster'. * 'items' contains 'vec:value(K1:K2:..)' column * 'central' contains 'central:k1-k50' column * * @author daidong * */ public class KMeans { public static class KMeansMapper extends TableMapper<ImmutableBytesWritable, Text> { public void map(ImmutableBytesWritable row, Result value, Context context) throws InterruptedException, IOException{ byte[] vector = value.getValue("vec".getBytes(), "value".getBytes()); String[] v = Bytes.toString(vector).split(":"); Configuration conf = HBaseConfiguration.create(); HTable centrals = new HTable(conf, "central".getBytes()); double least = Double.MAX_VALUE; int belongto = -1; for (int i = 0; i < 120; i++){ Get g = new Get(Bytes.toBytes(i)); Result t = centrals.get(g); byte[] r = t.getValue("central".getBytes(), "value".getBytes()); String[] rs = Bytes.toString(r).split(":"); double distance = 0.0; for (int j = 0; j < v.length; j++){ double v1 = Double.parseDouble(v[j]); double v2 = Double.parseDouble(rs[j]); distance += Math.abs(v1 - v2); } if (distance < least){ least = distance; belongto = i; } } byte[] clustering = Bytes.toBytes(belongto); context.write(new ImmutableBytesWritable(clustering), new Text(vector)); } } public static class KMeansReducer extends TableReducer<ImmutableBytesWritable, Text, ImmutableBytesWritable>{ public void reduce(ImmutableBytesWritable key, Iterable<Text> value, Context context) throws InterruptedException, IOException{ double[] avg = new double[50]; for (int i = 0; i < 50; i++){ avg[i] = 0.0; } int num = 0; for (Text v : value){ num ++; byte[] vec = v.getBytes(); int i = 0; for (String vi : Bytes.toString(vec).split(":")){ avg[i++] += Double.parseDouble(vi); } } for (int i = 0; i < 50; i++){ avg[i] = avg[i]/num; } String central = ""; for (int i = 0; i < 49; i++){ central = central + avg[i] + ":"; } central = central + avg[49]; Put p = new Put(key.get()); p.add("central".getBytes(), "value".getBytes(), central.getBytes()); context.write(key, p); } } /** * @param args * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { long start = System.currentTimeMillis(); for (int i = 0; i < 1; i++){ Configuration config = HBaseConfiguration.create(); Job job = new Job(config,"KMeans"+i); job.setJarByClass(WordCount.class); Scan scan = new Scan(); scan.setCaching(500); // 1 is the default in Scan, which will be bad for MapReduce jobs scan.setCacheBlocks(false); // don't set to true for MR jobs // set other scan attrs TableMapReduceUtil.initTableMapperJob( "items", // input table scan, // Scan instance to control CF and attribute selection KMeansMapper.class, // mapper class ImmutableBytesWritable.class, // mapper output key Text.class, // mapper output value job); TableMapReduceUtil.initTableReducerJob( "cluster", // output table KMeansReducer.class, // reducer class job); boolean b = job.waitForCompletion(true); if (!b) { throw new IOException("error with job!"); } } long end = System.currentTimeMillis(); System.out.println("One Round Time: " + (end - start)); } }
KMeans
hbase-examples/src/main/java/org/apache/hadoop/hbase/mapreduce/KMeans.java
KMeans
<ide><path>base-examples/src/main/java/org/apache/hadoop/hbase/mapreduce/KMeans.java <ide> import org.apache.hadoop.mapreduce.Job; <ide> <ide> /** <del>* There are two tables in WordCount MapReduce: 'items', 'cluster'. <add>* There are two tables in WordCount MapReduce: 'items', 'central'. <ide> * 'items' contains 'vec:value(K1:K2:..)' column <ide> * 'central' contains 'central:k1-k50' column <ide> * <ide> */ <ide> public class KMeans { <ide> <del> public static class KMeansMapper extends TableMapper<ImmutableBytesWritable, Text> { <add> public static class KMeansMapper extends TableMapper<ImmutableBytesWritable, Text> { <add> <add> private HTable centrals = null; <add> <add> @SuppressWarnings("resource") <add> @Override <add> public void setup(Context context){ <add> Configuration conf = HBaseConfiguration.create(); <add> try { <add> HTable centrals = new HTable(conf, "central".getBytes()); <add> } catch (IOException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> <add> } <ide> public void map(ImmutableBytesWritable row, Result value, Context context) throws InterruptedException, IOException{ <ide> byte[] vector = value.getValue("vec".getBytes(), "value".getBytes()); <ide> String[] v = Bytes.toString(vector).split(":"); <ide> <del> Configuration conf = HBaseConfiguration.create(); <del> HTable centrals = new HTable(conf, "central".getBytes()); <ide> double least = Double.MAX_VALUE; <ide> int belongto = -1; <ide> <ide> job); <ide> <ide> TableMapReduceUtil.initTableReducerJob( <del> "cluster", // output table <add> "central", // output table <ide> KMeansReducer.class, // reducer class <ide> job); <ide>
Java
apache-2.0
6168994ad635fd25a6345d99c452deb5a1c79b72
0
oplinkoms/onos,opennetworkinglab/onos,gkatsikas/onos,osinstom/onos,oplinkoms/onos,opennetworkinglab/onos,kuujo/onos,opennetworkinglab/onos,kuujo/onos,kuujo/onos,osinstom/onos,kuujo/onos,kuujo/onos,osinstom/onos,kuujo/onos,opennetworkinglab/onos,kuujo/onos,gkatsikas/onos,oplinkoms/onos,gkatsikas/onos,oplinkoms/onos,oplinkoms/onos,gkatsikas/onos,oplinkoms/onos,opennetworkinglab/onos,opennetworkinglab/onos,osinstom/onos,osinstom/onos,gkatsikas/onos,oplinkoms/onos,gkatsikas/onos
/* * Copyright 2017-present Open Networking Foundation * * 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.onosproject.p4tutorial.icmpdropper; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.onosproject.app.ApplicationAdminService; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceListener; import org.onosproject.net.device.DeviceService; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.FlowRule; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.criteria.PiCriterion; import org.onosproject.net.behaviour.PiPipelineProgrammable; import org.onosproject.net.pi.runtime.PiAction; import org.onosproject.net.pi.model.PiActionId; import org.onosproject.net.pi.model.PiMatchFieldId; import org.onosproject.net.pi.service.PiPipeconfService; import org.onosproject.net.pi.model.PiTableId; import org.onosproject.p4tutorial.pipeconf.PipeconfFactory; import org.slf4j.Logger; import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_ADDED; import static org.slf4j.LoggerFactory.getLogger; /** * Simple application that drops all ICMP packets. */ @Component(immediate = true) public class IcmpDropper { private static final Logger log = getLogger(IcmpDropper.class); private static final String APP_NAME = "org.onosproject.p4tutorial.icmpdropper"; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private DeviceService deviceService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private FlowRuleService flowRuleService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private ApplicationAdminService appService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private PiPipeconfService piPipeconfService; private final DeviceListener deviceListener = new InternalDeviceListener(); private ApplicationId appId; @Activate public void activate() { log.info("Starting..."); appId = coreService.registerApplication(APP_NAME); // Register listener for handling new devices. deviceService.addListener(deviceListener); // Install rules to existing devices. deviceService.getDevices() .forEach(device -> installDropRule(device.id())); log.info("STARTED", appId.id()); } @Deactivate public void deactivate() { log.info("Stopping..."); deviceService.removeListener(deviceListener); flowRuleService.removeFlowRulesById(appId); log.info("STOPPED"); } private boolean checkPipeconf(Device device) { if (!device.is(PiPipelineProgrammable.class)) { // Device is not PI-pipeline programmable. Ignore. return false; } if (!piPipeconfService.ofDevice(device.id()).isPresent() || !piPipeconfService.ofDevice(device.id()).get().equals(PipeconfFactory.PIPECONF_ID)) { log.warn("Device {} has pipeconf {} instead of {}, can't install flow rule for this device", device.id(), piPipeconfService.ofDevice(device.id()).get(), PipeconfFactory.PIPECONF_ID); return false; } return true; } private void installDropRule(DeviceId deviceId) { PiMatchFieldId ipv4ProtoFieldId = PiMatchFieldId.of("hdr.ipv4.protocol"); PiActionId dropActionId = PiActionId.of("_drop"); PiCriterion piCriterion = PiCriterion.builder() .matchExact(ipv4ProtoFieldId, (byte) 0x01) .build(); PiAction dropAction = PiAction.builder() .withId(dropActionId) .build(); FlowRule flowRule = DefaultFlowRule.builder() .forDevice(deviceId) .forTable(PiTableId.of("ip_proto_filter_table")) .fromApp(appId) .makePermanent() .withPriority(1000) .withSelector(DefaultTrafficSelector.builder() .matchPi(piCriterion) .build()) .withTreatment( DefaultTrafficTreatment.builder() .piTableAction(dropAction) .build()) .build(); log.warn("Installing ICMP drop rule to {}", deviceId); flowRuleService.applyFlowRules(flowRule); } /** * A listener of device events that installs a rule to drop packet for each new device. */ private class InternalDeviceListener implements DeviceListener { @Override public void event(DeviceEvent event) { Device device = event.subject(); if (checkPipeconf(device)) { installDropRule(device.id()); } } @Override public boolean isRelevant(DeviceEvent event) { // Reacts only to new devices. return event.type() == DEVICE_ADDED; } } }
apps/p4-tutorial/icmpdropper/src/main/java/org/onosproject/p4tutorial/icmpdropper/IcmpDropper.java
/* * Copyright 2017-present Open Networking Foundation * * 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.onosproject.p4tutorial.icmpdropper; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.onosproject.app.ApplicationAdminService; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceListener; import org.onosproject.net.device.DeviceService; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.FlowRule; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.criteria.PiCriterion; import org.onosproject.net.behaviour.PiPipelineProgrammable; import org.onosproject.net.pi.runtime.PiAction; import org.onosproject.net.pi.model.PiActionId; import org.onosproject.net.pi.model.PiMatchFieldId; import org.onosproject.net.pi.service.PiPipeconfService; import org.onosproject.net.pi.model.PiTableId; import org.onosproject.p4tutorial.pipeconf.PipeconfFactory; import org.slf4j.Logger; import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_ADDED; import static org.slf4j.LoggerFactory.getLogger; /** * Simple application that drops all ICMP packets. */ @Component(immediate = true) public class IcmpDropper { private static final Logger log = getLogger(IcmpDropper.class); private static final String APP_NAME = "org.onosproject.p4tutorial.icmpdropper"; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private DeviceService deviceService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private FlowRuleService flowRuleService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private ApplicationAdminService appService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private PiPipeconfService piPipeconfService; private final DeviceListener deviceListener = new InternalDeviceListener(); private ApplicationId appId; @Activate public void activate() { log.info("Starting..."); appId = coreService.registerApplication(APP_NAME); // Register listener for handling new devices. deviceService.addListener(deviceListener); // Install rules to existing devices. deviceService.getDevices() .forEach(device -> installDropRule(device.id())); log.info("STARTED", appId.id()); } @Deactivate public void deactivate() { log.info("Stopping..."); deviceService.removeListener(deviceListener); flowRuleService.removeFlowRulesById(appId); log.info("STOPPED"); } private boolean checkPipeconf(Device device) { if (!device.is(PiPipelineProgrammable.class)) { // Device is not PI-pipeline programmable. Ignore. return false; } if (!piPipeconfService.ofDevice(device.id()).isPresent() || !piPipeconfService.ofDevice(device.id()).get().equals(PipeconfFactory.PIPECONF_ID)) { log.warn("Device {} has pipeconf {} instead of {}, can't install flow rule for this device", device.id(), piPipeconfService.ofDevice(device.id()).get(), PipeconfFactory.PIPECONF_ID); return false; } return true; } private void installDropRule(DeviceId deviceId) { PiMatchFieldId ipv4ProtoFieldId = PiMatchFieldId.of("ipv4.protocol"); PiActionId dropActionId = PiActionId.of("_drop"); PiCriterion piCriterion = PiCriterion.builder() .matchExact(ipv4ProtoFieldId, (byte) 0x01) .build(); PiAction dropAction = PiAction.builder() .withId(dropActionId) .build(); FlowRule flowRule = DefaultFlowRule.builder() .forDevice(deviceId) .forTable(PiTableId.of("ip_proto_filter_table")) .fromApp(appId) .makePermanent() .withPriority(1000) .withSelector(DefaultTrafficSelector.builder() .matchPi(piCriterion) .build()) .withTreatment( DefaultTrafficTreatment.builder() .piTableAction(dropAction) .build()) .build(); log.warn("Installing ICMP drop rule to {}", deviceId); flowRuleService.applyFlowRules(flowRule); } /** * A listener of device events that installs a rule to drop packet for each new device. */ private class InternalDeviceListener implements DeviceListener { @Override public void event(DeviceEvent event) { Device device = event.subject(); if (checkPipeconf(device)) { installDropRule(device.id()); } } @Override public boolean isRelevant(DeviceEvent event) { // Reacts only to new devices. return event.type() == DEVICE_ADDED; } } }
fix 'unable to translate flow rule' in p4-tutorial icmpdropper Change-Id: I6dbcc19f33d0db56cfce1d81c992e5592e82cf8a
apps/p4-tutorial/icmpdropper/src/main/java/org/onosproject/p4tutorial/icmpdropper/IcmpDropper.java
fix 'unable to translate flow rule' in p4-tutorial icmpdropper
<ide><path>pps/p4-tutorial/icmpdropper/src/main/java/org/onosproject/p4tutorial/icmpdropper/IcmpDropper.java <ide> } <ide> <ide> private void installDropRule(DeviceId deviceId) { <del> PiMatchFieldId ipv4ProtoFieldId = PiMatchFieldId.of("ipv4.protocol"); <add> PiMatchFieldId ipv4ProtoFieldId = PiMatchFieldId.of("hdr.ipv4.protocol"); <ide> PiActionId dropActionId = PiActionId.of("_drop"); <ide> <ide> PiCriterion piCriterion = PiCriterion.builder()
Java
apache-2.0
7240d6199382f17d24e8eec10db5864eae061081
0
billchen198318/bamboobsc,billchen198318/bamboobsc
/* * Copyright 2012-2016 bambooCORE, greenstep of copyright Chen Xin Nien * * 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. * * ----------------------------------------------------------------------- * * author: Chen Xin Nien * contact: [email protected] * */ package com.netsteadfast.greenstep.bsc.service.logic.impl; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; import com.netsteadfast.greenstep.BscConstants; import com.netsteadfast.greenstep.base.Constants; import com.netsteadfast.greenstep.base.SysMessageUtil; import com.netsteadfast.greenstep.base.exception.ServiceException; import com.netsteadfast.greenstep.base.model.DefaultResult; import com.netsteadfast.greenstep.base.model.GreenStepSysMsgConstants; import com.netsteadfast.greenstep.base.model.ServiceAuthority; import com.netsteadfast.greenstep.base.model.ServiceMethodAuthority; import com.netsteadfast.greenstep.base.model.ServiceMethodType; import com.netsteadfast.greenstep.base.model.SystemMessage; import com.netsteadfast.greenstep.base.model.YesNo; import com.netsteadfast.greenstep.base.service.logic.BscBaseLogicService; import com.netsteadfast.greenstep.bsc.service.IDegreeFeedbackAssignService; import com.netsteadfast.greenstep.bsc.service.IEmployeeHierService; import com.netsteadfast.greenstep.bsc.service.IEmployeeOrgaService; import com.netsteadfast.greenstep.bsc.service.IKpiEmplService; import com.netsteadfast.greenstep.bsc.service.IMeasureDataService; import com.netsteadfast.greenstep.bsc.service.IMonitorItemScoreService; import com.netsteadfast.greenstep.bsc.service.IPdcaItemOwnerService; import com.netsteadfast.greenstep.bsc.service.IPdcaMeasureFreqService; import com.netsteadfast.greenstep.bsc.service.IPdcaOwnerService; import com.netsteadfast.greenstep.bsc.service.IReportRoleViewService; import com.netsteadfast.greenstep.bsc.service.ITsaMeasureFreqService; import com.netsteadfast.greenstep.bsc.service.logic.IEmployeeLogicService; import com.netsteadfast.greenstep.model.UploadTypes; import com.netsteadfast.greenstep.po.hbm.BbDegreeFeedbackAssign; import com.netsteadfast.greenstep.po.hbm.BbEmployeeHier; import com.netsteadfast.greenstep.po.hbm.BbEmployeeOrga; import com.netsteadfast.greenstep.po.hbm.BbKpiEmpl; import com.netsteadfast.greenstep.po.hbm.BbMeasureData; import com.netsteadfast.greenstep.po.hbm.BbMonitorItemScore; import com.netsteadfast.greenstep.po.hbm.BbPdcaItemOwner; import com.netsteadfast.greenstep.po.hbm.BbPdcaMeasureFreq; import com.netsteadfast.greenstep.po.hbm.BbPdcaOwner; import com.netsteadfast.greenstep.po.hbm.BbReportRoleView; import com.netsteadfast.greenstep.po.hbm.BbTsaMeasureFreq; import com.netsteadfast.greenstep.po.hbm.TbSysCalendarNote; import com.netsteadfast.greenstep.po.hbm.TbSysMsgNotice; import com.netsteadfast.greenstep.po.hbm.TbUserRole; import com.netsteadfast.greenstep.service.ISysCalendarNoteService; import com.netsteadfast.greenstep.service.ISysMsgNoticeService; import com.netsteadfast.greenstep.service.logic.IRoleLogicService; import com.netsteadfast.greenstep.util.IconUtils; import com.netsteadfast.greenstep.util.SimpleUtils; import com.netsteadfast.greenstep.util.UploadSupportUtils; import com.netsteadfast.greenstep.vo.AccountVO; import com.netsteadfast.greenstep.vo.DegreeFeedbackAssignVO; import com.netsteadfast.greenstep.vo.EmployeeHierVO; import com.netsteadfast.greenstep.vo.EmployeeOrgaVO; import com.netsteadfast.greenstep.vo.EmployeeVO; import com.netsteadfast.greenstep.vo.KpiEmplVO; import com.netsteadfast.greenstep.vo.MeasureDataVO; import com.netsteadfast.greenstep.vo.MonitorItemScoreVO; import com.netsteadfast.greenstep.vo.OrganizationVO; import com.netsteadfast.greenstep.vo.PdcaItemOwnerVO; import com.netsteadfast.greenstep.vo.PdcaMeasureFreqVO; import com.netsteadfast.greenstep.vo.PdcaOwnerVO; import com.netsteadfast.greenstep.vo.ReportRoleViewVO; import com.netsteadfast.greenstep.vo.SysCalendarNoteVO; import com.netsteadfast.greenstep.vo.SysMsgNoticeVO; import com.netsteadfast.greenstep.vo.TsaMeasureFreqVO; import com.netsteadfast.greenstep.vo.UserRoleVO; @ServiceAuthority(check=true) @Service("bsc.service.logic.EmployeeLogicService") @Transactional(propagation=Propagation.REQUIRED, readOnly=true) public class EmployeeLogicServiceImpl extends BscBaseLogicService implements IEmployeeLogicService { protected Logger logger=Logger.getLogger(EmployeeLogicServiceImpl.class); private final static String TREE_ICON_ID = "PERSON"; private IEmployeeOrgaService<EmployeeOrgaVO, BbEmployeeOrga, String> employeeOrgaService; private ISysMsgNoticeService<SysMsgNoticeVO, TbSysMsgNotice, String> sysMsgNoticeService; private ISysCalendarNoteService<SysCalendarNoteVO, TbSysCalendarNote, String> sysCalendarNoteService; private IReportRoleViewService<ReportRoleViewVO, BbReportRoleView, String> reportRoleViewService; private IKpiEmplService<KpiEmplVO, BbKpiEmpl, String> kpiEmplService; private IDegreeFeedbackAssignService<DegreeFeedbackAssignVO, BbDegreeFeedbackAssign, String> degreeFeedbackAssignService; private IMeasureDataService<MeasureDataVO, BbMeasureData, String> measureDataService; private IPdcaOwnerService<PdcaOwnerVO, BbPdcaOwner, String> pdcaOwnerService; private IPdcaItemOwnerService<PdcaItemOwnerVO, BbPdcaItemOwner, String> pdcaItemOwnerService; private IRoleLogicService roleLogicService; private IMonitorItemScoreService<MonitorItemScoreVO, BbMonitorItemScore, String> monitorItemScoreService; private IEmployeeHierService<EmployeeHierVO, BbEmployeeHier, String> employeeHierService; private IPdcaMeasureFreqService<PdcaMeasureFreqVO, BbPdcaMeasureFreq, String> pdcaMeasureFreqService; private ITsaMeasureFreqService<TsaMeasureFreqVO, BbTsaMeasureFreq, String> tsaMeasureFreqService; public EmployeeLogicServiceImpl() { super(); } public IEmployeeOrgaService<EmployeeOrgaVO, BbEmployeeOrga, String> getEmployeeOrgaService() { return employeeOrgaService; } @Autowired @Resource(name="bsc.service.EmployeeOrgaService") @Required public void setEmployeeOrgaService(IEmployeeOrgaService<EmployeeOrgaVO, BbEmployeeOrga, String> employeeOrgaService) { this.employeeOrgaService = employeeOrgaService; } public ISysMsgNoticeService<SysMsgNoticeVO, TbSysMsgNotice, String> getSysMsgNoticeService() { return sysMsgNoticeService; } @Autowired @Resource(name="core.service.SysMsgNoticeService") @Required public void setSysMsgNoticeService( ISysMsgNoticeService<SysMsgNoticeVO, TbSysMsgNotice, String> sysMsgNoticeService) { this.sysMsgNoticeService = sysMsgNoticeService; } public ISysCalendarNoteService<SysCalendarNoteVO, TbSysCalendarNote, String> getSysCalendarNoteService() { return sysCalendarNoteService; } @Autowired @Resource(name="core.service.SysCalendarNoteService") @Required public void setSysCalendarNoteService( ISysCalendarNoteService<SysCalendarNoteVO, TbSysCalendarNote, String> sysCalendarNoteService) { this.sysCalendarNoteService = sysCalendarNoteService; } public IReportRoleViewService<ReportRoleViewVO, BbReportRoleView, String> getReportRoleViewService() { return reportRoleViewService; } @Autowired @Resource(name="bsc.service.ReportRoleViewService") @Required public void setReportRoleViewService( IReportRoleViewService<ReportRoleViewVO, BbReportRoleView, String> reportRoleViewService) { this.reportRoleViewService = reportRoleViewService; } public IKpiEmplService<KpiEmplVO, BbKpiEmpl, String> getKpiEmplService() { return kpiEmplService; } @Autowired @Resource(name="bsc.service.KpiEmplService") @Required public void setKpiEmplService( IKpiEmplService<KpiEmplVO, BbKpiEmpl, String> kpiEmplService) { this.kpiEmplService = kpiEmplService; } public IDegreeFeedbackAssignService<DegreeFeedbackAssignVO, BbDegreeFeedbackAssign, String> getDegreeFeedbackAssignService() { return degreeFeedbackAssignService; } @Autowired @Resource(name="bsc.service.DegreeFeedbackAssignService") @Required public void setDegreeFeedbackAssignService( IDegreeFeedbackAssignService<DegreeFeedbackAssignVO, BbDegreeFeedbackAssign, String> degreeFeedbackAssignService) { this.degreeFeedbackAssignService = degreeFeedbackAssignService; } public IMeasureDataService<MeasureDataVO, BbMeasureData, String> getMeasureDataService() { return measureDataService; } @Autowired @Resource(name="bsc.service.MeasureDataService") @Required public void setMeasureDataService( IMeasureDataService<MeasureDataVO, BbMeasureData, String> measureDataService) { this.measureDataService = measureDataService; } public IPdcaOwnerService<PdcaOwnerVO, BbPdcaOwner, String> getPdcaOwnerService() { return pdcaOwnerService; } @Autowired @Resource(name="bsc.service.PdcaOwnerService") @Required public void setPdcaOwnerService(IPdcaOwnerService<PdcaOwnerVO, BbPdcaOwner, String> pdcaOwnerService) { this.pdcaOwnerService = pdcaOwnerService; } public IPdcaItemOwnerService<PdcaItemOwnerVO, BbPdcaItemOwner, String> getPdcaItemOwnerService() { return pdcaItemOwnerService; } @Autowired @Resource(name="bsc.service.PdcaItemOwnerService") @Required public void setPdcaItemOwnerService( IPdcaItemOwnerService<PdcaItemOwnerVO, BbPdcaItemOwner, String> pdcaItemOwnerService) { this.pdcaItemOwnerService = pdcaItemOwnerService; } public IRoleLogicService getRoleLogicService() { return roleLogicService; } @Autowired @Resource(name="core.service.logic.RoleLogicService") @Required public void setRoleLogicService(IRoleLogicService roleLogicService) { this.roleLogicService = roleLogicService; } public IMonitorItemScoreService<MonitorItemScoreVO, BbMonitorItemScore, String> getMonitorItemScoreService() { return monitorItemScoreService; } @Autowired @Resource(name="bsc.service.MonitorItemScoreService") @Required public void setMonitorItemScoreService( IMonitorItemScoreService<MonitorItemScoreVO, BbMonitorItemScore, String> monitorItemScoreService) { this.monitorItemScoreService = monitorItemScoreService; } public IEmployeeHierService<EmployeeHierVO, BbEmployeeHier, String> getEmployeeHierService() { return employeeHierService; } @Autowired @Resource(name="bsc.service.EmployeeHierService") @Required public void setEmployeeHierService(IEmployeeHierService<EmployeeHierVO, BbEmployeeHier, String> employeeHierService) { this.employeeHierService = employeeHierService; } public IPdcaMeasureFreqService<PdcaMeasureFreqVO, BbPdcaMeasureFreq, String> getPdcaMeasureFreqService() { return pdcaMeasureFreqService; } @Autowired @Resource(name="bsc.service.PdcaMeasureFreqService") @Required public void setPdcaMeasureFreqService( IPdcaMeasureFreqService<PdcaMeasureFreqVO, BbPdcaMeasureFreq, String> pdcaMeasureFreqService) { this.pdcaMeasureFreqService = pdcaMeasureFreqService; } public ITsaMeasureFreqService<TsaMeasureFreqVO, BbTsaMeasureFreq, String> getTsaMeasureFreqService() { return tsaMeasureFreqService; } @Autowired @Resource(name="bsc.service.TsaMeasureFreqService") @Required public void setTsaMeasureFreqService( ITsaMeasureFreqService<TsaMeasureFreqVO, BbTsaMeasureFreq, String> tsaMeasureFreqService) { this.tsaMeasureFreqService = tsaMeasureFreqService; } private boolean isAdministrator(String account) { if (account.equals("admin") || account.equals(Constants.SYSTEM_BACKGROUND_USER)) { return true; } return false; } private AccountVO tranAccount(EmployeeVO employee) throws Exception { AccountVO account = new AccountVO(); account.setAccount(employee.getAccount()); account.setOnJob(YesNo.YES); account.setPassword( this.getAccountService().tranPassword(employee.getPassword()) ); return account; } @ServiceMethodAuthority(type={ServiceMethodType.INSERT}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<EmployeeVO> create(EmployeeVO employee, List<String> organizationOid) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getEmpId())) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } Map<String, Object> params = new HashMap<String, Object>(); params.put("empId", employee.getEmpId()); if (this.getEmployeeService().countByParams(params) > 0) { throw new ServiceException("Please change another Id!"); } AccountVO account = this.tranAccount(employee); if (this.isAdministrator(account.getAccount())) { throw new ServiceException("Please change another Account!"); } DefaultResult<AccountVO> mResult = this.getAccountService().saveObject(account); if (mResult.getValue()==null) { throw new ServiceException( mResult.getSystemMessage().getValue() ); } DefaultResult<EmployeeVO> result = this.getEmployeeService().saveObject(employee); employee = result.getValue(); this.createEmployeeOrganization(result.getValue(), organizationOid); // create default role UserRoleVO userRole = new UserRoleVO(); userRole.setAccount(result.getValue().getAccount()); userRole.setRole( this.roleLogicService.getDefaultUserRole() ); userRole.setDescription(result.getValue().getAccount() + " `s role!"); this.getUserRoleService().saveObject(userRole); this.createHierarchy(employee, BscConstants.EMPLOYEE_HIER_ZERO_OID); return result; } @ServiceMethodAuthority(type={ServiceMethodType.UPDATE}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<EmployeeVO> update(EmployeeVO employee, List<String> organizationOid) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getOid()) ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } EmployeeVO dbEmployee = this.findEmployeeData( employee.getOid() ); this.deleteEmployeeOrganization( dbEmployee ); employee.setAccount(dbEmployee.getAccount() ); employee.setEmpId( dbEmployee.getEmpId() ); DefaultResult<EmployeeVO> result = this.getEmployeeService().updateObject(employee); if (result.getValue()==null) { throw new ServiceException(result.getSystemMessage().getValue()); } this.createEmployeeOrganization(result.getValue(), organizationOid); return result; } @ServiceMethodAuthority(type={ServiceMethodType.UPDATE}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<AccountVO> updatePassword(EmployeeVO employee, String newPassword) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getOid()) || super.isBlank(employee.getPassword()) || super.isBlank(newPassword) ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } EmployeeVO dbEmployee = this.findEmployeeData(employee.getOid()); AccountVO account = this.findAccountData( dbEmployee.getAccount() ); if (!account.getPassword().equals( this.getAccountService().tranPassword(employee.getPassword()) ) ) { throw new ServiceException("The current password(old password) is incorrect!"); } account.setPassword( this.getAccountService().tranPassword(newPassword) ); return getAccountService().updateObject(account); } @ServiceMethodAuthority(type={ServiceMethodType.DELETE}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<Boolean> delete(EmployeeVO employee) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getOid()) ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } employee = this.findEmployeeData(employee.getOid()); AccountVO account = this.findAccountData(employee.getAccount()); if (this.isAdministrator(account.getAccount())) { throw new ServiceException("Administrator cannot delete!"); } // check account data for other table use. this.checkInformationRelated(account, employee); this.deleteEmployeeOrganization(employee); // delete user role Map<String, Object> params = new HashMap<String, Object>(); params.put("account", account.getAccount()); List<TbUserRole> userRoles = this.getUserRoleService().findListByParams(params); for (int i=0; userRoles!=null && i<userRoles.size(); i++) { TbUserRole uRole = userRoles.get(i); this.getUserRoleService().delete(uRole); } // delete BB_REPORT_ROLE_VIEW params.clear(); params.put("idName", account.getAccount()); List<BbReportRoleView> reportRoleViews = this.reportRoleViewService.findListByParams(params); for (int i=0; reportRoleViews!=null && i<reportRoleViews.size(); i++) { BbReportRoleView reportRoleView = reportRoleViews.get( i ); this.reportRoleViewService.delete(reportRoleView); } // delete from BB_MEASURE_DATA where EMP_ID = :empId this.measureDataService.deleteForEmpId( employee.getEmpId() ); this.monitorItemScoreService.deleteForEmpId( employee.getEmpId() ); this.deleteHierarchy(employee); this.getAccountService().deleteByPKng(account.getOid()); return getEmployeeService().deleteObject(employee); } private void checkInformationRelated(AccountVO account, EmployeeVO employee) throws ServiceException, Exception { if (account==null || super.isBlank(account.getAccount()) || employee==null || super.isBlank(employee.getEmpId()) ) { return; } Map<String, Object> params = new HashMap<String, Object>(); // tb_sys_msg_notice params.put("toAccount", account.getAccount()); if (this.sysMsgNoticeService.countByParams(params) > 0 ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // tb_sys_calendar_note params.clear(); params.put("account", account.getAccount()); if (this.sysCalendarNoteService.countByParams(params) > 0 ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_kpi_empl params.clear(); params.put("empId", employee.getEmpId()); if (this.kpiEmplService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_pdca_owner if (this.pdcaOwnerService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_pdca_item_owner if (this.pdcaItemOwnerService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_pdca_measure_freq params.clear(); params.put("empId", employee.getEmpId()); if (this.pdcaMeasureFreqService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_tsa_measure_freq if (this.tsaMeasureFreqService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_degree_feedback_assign params.clear(); params.put("ownerId", employee.getEmpId()); if (this.degreeFeedbackAssignService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } params.clear(); params.put("raterId", employee.getEmpId()); if (this.degreeFeedbackAssignService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } if (this.foundChild(employee)) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } } private void createEmployeeOrganization(EmployeeVO employee, List<String> organizationOid) throws ServiceException, Exception { if (employee==null || StringUtils.isBlank(employee.getEmpId()) || organizationOid==null || organizationOid.size() < 1 ) { return; } for (String oid : organizationOid) { OrganizationVO organization = this.findOrganizationData(oid); EmployeeOrgaVO empOrg = new EmployeeOrgaVO(); empOrg.setEmpId(employee.getEmpId()); empOrg.setOrgId(organization.getOrgId()); this.employeeOrgaService.saveObject(empOrg); } } private void deleteEmployeeOrganization(EmployeeVO employee) throws ServiceException, Exception { if (employee==null || StringUtils.isBlank(employee.getEmpId()) ) { return; } Map<String, Object> params = new HashMap<String, Object>(); params.put("empId", employee.getEmpId()); List<BbEmployeeOrga> searchList = this.employeeOrgaService.findListByParams(params); if (searchList==null || searchList.size()<1 ) { return; } for (BbEmployeeOrga empOrg : searchList) { this.employeeOrgaService.delete(empOrg); } } private void createHierarchy(EmployeeVO employee, String supOid) throws ServiceException, Exception { if (null == employee || super.isBlank(employee.getOid()) || super.isBlank(supOid)) { return; } EmployeeHierVO hier = new EmployeeHierVO(); hier.setEmpOid(employee.getOid()); hier.setSupOid(supOid); this.employeeHierService.saveObject(hier); } @ServiceMethodAuthority(type={ServiceMethodType.SELECT}) @Override public List<Map<String, Object>> getTreeData(String basePath) throws ServiceException, Exception { List<Map<String, Object>> items = new LinkedList<Map<String, Object>>(); List<EmployeeVO> empList = this.getEmployeeService().findForJoinHier(); if (empList==null || empList.size()<1 ) { return items; } for (EmployeeVO emp : empList) { // 先放沒有父親的員工資料 if (!(super.isBlank(emp.getSupOid()) || BscConstants.EMPLOYEE_HIER_ZERO_OID.equals(emp.getSupOid()) ) ) { continue; } Map<String, Object> parentDataMap = new LinkedHashMap<String, Object>(); parentDataMap.put("type", "parent"); parentDataMap.put("id", emp.getOid()); parentDataMap.put("name", IconUtils.getMenuIcon(basePath, TREE_ICON_ID) + StringEscapeUtils.escapeHtml4(this.getTreeShowName(emp)) ); parentDataMap.put("oid", emp.getOid()); items.add(parentDataMap); } // 再開始放孩子 for (int ix=0; ix<items.size(); ix++) { Map<String, Object> parentDataMap=items.get(ix); String oid = (String)parentDataMap.get("oid"); this.getTreeData(basePath, parentDataMap, empList, oid); } return items; } private void getTreeData(String basePath, Map<String, Object> putObject, List<EmployeeVO> searchList, String supOid) throws Exception { List<String> childList = new LinkedList<String>(); this.getChildEmpLevelOne(searchList, supOid, childList); if (childList.size()<1) { return; } for (String childEmpOid : childList) { EmployeeVO emp = this.getEmployeeFromSearchList(searchList, childEmpOid, false); EmployeeVO childEmp = this.getEmployeeFromSearchList(searchList, childEmpOid, true); if (emp==null) { continue; } Map<String, Object> thePutObject=null; @SuppressWarnings("unchecked") List<Map<String, Object>> childrenList = (List<Map<String, Object>>)putObject.get("children"); if (childrenList==null) { childrenList=new LinkedList<Map<String, Object>>(); } Map<String, Object> nodeMap=new LinkedHashMap<String, Object>(); nodeMap.put("id", emp.getOid()); nodeMap.put("name", IconUtils.getMenuIcon(basePath, TREE_ICON_ID) + StringEscapeUtils.escapeHtml4(this.getTreeShowName(emp)) ); nodeMap.put("oid", emp.getOid() ); childrenList.add(nodeMap); putObject.put("children", childrenList); if (childEmp!=null) { thePutObject=nodeMap; } else { nodeMap.put("type", "Leaf"); thePutObject=putObject; } if (childEmp!=null) { this.getTreeData(basePath, thePutObject, searchList, childEmpOid); } } } private List<String> getChildEmpLevelOne(List<EmployeeVO> searchList, String supOid, List<String> childList) throws Exception { if (childList==null) { childList=new LinkedList<String>(); } for (EmployeeVO emp : searchList) { if (supOid.equals(emp.getSupOid())) { childList.add(emp.getOid()); } } return childList; } private EmployeeVO getEmployeeFromSearchList(List<EmployeeVO> searchList, String empOid, boolean isChild) throws Exception { for (EmployeeVO emp : searchList) { if (!isChild) { if (emp.getOid().equals(empOid)) { return emp; } } else { if (emp.getSupOid().equals(empOid)) { return emp; } } } return null; } private String getTreeShowName(EmployeeVO employee) throws Exception { if ( !super.isBlank(employee.getJobTitle()) ) { return employee.getEmpId() + " - " + StringEscapeUtils.escapeHtml4(employee.getFullName()) + " ( " + employee.getJobTitle().trim() + " )"; } return employee.getEmpId() + " - " + StringEscapeUtils.escapeHtml4(employee.getFullName()); } private boolean foundChild(EmployeeVO employee) throws ServiceException, Exception { if (null == employee || super.isBlank(employee.getOid())) { return false; } Map<String, Object> params = new HashMap<String, Object>(); params.put("supOid", employee.getOid()); if (this.employeeHierService.countByParams(params) > 0 ) { return true; } return false; } private boolean foundChild(String supOid, String checkEmpOid) throws ServiceException, Exception { List<EmployeeVO> treeList = this.getEmployeeService().findForJoinHier(); if (treeList==null || treeList.size() <1 ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } boolean f = false; List<EmployeeVO> childList=new LinkedList<EmployeeVO>(); this.getChild(checkEmpOid, treeList, childList); for (int ix=0; childList!=null && ix<childList.size(); ix++) { if (childList.get(ix).getOid().equals(checkEmpOid)) { f = true; } } return f; } private void getChild(String supOid, List<EmployeeVO> tree, List<EmployeeVO> put) throws Exception { if (put==null || tree==null) { return; } if (StringUtils.isBlank(supOid) || BscConstants.EMPLOYEE_HIER_ZERO_OID.equals(supOid) ) { return; } for (EmployeeVO emp : tree) { if (emp.getSupOid().equals(supOid)) { put.add(emp); this.getChild(emp.getOid(), tree, put); } } } private void deleteHierarchy(EmployeeVO employee) throws ServiceException, Exception { if (null == employee || super.isBlank(employee.getOid())) { return; } Map<String, Object> params = new HashMap<String, Object>(); params.put("empOid", employee.getOid()); List<BbEmployeeHier> hierList = this.employeeHierService.findListByParams(params); if (null == hierList) { return; } for (BbEmployeeHier hier : hierList) { employeeHierService.delete(hier); } } @ServiceMethodAuthority(type={ServiceMethodType.UPDATE}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<Boolean> updateSupervisor(EmployeeVO employee, String supervisorOid) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getOid()) || super.isBlank(supervisorOid)) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } DefaultResult<Boolean> result = new DefaultResult<Boolean>(); result.setValue(Boolean.FALSE); result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.UPDATE_FAIL)) ); employee = this.findEmployeeData(employee.getOid()); this.deleteHierarchy(employee); if ("root".equals(supervisorOid) || "r".equals(supervisorOid)) { this.createHierarchy(employee, BscConstants.EMPLOYEE_HIER_ZERO_OID); } else { EmployeeVO newHierEmployee = this.findEmployeeData(supervisorOid); // 找當前員工的的資料, 不因該存在要update的新關聯主管 if ( this.foundChild(employee.getOid(), newHierEmployee.getOid()) ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_ERRORS)); } this.createHierarchy(employee, newHierEmployee.getOid()); } result.setValue(Boolean.TRUE); result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.UPDATE_SUCCESS)) ); return result; } /** * for upgrade 0.7.1 need data * * @throws ServiceException * @throws Exception */ @ServiceMethodAuthority(type={ServiceMethodType.INSERT}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public void initHierarchyForFirst() throws ServiceException, Exception { List<EmployeeVO> employeeList = this.getEmployeeService().findListVOByParams(null); if (null == employeeList || employeeList.size() < 1) { return; } Map<String, Object> paramMap = new HashMap<String, Object>(); for (EmployeeVO employee : employeeList) { paramMap.clear(); paramMap.put("empOid", employee.getOid()); if (this.employeeHierService.countByParams(paramMap) > 0) { continue; } this.createHierarchy(employee, BscConstants.EMPLOYEE_HIER_ZERO_OID); } } /** * 這個 Method 的 ServiceMethodAuthority 權限給查詢狀態 * 這裡的 basePath 只是要取 getTreeData 時參數要用, 再這是沒有用處的 */ @ServiceMethodAuthority(type={ServiceMethodType.SELECT}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<String> createOrgChartData(String basePath, EmployeeVO currentEmployee) throws ServiceException, Exception { if (null != currentEmployee && !super.isBlank(currentEmployee.getOid())) { currentEmployee = this.findEmployeeData( currentEmployee.getOid() ); } List<Map<String, Object>> treeMap = this.getTreeData(basePath); if (null == treeMap || treeMap.size() < 1) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)); } this.resetTreeMapContentForOrgChartData(treeMap, currentEmployee); Map<String, Object> rootMap = new HashMap<String, Object>(); rootMap.put("name", "Employee hierarchy"); rootMap.put("title", "hierarchy structure"); rootMap.put("children", treeMap); ObjectMapper objectMapper = new ObjectMapper(); String jsonData = objectMapper.writeValueAsString(rootMap); String uploadOid = UploadSupportUtils.create( Constants.getSystem(), UploadTypes.IS_TEMP, false, jsonData.getBytes(), SimpleUtils.getUUIDStr() + ".json"); DefaultResult<String> result = new DefaultResult<String>(); result.setValue(uploadOid); result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.INSERT_SUCCESS)) ); return result; } /** * 這個 Method 的 ServiceMethodAuthority 權限給查詢狀態 * 這裡的 basePath 只是要取 getTreeData 時參數要用, 再這是沒有用處的 */ @ServiceMethodAuthority(type={ServiceMethodType.SELECT}) @Override public DefaultResult<Map<String, Object>> getOrgChartData(String basePath, EmployeeVO currentEmployee) throws ServiceException, Exception { if (null != currentEmployee && !super.isBlank(currentEmployee.getOid())) { currentEmployee = this.findEmployeeData( currentEmployee.getOid() ); } List<Map<String, Object>> treeMap = this.getTreeData(basePath); if (null == treeMap || treeMap.size() < 1) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)); } this.resetTreeMapContentForOrgChartData(treeMap, currentEmployee); Map<String, Object> rootMap = new HashMap<String, Object>(); rootMap.put("name", "Employee hierarchy"); rootMap.put("title", "hierarchy structure"); rootMap.put("children", treeMap); DefaultResult<Map<String, Object>> result = new DefaultResult<Map<String, Object>>(); result.setValue( rootMap ); result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.INSERT_SUCCESS)) ); return result; } @SuppressWarnings("unchecked") private void resetTreeMapContentForOrgChartData(List<Map<String, Object>> childMapList, EmployeeVO currentEmployee) throws Exception { for (Map<String, Object> nodeMap : childMapList) { String nodeEmployeeOid = String.valueOf( nodeMap.get("id") ); // 與 node.get("oid") 一樣 // 去除 OrgChart 不需要的資料 nodeMap.remove("type"); nodeMap.remove("id"); nodeMap.remove("name"); nodeMap.remove("oid"); EmployeeVO nodeEmployee = this.findEmployeeData(nodeEmployeeOid); // OrgChart 需要的資料, nodeMap 需要填入 name 與 title if (currentEmployee != null && !super.isBlank(currentEmployee.getOid()) && currentEmployee.getOid().equals(nodeEmployeeOid)) { // 有帶入當前員工來區別顏色 nodeMap.put("name", "<font color='#8A0808'>" + nodeEmployee.getEmpId() + " - " + nodeEmployee.getFullName() + "</font>" ); nodeMap.put("title", "<font color='#8A0808'>" + ( super.isBlank(nodeEmployee.getJobTitle()) ? "no job description" : nodeEmployee.getJobTitle().trim() ) + "</font>" ); } else { nodeMap.put("name", nodeEmployee.getEmpId() + " - " + nodeEmployee.getFullName()); nodeMap.put("title", ( super.isBlank(nodeEmployee.getJobTitle()) ? "no job description" : nodeEmployee.getJobTitle().trim() ) ); } if (nodeMap.get("children") != null && (nodeMap.get("children") instanceof List<?>)) { // 還有孩子項目資料 this.resetTreeMapContentForOrgChartData( (List<Map<String, Object>>) nodeMap.get("children"), currentEmployee ); } } } }
gsbsc-standard/src/com/netsteadfast/greenstep/bsc/service/logic/impl/EmployeeLogicServiceImpl.java
/* * Copyright 2012-2016 bambooCORE, greenstep of copyright Chen Xin Nien * * 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. * * ----------------------------------------------------------------------- * * author: Chen Xin Nien * contact: [email protected] * */ package com.netsteadfast.greenstep.bsc.service.logic.impl; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; import com.netsteadfast.greenstep.BscConstants; import com.netsteadfast.greenstep.base.Constants; import com.netsteadfast.greenstep.base.SysMessageUtil; import com.netsteadfast.greenstep.base.exception.ServiceException; import com.netsteadfast.greenstep.base.model.DefaultResult; import com.netsteadfast.greenstep.base.model.GreenStepSysMsgConstants; import com.netsteadfast.greenstep.base.model.ServiceAuthority; import com.netsteadfast.greenstep.base.model.ServiceMethodAuthority; import com.netsteadfast.greenstep.base.model.ServiceMethodType; import com.netsteadfast.greenstep.base.model.SystemMessage; import com.netsteadfast.greenstep.base.model.YesNo; import com.netsteadfast.greenstep.base.service.logic.BscBaseLogicService; import com.netsteadfast.greenstep.bsc.service.IDegreeFeedbackAssignService; import com.netsteadfast.greenstep.bsc.service.IEmployeeHierService; import com.netsteadfast.greenstep.bsc.service.IEmployeeOrgaService; import com.netsteadfast.greenstep.bsc.service.IKpiEmplService; import com.netsteadfast.greenstep.bsc.service.IMeasureDataService; import com.netsteadfast.greenstep.bsc.service.IMonitorItemScoreService; import com.netsteadfast.greenstep.bsc.service.IPdcaItemOwnerService; import com.netsteadfast.greenstep.bsc.service.IPdcaMeasureFreqService; import com.netsteadfast.greenstep.bsc.service.IPdcaOwnerService; import com.netsteadfast.greenstep.bsc.service.IReportRoleViewService; import com.netsteadfast.greenstep.bsc.service.ITsaMeasureFreqService; import com.netsteadfast.greenstep.bsc.service.logic.IEmployeeLogicService; import com.netsteadfast.greenstep.model.UploadTypes; import com.netsteadfast.greenstep.po.hbm.BbDegreeFeedbackAssign; import com.netsteadfast.greenstep.po.hbm.BbEmployeeHier; import com.netsteadfast.greenstep.po.hbm.BbEmployeeOrga; import com.netsteadfast.greenstep.po.hbm.BbKpiEmpl; import com.netsteadfast.greenstep.po.hbm.BbMeasureData; import com.netsteadfast.greenstep.po.hbm.BbMonitorItemScore; import com.netsteadfast.greenstep.po.hbm.BbPdcaItemOwner; import com.netsteadfast.greenstep.po.hbm.BbPdcaMeasureFreq; import com.netsteadfast.greenstep.po.hbm.BbPdcaOwner; import com.netsteadfast.greenstep.po.hbm.BbReportRoleView; import com.netsteadfast.greenstep.po.hbm.BbTsaMeasureFreq; import com.netsteadfast.greenstep.po.hbm.TbSysCalendarNote; import com.netsteadfast.greenstep.po.hbm.TbSysMsgNotice; import com.netsteadfast.greenstep.po.hbm.TbUserRole; import com.netsteadfast.greenstep.service.ISysCalendarNoteService; import com.netsteadfast.greenstep.service.ISysMsgNoticeService; import com.netsteadfast.greenstep.service.logic.IRoleLogicService; import com.netsteadfast.greenstep.util.IconUtils; import com.netsteadfast.greenstep.util.SimpleUtils; import com.netsteadfast.greenstep.util.UploadSupportUtils; import com.netsteadfast.greenstep.vo.AccountVO; import com.netsteadfast.greenstep.vo.DegreeFeedbackAssignVO; import com.netsteadfast.greenstep.vo.EmployeeHierVO; import com.netsteadfast.greenstep.vo.EmployeeOrgaVO; import com.netsteadfast.greenstep.vo.EmployeeVO; import com.netsteadfast.greenstep.vo.KpiEmplVO; import com.netsteadfast.greenstep.vo.MeasureDataVO; import com.netsteadfast.greenstep.vo.MonitorItemScoreVO; import com.netsteadfast.greenstep.vo.OrganizationVO; import com.netsteadfast.greenstep.vo.PdcaItemOwnerVO; import com.netsteadfast.greenstep.vo.PdcaMeasureFreqVO; import com.netsteadfast.greenstep.vo.PdcaOwnerVO; import com.netsteadfast.greenstep.vo.ReportRoleViewVO; import com.netsteadfast.greenstep.vo.SysCalendarNoteVO; import com.netsteadfast.greenstep.vo.SysMsgNoticeVO; import com.netsteadfast.greenstep.vo.TsaMeasureFreqVO; import com.netsteadfast.greenstep.vo.UserRoleVO; @ServiceAuthority(check=true) @Service("bsc.service.logic.EmployeeLogicService") @Transactional(propagation=Propagation.REQUIRED, readOnly=true) public class EmployeeLogicServiceImpl extends BscBaseLogicService implements IEmployeeLogicService { protected Logger logger=Logger.getLogger(EmployeeLogicServiceImpl.class); private final static String TREE_ICON_ID = "PERSON"; private IEmployeeOrgaService<EmployeeOrgaVO, BbEmployeeOrga, String> employeeOrgaService; private ISysMsgNoticeService<SysMsgNoticeVO, TbSysMsgNotice, String> sysMsgNoticeService; private ISysCalendarNoteService<SysCalendarNoteVO, TbSysCalendarNote, String> sysCalendarNoteService; private IReportRoleViewService<ReportRoleViewVO, BbReportRoleView, String> reportRoleViewService; private IKpiEmplService<KpiEmplVO, BbKpiEmpl, String> kpiEmplService; private IDegreeFeedbackAssignService<DegreeFeedbackAssignVO, BbDegreeFeedbackAssign, String> degreeFeedbackAssignService; private IMeasureDataService<MeasureDataVO, BbMeasureData, String> measureDataService; private IPdcaOwnerService<PdcaOwnerVO, BbPdcaOwner, String> pdcaOwnerService; private IPdcaItemOwnerService<PdcaItemOwnerVO, BbPdcaItemOwner, String> pdcaItemOwnerService; private IRoleLogicService roleLogicService; private IMonitorItemScoreService<MonitorItemScoreVO, BbMonitorItemScore, String> monitorItemScoreService; private IEmployeeHierService<EmployeeHierVO, BbEmployeeHier, String> employeeHierService; private IPdcaMeasureFreqService<PdcaMeasureFreqVO, BbPdcaMeasureFreq, String> pdcaMeasureFreqService; private ITsaMeasureFreqService<TsaMeasureFreqVO, BbTsaMeasureFreq, String> tsaMeasureFreqService; public EmployeeLogicServiceImpl() { super(); } public IEmployeeOrgaService<EmployeeOrgaVO, BbEmployeeOrga, String> getEmployeeOrgaService() { return employeeOrgaService; } @Autowired @Resource(name="bsc.service.EmployeeOrgaService") @Required public void setEmployeeOrgaService(IEmployeeOrgaService<EmployeeOrgaVO, BbEmployeeOrga, String> employeeOrgaService) { this.employeeOrgaService = employeeOrgaService; } public ISysMsgNoticeService<SysMsgNoticeVO, TbSysMsgNotice, String> getSysMsgNoticeService() { return sysMsgNoticeService; } @Autowired @Resource(name="core.service.SysMsgNoticeService") @Required public void setSysMsgNoticeService( ISysMsgNoticeService<SysMsgNoticeVO, TbSysMsgNotice, String> sysMsgNoticeService) { this.sysMsgNoticeService = sysMsgNoticeService; } public ISysCalendarNoteService<SysCalendarNoteVO, TbSysCalendarNote, String> getSysCalendarNoteService() { return sysCalendarNoteService; } @Autowired @Resource(name="core.service.SysCalendarNoteService") @Required public void setSysCalendarNoteService( ISysCalendarNoteService<SysCalendarNoteVO, TbSysCalendarNote, String> sysCalendarNoteService) { this.sysCalendarNoteService = sysCalendarNoteService; } public IReportRoleViewService<ReportRoleViewVO, BbReportRoleView, String> getReportRoleViewService() { return reportRoleViewService; } @Autowired @Resource(name="bsc.service.ReportRoleViewService") @Required public void setReportRoleViewService( IReportRoleViewService<ReportRoleViewVO, BbReportRoleView, String> reportRoleViewService) { this.reportRoleViewService = reportRoleViewService; } public IKpiEmplService<KpiEmplVO, BbKpiEmpl, String> getKpiEmplService() { return kpiEmplService; } @Autowired @Resource(name="bsc.service.KpiEmplService") @Required public void setKpiEmplService( IKpiEmplService<KpiEmplVO, BbKpiEmpl, String> kpiEmplService) { this.kpiEmplService = kpiEmplService; } public IDegreeFeedbackAssignService<DegreeFeedbackAssignVO, BbDegreeFeedbackAssign, String> getDegreeFeedbackAssignService() { return degreeFeedbackAssignService; } @Autowired @Resource(name="bsc.service.DegreeFeedbackAssignService") @Required public void setDegreeFeedbackAssignService( IDegreeFeedbackAssignService<DegreeFeedbackAssignVO, BbDegreeFeedbackAssign, String> degreeFeedbackAssignService) { this.degreeFeedbackAssignService = degreeFeedbackAssignService; } public IMeasureDataService<MeasureDataVO, BbMeasureData, String> getMeasureDataService() { return measureDataService; } @Autowired @Resource(name="bsc.service.MeasureDataService") @Required public void setMeasureDataService( IMeasureDataService<MeasureDataVO, BbMeasureData, String> measureDataService) { this.measureDataService = measureDataService; } public IPdcaOwnerService<PdcaOwnerVO, BbPdcaOwner, String> getPdcaOwnerService() { return pdcaOwnerService; } @Autowired @Resource(name="bsc.service.PdcaOwnerService") @Required public void setPdcaOwnerService(IPdcaOwnerService<PdcaOwnerVO, BbPdcaOwner, String> pdcaOwnerService) { this.pdcaOwnerService = pdcaOwnerService; } public IPdcaItemOwnerService<PdcaItemOwnerVO, BbPdcaItemOwner, String> getPdcaItemOwnerService() { return pdcaItemOwnerService; } @Autowired @Resource(name="bsc.service.PdcaItemOwnerService") @Required public void setPdcaItemOwnerService( IPdcaItemOwnerService<PdcaItemOwnerVO, BbPdcaItemOwner, String> pdcaItemOwnerService) { this.pdcaItemOwnerService = pdcaItemOwnerService; } public IRoleLogicService getRoleLogicService() { return roleLogicService; } @Autowired @Resource(name="core.service.logic.RoleLogicService") @Required public void setRoleLogicService(IRoleLogicService roleLogicService) { this.roleLogicService = roleLogicService; } public IMonitorItemScoreService<MonitorItemScoreVO, BbMonitorItemScore, String> getMonitorItemScoreService() { return monitorItemScoreService; } @Autowired @Resource(name="bsc.service.MonitorItemScoreService") @Required public void setMonitorItemScoreService( IMonitorItemScoreService<MonitorItemScoreVO, BbMonitorItemScore, String> monitorItemScoreService) { this.monitorItemScoreService = monitorItemScoreService; } public IEmployeeHierService<EmployeeHierVO, BbEmployeeHier, String> getEmployeeHierService() { return employeeHierService; } @Autowired @Resource(name="bsc.service.EmployeeHierService") @Required public void setEmployeeHierService(IEmployeeHierService<EmployeeHierVO, BbEmployeeHier, String> employeeHierService) { this.employeeHierService = employeeHierService; } public IPdcaMeasureFreqService<PdcaMeasureFreqVO, BbPdcaMeasureFreq, String> getPdcaMeasureFreqService() { return pdcaMeasureFreqService; } @Autowired @Resource(name="bsc.service.PdcaMeasureFreqService") @Required public void setPdcaMeasureFreqService( IPdcaMeasureFreqService<PdcaMeasureFreqVO, BbPdcaMeasureFreq, String> pdcaMeasureFreqService) { this.pdcaMeasureFreqService = pdcaMeasureFreqService; } public ITsaMeasureFreqService<TsaMeasureFreqVO, BbTsaMeasureFreq, String> getTsaMeasureFreqService() { return tsaMeasureFreqService; } @Autowired @Resource(name="bsc.service.TsaMeasureFreqService") @Required public void setTsaMeasureFreqService( ITsaMeasureFreqService<TsaMeasureFreqVO, BbTsaMeasureFreq, String> tsaMeasureFreqService) { this.tsaMeasureFreqService = tsaMeasureFreqService; } private boolean isAdministrator(String account) { if (account.equals("admin") || account.equals(Constants.SYSTEM_BACKGROUND_USER)) { return true; } return false; } private AccountVO tranAccount(EmployeeVO employee) throws Exception { AccountVO account = new AccountVO(); account.setAccount(employee.getAccount()); account.setOnJob(YesNo.YES); account.setPassword( this.getAccountService().tranPassword(employee.getPassword()) ); return account; } @ServiceMethodAuthority(type={ServiceMethodType.INSERT}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<EmployeeVO> create(EmployeeVO employee, List<String> organizationOid) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getEmpId())) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } Map<String, Object> params = new HashMap<String, Object>(); params.put("empId", employee.getEmpId()); if (this.getEmployeeService().countByParams(params) > 0) { throw new ServiceException("Please change another Id!"); } AccountVO account = this.tranAccount(employee); if (this.isAdministrator(account.getAccount())) { throw new ServiceException("Please change another Account!"); } DefaultResult<AccountVO> mResult = this.getAccountService().saveObject(account); if (mResult.getValue()==null) { throw new ServiceException( mResult.getSystemMessage().getValue() ); } DefaultResult<EmployeeVO> result = this.getEmployeeService().saveObject(employee); this.createEmployeeOrganization(result.getValue(), organizationOid); // create default role UserRoleVO userRole = new UserRoleVO(); userRole.setAccount(result.getValue().getAccount()); userRole.setRole( this.roleLogicService.getDefaultUserRole() ); userRole.setDescription(result.getValue().getAccount() + " `s role!"); this.getUserRoleService().saveObject(userRole); this.createHierarchy(employee, BscConstants.EMPLOYEE_HIER_ZERO_OID); return result; } @ServiceMethodAuthority(type={ServiceMethodType.UPDATE}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<EmployeeVO> update(EmployeeVO employee, List<String> organizationOid) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getOid()) ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } EmployeeVO dbEmployee = this.findEmployeeData( employee.getOid() ); this.deleteEmployeeOrganization( dbEmployee ); employee.setAccount(dbEmployee.getAccount() ); employee.setEmpId( dbEmployee.getEmpId() ); DefaultResult<EmployeeVO> result = this.getEmployeeService().updateObject(employee); if (result.getValue()==null) { throw new ServiceException(result.getSystemMessage().getValue()); } this.createEmployeeOrganization(result.getValue(), organizationOid); return result; } @ServiceMethodAuthority(type={ServiceMethodType.UPDATE}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<AccountVO> updatePassword(EmployeeVO employee, String newPassword) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getOid()) || super.isBlank(employee.getPassword()) || super.isBlank(newPassword) ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } EmployeeVO dbEmployee = this.findEmployeeData(employee.getOid()); AccountVO account = this.findAccountData( dbEmployee.getAccount() ); if (!account.getPassword().equals( this.getAccountService().tranPassword(employee.getPassword()) ) ) { throw new ServiceException("The current password(old password) is incorrect!"); } account.setPassword( this.getAccountService().tranPassword(newPassword) ); return getAccountService().updateObject(account); } @ServiceMethodAuthority(type={ServiceMethodType.DELETE}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<Boolean> delete(EmployeeVO employee) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getOid()) ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } employee = this.findEmployeeData(employee.getOid()); AccountVO account = this.findAccountData(employee.getAccount()); if (this.isAdministrator(account.getAccount())) { throw new ServiceException("Administrator cannot delete!"); } // check account data for other table use. this.checkInformationRelated(account, employee); this.deleteEmployeeOrganization(employee); // delete user role Map<String, Object> params = new HashMap<String, Object>(); params.put("account", account.getAccount()); List<TbUserRole> userRoles = this.getUserRoleService().findListByParams(params); for (int i=0; userRoles!=null && i<userRoles.size(); i++) { TbUserRole uRole = userRoles.get(i); this.getUserRoleService().delete(uRole); } // delete BB_REPORT_ROLE_VIEW params.clear(); params.put("idName", account.getAccount()); List<BbReportRoleView> reportRoleViews = this.reportRoleViewService.findListByParams(params); for (int i=0; reportRoleViews!=null && i<reportRoleViews.size(); i++) { BbReportRoleView reportRoleView = reportRoleViews.get( i ); this.reportRoleViewService.delete(reportRoleView); } // delete from BB_MEASURE_DATA where EMP_ID = :empId this.measureDataService.deleteForEmpId( employee.getEmpId() ); this.monitorItemScoreService.deleteForEmpId( employee.getEmpId() ); this.deleteHierarchy(employee); this.getAccountService().deleteByPKng(account.getOid()); return getEmployeeService().deleteObject(employee); } private void checkInformationRelated(AccountVO account, EmployeeVO employee) throws ServiceException, Exception { if (account==null || super.isBlank(account.getAccount()) || employee==null || super.isBlank(employee.getEmpId()) ) { return; } Map<String, Object> params = new HashMap<String, Object>(); // tb_sys_msg_notice params.put("toAccount", account.getAccount()); if (this.sysMsgNoticeService.countByParams(params) > 0 ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // tb_sys_calendar_note params.clear(); params.put("account", account.getAccount()); if (this.sysCalendarNoteService.countByParams(params) > 0 ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_kpi_empl params.clear(); params.put("empId", employee.getEmpId()); if (this.kpiEmplService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_pdca_owner if (this.pdcaOwnerService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_pdca_item_owner if (this.pdcaItemOwnerService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_pdca_measure_freq params.clear(); params.put("empId", employee.getEmpId()); if (this.pdcaMeasureFreqService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_tsa_measure_freq if (this.tsaMeasureFreqService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } // bb_degree_feedback_assign params.clear(); params.put("ownerId", employee.getEmpId()); if (this.degreeFeedbackAssignService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } params.clear(); params.put("raterId", employee.getEmpId()); if (this.degreeFeedbackAssignService.countByParams(params) > 0) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } if (this.foundChild(employee)) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE)); } } private void createEmployeeOrganization(EmployeeVO employee, List<String> organizationOid) throws ServiceException, Exception { if (employee==null || StringUtils.isBlank(employee.getEmpId()) || organizationOid==null || organizationOid.size() < 1 ) { return; } for (String oid : organizationOid) { OrganizationVO organization = this.findOrganizationData(oid); EmployeeOrgaVO empOrg = new EmployeeOrgaVO(); empOrg.setEmpId(employee.getEmpId()); empOrg.setOrgId(organization.getOrgId()); this.employeeOrgaService.saveObject(empOrg); } } private void deleteEmployeeOrganization(EmployeeVO employee) throws ServiceException, Exception { if (employee==null || StringUtils.isBlank(employee.getEmpId()) ) { return; } Map<String, Object> params = new HashMap<String, Object>(); params.put("empId", employee.getEmpId()); List<BbEmployeeOrga> searchList = this.employeeOrgaService.findListByParams(params); if (searchList==null || searchList.size()<1 ) { return; } for (BbEmployeeOrga empOrg : searchList) { this.employeeOrgaService.delete(empOrg); } } private void createHierarchy(EmployeeVO employee, String supOid) throws ServiceException, Exception { if (null == employee || super.isBlank(employee.getOid()) || super.isBlank(supOid)) { return; } EmployeeHierVO hier = new EmployeeHierVO(); hier.setEmpOid(employee.getOid()); hier.setSupOid(supOid); this.employeeHierService.saveObject(hier); } @ServiceMethodAuthority(type={ServiceMethodType.SELECT}) @Override public List<Map<String, Object>> getTreeData(String basePath) throws ServiceException, Exception { List<Map<String, Object>> items = new LinkedList<Map<String, Object>>(); List<EmployeeVO> empList = this.getEmployeeService().findForJoinHier(); if (empList==null || empList.size()<1 ) { return items; } for (EmployeeVO emp : empList) { // 先放沒有父親的員工資料 if (!(super.isBlank(emp.getSupOid()) || BscConstants.EMPLOYEE_HIER_ZERO_OID.equals(emp.getSupOid()) ) ) { continue; } Map<String, Object> parentDataMap = new LinkedHashMap<String, Object>(); parentDataMap.put("type", "parent"); parentDataMap.put("id", emp.getOid()); parentDataMap.put("name", IconUtils.getMenuIcon(basePath, TREE_ICON_ID) + StringEscapeUtils.escapeHtml4(this.getTreeShowName(emp)) ); parentDataMap.put("oid", emp.getOid()); items.add(parentDataMap); } // 再開始放孩子 for (int ix=0; ix<items.size(); ix++) { Map<String, Object> parentDataMap=items.get(ix); String oid = (String)parentDataMap.get("oid"); this.getTreeData(basePath, parentDataMap, empList, oid); } return items; } private void getTreeData(String basePath, Map<String, Object> putObject, List<EmployeeVO> searchList, String supOid) throws Exception { List<String> childList = new LinkedList<String>(); this.getChildEmpLevelOne(searchList, supOid, childList); if (childList.size()<1) { return; } for (String childEmpOid : childList) { EmployeeVO emp = this.getEmployeeFromSearchList(searchList, childEmpOid, false); EmployeeVO childEmp = this.getEmployeeFromSearchList(searchList, childEmpOid, true); if (emp==null) { continue; } Map<String, Object> thePutObject=null; @SuppressWarnings("unchecked") List<Map<String, Object>> childrenList = (List<Map<String, Object>>)putObject.get("children"); if (childrenList==null) { childrenList=new LinkedList<Map<String, Object>>(); } Map<String, Object> nodeMap=new LinkedHashMap<String, Object>(); nodeMap.put("id", emp.getOid()); nodeMap.put("name", IconUtils.getMenuIcon(basePath, TREE_ICON_ID) + StringEscapeUtils.escapeHtml4(this.getTreeShowName(emp)) ); nodeMap.put("oid", emp.getOid() ); childrenList.add(nodeMap); putObject.put("children", childrenList); if (childEmp!=null) { thePutObject=nodeMap; } else { nodeMap.put("type", "Leaf"); thePutObject=putObject; } if (childEmp!=null) { this.getTreeData(basePath, thePutObject, searchList, childEmpOid); } } } private List<String> getChildEmpLevelOne(List<EmployeeVO> searchList, String supOid, List<String> childList) throws Exception { if (childList==null) { childList=new LinkedList<String>(); } for (EmployeeVO emp : searchList) { if (supOid.equals(emp.getSupOid())) { childList.add(emp.getOid()); } } return childList; } private EmployeeVO getEmployeeFromSearchList(List<EmployeeVO> searchList, String empOid, boolean isChild) throws Exception { for (EmployeeVO emp : searchList) { if (!isChild) { if (emp.getOid().equals(empOid)) { return emp; } } else { if (emp.getSupOid().equals(empOid)) { return emp; } } } return null; } private String getTreeShowName(EmployeeVO employee) throws Exception { if ( !super.isBlank(employee.getJobTitle()) ) { return employee.getEmpId() + " - " + StringEscapeUtils.escapeHtml4(employee.getFullName()) + " ( " + employee.getJobTitle().trim() + " )"; } return employee.getEmpId() + " - " + StringEscapeUtils.escapeHtml4(employee.getFullName()); } private boolean foundChild(EmployeeVO employee) throws ServiceException, Exception { if (null == employee || super.isBlank(employee.getOid())) { return false; } Map<String, Object> params = new HashMap<String, Object>(); params.put("supOid", employee.getOid()); if (this.employeeHierService.countByParams(params) > 0 ) { return true; } return false; } private boolean foundChild(String supOid, String checkEmpOid) throws ServiceException, Exception { List<EmployeeVO> treeList = this.getEmployeeService().findForJoinHier(); if (treeList==null || treeList.size() <1 ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } boolean f = false; List<EmployeeVO> childList=new LinkedList<EmployeeVO>(); this.getChild(checkEmpOid, treeList, childList); for (int ix=0; childList!=null && ix<childList.size(); ix++) { if (childList.get(ix).getOid().equals(checkEmpOid)) { f = true; } } return f; } private void getChild(String supOid, List<EmployeeVO> tree, List<EmployeeVO> put) throws Exception { if (put==null || tree==null) { return; } if (StringUtils.isBlank(supOid) || BscConstants.EMPLOYEE_HIER_ZERO_OID.equals(supOid) ) { return; } for (EmployeeVO emp : tree) { if (emp.getSupOid().equals(supOid)) { put.add(emp); this.getChild(emp.getOid(), tree, put); } } } private void deleteHierarchy(EmployeeVO employee) throws ServiceException, Exception { if (null == employee || super.isBlank(employee.getOid())) { return; } Map<String, Object> params = new HashMap<String, Object>(); params.put("empOid", employee.getOid()); List<BbEmployeeHier> hierList = this.employeeHierService.findListByParams(params); if (null == hierList) { return; } for (BbEmployeeHier hier : hierList) { employeeHierService.delete(hier); } } @ServiceMethodAuthority(type={ServiceMethodType.UPDATE}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<Boolean> updateSupervisor(EmployeeVO employee, String supervisorOid) throws ServiceException, Exception { if (employee==null || super.isBlank(employee.getOid()) || super.isBlank(supervisorOid)) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); } DefaultResult<Boolean> result = new DefaultResult<Boolean>(); result.setValue(Boolean.FALSE); result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.UPDATE_FAIL)) ); employee = this.findEmployeeData(employee.getOid()); this.deleteHierarchy(employee); if ("root".equals(supervisorOid) || "r".equals(supervisorOid)) { this.createHierarchy(employee, BscConstants.EMPLOYEE_HIER_ZERO_OID); } else { EmployeeVO newHierEmployee = this.findEmployeeData(supervisorOid); // 找當前員工的的資料, 不因該存在要update的新關聯主管 if ( this.foundChild(employee.getOid(), newHierEmployee.getOid()) ) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_ERRORS)); } this.createHierarchy(employee, newHierEmployee.getOid()); } result.setValue(Boolean.TRUE); result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.UPDATE_SUCCESS)) ); return result; } /** * for upgrade 0.7.1 need data * * @throws ServiceException * @throws Exception */ @ServiceMethodAuthority(type={ServiceMethodType.INSERT}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public void initHierarchyForFirst() throws ServiceException, Exception { List<EmployeeVO> employeeList = this.getEmployeeService().findListVOByParams(null); if (null == employeeList || employeeList.size() < 1) { return; } Map<String, Object> paramMap = new HashMap<String, Object>(); for (EmployeeVO employee : employeeList) { paramMap.clear(); paramMap.put("empOid", employee.getOid()); if (this.employeeHierService.countByParams(paramMap) > 0) { continue; } this.createHierarchy(employee, BscConstants.EMPLOYEE_HIER_ZERO_OID); } } /** * 這個 Method 的 ServiceMethodAuthority 權限給查詢狀態 * 這裡的 basePath 只是要取 getTreeData 時參數要用, 再這是沒有用處的 */ @ServiceMethodAuthority(type={ServiceMethodType.SELECT}) @Transactional( propagation=Propagation.REQUIRED, readOnly=false, rollbackFor={RuntimeException.class, IOException.class, Exception.class} ) @Override public DefaultResult<String> createOrgChartData(String basePath, EmployeeVO currentEmployee) throws ServiceException, Exception { if (null != currentEmployee && !super.isBlank(currentEmployee.getOid())) { currentEmployee = this.findEmployeeData( currentEmployee.getOid() ); } List<Map<String, Object>> treeMap = this.getTreeData(basePath); if (null == treeMap || treeMap.size() < 1) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)); } this.resetTreeMapContentForOrgChartData(treeMap, currentEmployee); Map<String, Object> rootMap = new HashMap<String, Object>(); rootMap.put("name", "Employee hierarchy"); rootMap.put("title", "hierarchy structure"); rootMap.put("children", treeMap); ObjectMapper objectMapper = new ObjectMapper(); String jsonData = objectMapper.writeValueAsString(rootMap); String uploadOid = UploadSupportUtils.create( Constants.getSystem(), UploadTypes.IS_TEMP, false, jsonData.getBytes(), SimpleUtils.getUUIDStr() + ".json"); DefaultResult<String> result = new DefaultResult<String>(); result.setValue(uploadOid); result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.INSERT_SUCCESS)) ); return result; } /** * 這個 Method 的 ServiceMethodAuthority 權限給查詢狀態 * 這裡的 basePath 只是要取 getTreeData 時參數要用, 再這是沒有用處的 */ @ServiceMethodAuthority(type={ServiceMethodType.SELECT}) @Override public DefaultResult<Map<String, Object>> getOrgChartData(String basePath, EmployeeVO currentEmployee) throws ServiceException, Exception { if (null != currentEmployee && !super.isBlank(currentEmployee.getOid())) { currentEmployee = this.findEmployeeData( currentEmployee.getOid() ); } List<Map<String, Object>> treeMap = this.getTreeData(basePath); if (null == treeMap || treeMap.size() < 1) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)); } this.resetTreeMapContentForOrgChartData(treeMap, currentEmployee); Map<String, Object> rootMap = new HashMap<String, Object>(); rootMap.put("name", "Employee hierarchy"); rootMap.put("title", "hierarchy structure"); rootMap.put("children", treeMap); DefaultResult<Map<String, Object>> result = new DefaultResult<Map<String, Object>>(); result.setValue( rootMap ); result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.INSERT_SUCCESS)) ); return result; } @SuppressWarnings("unchecked") private void resetTreeMapContentForOrgChartData(List<Map<String, Object>> childMapList, EmployeeVO currentEmployee) throws Exception { for (Map<String, Object> nodeMap : childMapList) { String nodeEmployeeOid = String.valueOf( nodeMap.get("id") ); // 與 node.get("oid") 一樣 // 去除 OrgChart 不需要的資料 nodeMap.remove("type"); nodeMap.remove("id"); nodeMap.remove("name"); nodeMap.remove("oid"); EmployeeVO nodeEmployee = this.findEmployeeData(nodeEmployeeOid); // OrgChart 需要的資料, nodeMap 需要填入 name 與 title if (currentEmployee != null && !super.isBlank(currentEmployee.getOid()) && currentEmployee.getOid().equals(nodeEmployeeOid)) { // 有帶入當前員工來區別顏色 nodeMap.put("name", "<font color='#8A0808'>" + nodeEmployee.getEmpId() + " - " + nodeEmployee.getFullName() + "</font>" ); nodeMap.put("title", "<font color='#8A0808'>" + ( super.isBlank(nodeEmployee.getJobTitle()) ? "no job description" : nodeEmployee.getJobTitle().trim() ) + "</font>" ); } else { nodeMap.put("name", nodeEmployee.getEmpId() + " - " + nodeEmployee.getFullName()); nodeMap.put("title", ( super.isBlank(nodeEmployee.getJobTitle()) ? "no job description" : nodeEmployee.getJobTitle().trim() ) ); } if (nodeMap.get("children") != null && (nodeMap.get("children") instanceof List<?>)) { // 還有孩子項目資料 this.resetTreeMapContentForOrgChartData( (List<Map<String, Object>>) nodeMap.get("children"), currentEmployee ); } } } }
Bug fix, create new employee no create Hierarchy data.
gsbsc-standard/src/com/netsteadfast/greenstep/bsc/service/logic/impl/EmployeeLogicServiceImpl.java
Bug fix, create new employee no create Hierarchy data.
<ide><path>sbsc-standard/src/com/netsteadfast/greenstep/bsc/service/logic/impl/EmployeeLogicServiceImpl.java <ide> throw new ServiceException( mResult.getSystemMessage().getValue() ); <ide> } <ide> DefaultResult<EmployeeVO> result = this.getEmployeeService().saveObject(employee); <add> employee = result.getValue(); <ide> this.createEmployeeOrganization(result.getValue(), organizationOid); <ide> <ide> // create default role
Java
bsd-3-clause
c89333e883e639c909dee78dd866cbda078be5c9
0
APNIC-net/whowas-service,APNIC-net/whowas-service,APNIC-net/whowas-service
package net.apnic.whowas.rdap.config; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import net.apnic.whowas.rdap.controller.RDAPResponseMaker; import net.apnic.whowas.rdap.Link; import net.apnic.whowas.rdap.Notice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * General configuration bootstrap class that build and passes information * recieved through config files. */ @Configuration @ConfigurationProperties(prefix="rdap") public class RDAPConfiguration { private static final Notice TRUNCATED_NOTICE; static { TRUNCATED_NOTICE = new Notice( "Data Policy", "object truncated due to unexplainable reason", Arrays.asList("Some of the data in this object has been removed."), null); } private List<ConfigNotice> configNotices = null; private List<Notice> defaultNotices = null; private String defaultPort43 = null; /** * Config class represents a link object in this applications configuration * file. */ public static class ConfigLink { private String href; private String rel; private String type; public String getHref() { return href; } public String getRel() { return rel; } public String getType() { return type; } public void setHref(String href) { this.href = href; } public void setRel(String rel) { this.rel = rel; } public void setType(String type) { this.type = type; } public Link toLink() { return new Link(null, getRel(), getHref(), getType()); } } /** * Config class represents a notice object in this applcations configuration * file. */ public static class ConfigNotice { private List<String> description = new ArrayList<String>(); private List<ConfigLink> links = new ArrayList<ConfigLink>(); private String title; public List<String> getDescription() { return description; } public List<ConfigLink> getLinks() { return links; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Notice toNotice() { return new Notice(getTitle(), getDescription(), getLinks().stream().map(cLink -> cLink.toLink()) .collect(Collectors.toList())); } } /** * Constructs a set of default notices provided with every rdap response. */ private void configDefaultNotices() { defaultNotices = Collections.unmodifiableList( Optional.ofNullable(configNotices) .map(cn -> cn.stream().map(cNotice -> cNotice.toNotice()) .collect(Collectors.toList())) .orElse(Collections.emptyList())); configNotices = null; } /** * Bean for a list of default RDAP notices. */ @Bean public List<Notice> defaultNotices() { if(defaultNotices == null) { configDefaultNotices(); } return defaultNotices; } public List<ConfigNotice> getNotices() { return configNotices; } public String getPort43() { return defaultPort43 == null || defaultPort43.isEmpty() ? null : defaultPort43; } @Autowired @Bean public RDAPResponseMaker rdapResponseMaker(List<Notice> defaultNotices) { return new RDAPResponseMaker(defaultNotices, TRUNCATED_NOTICE, getPort43()); } public void setNotices(List<ConfigNotice> notices) { this.configNotices = notices; } public void setPort43(String port43) { this.defaultPort43 = port43; } }
src/main/java/net/apnic/whowas/rdap/config/RDAPConfiguration.java
package net.apnic.whowas.rdap.config; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import net.apnic.whowas.rdap.controller.RDAPResponseMaker; import net.apnic.whowas.rdap.Link; import net.apnic.whowas.rdap.Notice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * General configuration bootstrap class that build and passes information * recieved through config files. */ @Configuration @ConfigurationProperties(prefix="rdap") public class RDAPConfiguration { private static final Notice TRUNCATED_NOTICE; static { TRUNCATED_NOTICE = new Notice( "Search Policy", "result set truncated due to limits", Arrays.asList("Search results limited"), null); } private List<ConfigNotice> configNotices = null; private List<Notice> defaultNotices = null; private String defaultPort43 = null; /** * Config class represents a link object in this applications configuration * file. */ public static class ConfigLink { private String href; private String rel; private String type; public String getHref() { return href; } public String getRel() { return rel; } public String getType() { return type; } public void setHref(String href) { this.href = href; } public void setRel(String rel) { this.rel = rel; } public void setType(String type) { this.type = type; } public Link toLink() { return new Link(null, getRel(), getHref(), getType()); } } /** * Config class represents a notice object in this applcations configuration * file. */ public static class ConfigNotice { private List<String> description = new ArrayList<String>(); private List<ConfigLink> links = new ArrayList<ConfigLink>(); private String title; public List<String> getDescription() { return description; } public List<ConfigLink> getLinks() { return links; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Notice toNotice() { return new Notice(getTitle(), getDescription(), getLinks().stream().map(cLink -> cLink.toLink()) .collect(Collectors.toList())); } } /** * Constructs a set of default notices provided with every rdap response. */ private void configDefaultNotices() { defaultNotices = Collections.unmodifiableList( Optional.ofNullable(configNotices) .map(cn -> cn.stream().map(cNotice -> cNotice.toNotice()) .collect(Collectors.toList())) .orElse(Collections.emptyList())); configNotices = null; } /** * Bean for a list of default RDAP notices. */ @Bean public List<Notice> defaultNotices() { if(defaultNotices == null) { configDefaultNotices(); } return defaultNotices; } public List<ConfigNotice> getNotices() { return configNotices; } public String getPort43() { return defaultPort43 == null || defaultPort43.isEmpty() ? null : defaultPort43; } @Autowired @Bean public RDAPResponseMaker rdapResponseMaker(List<Notice> defaultNotices) { return new RDAPResponseMaker(defaultNotices, TRUNCATED_NOTICE, getPort43()); } public void setNotices(List<ConfigNotice> notices) { this.configNotices = notices; } public void setPort43(String port43) { this.defaultPort43 = port43; } }
Fix for truncated response wording. Fixes working used for search truncated response.
src/main/java/net/apnic/whowas/rdap/config/RDAPConfiguration.java
Fix for truncated response wording.
<ide><path>rc/main/java/net/apnic/whowas/rdap/config/RDAPConfiguration.java <ide> static <ide> { <ide> TRUNCATED_NOTICE = new Notice( <del> "Search Policy", <del> "result set truncated due to limits", <del> Arrays.asList("Search results limited"), null); <add> "Data Policy", <add> "object truncated due to unexplainable reason", <add> Arrays.asList("Some of the data in this object has been removed."), <add> null); <ide> } <ide> <ide> private List<ConfigNotice> configNotices = null;
Java
mit
error: pathspec 'library/src/main/java/com/qiniu/android/http/IReport.java' did not match any file(s) known to git
f85c39fda098f3b1db2b8c9a881f0fdd3a1aafec
1
CtJason/android-sdk,qinxd1988/android-sdk,sxci/android-sdk,java02014/android-sdk,Haoxiqiang/android-sdk,fanxu123/qiniu-sdk,qiniu/android-sdk,jemygraw/android-sdk,itwang/android-sdk,b2b2244424/android-sdk,hgkmail/android-sdk
package com.qiniu.android.http; import org.apache.http.Header; public interface IReport { Header[] appendStatHeaders(Header[] headers); void updateErrorInfo(ResponseInfo info); void updateSpeedInfo(ResponseInfo info); }
library/src/main/java/com/qiniu/android/http/IReport.java
add report interface
library/src/main/java/com/qiniu/android/http/IReport.java
add report interface
<ide><path>ibrary/src/main/java/com/qiniu/android/http/IReport.java <add>package com.qiniu.android.http; <add> <add>import org.apache.http.Header; <add> <add>public interface IReport { <add> Header[] appendStatHeaders(Header[] headers); <add> <add> void updateErrorInfo(ResponseInfo info); <add> <add> void updateSpeedInfo(ResponseInfo info); <add>}
Java
apache-2.0
d39325260d19dd274d33ec51b239c230803b7cb0
0
vam-google/google-cloud-java,vam-google/google-cloud-java,vam-google/google-cloud-java,vam-google/google-cloud-java,vam-google/google-cloud-java,vam-google/google-cloud-java
/* * Copyright 2015 Google LLC * * 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.cloud.storage.spi.v1; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.client.util.IOUtils; import com.google.api.services.storage.Storage; import com.google.api.services.storage.Storage.Objects.Get; import com.google.api.services.storage.Storage.Objects.Insert; import com.google.api.services.storage.model.Bucket; import com.google.api.services.storage.model.BucketAccessControl; import com.google.api.services.storage.model.Buckets; import com.google.api.services.storage.model.ComposeRequest; import com.google.api.services.storage.model.ComposeRequest.SourceObjects.ObjectPreconditions; import com.google.api.services.storage.model.Notification; import com.google.api.services.storage.model.ObjectAccessControl; import com.google.api.services.storage.model.Objects; import com.google.api.services.storage.model.Policy; import com.google.api.services.storage.model.ServiceAccount; import com.google.api.services.storage.model.StorageObject; import com.google.api.services.storage.model.TestIamPermissionsResponse; import com.google.cloud.BaseServiceException; import com.google.cloud.Tuple; import com.google.cloud.http.CensusHttpModule; import com.google.cloud.http.HttpTransportOptions; import com.google.cloud.storage.StorageException; import com.google.cloud.storage.StorageOptions; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import com.google.common.io.BaseEncoding; import io.opencensus.common.Scope; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.Span; import io.opencensus.trace.Status; import io.opencensus.trace.Tracer; import io.opencensus.trace.Tracing; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.http.HttpStatus; public class HttpStorageRpc implements StorageRpc { public static final String DEFAULT_PROJECTION = "full"; private static final String ENCRYPTION_KEY_PREFIX = "x-goog-encryption-"; private static final String SOURCE_ENCRYPTION_KEY_PREFIX = "x-goog-copy-source-encryption-"; private final StorageOptions options; private final Storage storage; private final Tracer tracer = Tracing.getTracer(); private final CensusHttpModule censusHttpModule; private final HttpRequestInitializer batchRequestInitializer; private static final long MEGABYTE = 1024L * 1024L; public HttpStorageRpc(StorageOptions options) { HttpTransportOptions transportOptions = (HttpTransportOptions) options.getTransportOptions(); HttpTransport transport = transportOptions.getHttpTransportFactory().create(); HttpRequestInitializer initializer = transportOptions.getHttpRequestInitializer(options); this.options = options; // Open Census initialization censusHttpModule = new CensusHttpModule(tracer, true); initializer = censusHttpModule.getHttpRequestInitializer(initializer); batchRequestInitializer = censusHttpModule.getHttpRequestInitializer(null); HttpStorageRpcSpans.registerAllSpanNamesForCollection(); storage = new Storage.Builder(transport, new JacksonFactory(), initializer) .setRootUrl(options.getHost()) .setApplicationName(options.getApplicationName()) .build(); } private class DefaultRpcBatch implements RpcBatch { // Batch size is limited as, due to some current service implementation details, the service // performs better if the batches are split for better distribution. See // https://github.com/GoogleCloudPlatform/google-cloud-java/pull/952#issuecomment-213466772 for // background. private static final int MAX_BATCH_SIZE = 100; private final Storage storage; private final LinkedList<BatchRequest> batches; private int currentBatchSize; private DefaultRpcBatch(Storage storage) { this.storage = storage; batches = new LinkedList<>(); // add OpenCensus HttpRequestInitializer batches.add(storage.batch(batchRequestInitializer)); } @Override public void addDelete(StorageObject storageObject, RpcBatch.Callback<Void> callback, Map<Option, ?> options) { try { if (currentBatchSize == MAX_BATCH_SIZE) { batches.add(storage.batch()); currentBatchSize = 0; } deleteCall(storageObject, options).queue(batches.getLast(), toJsonCallback(callback)); currentBatchSize++; } catch (IOException ex) { throw translate(ex); } } @Override public void addPatch(StorageObject storageObject, RpcBatch.Callback<StorageObject> callback, Map<Option, ?> options) { try { if (currentBatchSize == MAX_BATCH_SIZE) { batches.add(storage.batch()); currentBatchSize = 0; } patchCall(storageObject, options).queue(batches.getLast(), toJsonCallback(callback)); currentBatchSize++; } catch (IOException ex) { throw translate(ex); } } @Override public void addGet(StorageObject storageObject, RpcBatch.Callback<StorageObject> callback, Map<Option, ?> options) { try { if (currentBatchSize == MAX_BATCH_SIZE) { batches.add(storage.batch()); currentBatchSize = 0; } getCall(storageObject, options).queue(batches.getLast(), toJsonCallback(callback)); currentBatchSize++; } catch (IOException ex) { throw translate(ex); } } @Override public void submit() { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_BATCH_SUBMIT); Scope scope = tracer.withSpan(span); try { span.putAttribute("batch size", AttributeValue.longAttributeValue(batches.size())); for (BatchRequest batch : batches) { // TODO(hailongwen@): instrument 'google-api-java-client' to further break down the span. // Here we only add a annotation to at least know how much time each batch takes. span.addAnnotation("Execute batch request"); batch.setBatchUrl(new GenericUrl("https://www.googleapis.com/batch/storage/v1")); batch.execute(); } } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } } private static <T> JsonBatchCallback<T> toJsonCallback(final RpcBatch.Callback<T> callback) { return new JsonBatchCallback<T>() { @Override public void onSuccess(T response, HttpHeaders httpHeaders) throws IOException { callback.onSuccess(response); } @Override public void onFailure(GoogleJsonError googleJsonError, HttpHeaders httpHeaders) throws IOException { callback.onFailure(googleJsonError); } }; } private static StorageException translate(IOException exception) { return new StorageException(exception); } private static StorageException translate(GoogleJsonError exception) { return new StorageException(exception); } private static void setEncryptionHeaders(HttpHeaders headers, String headerPrefix, Map<Option, ?> options) { String key = Option.CUSTOMER_SUPPLIED_KEY.getString(options); if (key != null) { BaseEncoding base64 = BaseEncoding.base64(); HashFunction hashFunction = Hashing.sha256(); headers.set(headerPrefix + "algorithm", "AES256"); headers.set(headerPrefix + "key", key); headers.set(headerPrefix + "key-sha256", base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes())); } } /** * Helper method to start a span. */ private Span startSpan(String spanName) { return tracer .spanBuilder(spanName) .setRecordEvents(censusHttpModule.isRecordEvents()) .startSpan(); } @Override public Bucket create(Bucket bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_BUCKET); Scope scope = tracer.withSpan(span); try { return storage.buckets() .insert(this.options.getProjectId(), bucket) .setProjection(DEFAULT_PROJECTION) .setPredefinedAcl(Option.PREDEFINED_ACL.getString(options)) .setPredefinedDefaultObjectAcl(Option.PREDEFINED_DEFAULT_OBJECT_ACL.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public StorageObject create(StorageObject storageObject, final InputStream content, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_OBJECT); Scope scope = tracer.withSpan(span); try { Storage.Objects.Insert insert = storage.objects() .insert(storageObject.getBucket(), storageObject, new InputStreamContent(storageObject.getContentType(), content)); insert.getMediaHttpUploader().setDirectUploadEnabled(true); setEncryptionHeaders(insert.getRequestHeaders(), ENCRYPTION_KEY_PREFIX, options); return insert.setProjection(DEFAULT_PROJECTION) .setPredefinedAcl(Option.PREDEFINED_ACL.getString(options)) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .setKmsKeyName(Option.KMS_KEY_NAME.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Tuple<String, Iterable<Bucket>> list(Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_BUCKETS); Scope scope = tracer.withSpan(span); try { Buckets buckets = storage.buckets() .list(this.options.getProjectId()) .setProjection(DEFAULT_PROJECTION) .setPrefix(Option.PREFIX.getString(options)) .setMaxResults(Option.MAX_RESULTS.getLong(options)) .setPageToken(Option.PAGE_TOKEN.getString(options)) .setFields(Option.FIELDS.getString(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); return Tuple.<String, Iterable<Bucket>>of(buckets.getNextPageToken(), buckets.getItems()); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Tuple<String, Iterable<StorageObject>> list(final String bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_OBJECTS); Scope scope = tracer.withSpan(span); try { Objects objects = storage.objects() .list(bucket) .setProjection(DEFAULT_PROJECTION) .setVersions(Option.VERSIONS.getBoolean(options)) .setDelimiter(Option.DELIMITER.getString(options)) .setPrefix(Option.PREFIX.getString(options)) .setMaxResults(Option.MAX_RESULTS.getLong(options)) .setPageToken(Option.PAGE_TOKEN.getString(options)) .setFields(Option.FIELDS.getString(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); Iterable<StorageObject> storageObjects = Iterables.concat( firstNonNull(objects.getItems(), ImmutableList.<StorageObject>of()), objects.getPrefixes() != null ? Lists.transform(objects.getPrefixes(), objectFromPrefix(bucket)) : ImmutableList.<StorageObject>of()); return Tuple.of(objects.getNextPageToken(), storageObjects); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } private static Function<String, StorageObject> objectFromPrefix(final String bucket) { return new Function<String, StorageObject>() { @Override public StorageObject apply(String prefix) { return new StorageObject() .set("isDirectory", true) .setBucket(bucket) .setName(prefix) .setSize(BigInteger.ZERO); } }; } @Override public Bucket get(Bucket bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_BUCKET); Scope scope = tracer.withSpan(span); try { return storage.buckets() .get(bucket.getName()) .setProjection(DEFAULT_PROJECTION) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setFields(Option.FIELDS.getString(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } private Storage.Objects.Get getCall(StorageObject object, Map<Option, ?> options) throws IOException { return storage.objects() .get(object.getBucket(), object.getName()) .setGeneration(object.getGeneration()) .setProjection(DEFAULT_PROJECTION) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setFields(Option.FIELDS.getString(options)) .setUserProject(Option.USER_PROJECT.getString(options)); } @Override public StorageObject get(StorageObject object, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_OBJECT); Scope scope = tracer.withSpan(span); try { return getCall(object, options).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public Bucket patch(Bucket bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_BUCKET); Scope scope = tracer.withSpan(span); try { return storage.buckets() .patch(bucket.getName(), bucket) .setProjection(DEFAULT_PROJECTION) .setPredefinedAcl(Option.PREDEFINED_ACL.getString(options)) .setPredefinedDefaultObjectAcl(Option.PREDEFINED_DEFAULT_OBJECT_ACL.getString(options)) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } private Storage.Objects.Patch patchCall(StorageObject storageObject, Map<Option, ?> options) throws IOException { return storage.objects() .patch(storageObject.getBucket(), storageObject.getName(), storageObject) .setProjection(DEFAULT_PROJECTION) .setPredefinedAcl(Option.PREDEFINED_ACL.getString(options)) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)); } @Override public StorageObject patch(StorageObject storageObject, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_OBJECT); Scope scope = tracer.withSpan(span); try { return patchCall(storageObject, options).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public boolean delete(Bucket bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_BUCKET); Scope scope = tracer.withSpan(span); try { storage.buckets() .delete(bucket.getName()) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } private Storage.Objects.Delete deleteCall(StorageObject blob, Map<Option, ?> options) throws IOException { return storage.objects() .delete(blob.getBucket(), blob.getName()) .setGeneration(blob.getGeneration()) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)); } @Override public boolean delete(StorageObject blob, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_OBJECT); Scope scope = tracer.withSpan(span); try { deleteCall(blob, options).execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public StorageObject compose(Iterable<StorageObject> sources, StorageObject target, Map<Option, ?> targetOptions) { ComposeRequest request = new ComposeRequest(); request.setDestination(target); List<ComposeRequest.SourceObjects> sourceObjects = new ArrayList<>(); for (StorageObject source : sources) { ComposeRequest.SourceObjects sourceObject = new ComposeRequest.SourceObjects(); sourceObject.setName(source.getName()); Long generation = source.getGeneration(); if (generation != null) { sourceObject.setGeneration(generation); sourceObject.setObjectPreconditions( new ObjectPreconditions().setIfGenerationMatch(generation)); } sourceObjects.add(sourceObject); } request.setSourceObjects(sourceObjects); Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_COMPOSE); Scope scope = tracer.withSpan(span); try { return storage.objects() .compose(target.getBucket(), target.getName(), request) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(targetOptions)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(targetOptions)) .setUserProject(Option.USER_PROJECT.getString(targetOptions)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public byte[] load(StorageObject from, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LOAD); Scope scope = tracer.withSpan(span); try { Storage.Objects.Get getRequest = storage.objects() .get(from.getBucket(), from.getName()) .setGeneration(from.getGeneration()) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)); setEncryptionHeaders(getRequest.getRequestHeaders(), ENCRYPTION_KEY_PREFIX, options); ByteArrayOutputStream out = new ByteArrayOutputStream(); getRequest.executeMedia().download(out); return out.toByteArray(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public RpcBatch createBatch() { return new DefaultRpcBatch(storage); } @Override public Tuple<String, byte[]> read(StorageObject from, Map<Option, ?> options, long position, int bytes) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_READ); Scope scope = tracer.withSpan(span); try { Get req = storage.objects() .get(from.getBucket(), from.getName()) .setGeneration(from.getGeneration()) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)); checkArgument(position >= 0, "Position should be non-negative, is %d", position); StringBuilder range = new StringBuilder(); range.append("bytes=").append(position).append("-").append(position + bytes - 1); HttpHeaders requestHeaders = req.getRequestHeaders(); requestHeaders.setRange(range.toString()); setEncryptionHeaders(requestHeaders, ENCRYPTION_KEY_PREFIX, options); ByteArrayOutputStream output = new ByteArrayOutputStream(bytes); HttpResponse httpResponse = req.executeMedia(); // todo(mziccard) remove when // https://github.com/GoogleCloudPlatform/google-cloud-java/issues/982 is fixed String contentEncoding = httpResponse.getContentEncoding(); if (contentEncoding != null && contentEncoding.contains("gzip")) { try { Field responseField = httpResponse.getClass().getDeclaredField("response"); responseField.setAccessible(true); LowLevelHttpResponse lowLevelHttpResponse = (LowLevelHttpResponse) responseField.get(httpResponse); IOUtils.copy(lowLevelHttpResponse.getContent(), output); } catch (IllegalAccessException|NoSuchFieldException ex) { throw new StorageException( BaseServiceException.UNKNOWN_CODE, "Error parsing gzip response", ex); } } else { httpResponse.download(output); } String etag = req.getLastResponseHeaders().getETag(); return Tuple.of(etag, output.toByteArray()); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) { return Tuple.of(null, new byte[0]); } throw serviceException; } finally { scope.close(); span.end(); } } @Override public void write(String uploadId, byte[] toWrite, int toWriteOffset, long destOffset, int length, boolean last) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_WRITE); Scope scope = tracer.withSpan(span); try { if (length == 0 && !last) { return; } GenericUrl url = new GenericUrl(uploadId); HttpRequest httpRequest = storage.getRequestFactory().buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length)); long limit = destOffset + length; StringBuilder range = new StringBuilder("bytes "); if (length == 0) { range.append('*'); } else { range.append(destOffset).append('-').append(limit - 1); } range.append('/'); if (last) { range.append(limit); } else { range.append('*'); } httpRequest.getHeaders().setContentRange(range.toString()); int code; String message; IOException exception = null; try { HttpResponse response = httpRequest.execute(); code = response.getStatusCode(); message = response.getStatusMessage(); } catch (HttpResponseException ex) { exception = ex; code = ex.getStatusCode(); message = ex.getStatusMessage(); } if (!last && code != 308 || last && !(code == 200 || code == 201)) { if (exception != null) { throw exception; } GoogleJsonError error = new GoogleJsonError(); error.setCode(code); error.setMessage(message); throw translate(error); } } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public String open(StorageObject object, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_OPEN); Scope scope = tracer.withSpan(span); try { Insert req = storage.objects().insert(object.getBucket(), object); GenericUrl url = req.buildHttpRequest().getUrl(); String scheme = url.getScheme(); String host = url.getHost(); int port = url.getPort(); port = port < 0 ? port : url.toURL().getDefaultPort(); String path = "/upload" + url.getRawPath(); url = new GenericUrl(scheme + "://" + host + ":" + port + path); url.set("uploadType", "resumable"); url.set("name", object.getName()); for (Option option : options.keySet()) { Object content = option.get(options); if (content != null) { url.set(option.value(), content.toString()); } } JsonFactory jsonFactory = storage.getJsonFactory(); HttpRequestFactory requestFactory = storage.getRequestFactory(); HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, object)); HttpHeaders requestHeaders = httpRequest.getHeaders(); requestHeaders.set("X-Upload-Content-Type", firstNonNull(object.getContentType(), "application/octet-stream")); String key = Option.CUSTOMER_SUPPLIED_KEY.getString(options); if (key != null) { BaseEncoding base64 = BaseEncoding.base64(); HashFunction hashFunction = Hashing.sha256(); requestHeaders.set("x-goog-encryption-algorithm", "AES256"); requestHeaders.set("x-goog-encryption-key", key); requestHeaders.set("x-goog-encryption-key-sha256", base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes())); } HttpResponse response = httpRequest.execute(); if (response.getStatusCode() != 200) { GoogleJsonError error = new GoogleJsonError(); error.setCode(response.getStatusCode()); error.setMessage(response.getStatusMessage()); throw translate(error); } return response.getHeaders().getLocation(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public RewriteResponse openRewrite(RewriteRequest rewriteRequest) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_OPEN_REWRITE); Scope scope = tracer.withSpan(span); try { return rewrite(rewriteRequest, null); } finally { scope.close(); span.end(); } } @Override public RewriteResponse continueRewrite(RewriteResponse previousResponse) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CONTINUE_REWRITE); Scope scope = tracer.withSpan(span); try { return rewrite(previousResponse.rewriteRequest, previousResponse.rewriteToken); } finally { scope.close(); span.end(); } } private RewriteResponse rewrite(RewriteRequest req, String token) { try { String userProject = Option.USER_PROJECT.getString(req.sourceOptions); if (userProject == null) { userProject = Option.USER_PROJECT.getString(req.targetOptions); } String kmsKeyName = Option.KMS_KEY_NAME.getString(req.targetOptions); Long maxBytesRewrittenPerCall = req.megabytesRewrittenPerCall != null ? req.megabytesRewrittenPerCall * MEGABYTE : null; Storage.Objects.Rewrite rewrite = storage.objects() .rewrite(req.source.getBucket(), req.source.getName(), req.target.getBucket(), req.target.getName(), req.overrideInfo ? req.target : null) .setSourceGeneration(req.source.getGeneration()) .setRewriteToken(token) .setMaxBytesRewrittenPerCall(maxBytesRewrittenPerCall) .setProjection(DEFAULT_PROJECTION) .setIfSourceMetagenerationMatch(Option.IF_SOURCE_METAGENERATION_MATCH.getLong(req.sourceOptions)) .setIfSourceMetagenerationNotMatch( Option.IF_SOURCE_METAGENERATION_NOT_MATCH.getLong(req.sourceOptions)) .setIfSourceGenerationMatch(Option.IF_SOURCE_GENERATION_MATCH.getLong(req.sourceOptions)) .setIfSourceGenerationNotMatch(Option.IF_SOURCE_GENERATION_NOT_MATCH.getLong(req.sourceOptions)) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(req.targetOptions)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(req.targetOptions)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(req.targetOptions)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(req.targetOptions)) .setUserProject(userProject) .setDestinationKmsKeyName(kmsKeyName); HttpHeaders requestHeaders = rewrite.getRequestHeaders(); setEncryptionHeaders(requestHeaders, SOURCE_ENCRYPTION_KEY_PREFIX, req.sourceOptions); setEncryptionHeaders(requestHeaders, ENCRYPTION_KEY_PREFIX, req.targetOptions); com.google.api.services.storage.model.RewriteResponse rewriteResponse = rewrite.execute(); return new RewriteResponse( req, rewriteResponse.getResource(), rewriteResponse.getObjectSize().longValue(), rewriteResponse.getDone(), rewriteResponse.getRewriteToken(), rewriteResponse.getTotalBytesRewritten().longValue()); } catch (IOException ex) { tracer.getCurrentSpan().setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } } @Override public BucketAccessControl getAcl(String bucket, String entity, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_BUCKET_ACL); Scope scope = tracer.withSpan(span); try { return storage.bucketAccessControls().get(bucket, entity) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public boolean deleteAcl(String bucket, String entity, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_BUCKET_ACL); Scope scope = tracer.withSpan(span); try { storage.bucketAccessControls().delete(bucket, entity) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public BucketAccessControl createAcl(BucketAccessControl acl, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_BUCKET_ACL); Scope scope = tracer.withSpan(span); try { return storage.bucketAccessControls().insert(acl.getBucket(), acl) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public BucketAccessControl patchAcl(BucketAccessControl acl, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_BUCKET_ACL); Scope scope = tracer.withSpan(span); try { return storage.bucketAccessControls() .patch(acl.getBucket(), acl.getEntity(), acl) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public List<BucketAccessControl> listAcls(String bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_BUCKET_ACLS); Scope scope = tracer.withSpan(span); try { return storage.bucketAccessControls().list(bucket) .setUserProject(Option.USER_PROJECT.getString(options)) .execute().getItems(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl getDefaultAcl(String bucket, String entity) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_OBJECT_DEFAULT_ACL); Scope scope = tracer.withSpan(span); try { return storage.defaultObjectAccessControls().get(bucket, entity).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public boolean deleteDefaultAcl(String bucket, String entity) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_OBJECT_DEFAULT_ACL); Scope scope = tracer.withSpan(span); try { storage.defaultObjectAccessControls().delete(bucket, entity).execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl createDefaultAcl(ObjectAccessControl acl) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_OBJECT_DEFAULT_ACL); Scope scope = tracer.withSpan(span); try { return storage.defaultObjectAccessControls().insert(acl.getBucket(), acl).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl patchDefaultAcl(ObjectAccessControl acl) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_OBJECT_DEFAULT_ACL); Scope scope = tracer.withSpan(span); try { return storage.defaultObjectAccessControls() .patch(acl.getBucket(), acl.getEntity(), acl) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public List<ObjectAccessControl> listDefaultAcls(String bucket) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_OBJECT_DEFAULT_ACLS); Scope scope = tracer.withSpan(span); try { return storage.defaultObjectAccessControls().list(bucket).execute().getItems(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl getAcl(String bucket, String object, Long generation, String entity) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_OBJECT_ACL); Scope scope = tracer.withSpan(span); try { return storage.objectAccessControls().get(bucket, object, entity) .setGeneration(generation) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public boolean deleteAcl(String bucket, String object, Long generation, String entity) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_OBJECT_ACL); Scope scope = tracer.withSpan(span); try { storage.objectAccessControls().delete(bucket, object, entity) .setGeneration(generation) .execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl createAcl(ObjectAccessControl acl) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_OBJECT_ACL); Scope scope = tracer.withSpan(span); try { return storage.objectAccessControls().insert(acl.getBucket(), acl.getObject(), acl) .setGeneration(acl.getGeneration()) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl patchAcl(ObjectAccessControl acl) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_OBJECT_ACL); Scope scope = tracer.withSpan(span); try { return storage.objectAccessControls() .patch(acl.getBucket(), acl.getObject(), acl.getEntity(), acl) .setGeneration(acl.getGeneration()) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public List<ObjectAccessControl> listAcls(String bucket, String object, Long generation) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_OBJECT_ACLS); Scope scope = tracer.withSpan(span); try { return storage.objectAccessControls().list(bucket, object) .setGeneration(generation) .execute().getItems(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Policy getIamPolicy(String bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_BUCKET_IAM_POLICY); Scope scope = tracer.withSpan(span); try { return storage.buckets().getIamPolicy(bucket) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Policy setIamPolicy(String bucket, Policy policy, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_SET_BUCKET_IAM_POLICY); Scope scope = tracer.withSpan(span); try { return storage.buckets().setIamPolicy(bucket, policy) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public TestIamPermissionsResponse testIamPermissions(String bucket, List<String> permissions, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_TEST_BUCKET_IAM_PERMISSIONS); Scope scope = tracer.withSpan(span); try { return storage.buckets().testIamPermissions(bucket, permissions) .setUserProject(Option.USER_PROJECT.getString(options)).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public boolean deleteNotification(String bucket, String notification) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_NOTIFICATION); Scope scope = tracer.withSpan(span); try { storage.notifications().delete(bucket, notification).execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public List<Notification> listNotifications(String bucket) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_NOTIFICATIONS); Scope scope = tracer.withSpan(span); try { return storage.notifications().list(bucket).execute().getItems(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Notification createNotification(String bucket, Notification notification) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_NOTIFICATION); Scope scope = tracer.withSpan(span); try { return storage.notifications().insert(bucket, notification).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ServiceAccount getServiceAccount(String projectId) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_SERVICE_ACCOUNT); Scope scope = tracer.withSpan(span); try { return storage.projects().serviceAccount().get(projectId).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } }
google-cloud-clients/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/v1/HttpStorageRpc.java
/* * Copyright 2015 Google LLC * * 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.cloud.storage.spi.v1; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.client.util.IOUtils; import com.google.api.services.storage.Storage; import com.google.api.services.storage.Storage.Objects.Get; import com.google.api.services.storage.Storage.Objects.Insert; import com.google.api.services.storage.model.Bucket; import com.google.api.services.storage.model.BucketAccessControl; import com.google.api.services.storage.model.Buckets; import com.google.api.services.storage.model.ComposeRequest; import com.google.api.services.storage.model.ComposeRequest.SourceObjects.ObjectPreconditions; import com.google.api.services.storage.model.Notification; import com.google.api.services.storage.model.ObjectAccessControl; import com.google.api.services.storage.model.Objects; import com.google.api.services.storage.model.Policy; import com.google.api.services.storage.model.ServiceAccount; import com.google.api.services.storage.model.StorageObject; import com.google.api.services.storage.model.TestIamPermissionsResponse; import com.google.cloud.BaseServiceException; import com.google.cloud.Tuple; import com.google.cloud.http.CensusHttpModule; import com.google.cloud.http.HttpTransportOptions; import com.google.cloud.storage.StorageException; import com.google.cloud.storage.StorageOptions; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import com.google.common.io.BaseEncoding; import io.opencensus.common.Scope; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.Span; import io.opencensus.trace.Status; import io.opencensus.trace.Tracer; import io.opencensus.trace.Tracing; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.http.HttpStatus; public class HttpStorageRpc implements StorageRpc { public static final String DEFAULT_PROJECTION = "full"; private static final String ENCRYPTION_KEY_PREFIX = "x-goog-encryption-"; private static final String SOURCE_ENCRYPTION_KEY_PREFIX = "x-goog-copy-source-encryption-"; private final StorageOptions options; private final Storage storage; private final Tracer tracer = Tracing.getTracer(); private final CensusHttpModule censusHttpModule; private final HttpRequestInitializer batchRequestInitializer; private static final long MEGABYTE = 1024L * 1024L; public HttpStorageRpc(StorageOptions options) { HttpTransportOptions transportOptions = (HttpTransportOptions) options.getTransportOptions(); HttpTransport transport = transportOptions.getHttpTransportFactory().create(); HttpRequestInitializer initializer = transportOptions.getHttpRequestInitializer(options); this.options = options; // Open Census initialization censusHttpModule = new CensusHttpModule(tracer, true); initializer = censusHttpModule.getHttpRequestInitializer(initializer); batchRequestInitializer = censusHttpModule.getHttpRequestInitializer(null); HttpStorageRpcSpans.registerAllSpanNamesForCollection(); storage = new Storage.Builder(transport, new JacksonFactory(), initializer) .setRootUrl(options.getHost()) .setApplicationName(options.getApplicationName()) .build(); } private class DefaultRpcBatch implements RpcBatch { // Batch size is limited as, due to some current service implementation details, the service // performs better if the batches are split for better distribution. See // https://github.com/GoogleCloudPlatform/google-cloud-java/pull/952#issuecomment-213466772 for // background. private static final int MAX_BATCH_SIZE = 100; private final Storage storage; private final LinkedList<BatchRequest> batches; private int currentBatchSize; private DefaultRpcBatch(Storage storage) { this.storage = storage; batches = new LinkedList<>(); // add OpenCensus HttpRequestInitializer batches.add(storage.batch(batchRequestInitializer)); } @Override public void addDelete(StorageObject storageObject, RpcBatch.Callback<Void> callback, Map<Option, ?> options) { try { if (currentBatchSize == MAX_BATCH_SIZE) { batches.add(storage.batch()); currentBatchSize = 0; } deleteCall(storageObject, options).queue(batches.getLast(), toJsonCallback(callback)); currentBatchSize++; } catch (IOException ex) { throw translate(ex); } } @Override public void addPatch(StorageObject storageObject, RpcBatch.Callback<StorageObject> callback, Map<Option, ?> options) { try { if (currentBatchSize == MAX_BATCH_SIZE) { batches.add(storage.batch()); currentBatchSize = 0; } patchCall(storageObject, options).queue(batches.getLast(), toJsonCallback(callback)); currentBatchSize++; } catch (IOException ex) { throw translate(ex); } } @Override public void addGet(StorageObject storageObject, RpcBatch.Callback<StorageObject> callback, Map<Option, ?> options) { try { if (currentBatchSize == MAX_BATCH_SIZE) { batches.add(storage.batch()); currentBatchSize = 0; } getCall(storageObject, options).queue(batches.getLast(), toJsonCallback(callback)); currentBatchSize++; } catch (IOException ex) { throw translate(ex); } } @Override public void submit() { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_BATCH_SUBMIT); Scope scope = tracer.withSpan(span); try { span.putAttribute("batch size", AttributeValue.longAttributeValue(batches.size())); for (BatchRequest batch : batches) { // TODO(hailongwen@): instrument 'google-api-java-client' to further break down the span. // Here we only add a annotation to at least know how much time each batch takes. span.addAnnotation("Execute batch request"); batch.setBatchUrl(new GenericUrl("https://www.googleapis.com/batch/storage/v1")); batch.execute(); } } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } } private static <T> JsonBatchCallback<T> toJsonCallback(final RpcBatch.Callback<T> callback) { return new JsonBatchCallback<T>() { @Override public void onSuccess(T response, HttpHeaders httpHeaders) throws IOException { callback.onSuccess(response); } @Override public void onFailure(GoogleJsonError googleJsonError, HttpHeaders httpHeaders) throws IOException { callback.onFailure(googleJsonError); } }; } private static StorageException translate(IOException exception) { return new StorageException(exception); } private static StorageException translate(GoogleJsonError exception) { return new StorageException(exception); } private static void setEncryptionHeaders(HttpHeaders headers, String headerPrefix, Map<Option, ?> options) { String key = Option.CUSTOMER_SUPPLIED_KEY.getString(options); if (key != null) { BaseEncoding base64 = BaseEncoding.base64(); HashFunction hashFunction = Hashing.sha256(); headers.set(headerPrefix + "algorithm", "AES256"); headers.set(headerPrefix + "key", key); headers.set(headerPrefix + "key-sha256", base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes())); } } /** * Helper method to start a span. */ private Span startSpan(String spanName) { return tracer .spanBuilder(spanName) .setRecordEvents(censusHttpModule.isRecordEvents()) .startSpan(); } @Override public Bucket create(Bucket bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_BUCKET); Scope scope = tracer.withSpan(span); try { return storage.buckets() .insert(this.options.getProjectId(), bucket) .setProjection(DEFAULT_PROJECTION) .setPredefinedAcl(Option.PREDEFINED_ACL.getString(options)) .setPredefinedDefaultObjectAcl(Option.PREDEFINED_DEFAULT_OBJECT_ACL.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public StorageObject create(StorageObject storageObject, final InputStream content, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_OBJECT); Scope scope = tracer.withSpan(span); try { Storage.Objects.Insert insert = storage.objects() .insert(storageObject.getBucket(), storageObject, new InputStreamContent(storageObject.getContentType(), content)); insert.getMediaHttpUploader().setDirectUploadEnabled(true); setEncryptionHeaders(insert.getRequestHeaders(), ENCRYPTION_KEY_PREFIX, options); return insert.setProjection(DEFAULT_PROJECTION) .setPredefinedAcl(Option.PREDEFINED_ACL.getString(options)) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .setKmsKeyName(Option.KMS_KEY_NAME.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Tuple<String, Iterable<Bucket>> list(Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_BUCKETS); Scope scope = tracer.withSpan(span); try { Buckets buckets = storage.buckets() .list(this.options.getProjectId()) .setProjection(DEFAULT_PROJECTION) .setPrefix(Option.PREFIX.getString(options)) .setMaxResults(Option.MAX_RESULTS.getLong(options)) .setPageToken(Option.PAGE_TOKEN.getString(options)) .setFields(Option.FIELDS.getString(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); return Tuple.<String, Iterable<Bucket>>of(buckets.getNextPageToken(), buckets.getItems()); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Tuple<String, Iterable<StorageObject>> list(final String bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_OBJECTS); Scope scope = tracer.withSpan(span); try { Objects objects = storage.objects() .list(bucket) .setProjection(DEFAULT_PROJECTION) .setVersions(Option.VERSIONS.getBoolean(options)) .setDelimiter(Option.DELIMITER.getString(options)) .setPrefix(Option.PREFIX.getString(options)) .setMaxResults(Option.MAX_RESULTS.getLong(options)) .setPageToken(Option.PAGE_TOKEN.getString(options)) .setFields(Option.FIELDS.getString(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); Iterable<StorageObject> storageObjects = Iterables.concat( firstNonNull(objects.getItems(), ImmutableList.<StorageObject>of()), objects.getPrefixes() != null ? Lists.transform(objects.getPrefixes(), objectFromPrefix(bucket)) : ImmutableList.<StorageObject>of()); return Tuple.of(objects.getNextPageToken(), storageObjects); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } private static Function<String, StorageObject> objectFromPrefix(final String bucket) { return new Function<String, StorageObject>() { @Override public StorageObject apply(String prefix) { return new StorageObject() .set("isDirectory", true) .setBucket(bucket) .setName(prefix) .setSize(BigInteger.ZERO); } }; } @Override public Bucket get(Bucket bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_BUCKET); Scope scope = tracer.withSpan(span); try { return storage.buckets() .get(bucket.getName()) .setProjection(DEFAULT_PROJECTION) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setFields(Option.FIELDS.getString(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } private Storage.Objects.Get getCall(StorageObject object, Map<Option, ?> options) throws IOException { return storage.objects() .get(object.getBucket(), object.getName()) .setGeneration(object.getGeneration()) .setProjection(DEFAULT_PROJECTION) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setFields(Option.FIELDS.getString(options)) .setUserProject(Option.USER_PROJECT.getString(options)); } @Override public StorageObject get(StorageObject object, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_OBJECT); Scope scope = tracer.withSpan(span); try { return getCall(object, options).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public Bucket patch(Bucket bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_BUCKET); Scope scope = tracer.withSpan(span); try { return storage.buckets() .patch(bucket.getName(), bucket) .setProjection(DEFAULT_PROJECTION) .setPredefinedAcl(Option.PREDEFINED_ACL.getString(options)) .setPredefinedDefaultObjectAcl(Option.PREDEFINED_DEFAULT_OBJECT_ACL.getString(options)) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } private Storage.Objects.Patch patchCall(StorageObject storageObject, Map<Option, ?> options) throws IOException { return storage.objects() .patch(storageObject.getBucket(), storageObject.getName(), storageObject) .setProjection(DEFAULT_PROJECTION) .setPredefinedAcl(Option.PREDEFINED_ACL.getString(options)) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)); } @Override public StorageObject patch(StorageObject storageObject, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_OBJECT); Scope scope = tracer.withSpan(span); try { return patchCall(storageObject, options).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public boolean delete(Bucket bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_BUCKET); Scope scope = tracer.withSpan(span); try { storage.buckets() .delete(bucket.getName()) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } private Storage.Objects.Delete deleteCall(StorageObject blob, Map<Option, ?> options) throws IOException { return storage.objects() .delete(blob.getBucket(), blob.getName()) .setGeneration(blob.getGeneration()) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)); } @Override public boolean delete(StorageObject blob, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_OBJECT); Scope scope = tracer.withSpan(span); try { deleteCall(blob, options).execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public StorageObject compose(Iterable<StorageObject> sources, StorageObject target, Map<Option, ?> targetOptions) { ComposeRequest request = new ComposeRequest(); request.setDestination(target); List<ComposeRequest.SourceObjects> sourceObjects = new ArrayList<>(); for (StorageObject source : sources) { ComposeRequest.SourceObjects sourceObject = new ComposeRequest.SourceObjects(); sourceObject.setName(source.getName()); Long generation = source.getGeneration(); if (generation != null) { sourceObject.setGeneration(generation); sourceObject.setObjectPreconditions( new ObjectPreconditions().setIfGenerationMatch(generation)); } sourceObjects.add(sourceObject); } request.setSourceObjects(sourceObjects); Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_COMPOSE); Scope scope = tracer.withSpan(span); try { return storage.objects() .compose(target.getBucket(), target.getName(), request) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(targetOptions)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(targetOptions)) .setUserProject(Option.USER_PROJECT.getString(targetOptions)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public byte[] load(StorageObject from, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LOAD); Scope scope = tracer.withSpan(span); try { Storage.Objects.Get getRequest = storage.objects() .get(from.getBucket(), from.getName()) .setGeneration(from.getGeneration()) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)); setEncryptionHeaders(getRequest.getRequestHeaders(), ENCRYPTION_KEY_PREFIX, options); ByteArrayOutputStream out = new ByteArrayOutputStream(); getRequest.executeMedia().download(out); return out.toByteArray(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public RpcBatch createBatch() { return new DefaultRpcBatch(storage); } @Override public Tuple<String, byte[]> read(StorageObject from, Map<Option, ?> options, long position, int bytes) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_READ); Scope scope = tracer.withSpan(span); try { Get req = storage.objects() .get(from.getBucket(), from.getName()) .setGeneration(from.getGeneration()) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(options)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(options)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(options)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(options)) .setUserProject(Option.USER_PROJECT.getString(options)); checkArgument(position >= 0, "Position should be non-negative, is %d", position); StringBuilder range = new StringBuilder(); range.append("bytes=").append(position).append("-").append(position + bytes - 1); HttpHeaders requestHeaders = req.getRequestHeaders(); requestHeaders.setRange(range.toString()); setEncryptionHeaders(requestHeaders, ENCRYPTION_KEY_PREFIX, options); ByteArrayOutputStream output = new ByteArrayOutputStream(bytes); HttpResponse httpResponse = req.executeMedia(); // todo(mziccard) remove when // https://github.com/GoogleCloudPlatform/google-cloud-java/issues/982 is fixed String contentEncoding = httpResponse.getContentEncoding(); if (contentEncoding != null && contentEncoding.contains("gzip")) { try { Field responseField = httpResponse.getClass().getDeclaredField("response"); responseField.setAccessible(true); LowLevelHttpResponse lowLevelHttpResponse = (LowLevelHttpResponse) responseField.get(httpResponse); IOUtils.copy(lowLevelHttpResponse.getContent(), output); } catch (IllegalAccessException|NoSuchFieldException ex) { throw new StorageException( BaseServiceException.UNKNOWN_CODE, "Error parsing gzip response", ex); } } else { httpResponse.download(output); } String etag = req.getLastResponseHeaders().getETag(); return Tuple.of(etag, output.toByteArray()); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) { return Tuple.of(null, new byte[0]); } throw serviceException; } finally { scope.close(); span.end(); } } @Override public void write(String uploadId, byte[] toWrite, int toWriteOffset, long destOffset, int length, boolean last) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_WRITE); Scope scope = tracer.withSpan(span); try { if (length == 0 && !last) { return; } GenericUrl url = new GenericUrl(uploadId); HttpRequest httpRequest = storage.getRequestFactory().buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length)); long limit = destOffset + length; StringBuilder range = new StringBuilder("bytes "); if (length == 0) { range.append('*'); } else { range.append(destOffset).append('-').append(limit - 1); } range.append('/'); if (last) { range.append(limit); } else { range.append('*'); } httpRequest.getHeaders().setContentRange(range.toString()); int code; String message; IOException exception = null; try { HttpResponse response = httpRequest.execute(); code = response.getStatusCode(); message = response.getStatusMessage(); } catch (HttpResponseException ex) { exception = ex; code = ex.getStatusCode(); message = ex.getStatusMessage(); } if (!last && code != 308 || last && !(code == 200 || code == 201)) { if (exception != null) { throw exception; } GoogleJsonError error = new GoogleJsonError(); error.setCode(code); error.setMessage(message); throw translate(error); } } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public String open(StorageObject object, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_OPEN); Scope scope = tracer.withSpan(span); try { Insert req = storage.objects().insert(object.getBucket(), object); GenericUrl url = req.buildHttpRequest().getUrl(); String scheme = url.getScheme(); String host = url.getHost(); String path = "/upload" + url.getRawPath(); url = new GenericUrl(scheme + "://" + host + path); url.set("uploadType", "resumable"); url.set("name", object.getName()); for (Option option : options.keySet()) { Object content = option.get(options); if (content != null) { url.set(option.value(), content.toString()); } } JsonFactory jsonFactory = storage.getJsonFactory(); HttpRequestFactory requestFactory = storage.getRequestFactory(); HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, object)); HttpHeaders requestHeaders = httpRequest.getHeaders(); requestHeaders.set("X-Upload-Content-Type", firstNonNull(object.getContentType(), "application/octet-stream")); String key = Option.CUSTOMER_SUPPLIED_KEY.getString(options); if (key != null) { BaseEncoding base64 = BaseEncoding.base64(); HashFunction hashFunction = Hashing.sha256(); requestHeaders.set("x-goog-encryption-algorithm", "AES256"); requestHeaders.set("x-goog-encryption-key", key); requestHeaders.set("x-goog-encryption-key-sha256", base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes())); } HttpResponse response = httpRequest.execute(); if (response.getStatusCode() != 200) { GoogleJsonError error = new GoogleJsonError(); error.setCode(response.getStatusCode()); error.setMessage(response.getStatusMessage()); throw translate(error); } return response.getHeaders().getLocation(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public RewriteResponse openRewrite(RewriteRequest rewriteRequest) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_OPEN_REWRITE); Scope scope = tracer.withSpan(span); try { return rewrite(rewriteRequest, null); } finally { scope.close(); span.end(); } } @Override public RewriteResponse continueRewrite(RewriteResponse previousResponse) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CONTINUE_REWRITE); Scope scope = tracer.withSpan(span); try { return rewrite(previousResponse.rewriteRequest, previousResponse.rewriteToken); } finally { scope.close(); span.end(); } } private RewriteResponse rewrite(RewriteRequest req, String token) { try { String userProject = Option.USER_PROJECT.getString(req.sourceOptions); if (userProject == null) { userProject = Option.USER_PROJECT.getString(req.targetOptions); } String kmsKeyName = Option.KMS_KEY_NAME.getString(req.targetOptions); Long maxBytesRewrittenPerCall = req.megabytesRewrittenPerCall != null ? req.megabytesRewrittenPerCall * MEGABYTE : null; Storage.Objects.Rewrite rewrite = storage.objects() .rewrite(req.source.getBucket(), req.source.getName(), req.target.getBucket(), req.target.getName(), req.overrideInfo ? req.target : null) .setSourceGeneration(req.source.getGeneration()) .setRewriteToken(token) .setMaxBytesRewrittenPerCall(maxBytesRewrittenPerCall) .setProjection(DEFAULT_PROJECTION) .setIfSourceMetagenerationMatch(Option.IF_SOURCE_METAGENERATION_MATCH.getLong(req.sourceOptions)) .setIfSourceMetagenerationNotMatch( Option.IF_SOURCE_METAGENERATION_NOT_MATCH.getLong(req.sourceOptions)) .setIfSourceGenerationMatch(Option.IF_SOURCE_GENERATION_MATCH.getLong(req.sourceOptions)) .setIfSourceGenerationNotMatch(Option.IF_SOURCE_GENERATION_NOT_MATCH.getLong(req.sourceOptions)) .setIfMetagenerationMatch(Option.IF_METAGENERATION_MATCH.getLong(req.targetOptions)) .setIfMetagenerationNotMatch(Option.IF_METAGENERATION_NOT_MATCH.getLong(req.targetOptions)) .setIfGenerationMatch(Option.IF_GENERATION_MATCH.getLong(req.targetOptions)) .setIfGenerationNotMatch(Option.IF_GENERATION_NOT_MATCH.getLong(req.targetOptions)) .setUserProject(userProject) .setDestinationKmsKeyName(kmsKeyName); HttpHeaders requestHeaders = rewrite.getRequestHeaders(); setEncryptionHeaders(requestHeaders, SOURCE_ENCRYPTION_KEY_PREFIX, req.sourceOptions); setEncryptionHeaders(requestHeaders, ENCRYPTION_KEY_PREFIX, req.targetOptions); com.google.api.services.storage.model.RewriteResponse rewriteResponse = rewrite.execute(); return new RewriteResponse( req, rewriteResponse.getResource(), rewriteResponse.getObjectSize().longValue(), rewriteResponse.getDone(), rewriteResponse.getRewriteToken(), rewriteResponse.getTotalBytesRewritten().longValue()); } catch (IOException ex) { tracer.getCurrentSpan().setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } } @Override public BucketAccessControl getAcl(String bucket, String entity, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_BUCKET_ACL); Scope scope = tracer.withSpan(span); try { return storage.bucketAccessControls().get(bucket, entity) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public boolean deleteAcl(String bucket, String entity, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_BUCKET_ACL); Scope scope = tracer.withSpan(span); try { storage.bucketAccessControls().delete(bucket, entity) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public BucketAccessControl createAcl(BucketAccessControl acl, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_BUCKET_ACL); Scope scope = tracer.withSpan(span); try { return storage.bucketAccessControls().insert(acl.getBucket(), acl) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public BucketAccessControl patchAcl(BucketAccessControl acl, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_BUCKET_ACL); Scope scope = tracer.withSpan(span); try { return storage.bucketAccessControls() .patch(acl.getBucket(), acl.getEntity(), acl) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public List<BucketAccessControl> listAcls(String bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_BUCKET_ACLS); Scope scope = tracer.withSpan(span); try { return storage.bucketAccessControls().list(bucket) .setUserProject(Option.USER_PROJECT.getString(options)) .execute().getItems(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl getDefaultAcl(String bucket, String entity) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_OBJECT_DEFAULT_ACL); Scope scope = tracer.withSpan(span); try { return storage.defaultObjectAccessControls().get(bucket, entity).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public boolean deleteDefaultAcl(String bucket, String entity) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_OBJECT_DEFAULT_ACL); Scope scope = tracer.withSpan(span); try { storage.defaultObjectAccessControls().delete(bucket, entity).execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl createDefaultAcl(ObjectAccessControl acl) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_OBJECT_DEFAULT_ACL); Scope scope = tracer.withSpan(span); try { return storage.defaultObjectAccessControls().insert(acl.getBucket(), acl).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl patchDefaultAcl(ObjectAccessControl acl) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_OBJECT_DEFAULT_ACL); Scope scope = tracer.withSpan(span); try { return storage.defaultObjectAccessControls() .patch(acl.getBucket(), acl.getEntity(), acl) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public List<ObjectAccessControl> listDefaultAcls(String bucket) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_OBJECT_DEFAULT_ACLS); Scope scope = tracer.withSpan(span); try { return storage.defaultObjectAccessControls().list(bucket).execute().getItems(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl getAcl(String bucket, String object, Long generation, String entity) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_OBJECT_ACL); Scope scope = tracer.withSpan(span); try { return storage.objectAccessControls().get(bucket, object, entity) .setGeneration(generation) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return null; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public boolean deleteAcl(String bucket, String object, Long generation, String entity) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_OBJECT_ACL); Scope scope = tracer.withSpan(span); try { storage.objectAccessControls().delete(bucket, object, entity) .setGeneration(generation) .execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl createAcl(ObjectAccessControl acl) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_OBJECT_ACL); Scope scope = tracer.withSpan(span); try { return storage.objectAccessControls().insert(acl.getBucket(), acl.getObject(), acl) .setGeneration(acl.getGeneration()) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ObjectAccessControl patchAcl(ObjectAccessControl acl) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_OBJECT_ACL); Scope scope = tracer.withSpan(span); try { return storage.objectAccessControls() .patch(acl.getBucket(), acl.getObject(), acl.getEntity(), acl) .setGeneration(acl.getGeneration()) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public List<ObjectAccessControl> listAcls(String bucket, String object, Long generation) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_OBJECT_ACLS); Scope scope = tracer.withSpan(span); try { return storage.objectAccessControls().list(bucket, object) .setGeneration(generation) .execute().getItems(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Policy getIamPolicy(String bucket, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_BUCKET_IAM_POLICY); Scope scope = tracer.withSpan(span); try { return storage.buckets().getIamPolicy(bucket) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Policy setIamPolicy(String bucket, Policy policy, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_SET_BUCKET_IAM_POLICY); Scope scope = tracer.withSpan(span); try { return storage.buckets().setIamPolicy(bucket, policy) .setUserProject(Option.USER_PROJECT.getString(options)) .execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public TestIamPermissionsResponse testIamPermissions(String bucket, List<String> permissions, Map<Option, ?> options) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_TEST_BUCKET_IAM_PERMISSIONS); Scope scope = tracer.withSpan(span); try { return storage.buckets().testIamPermissions(bucket, permissions) .setUserProject(Option.USER_PROJECT.getString(options)).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public boolean deleteNotification(String bucket, String notification) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_NOTIFICATION); Scope scope = tracer.withSpan(span); try { storage.notifications().delete(bucket, notification).execute(); return true; } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); StorageException serviceException = translate(ex); if (serviceException.getCode() == HTTP_NOT_FOUND) { return false; } throw serviceException; } finally { scope.close(); span.end(); } } @Override public List<Notification> listNotifications(String bucket) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_LIST_NOTIFICATIONS); Scope scope = tracer.withSpan(span); try { return storage.notifications().list(bucket).execute().getItems(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public Notification createNotification(String bucket, Notification notification) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_NOTIFICATION); Scope scope = tracer.withSpan(span); try { return storage.notifications().insert(bucket, notification).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } @Override public ServiceAccount getServiceAccount(String projectId) { Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_SERVICE_ACCOUNT); Scope scope = tracer.withSpan(span); try { return storage.projects().serviceAccount().get(projectId).execute(); } catch (IOException ex) { span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage())); throw translate(ex); } finally { scope.close(); span.end(); } } }
Add port to storage upload url (#3324)
google-cloud-clients/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/v1/HttpStorageRpc.java
Add port to storage upload url (#3324)
<ide><path>oogle-cloud-clients/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/v1/HttpStorageRpc.java <ide> GenericUrl url = req.buildHttpRequest().getUrl(); <ide> String scheme = url.getScheme(); <ide> String host = url.getHost(); <add> int port = url.getPort(); <add> port = port < 0 ? port : url.toURL().getDefaultPort(); <ide> String path = "/upload" + url.getRawPath(); <del> url = new GenericUrl(scheme + "://" + host + path); <add> url = new GenericUrl(scheme + "://" + host + ":" + port + path); <ide> url.set("uploadType", "resumable"); <ide> url.set("name", object.getName()); <ide> for (Option option : options.keySet()) {
Java
apache-2.0
8a39361937c4bb9f31a5faa612c98371cbc05bc5
0
donNewtonAlpha/onos,oplinkoms/onos,oplinkoms/onos,y-higuchi/onos,y-higuchi/onos,sdnwiselab/onos,opennetworkinglab/onos,maheshraju-Huawei/actn,VinodKumarS-Huawei/ietf96yang,mengmoya/onos,y-higuchi/onos,sdnwiselab/onos,opennetworkinglab/onos,osinstom/onos,oplinkoms/onos,maheshraju-Huawei/actn,LorenzReinhart/ONOSnew,VinodKumarS-Huawei/ietf96yang,donNewtonAlpha/onos,Shashikanth-Huawei/bmp,LorenzReinhart/ONOSnew,osinstom/onos,y-higuchi/onos,kuujo/onos,y-higuchi/onos,gkatsikas/onos,osinstom/onos,opennetworkinglab/onos,kuujo/onos,kuujo/onos,sdnwiselab/onos,gkatsikas/onos,osinstom/onos,Shashikanth-Huawei/bmp,Shashikanth-Huawei/bmp,kuujo/onos,mengmoya/onos,donNewtonAlpha/onos,VinodKumarS-Huawei/ietf96yang,oplinkoms/onos,sdnwiselab/onos,opennetworkinglab/onos,LorenzReinhart/ONOSnew,kuujo/onos,VinodKumarS-Huawei/ietf96yang,oplinkoms/onos,oplinkoms/onos,gkatsikas/onos,maheshraju-Huawei/actn,sdnwiselab/onos,Shashikanth-Huawei/bmp,sdnwiselab/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,opennetworkinglab/onos,gkatsikas/onos,mengmoya/onos,opennetworkinglab/onos,LorenzReinhart/ONOSnew,VinodKumarS-Huawei/ietf96yang,gkatsikas/onos,mengmoya/onos,kuujo/onos,kuujo/onos,osinstom/onos,donNewtonAlpha/onos,gkatsikas/onos,mengmoya/onos,maheshraju-Huawei/actn,donNewtonAlpha/onos,Shashikanth-Huawei/bmp,maheshraju-Huawei/actn
protocols/openflow/drivers/src/main/java/org/onosproject/openflow/drivers/OFSwitchImplSpringOpenTTPDellOSR.java
/* * Copyright 2015-present Open Networking Laboratory * * 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.onosproject.openflow.drivers; import org.onosproject.openflow.controller.Dpid; import org.projectfloodlight.openflow.protocol.OFDescStatsReply; import org.projectfloodlight.openflow.types.TableId; /** * OFDescriptionStatistics Vendor (Manufacturer Desc.): Dell Make (Hardware * Desc.) : OpenFlow 1.3 Reference Userspace Switch Model (Datapath Desc.) : * None Software : Serial : None. */ //TODO: Knock-off this class as we don't need any switch/app specific //drivers in the south bound layers. public class OFSwitchImplSpringOpenTTPDellOSR extends OFSwitchImplSpringOpenTTP { /* Table IDs to be used for Dell Open Segment Routers*/ private static final int DELL_TABLE_VLAN = 17; private static final int DELL_TABLE_TMAC = 18; private static final int DELL_TABLE_IPV4_UNICAST = 30; private static final int DELL_TABLE_MPLS = 25; private static final int DELL_TABLE_ACL = 40; public OFSwitchImplSpringOpenTTPDellOSR(Dpid dpid, OFDescStatsReply desc) { super(dpid, desc); vlanTableId = DELL_TABLE_VLAN; tmacTableId = DELL_TABLE_TMAC; ipv4UnicastTableId = DELL_TABLE_IPV4_UNICAST; mplsTableId = DELL_TABLE_MPLS; aclTableId = DELL_TABLE_ACL; } @Override public TableType getTableType(TableId tid) { switch (tid.getValue()) { case DELL_TABLE_IPV4_UNICAST: return TableType.IP; case DELL_TABLE_MPLS: return TableType.MPLS; case DELL_TABLE_ACL: return TableType.ACL; case DELL_TABLE_VLAN: return TableType.VLAN; case DELL_TABLE_TMAC: return TableType.ETHER; default: log.error("Table type for Table id {} is not supported in the driver", tid); return TableType.NONE; } } }
Removed orphaned Java file that is no longer built or used Change-Id: Ib9bfbd7666233f1debfc3673ca568b7ca55fe159
protocols/openflow/drivers/src/main/java/org/onosproject/openflow/drivers/OFSwitchImplSpringOpenTTPDellOSR.java
Removed orphaned Java file that is no longer built or used
<ide><path>rotocols/openflow/drivers/src/main/java/org/onosproject/openflow/drivers/OFSwitchImplSpringOpenTTPDellOSR.java <del>/* <del> * Copyright 2015-present Open Networking Laboratory <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package org.onosproject.openflow.drivers; <del> <del>import org.onosproject.openflow.controller.Dpid; <del>import org.projectfloodlight.openflow.protocol.OFDescStatsReply; <del>import org.projectfloodlight.openflow.types.TableId; <del> <del>/** <del> * OFDescriptionStatistics Vendor (Manufacturer Desc.): Dell Make (Hardware <del> * Desc.) : OpenFlow 1.3 Reference Userspace Switch Model (Datapath Desc.) : <del> * None Software : Serial : None. <del> */ <del>//TODO: Knock-off this class as we don't need any switch/app specific <del>//drivers in the south bound layers. <del>public class OFSwitchImplSpringOpenTTPDellOSR extends OFSwitchImplSpringOpenTTP { <del> <del> /* Table IDs to be used for Dell Open Segment Routers*/ <del> private static final int DELL_TABLE_VLAN = 17; <del> private static final int DELL_TABLE_TMAC = 18; <del> private static final int DELL_TABLE_IPV4_UNICAST = 30; <del> private static final int DELL_TABLE_MPLS = 25; <del> private static final int DELL_TABLE_ACL = 40; <del> <del> public OFSwitchImplSpringOpenTTPDellOSR(Dpid dpid, OFDescStatsReply desc) { <del> super(dpid, desc); <del> vlanTableId = DELL_TABLE_VLAN; <del> tmacTableId = DELL_TABLE_TMAC; <del> ipv4UnicastTableId = DELL_TABLE_IPV4_UNICAST; <del> mplsTableId = DELL_TABLE_MPLS; <del> aclTableId = DELL_TABLE_ACL; <del> } <del> <del> @Override <del> public TableType getTableType(TableId tid) { <del> switch (tid.getValue()) { <del> case DELL_TABLE_IPV4_UNICAST: <del> return TableType.IP; <del> case DELL_TABLE_MPLS: <del> return TableType.MPLS; <del> case DELL_TABLE_ACL: <del> return TableType.ACL; <del> case DELL_TABLE_VLAN: <del> return TableType.VLAN; <del> case DELL_TABLE_TMAC: <del> return TableType.ETHER; <del> default: <del> log.error("Table type for Table id {} is not supported in the driver", tid); <del> return TableType.NONE; <del> } <del> } <del>}
Java
apache-2.0
53dc8b64d533adf245ee653aff78675dce9f6790
0
xdegenne/alien4cloud,PierreLemordant/alien4cloud,alien4cloud/alien4cloud,san-tak/alien4cloud,xdegenne/alien4cloud,OresteVisari/alien4cloud,loicalbertin/alien4cloud,OresteVisari/alien4cloud,loicalbertin/alien4cloud,alien4cloud/alien4cloud,xdegenne/alien4cloud,san-tak/alien4cloud,PierreLemordant/alien4cloud,alien4cloud/alien4cloud,igorng/alien4cloud,igorng/alien4cloud,broly-git/alien4cloud,xdegenne/alien4cloud,ngouagna/alien4cloud,san-tak/alien4cloud,PierreLemordant/alien4cloud,ngouagna/alien4cloud,PierreLemordant/alien4cloud,loicalbertin/alien4cloud,OresteVisari/alien4cloud,ahgittin/alien4cloud,loicalbertin/alien4cloud,igorng/alien4cloud,OresteVisari/alien4cloud,ahgittin/alien4cloud,broly-git/alien4cloud,ngouagna/alien4cloud,broly-git/alien4cloud,ngouagna/alien4cloud,igorng/alien4cloud,ahgittin/alien4cloud,ahgittin/alien4cloud,broly-git/alien4cloud,alien4cloud/alien4cloud,san-tak/alien4cloud
package alien4cloud.model.cloud; import lombok.AllArgsConstructor; @AllArgsConstructor public enum IaaSType { AZURE("azure"), OPENSTACK("openstack"), VMWARE("vmware"), AMAZON("amazon"), VIRTUALBOX("virtualbox"), OTHER("other"); private String name; @Override public String toString() { return name; } }
alien4cloud-core/src/main/java/alien4cloud/model/cloud/IaaSType.java
package alien4cloud.model.cloud; public enum IaaSType { AZURE, OPENSTACK, VMWARE, AMAZON, VIRTUALBOX, OTHER }
ALIEN-538 : As a USER I want to be able to use Cloudify 3 as a cloud deployer. Make IaaSType toString more friendly
alien4cloud-core/src/main/java/alien4cloud/model/cloud/IaaSType.java
ALIEN-538 : As a USER I want to be able to use Cloudify 3 as a cloud deployer. Make IaaSType toString more friendly
<ide><path>lien4cloud-core/src/main/java/alien4cloud/model/cloud/IaaSType.java <ide> package alien4cloud.model.cloud; <ide> <add>import lombok.AllArgsConstructor; <add> <add>@AllArgsConstructor <ide> public enum IaaSType { <del> AZURE, OPENSTACK, VMWARE, AMAZON, VIRTUALBOX, OTHER <add> AZURE("azure"), OPENSTACK("openstack"), VMWARE("vmware"), AMAZON("amazon"), VIRTUALBOX("virtualbox"), OTHER("other"); <add> <add> private String name; <add> <add> @Override <add> public String toString() { <add> return name; <add> } <ide> }
Java
apache-2.0
9bf1237f0da32f205c3158442dda4c56d2ab63e6
0
klehmann/domino-jna
package com.mindoo.domino.jna.test; import java.util.EnumSet; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import com.mindoo.domino.jna.NotesCollection; import com.mindoo.domino.jna.NotesDatabase; import com.mindoo.domino.jna.NotesItem; import com.mindoo.domino.jna.NotesNote; import com.mindoo.domino.jna.NotesNote.IItemCallback; import com.mindoo.domino.jna.NotesViewEntryData; import com.mindoo.domino.jna.constants.Navigate; import com.mindoo.domino.jna.constants.ReadMask; import lotus.domino.Session; public class TestJava8Features extends BaseJNATestClass { @Test public void testJava8() { runWithSession(new IDominoCallable<Object>() { @Override public Object call(Session session) throws Exception { NotesDatabase db = getFakeNamesDb(); NotesCollection peopleView = db.openCollectionByName("People"); List<NotesViewEntryData> entries = peopleView.getAllEntries("0", 1, EnumSet.of(Navigate.NEXT_NONCATEGORY), 1, EnumSet.of(ReadMask.NOTEID), new NotesCollection.EntriesAsListCallback(1)); NotesNote note = db.openNoteById(entries.get(0).getNoteId()); AtomicInteger idx = new AtomicInteger(); note.getItems(new IItemCallback() { @Override public Action itemFound(NotesItem item) { System.out.println("#"+idx.getAndIncrement()+"\tItem name: "+item.getName()); // return Action.Stop; return Action.Continue; } }); System.out.println(); note.getItems((item,loop) -> { System.out.println("#"+loop.getIndex()+"\tItem name: "+item.getName()+", isfirst="+loop.isFirst()+", islast="+loop.isLast()); loop.stop(); }); return null; } }); } }
domino-jna/src/test/java/com/mindoo/domino/jna/test/TestJava8Features.java
package com.mindoo.domino.jna.test; import java.util.EnumSet; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import com.mindoo.domino.jna.NotesCollection; import com.mindoo.domino.jna.NotesDatabase; import com.mindoo.domino.jna.NotesItem; import com.mindoo.domino.jna.NotesNote; import com.mindoo.domino.jna.NotesNote.IItemCallback; import com.mindoo.domino.jna.NotesViewEntryData; import com.mindoo.domino.jna.constants.Navigate; import com.mindoo.domino.jna.constants.ReadMask; import lotus.domino.Session; public class TestJava8Features extends BaseJNATestClass { @Test public void testJava8() { runWithSession(new IDominoCallable<Object>() { @Override public Object call(Session session) throws Exception { NotesDatabase db = getFakeNamesDb(); NotesCollection peopleView = db.openCollectionByName("People"); List<NotesViewEntryData> entries = peopleView.getAllEntries("0", 1, EnumSet.of(Navigate.NEXT_NONCATEGORY), 1, EnumSet.of(ReadMask.NOTEID), new NotesCollection.EntriesAsListCallback(1)); NotesNote note = db.openNoteById(entries.get(0).getNoteId()); AtomicInteger idx = new AtomicInteger(); note.getItems(new IItemCallback() { @Override public Action itemFound(NotesItem item) { System.out.println("#"+idx.getAndIncrement()+"\tItem name: "+item.getName()); return Action.Continue; } }); System.out.println(); note.getItems((item,loop) -> { System.out.println("#"+loop.getIndex()+"\tItem name: "+item.getName()+", isfirst="+loop.isFirst()+", islast="+loop.isLast()); }); return null; } }); } }
Added stop call to new loop syntax
domino-jna/src/test/java/com/mindoo/domino/jna/test/TestJava8Features.java
Added stop call to new loop syntax
<ide><path>omino-jna/src/test/java/com/mindoo/domino/jna/test/TestJava8Features.java <ide> public Action itemFound(NotesItem item) { <ide> System.out.println("#"+idx.getAndIncrement()+"\tItem name: "+item.getName()); <ide> <add>// return Action.Stop; <add> <ide> return Action.Continue; <ide> } <ide> <ide> <ide> note.getItems((item,loop) -> { <ide> System.out.println("#"+loop.getIndex()+"\tItem name: "+item.getName()+", isfirst="+loop.isFirst()+", islast="+loop.isLast()); <add> loop.stop(); <ide> }); <ide> <ide> return null;
Java
apache-2.0
58d60d7a5773ed2dabfb251b7e271f84f449ebe7
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2002-2007 the original author or authors. * * 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.springframework.aop.scope; import org.springframework.aop.framework.autoproxy.AutoProxyUtils; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; /** * @author Rob Harrop * @author Juergen Hoeller * @author Mark Fisher * @since 2.1 */ public abstract class ScopedProxyUtils { private static final String TARGET_NAME_PREFIX = "scopedTarget."; /** * Generates a scoped proxy for the supplied target bean, registering the target * bean with an internal name and setting 'targetBeanName' on the scoped proxy. * @param definition the original bean definition * @param registry the bean definition registry * @param proxyTargetClass whether to create a target class proxy * @return the scoped proxy definition */ public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition, BeanDefinitionRegistry registry, boolean proxyTargetClass) { String originalBeanName = definition.getBeanName(); BeanDefinition targetDefinition = definition.getBeanDefinition(); // Create a scoped proxy definition for the original bean name, // "hiding" the target bean in an internal target definition. RootBeanDefinition scopedProxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class); scopedProxyDefinition.setSource(definition.getSource()); String targetBeanName = TARGET_NAME_PREFIX + originalBeanName; scopedProxyDefinition.getPropertyValues().addPropertyValue("targetBeanName", targetBeanName); if (proxyTargetClass) { targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); // ScopedFactoryBean's "proxyTargetClass" default is TRUE, so we don't need to set it explicitly here. } else { scopedProxyDefinition.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.FALSE); } // The target bean should be ignored in favor of the scoped proxy. if (targetDefinition instanceof AbstractBeanDefinition) { ((AbstractBeanDefinition) targetDefinition).setAutowireCandidate(false); } // Register the target bean as separate bean in the factory. registry.registerBeanDefinition(targetBeanName, targetDefinition); // Return the scoped proxy definition as primary bean definition // (potentially an inner bean). return new BeanDefinitionHolder(scopedProxyDefinition, originalBeanName, definition.getAliases()); } }
src/org/springframework/aop/scope/ScopedProxyUtils.java
/* * Copyright 2002-2007 the original author or authors. * * 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.springframework.aop.scope; import org.springframework.aop.framework.autoproxy.AutoProxyUtils; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; /** * @author Rob Harrop * @author Juergen Hoeller * @author Mark Fisher * @since 2.1 */ public class ScopedProxyUtils { private static final String TARGET_NAME_PREFIX = "scopedTarget."; /** * Generates a scoped proxy for the supplied target bean, registering the target * bean with an internal name and setting 'targetBeanName' on the scoped proxy. * @param definition * @param registry * @param proxyTargetClass * @return the scoped proxy definition */ public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition, BeanDefinitionRegistry registry, boolean proxyTargetClass) { String originalBeanName = definition.getBeanName(); BeanDefinition targetDefinition = definition.getBeanDefinition(); // Create a scoped proxy definition for the original bean name, // "hiding" the target bean in an internal target definition. String targetBeanName = TARGET_NAME_PREFIX + originalBeanName; RootBeanDefinition scopedProxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class); scopedProxyDefinition.getPropertyValues().addPropertyValue("targetBeanName", targetBeanName); if (proxyTargetClass) { targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); // ScopedFactoryBean's "proxyTargetClass" default is TRUE, so we don't need to set it explicitly here. } else { scopedProxyDefinition.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.FALSE); } // The target bean should be ignored in favor of the scoped proxy. if (targetDefinition instanceof AbstractBeanDefinition) { ((AbstractBeanDefinition) targetDefinition).setAutowireCandidate(false); } // Register the target bean as separate bean in the factory. registry.registerBeanDefinition(targetBeanName, targetDefinition); // Return the scoped proxy definition as primary bean definition // (potentially an inner bean). return new BeanDefinitionHolder(scopedProxyDefinition, originalBeanName, definition.getAliases()); } }
use source object from target definition for scoped proxy definition git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@13898 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
src/org/springframework/aop/scope/ScopedProxyUtils.java
use source object from target definition for scoped proxy definition
<ide><path>rc/org/springframework/aop/scope/ScopedProxyUtils.java <ide> * @author Mark Fisher <ide> * @since 2.1 <ide> */ <del>public class ScopedProxyUtils { <add>public abstract class ScopedProxyUtils { <ide> <ide> private static final String TARGET_NAME_PREFIX = "scopedTarget."; <ide> <ide> /** <ide> * Generates a scoped proxy for the supplied target bean, registering the target <ide> * bean with an internal name and setting 'targetBeanName' on the scoped proxy. <del> * @param definition <del> * @param registry <del> * @param proxyTargetClass <add> * @param definition the original bean definition <add> * @param registry the bean definition registry <add> * @param proxyTargetClass whether to create a target class proxy <ide> * @return the scoped proxy definition <ide> */ <ide> public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition, <ide> <ide> // Create a scoped proxy definition for the original bean name, <ide> // "hiding" the target bean in an internal target definition. <add> RootBeanDefinition scopedProxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class); <add> scopedProxyDefinition.setSource(definition.getSource()); <add> <ide> String targetBeanName = TARGET_NAME_PREFIX + originalBeanName; <del> RootBeanDefinition scopedProxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class); <ide> scopedProxyDefinition.getPropertyValues().addPropertyValue("targetBeanName", targetBeanName); <ide> <ide> if (proxyTargetClass) {
JavaScript
mit
84fd60ce83f90604f71fc967d54232abdfc791b1
0
marko-js/marko,marko-js/marko
'use strict'; var chai = require('chai'); chai.Assertion.includeStack = true; var expect = require('chai').expect; var nodePath = require('path'); var marko = require('../'); var through = require('through'); require('../node-require').install(); describe('marko/api' , function() { before(function() { require('../compiler').defaultOptions.checkUpToDate = false; }); beforeEach(function(done) { done(); }); it('should allow a template to be rendered using a callback', function(done) { marko.render( nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'), { name: 'John' }, function(err, output) { if (err) { return done(err); } expect(output).to.equal('Hello John!'); done(); }); }); it('should allow a template to be rendered to a writer wrapping a string builder', function(done) { var out = marko.createWriter(); out .on('finish', function() { expect(out.getOutput()).to.equal('Hello John!'); done(); }) .on('error', function(e) { done(e); }); marko.render( nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'), { name: 'John' }, out); out.end(); }); it('should allow a template to be rendered to a writer wrapping a stream', function(done) { var output = ''; var stream = through(function write(data) { output += data; }); var out = marko.createWriter(stream); out .on('end', function() { expect(output).to.equal('Hello John!'); done(); }) .on('error', function(e) { done(e); }); marko.render( nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'), { name: 'John' }, out).end(); }); it('should allow a template to be rendered to a stream', function(done) { var output = ''; var outStream = through(function write(data) { output += data; }); outStream.on('end', function() { expect(output).to.equal('Hello John!'); done(); }); marko.stream( nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'), { name: 'John' }) .pipe(outStream) .on('error', function(e) { done(e); }); }); /// TEMPLATE LOADING: it('should allow a template to be loaded and rendered using a callback', function(done) { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); template.render({ name: 'John' }, function(err, output) { if (err) { return done(err); } expect(output).to.equal('Hello John!'); done(); }); }); it('should allow a template to be loaded and rendered to a writer wrapping a string builder', function(done) { var out = marko.createWriter(); out .on('finish', function() { expect(out.getOutput()).to.equal('Hello John!'); done(); }) .on('error', function(e) { done(e); }); var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); template.render({ name: 'John' }, out); out.end(); }); it('should allow a template to be loaded and rendered to a writer wrapping a stream', function(done) { var output = ''; var stream = through(function write(data) { output += data; }); var out = marko.createWriter(stream) .on('end', function() { expect(output).to.equal('Hello John!'); done(); }) .on('error', function(e) { done(e); }); var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); template.render({ name: 'John' }, out).end(); }); it('should allow a template to be loaded and rendered to a stream', function(done) { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); var output = ''; var outStream = through(function write(data) { output += data; }); outStream.on('end', function() { expect(output).to.equal('Hello John!'); done(); }); template.stream({ name: 'John' }) .pipe(outStream) .on('error', function(e) { done(e); }); }); it('should allow a template to be rendered to a string synchronously using renderSync', function() { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); var output = template.renderSync({ name: 'John' }); expect(output).to.equal('Hello John!'); }); it('should allow a template to be rendered synchronously using global attributes', function() { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello-global.marko')); var data = { name: 'John', $global: { greeting: 'Greetings' } }; var output = template.renderSync(data) expect(output).to.equal('Greetings John!'); }); it('should allow a template to be rendered asynchronously using global attributes', function(done) { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello-global.marko')); var data = { name: 'John', $global: { greeting: 'Greetings' } }; template.render(data, function(error, output) { expect(output).to.equal('Greetings John!'); done(); }); }); it('should throw an error if beginAsync is used with renderSync', function() { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello-async.marko')); var output; var e; try { output = template.renderSync({ nameDataProvider: function(arg, callback) { setTimeout(function() { callback(null, 'John'); }, 100); } }); } catch(_e) { e = _e; } expect(output).to.equal(undefined); expect(e).to.not.equal(undefined); }); it('should throw errors correctly with renderSync', function() { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello-error.marko')); var output; var e; try { output = template.renderSync(); } catch(_e) { e = _e; } expect(output).to.equal(undefined); expect(e).to.not.equal(undefined); }); it('should allow a template to be loaded from a compiled JS module', function(done) { // Load the JS file to ensure the hello.marko.js file is created marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')) var templateModule = require(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko.js')); var template = marko.load(templateModule); template.render({ name: 'John' }, function(err, output) { if (err) { return done(err); } expect(output).to.equal('Hello John!'); done(); }); }); it('should allow a template to be required', function(done) { var templatePath = nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'); var template = require(templatePath); template.render( { name: 'John' }, function(err, output) { if (err) { return done(err); } expect(output).to.equal('Hello John!'); done(); }); }); });
test/api-tests.js
'use strict'; var chai = require('chai'); chai.Assertion.includeStack = true; var expect = require('chai').expect; var nodePath = require('path'); var marko = require('../'); var through = require('through'); require('../node-require').install(); describe('marko/api' , function() { before(function() { require('../compiler').defaultOptions.checkUpToDate = false; }); beforeEach(function(done) { done(); }); it('should allow a template to be rendered using a callback', function(done) { marko.render( nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'), { name: 'John' }, function(err, output) { if (err) { return done(err); } expect(output).to.equal('Hello John!'); done(); }); }); it('should allow a template to be rendered to a writer wrapping a string builder', function(done) { var out = marko.createWriter(); out .on('finish', function() { expect(out.getOutput()).to.equal('Hello John!'); done(); }) .on('error', function(e) { done(e); }); marko.render( nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'), { name: 'John' }, out); out.end(); }); it('should allow a template to be rendered to a writer wrapping a stream', function(done) { var output = ''; var stream = through(function write(data) { output += data; }); var out = marko.createWriter(stream); out .on('finish', function() { expect(output).to.equal('Hello John!'); done(); }) .on('error', function(e) { done(e); }); marko.render( nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'), { name: 'John' }, out).end(); }); it('should allow a template to be rendered to a stream', function(done) { var output = ''; var outStream = through(function write(data) { output += data; }); outStream.on('end', function() { expect(output).to.equal('Hello John!'); done(); }); marko.stream( nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'), { name: 'John' }) .pipe(outStream) .on('error', function(e) { done(e); }); }); /// TEMPLATE LOADING: it('should allow a template to be loaded and rendered using a callback', function(done) { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); template.render({ name: 'John' }, function(err, output) { if (err) { return done(err); } expect(output).to.equal('Hello John!'); done(); }); }); it('should allow a template to be loaded and rendered to a writer wrapping a string builder', function(done) { var out = marko.createWriter(); out .on('finish', function() { expect(out.getOutput()).to.equal('Hello John!'); done(); }) .on('error', function(e) { done(e); }); var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); template.render({ name: 'John' }, out); out.end(); }); it('should allow a template to be loaded and rendered to a writer wrapping a stream', function(done) { var output = ''; var stream = through(function write(data) { output += data; }); var out = marko.createWriter(stream) .on('finish', function() { expect(output).to.equal('Hello John!'); done(); }) .on('error', function(e) { done(e); }); var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); template.render({ name: 'John' }, out).end(); }); it('should allow a template to be loaded and rendered to a stream', function(done) { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); var output = ''; var outStream = through(function write(data) { output += data; }); outStream.on('end', function() { expect(output).to.equal('Hello John!'); done(); }); template.stream({ name: 'John' }) .pipe(outStream) .on('error', function(e) { done(e); }); }); it('should allow a template to be rendered to a string synchronously using renderSync', function() { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')); var output = template.renderSync({ name: 'John' }); expect(output).to.equal('Hello John!'); }); it('should allow a template to be rendered synchronously using global attributes', function() { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello-global.marko')); var data = { name: 'John', $global: { greeting: 'Greetings' } }; var output = template.renderSync(data) expect(output).to.equal('Greetings John!'); }); it('should allow a template to be rendered asynchronously using global attributes', function(done) { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello-global.marko')); var data = { name: 'John', $global: { greeting: 'Greetings' } }; template.render(data, function(error, output) { expect(output).to.equal('Greetings John!'); done(); }); }); it('should throw an error if beginAsync is used with renderSync', function() { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello-async.marko')); var output; var e; try { output = template.renderSync({ nameDataProvider: function(arg, callback) { setTimeout(function() { callback(null, 'John'); }, 100); } }); } catch(_e) { e = _e; } expect(output).to.equal(undefined); expect(e).to.not.equal(undefined); }); it('should throw errors correctly with renderSync', function() { var template = marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello-error.marko')); var output; var e; try { output = template.renderSync(); } catch(_e) { e = _e; } expect(output).to.equal(undefined); expect(e).to.not.equal(undefined); }); it('should allow a template to be loaded from a compiled JS module', function(done) { // Load the JS file to ensure the hello.marko.js file is created marko.load(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko')) var templateModule = require(nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko.js')); var template = marko.load(templateModule); template.render({ name: 'John' }, function(err, output) { if (err) { return done(err); } expect(output).to.equal('Hello John!'); done(); }); }); it('should allow a template to be required', function(done) { var templatePath = nodePath.join(__dirname, 'fixtures/templates/api-tests/hello.marko'); var template = require(templatePath); template.render( { name: 'John' }, function(err, output) { if (err) { return done(err); } expect(output).to.equal('Hello John!'); done(); }); }); });
async-writer no longer patches "finish" event for the through module
test/api-tests.js
async-writer no longer patches "finish" event for the through module
<ide><path>est/api-tests.js <ide> <ide> var out = marko.createWriter(stream); <ide> out <del> .on('finish', function() { <add> .on('end', function() { <ide> expect(output).to.equal('Hello John!'); <ide> done(); <ide> }) <ide> }); <ide> <ide> var out = marko.createWriter(stream) <del> .on('finish', function() { <add> .on('end', function() { <ide> expect(output).to.equal('Hello John!'); <ide> done(); <ide> })
Java
agpl-3.0
8706e7b421551ac74f0f697ff68f0a46aaa221ab
0
dgray16/libreplan,dgray16/libreplan,LibrePlan/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,dgray16/libreplan,Marine-22/libre,dgray16/libreplan,dgray16/libreplan,Marine-22/libre,dgray16/libreplan,poum/libreplan,poum/libreplan,Marine-22/libre,dgray16/libreplan,PaulLuchyn/libreplan,Marine-22/libre,PaulLuchyn/libreplan,poum/libreplan,LibrePlan/libreplan,poum/libreplan,PaulLuchyn/libreplan,poum/libreplan,Marine-22/libre,PaulLuchyn/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,skylow95/libreplan,LibrePlan/libreplan,Marine-22/libre,skylow95/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,poum/libreplan,skylow95/libreplan,skylow95/libreplan
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2012 Igalia, S.L. * * 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/>. */ package org.libreplan.business.resources.entities; import org.apache.commons.lang.StringUtils; import org.hibernate.validator.AssertTrue; import org.hibernate.validator.NotEmpty; import org.libreplan.business.common.Registry; import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.users.daos.IUserDAO; import org.libreplan.business.users.entities.User; /** * This class models a worker. * * Note: this class has a natural ordering that is inconsistent with equals. * * @author Fernando Bellas Permuy <[email protected]> * @author Susana Montes Pedreira <[email protected]> * @author Manuel Rego Casasnovas <[email protected]> */ public class Worker extends Resource { public static Worker create() { return create(new Worker()); } public static Worker create(String code) { return create(new Worker(), code); } public static Worker create(String firstName, String surname, String nif) { return create(new Worker(firstName, surname, nif)); } public static Worker createUnvalidated(String code, String firstName, String surname, String nif) { Worker worker = create(new Worker(), code); worker.firstName = firstName; worker.surname = surname; worker.nif = nif; return worker; } public void updateUnvalidated(String firstName, String surname, String nif) { if (!StringUtils.isBlank(firstName)) { this.firstName = firstName; } if (!StringUtils.isBlank(surname)) { this.surname = surname; } if (!StringUtils.isBlank(nif)) { this.nif = nif; } } private final static ResourceEnum type = ResourceEnum.WORKER; private String firstName; private String surname; private String nif; private User user; /** * Constructor for hibernate. Do not use! */ public Worker() { } private Worker(String firstName, String surname, String nif) { this.firstName = firstName; this.surname = surname; this.nif = nif; } public String getDescription() { return getSurname() + "," + getFirstName(); } @Override public String getShortDescription() { return getDescription() + " (" + getNif() + ")"; } @NotEmpty(message="worker's first name not specified") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @NotEmpty(message="worker's surname not specified") public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getName() { return getSurname() + ", " + getFirstName(); } @NotEmpty(message="Worker ID cannot be empty") public String getNif() { return nif; } public void setNif(String nif) { this.nif = nif; } public boolean isVirtual() { return false; } public boolean isReal() { return !isVirtual(); } @AssertTrue(message = "ID already used. It has to be be unique") public boolean checkConstraintUniqueFiscalCode() { if (!areFirstNameSurnameNifSpecified()) { return true; } try { /* Check the constraint. */ Worker worker = Registry.getWorkerDAO() .findByNifAnotherTransaction(nif); if (isNewObject()) { return false; } else { return worker.getId().equals(getId()); } } catch (InstanceNotFoundException e) { return true; } } protected boolean areFirstNameSurnameNifSpecified() { return !StringUtils.isBlank(firstName) && !StringUtils.isBlank(surname) && !StringUtils.isBlank(nif); } @Override protected boolean isCriterionSatisfactionOfCorrectType( CriterionSatisfaction c) { return c.getResourceType().equals(ResourceEnum.WORKER); } @Override public ResourceEnum getType() { return type; } @Override public String getHumanId() { if (firstName == null) { return surname; } if (surname == null) { return firstName; } return firstName + " " + surname; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @AssertTrue(message = "User already bound to other worker") public boolean checkUserNotBoundToOtherWorker() { if (user == null || user.isNewObject()) { return true; } IUserDAO userDAO = Registry.getUserDAO(); User foundUser = userDAO.findOnAnotherTransaction(user.getId()); if (foundUser == null) { return true; } Worker worker = foundUser.getWorker(); if (worker == null) { return true; } if (getId() == null) { return false; } return getId().equals(worker.getId()); } @AssertTrue(message = "Limiting resources cannot be bound to any user") public boolean checkLimitingResourceNotBoundToUser() { if (isLimitingResource()) { return user == null; } return true; } @AssertTrue(message = "Virtual resources cannot be bound to any user") public boolean checkVirtualResourceNotBoundToUser() { if (isVirtual()) { return user == null; } return true; } }
libreplan-business/src/main/java/org/libreplan/business/resources/entities/Worker.java
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2012 Igalia, S.L. * * 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/>. */ package org.libreplan.business.resources.entities; import org.apache.commons.lang.StringUtils; import org.hibernate.validator.AssertTrue; import org.hibernate.validator.NotEmpty; import org.libreplan.business.common.Registry; import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.users.daos.IUserDAO; import org.libreplan.business.users.entities.User; /** * This class models a worker. * * Note: this class has a natural ordering that is inconsistent with equals. * * @author Fernando Bellas Permuy <[email protected]> * @author Susana Montes Pedreira <[email protected]> * @author Manuel Rego Casasnovas <[email protected]> */ public class Worker extends Resource { public static Worker create() { return create(new Worker()); } public static Worker create(String code) { return create(new Worker(), code); } public static Worker create(String firstName, String surname, String nif) { return create(new Worker(firstName, surname, nif)); } public static Worker createUnvalidated(String code, String firstName, String surname, String nif) { Worker worker = create(new Worker(), code); worker.firstName = firstName; worker.surname = surname; worker.nif = nif; return worker; } public void updateUnvalidated(String firstName, String surname, String nif) { if (!StringUtils.isBlank(firstName)) { this.firstName = firstName; } if (!StringUtils.isBlank(surname)) { this.surname = surname; } if (!StringUtils.isBlank(nif)) { this.nif = nif; } } private final static ResourceEnum type = ResourceEnum.WORKER; private String firstName; private String surname; private String nif; private User user; /** * Constructor for hibernate. Do not use! */ public Worker() { } private Worker(String firstName, String surname, String nif) { this.firstName = firstName; this.surname = surname; this.nif = nif; } public String getDescription() { return getSurname() + "," + getFirstName(); } @Override public String getShortDescription() { return getDescription() + " (" + getNif() + ")"; } @NotEmpty(message="worker's first name not specified") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @NotEmpty(message="worker's surname not specified") public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getName() { return getSurname() + ", " + getFirstName(); } @NotEmpty(message="Worker ID cannot be empty") public String getNif() { return nif; } public void setNif(String nif) { this.nif = nif; } public boolean isVirtual() { return false; } public boolean isReal() { return !isVirtual(); } @AssertTrue(message = "ID already used. It has to be be unique") public boolean checkConstraintUniqueFiscalCode() { if (!areFirstNameSurnameNifSpecified()) { return true; } try { /* Check the constraint. */ Worker worker = Registry.getWorkerDAO() .findByNifAnotherTransaction(nif); if (isNewObject()) { return false; } else { return worker.getId().equals(getId()); } } catch (InstanceNotFoundException e) { return true; } } protected boolean areFirstNameSurnameNifSpecified() { return !StringUtils.isBlank(firstName) && !StringUtils.isBlank(surname) && !StringUtils.isBlank(nif); } @Override protected boolean isCriterionSatisfactionOfCorrectType( CriterionSatisfaction c) { return c.getResourceType().equals(ResourceEnum.WORKER); } @Override public ResourceEnum getType() { return type; } @Override public String getHumanId() { if (firstName == null) { return surname; } if (surname == null) { return firstName; } return firstName + " " + surname; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @AssertTrue(message = "User already bound to other worker") public boolean checkUserNotBoundToOtherWorker() { if (user == null || user.isNewObject()) { return true; } IUserDAO userDAO = Registry.getUserDAO(); User foundUser = userDAO.findOnAnotherTransaction(user.getId()); if (foundUser == null) { return true; } Worker worker = foundUser.getWorker(); if (worker == null) { return true; } if (getId() == null) { return false; } return getId().equals(worker.getId()); } }
Add assert to check that a limiting or virtual resource is not bound to any user
libreplan-business/src/main/java/org/libreplan/business/resources/entities/Worker.java
Add assert to check that a limiting or virtual resource is not bound to any user
<ide><path>ibreplan-business/src/main/java/org/libreplan/business/resources/entities/Worker.java <ide> return getId().equals(worker.getId()); <ide> } <ide> <add> @AssertTrue(message = "Limiting resources cannot be bound to any user") <add> public boolean checkLimitingResourceNotBoundToUser() { <add> if (isLimitingResource()) { <add> return user == null; <add> } <add> return true; <add> } <add> <add> @AssertTrue(message = "Virtual resources cannot be bound to any user") <add> public boolean checkVirtualResourceNotBoundToUser() { <add> if (isVirtual()) { <add> return user == null; <add> } <add> return true; <add> } <add> <ide> }
Java
apache-2.0
2794702414c2dad9d46d9edde05879b8f78f2375
0
sdnwiselab/onos,sdnwiselab/onos,kuujo/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,gkatsikas/onos,opennetworkinglab/onos,LorenzReinhart/ONOSnew,sdnwiselab/onos,LorenzReinhart/ONOSnew,opennetworkinglab/onos,gkatsikas/onos,sdnwiselab/onos,osinstom/onos,oplinkoms/onos,gkatsikas/onos,opennetworkinglab/onos,opennetworkinglab/onos,kuujo/onos,LorenzReinhart/ONOSnew,kuujo/onos,oplinkoms/onos,kuujo/onos,osinstom/onos,gkatsikas/onos,kuujo/onos,opennetworkinglab/onos,osinstom/onos,oplinkoms/onos,oplinkoms/onos,sdnwiselab/onos,opennetworkinglab/onos,gkatsikas/onos,oplinkoms/onos,sdnwiselab/onos,osinstom/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,oplinkoms/onos,kuujo/onos,osinstom/onos,kuujo/onos
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.store.primitives.resources.impl; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import io.atomix.copycat.server.Commit; import io.atomix.copycat.server.StateMachineExecutor; import io.atomix.copycat.server.session.ServerSession; import io.atomix.copycat.server.session.SessionListener; import io.atomix.resource.ResourceStateMachine; import org.onlab.util.Match; import org.onosproject.store.service.MapEvent; import org.onosproject.store.service.Versioned; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.function.Function; import java.util.stream.Collectors; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.CeilingEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.CeilingKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Clear; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.ContainsKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.ContainsValue; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.EntrySet; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FirstEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FirstKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FloorEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FloorKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Get; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.GetOrDefault; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.HigherEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.HigherKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.IsEmpty; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.KeySet; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LastEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LastKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Listen; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LowerEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LowerKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.PollFirstEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.PollLastEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Size; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.SubMap; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Unlisten; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.UpdateAndGet; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Values; import static org.onosproject.store.primitives.resources.impl.MapEntryUpdateResult.*; /** * State machine corresponding to {@link AtomixConsistentTreeMap} backed by a * {@link TreeMap}. */ public class AtomixConsistentTreeMapState extends ResourceStateMachine implements SessionListener { private final Map<Long, Commit<? extends Listen>> listeners = Maps.newHashMap(); private TreeMap<String, TreeMapEntryValue> tree = Maps.newTreeMap(); private final Set<String> preparedKeys = Sets.newHashSet(); private Function<Commit<SubMap>, NavigableMap<String, TreeMapEntryValue>> subMapFunction = this::subMap; private Function<Commit<FirstKey>, String> firstKeyFunction = this::firstKey; private Function<Commit<LastKey>, String> lastKeyFunction = this::lastKey; private Function<Commit<HigherEntry>, Map.Entry<String, Versioned<byte[]>>> higherEntryFunction = this::higherEntry; private Function<Commit<FirstEntry>, Map.Entry<String, Versioned<byte[]>>> firstEntryFunction = this::firstEntry; private Function<Commit<LastEntry>, Map.Entry<String, Versioned<byte[]>>> lastEntryFunction = this::lastEntry; private Function<Commit<PollFirstEntry>, Map.Entry<String, Versioned<byte[]>>> pollFirstEntryFunction = this::pollFirstEntry; private Function<Commit<PollLastEntry>, Map.Entry<String, Versioned<byte[]>>> pollLastEntryFunction = this::pollLastEntry; private Function<Commit<LowerEntry>, Map.Entry<String, Versioned<byte[]>>> lowerEntryFunction = this::lowerEntry; private Function<Commit<LowerKey>, String> lowerKeyFunction = this::lowerKey; private Function<Commit<FloorEntry>, Map.Entry<String, Versioned<byte[]>>> floorEntryFunction = this::floorEntry; private Function<Commit<CeilingEntry>, Map.Entry<String, Versioned<byte[]>>> ceilingEntryFunction = this::ceilingEntry; private Function<Commit<FloorKey>, String> floorKeyFunction = this::floorKey; private Function<Commit<CeilingKey>, String> ceilingKeyFunction = this::ceilingKey; private Function<Commit<HigherKey>, String> higherKeyFunction = this::higherKey; public AtomixConsistentTreeMapState(Properties properties) { super(properties); } @Override public void configure(StateMachineExecutor executor) { // Listeners executor.register(Listen.class, this::listen); executor.register(Unlisten.class, this::unlisten); // Queries executor.register(ContainsKey.class, this::containsKey); executor.register(ContainsValue.class, this::containsValue); executor.register(EntrySet.class, this::entrySet); executor.register(Get.class, this::get); executor.register(GetOrDefault.class, this::getOrDefault); executor.register(IsEmpty.class, this::isEmpty); executor.register(KeySet.class, this::keySet); executor.register(Size.class, this::size); executor.register(Values.class, this::values); executor.register(SubMap.class, subMapFunction); executor.register(FirstKey.class, firstKeyFunction); executor.register(LastKey.class, lastKeyFunction); executor.register(FirstEntry.class, firstEntryFunction); executor.register(LastEntry.class, lastEntryFunction); executor.register(PollFirstEntry.class, pollFirstEntryFunction); executor.register(PollLastEntry.class, pollLastEntryFunction); executor.register(LowerEntry.class, lowerEntryFunction); executor.register(LowerKey.class, lowerKeyFunction); executor.register(FloorEntry.class, floorEntryFunction); executor.register(FloorKey.class, floorKeyFunction); executor.register(CeilingEntry.class, ceilingEntryFunction); executor.register(CeilingKey.class, ceilingKeyFunction); executor.register(HigherEntry.class, higherEntryFunction); executor.register(HigherKey.class, higherKeyFunction); // Commands executor.register(UpdateAndGet.class, this::updateAndGet); executor.register(Clear.class, this::clear); } @Override public void delete() { listeners.values().forEach(Commit::close); listeners.clear(); tree.values().forEach(TreeMapEntryValue::discard); tree.clear(); } protected boolean containsKey(Commit<? extends ContainsKey> commit) { try { return toVersioned(tree.get((commit.operation().key()))) != null; } finally { commit.close(); } } protected boolean containsValue(Commit<? extends ContainsValue> commit) { try { Match<byte[]> valueMatch = Match .ifValue(commit.operation().value()); return tree.values().stream().anyMatch( value -> valueMatch.matches(value.value())); } finally { commit.close(); } } protected Versioned<byte[]> get(Commit<? extends Get> commit) { try { return toVersioned(tree.get(commit.operation().key())); } finally { commit.close(); } } protected Versioned<byte[]> getOrDefault(Commit<? extends GetOrDefault> commit) { try { Versioned<byte[]> value = toVersioned(tree.get(commit.operation().key())); return value != null ? value : new Versioned<>(commit.operation().defaultValue(), 0); } finally { commit.close(); } } protected int size(Commit<? extends Size> commit) { try { return tree.size(); } finally { commit.close(); } } protected boolean isEmpty(Commit<? extends IsEmpty> commit) { try { return tree.isEmpty(); } finally { commit.close(); } } protected Set<String> keySet(Commit<? extends KeySet> commit) { try { return tree.keySet().stream().collect(Collectors.toSet()); } finally { commit.close(); } } protected Collection<Versioned<byte[]>> values( Commit<? extends Values> commit) { try { return tree.values().stream().map(this::toVersioned) .collect(Collectors.toList()); } finally { commit.close(); } } protected Set<Map.Entry<String, Versioned<byte[]>>> entrySet( Commit<? extends EntrySet> commit) { try { return tree .entrySet() .stream() .map(e -> Maps.immutableEntry(e.getKey(), toVersioned(e.getValue()))) .collect(Collectors.toSet()); } finally { commit.close(); } } protected MapEntryUpdateResult<String, byte[]> updateAndGet( Commit<? extends UpdateAndGet> commit) { Status updateStatus = validate(commit.operation()); String key = commit.operation().key(); TreeMapEntryValue oldCommitValue = tree.get(commit.operation().key()); Versioned<byte[]> oldTreeValue = toVersioned(oldCommitValue); if (updateStatus != Status.OK) { commit.close(); return new MapEntryUpdateResult<>(updateStatus, "", key, oldTreeValue, oldTreeValue); } byte[] newValue = commit.operation().value(); long newVersion = commit.index(); Versioned<byte[]> newTreeValue = newValue == null ? null : new Versioned<byte[]>(newValue, newVersion); MapEvent.Type updateType = newValue == null ? MapEvent.Type.REMOVE : oldCommitValue == null ? MapEvent.Type.INSERT : MapEvent.Type.UPDATE; if (updateType == MapEvent.Type.REMOVE || updateType == MapEvent.Type.UPDATE) { tree.remove(key); oldCommitValue.discard(); } if (updateType == MapEvent.Type.INSERT || updateType == MapEvent.Type.UPDATE) { tree.put(key, new NonTransactionalCommit(newVersion, commit)); } else { commit.close(); } publish(Lists.newArrayList(new MapEvent<>("", key, newTreeValue, oldTreeValue))); return new MapEntryUpdateResult<>(updateStatus, "", key, oldTreeValue, newTreeValue); } protected Status clear( Commit<? extends Clear> commit) { try { Iterator<Map.Entry<String, TreeMapEntryValue>> iterator = tree .entrySet() .iterator(); while (iterator.hasNext()) { Map.Entry<String, TreeMapEntryValue> entry = iterator.next(); String key = entry.getKey(); TreeMapEntryValue value = entry.getValue(); Versioned<byte[]> removedValue = new Versioned<byte[]>(value.value(), value.version()); publish(Lists.newArrayList(new MapEvent<>("", key, null, removedValue))); value.discard(); iterator.remove(); } return Status.OK; } finally { commit.close(); } } protected void listen( Commit<? extends Listen> commit) { Long sessionId = commit.session().id(); listeners.put(sessionId, commit); commit.session() .onStateChange( state -> { if (state == ServerSession.State.CLOSED || state == ServerSession.State.EXPIRED) { Commit<? extends Listen> listener = listeners.remove(sessionId); if (listener != null) { listener.close(); } } }); } protected void unlisten( Commit<? extends Unlisten> commit) { try { Commit<? extends AtomixConsistentTreeMapCommands.Listen> listener = listeners.remove(commit.session().id()); if (listener != null) { listener.close(); } } finally { commit.close(); } } private Status validate(UpdateAndGet update) { TreeMapEntryValue existingValue = tree.get(update.key()); if (existingValue == null && update.value() == null) { return Status.NOOP; } if (preparedKeys.contains(update.key())) { return Status.WRITE_LOCK; } byte[] existingRawValue = existingValue == null ? null : existingValue.value(); Long existingVersion = existingValue == null ? null : existingValue.version(); return update.valueMatch().matches(existingRawValue) && update.versionMatch().matches(existingVersion) ? Status.OK : Status.PRECONDITION_FAILED; } protected NavigableMap<String, TreeMapEntryValue> subMap( Commit<? extends SubMap> commit) { //Do not support this until lazy communication is possible. At present // it transmits up to the entire map. try { SubMap<String, TreeMapEntryValue> subMap = commit.operation(); return tree.subMap(subMap.fromKey(), subMap.isInclusiveFrom(), subMap.toKey(), subMap.isInclusiveTo()); } finally { commit.close(); } } protected String firstKey(Commit<? extends FirstKey> commit) { try { if (tree.isEmpty()) { return null; } return tree.firstKey(); } finally { commit.close(); } } protected String lastKey(Commit<? extends LastKey> commit) { try { return tree.isEmpty() ? null : tree.lastKey(); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> higherEntry( Commit<? extends HigherEntry> commit) { try { if (tree.isEmpty()) { return null; } return toVersionedEntry( tree.higherEntry(commit.operation().key())); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> firstEntry( Commit<? extends FirstEntry> commit) { try { if (tree.isEmpty()) { return null; } return toVersionedEntry(tree.firstEntry()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> lastEntry( Commit<? extends LastEntry> commit) { try { if (tree.isEmpty()) { return null; } return toVersionedEntry(tree.lastEntry()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> pollFirstEntry( Commit<? extends PollFirstEntry> commit) { try { return toVersionedEntry(tree.pollFirstEntry()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> pollLastEntry( Commit<? extends PollLastEntry> commit) { try { return toVersionedEntry(tree.pollLastEntry()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> lowerEntry( Commit<? extends LowerEntry> commit) { try { return toVersionedEntry(tree.lowerEntry(commit.operation().key())); } finally { commit.close(); } } protected String lowerKey(Commit<? extends LowerKey> commit) { try { return tree.lowerKey(commit.operation().key()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> floorEntry( Commit<? extends FloorEntry> commit) { try { return toVersionedEntry(tree.floorEntry(commit.operation().key())); } finally { commit.close(); } } protected String floorKey(Commit<? extends FloorKey> commit) { try { return tree.floorKey(commit.operation().key()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> ceilingEntry( Commit<CeilingEntry> commit) { try { return toVersionedEntry( tree.ceilingEntry(commit.operation().key())); } finally { commit.close(); } } protected String ceilingKey(Commit<CeilingKey> commit) { try { return tree.ceilingKey(commit.operation().key()); } finally { commit.close(); } } protected String higherKey(Commit<HigherKey> commit) { try { return tree.higherKey(commit.operation().key()); } finally { commit.close(); } } private Versioned<byte[]> toVersioned(TreeMapEntryValue value) { return value == null ? null : new Versioned<byte[]>(value.value(), value.version()); } private Map.Entry<String, Versioned<byte[]>> toVersionedEntry( Map.Entry<String, TreeMapEntryValue> entry) { //FIXME is this the best type of entry to return? return entry == null ? null : new SimpleImmutableEntry<>( entry.getKey(), toVersioned(entry.getValue())); } private void publish(List<MapEvent<String, byte[]>> events) { listeners.values().forEach(commit -> commit.session() .publish(AtomixConsistentTreeMap.CHANGE_SUBJECT, events)); } @Override public void register(ServerSession session) { } @Override public void unregister(ServerSession session) { closeListener(session.id()); } @Override public void expire(ServerSession session) { closeListener(session.id()); } @Override public void close(ServerSession session) { closeListener(session.id()); } private void closeListener(Long sessionId) { Commit<? extends Listen> commit = listeners.remove(sessionId); if (commit != null) { commit.close(); } } private interface TreeMapEntryValue { byte[] value(); long version(); void discard(); } private class NonTransactionalCommit implements TreeMapEntryValue { private final long version; private final Commit<? extends UpdateAndGet> commit; public NonTransactionalCommit(long version, Commit<? extends UpdateAndGet> commit) { this.version = version; this.commit = commit; } @Override public byte[] value() { return commit.operation().value(); } @Override public long version() { return version; } @Override public void discard() { commit.close(); } } }
core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapState.java
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.store.primitives.resources.impl; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import io.atomix.copycat.server.Commit; import io.atomix.copycat.server.Snapshottable; import io.atomix.copycat.server.StateMachineExecutor; import io.atomix.copycat.server.session.ServerSession; import io.atomix.copycat.server.session.SessionListener; import io.atomix.copycat.server.storage.snapshot.SnapshotReader; import io.atomix.copycat.server.storage.snapshot.SnapshotWriter; import io.atomix.resource.ResourceStateMachine; import org.onlab.util.Match; import org.onosproject.store.service.MapEvent; import org.onosproject.store.service.Versioned; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.stream.Collectors; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.CeilingEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.CeilingKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Clear; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.ContainsKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.ContainsValue; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.EntrySet; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FirstEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FirstKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FloorEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FloorKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Get; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.GetOrDefault; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.HigherEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.HigherKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.IsEmpty; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.KeySet; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LastEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LastKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Listen; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LowerEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LowerKey; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.PollFirstEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.PollLastEntry; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Size; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.SubMap; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Unlisten; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.UpdateAndGet; import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Values; import static org.onosproject.store.primitives.resources.impl.MapEntryUpdateResult.*; /** * State machine corresponding to {@link AtomixConsistentTreeMap} backed by a * {@link TreeMap}. */ public class AtomixConsistentTreeMapState extends ResourceStateMachine implements SessionListener, Snapshottable { private final Map<Long, Commit<? extends Listen>> listeners = Maps.newHashMap(); private TreeMap<String, TreeMapEntryValue> tree = Maps.newTreeMap(); private final Set<String> preparedKeys = Sets.newHashSet(); private AtomicLong versionCounter = new AtomicLong(0); private Function<Commit<SubMap>, NavigableMap<String, TreeMapEntryValue>> subMapFunction = this::subMap; private Function<Commit<FirstKey>, String> firstKeyFunction = this::firstKey; private Function<Commit<LastKey>, String> lastKeyFunction = this::lastKey; private Function<Commit<HigherEntry>, Map.Entry<String, Versioned<byte[]>>> higherEntryFunction = this::higherEntry; private Function<Commit<FirstEntry>, Map.Entry<String, Versioned<byte[]>>> firstEntryFunction = this::firstEntry; private Function<Commit<LastEntry>, Map.Entry<String, Versioned<byte[]>>> lastEntryFunction = this::lastEntry; private Function<Commit<PollFirstEntry>, Map.Entry<String, Versioned<byte[]>>> pollFirstEntryFunction = this::pollFirstEntry; private Function<Commit<PollLastEntry>, Map.Entry<String, Versioned<byte[]>>> pollLastEntryFunction = this::pollLastEntry; private Function<Commit<LowerEntry>, Map.Entry<String, Versioned<byte[]>>> lowerEntryFunction = this::lowerEntry; private Function<Commit<LowerKey>, String> lowerKeyFunction = this::lowerKey; private Function<Commit<FloorEntry>, Map.Entry<String, Versioned<byte[]>>> floorEntryFunction = this::floorEntry; private Function<Commit<CeilingEntry>, Map.Entry<String, Versioned<byte[]>>> ceilingEntryFunction = this::ceilingEntry; private Function<Commit<FloorKey>, String> floorKeyFunction = this::floorKey; private Function<Commit<CeilingKey>, String> ceilingKeyFunction = this::ceilingKey; private Function<Commit<HigherKey>, String> higherKeyFunction = this::higherKey; public AtomixConsistentTreeMapState(Properties properties) { super(properties); } @Override public void snapshot(SnapshotWriter writer) { writer.writeLong(versionCounter.get()); } @Override public void install(SnapshotReader reader) { versionCounter = new AtomicLong(reader.readLong()); } @Override public void configure(StateMachineExecutor executor) { // Listeners executor.register(Listen.class, this::listen); executor.register(Unlisten.class, this::unlisten); // Queries executor.register(ContainsKey.class, this::containsKey); executor.register(ContainsValue.class, this::containsValue); executor.register(EntrySet.class, this::entrySet); executor.register(Get.class, this::get); executor.register(GetOrDefault.class, this::getOrDefault); executor.register(IsEmpty.class, this::isEmpty); executor.register(KeySet.class, this::keySet); executor.register(Size.class, this::size); executor.register(Values.class, this::values); executor.register(SubMap.class, subMapFunction); executor.register(FirstKey.class, firstKeyFunction); executor.register(LastKey.class, lastKeyFunction); executor.register(FirstEntry.class, firstEntryFunction); executor.register(LastEntry.class, lastEntryFunction); executor.register(PollFirstEntry.class, pollFirstEntryFunction); executor.register(PollLastEntry.class, pollLastEntryFunction); executor.register(LowerEntry.class, lowerEntryFunction); executor.register(LowerKey.class, lowerKeyFunction); executor.register(FloorEntry.class, floorEntryFunction); executor.register(FloorKey.class, floorKeyFunction); executor.register(CeilingEntry.class, ceilingEntryFunction); executor.register(CeilingKey.class, ceilingKeyFunction); executor.register(HigherEntry.class, higherEntryFunction); executor.register(HigherKey.class, higherKeyFunction); // Commands executor.register(UpdateAndGet.class, this::updateAndGet); executor.register(Clear.class, this::clear); } @Override public void delete() { listeners.values().forEach(Commit::close); listeners.clear(); tree.values().forEach(TreeMapEntryValue::discard); tree.clear(); } protected boolean containsKey(Commit<? extends ContainsKey> commit) { try { return toVersioned(tree.get((commit.operation().key()))) != null; } finally { commit.close(); } } protected boolean containsValue(Commit<? extends ContainsValue> commit) { try { Match<byte[]> valueMatch = Match .ifValue(commit.operation().value()); return tree.values().stream().anyMatch( value -> valueMatch.matches(value.value())); } finally { commit.close(); } } protected Versioned<byte[]> get(Commit<? extends Get> commit) { try { return toVersioned(tree.get(commit.operation().key())); } finally { commit.close(); } } protected Versioned<byte[]> getOrDefault(Commit<? extends GetOrDefault> commit) { try { Versioned<byte[]> value = toVersioned(tree.get(commit.operation().key())); return value != null ? value : new Versioned<>(commit.operation().defaultValue(), 0); } finally { commit.close(); } } protected int size(Commit<? extends Size> commit) { try { return tree.size(); } finally { commit.close(); } } protected boolean isEmpty(Commit<? extends IsEmpty> commit) { try { return tree.isEmpty(); } finally { commit.close(); } } protected Set<String> keySet(Commit<? extends KeySet> commit) { try { return tree.keySet().stream().collect(Collectors.toSet()); } finally { commit.close(); } } protected Collection<Versioned<byte[]>> values( Commit<? extends Values> commit) { try { return tree.values().stream().map(this::toVersioned) .collect(Collectors.toList()); } finally { commit.close(); } } protected Set<Map.Entry<String, Versioned<byte[]>>> entrySet( Commit<? extends EntrySet> commit) { try { return tree .entrySet() .stream() .map(e -> Maps.immutableEntry(e.getKey(), toVersioned(e.getValue()))) .collect(Collectors.toSet()); } finally { commit.close(); } } protected MapEntryUpdateResult<String, byte[]> updateAndGet( Commit<? extends UpdateAndGet> commit) { Status updateStatus = validate(commit.operation()); String key = commit.operation().key(); TreeMapEntryValue oldCommitValue = tree.get(commit.operation().key()); Versioned<byte[]> oldTreeValue = toVersioned(oldCommitValue); if (updateStatus != Status.OK) { commit.close(); return new MapEntryUpdateResult<>(updateStatus, "", key, oldTreeValue, oldTreeValue); } byte[] newValue = commit.operation().value(); long newVersion = versionCounter.incrementAndGet(); Versioned<byte[]> newTreeValue = newValue == null ? null : new Versioned<byte[]>(newValue, newVersion); MapEvent.Type updateType = newValue == null ? MapEvent.Type.REMOVE : oldCommitValue == null ? MapEvent.Type.INSERT : MapEvent.Type.UPDATE; if (updateType == MapEvent.Type.REMOVE || updateType == MapEvent.Type.UPDATE) { tree.remove(key); oldCommitValue.discard(); } if (updateType == MapEvent.Type.INSERT || updateType == MapEvent.Type.UPDATE) { tree.put(key, new NonTransactionalCommit(newVersion, commit)); } else { commit.close(); } publish(Lists.newArrayList(new MapEvent<>("", key, newTreeValue, oldTreeValue))); return new MapEntryUpdateResult<>(updateStatus, "", key, oldTreeValue, newTreeValue); } protected Status clear( Commit<? extends Clear> commit) { try { Iterator<Map.Entry<String, TreeMapEntryValue>> iterator = tree .entrySet() .iterator(); while (iterator.hasNext()) { Map.Entry<String, TreeMapEntryValue> entry = iterator.next(); String key = entry.getKey(); TreeMapEntryValue value = entry.getValue(); Versioned<byte[]> removedValue = new Versioned<byte[]>(value.value(), value.version()); publish(Lists.newArrayList(new MapEvent<>("", key, null, removedValue))); value.discard(); iterator.remove(); } return Status.OK; } finally { commit.close(); } } protected void listen( Commit<? extends Listen> commit) { Long sessionId = commit.session().id(); listeners.put(sessionId, commit); commit.session() .onStateChange( state -> { if (state == ServerSession.State.CLOSED || state == ServerSession.State.EXPIRED) { Commit<? extends Listen> listener = listeners.remove(sessionId); if (listener != null) { listener.close(); } } }); } protected void unlisten( Commit<? extends Unlisten> commit) { try { Commit<? extends AtomixConsistentTreeMapCommands.Listen> listener = listeners.remove(commit.session().id()); if (listener != null) { listener.close(); } } finally { commit.close(); } } private Status validate(UpdateAndGet update) { TreeMapEntryValue existingValue = tree.get(update.key()); if (existingValue == null && update.value() == null) { return Status.NOOP; } if (preparedKeys.contains(update.key())) { return Status.WRITE_LOCK; } byte[] existingRawValue = existingValue == null ? null : existingValue.value(); Long existingVersion = existingValue == null ? null : existingValue.version(); return update.valueMatch().matches(existingRawValue) && update.versionMatch().matches(existingVersion) ? Status.OK : Status.PRECONDITION_FAILED; } protected NavigableMap<String, TreeMapEntryValue> subMap( Commit<? extends SubMap> commit) { //Do not support this until lazy communication is possible. At present // it transmits up to the entire map. try { SubMap<String, TreeMapEntryValue> subMap = commit.operation(); return tree.subMap(subMap.fromKey(), subMap.isInclusiveFrom(), subMap.toKey(), subMap.isInclusiveTo()); } finally { commit.close(); } } protected String firstKey(Commit<? extends FirstKey> commit) { try { if (tree.isEmpty()) { return null; } return tree.firstKey(); } finally { commit.close(); } } protected String lastKey(Commit<? extends LastKey> commit) { try { return tree.isEmpty() ? null : tree.lastKey(); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> higherEntry( Commit<? extends HigherEntry> commit) { try { if (tree.isEmpty()) { return null; } return toVersionedEntry( tree.higherEntry(commit.operation().key())); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> firstEntry( Commit<? extends FirstEntry> commit) { try { if (tree.isEmpty()) { return null; } return toVersionedEntry(tree.firstEntry()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> lastEntry( Commit<? extends LastEntry> commit) { try { if (tree.isEmpty()) { return null; } return toVersionedEntry(tree.lastEntry()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> pollFirstEntry( Commit<? extends PollFirstEntry> commit) { try { return toVersionedEntry(tree.pollFirstEntry()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> pollLastEntry( Commit<? extends PollLastEntry> commit) { try { return toVersionedEntry(tree.pollLastEntry()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> lowerEntry( Commit<? extends LowerEntry> commit) { try { return toVersionedEntry(tree.lowerEntry(commit.operation().key())); } finally { commit.close(); } } protected String lowerKey(Commit<? extends LowerKey> commit) { try { return tree.lowerKey(commit.operation().key()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> floorEntry( Commit<? extends FloorEntry> commit) { try { return toVersionedEntry(tree.floorEntry(commit.operation().key())); } finally { commit.close(); } } protected String floorKey(Commit<? extends FloorKey> commit) { try { return tree.floorKey(commit.operation().key()); } finally { commit.close(); } } protected Map.Entry<String, Versioned<byte[]>> ceilingEntry( Commit<CeilingEntry> commit) { try { return toVersionedEntry( tree.ceilingEntry(commit.operation().key())); } finally { commit.close(); } } protected String ceilingKey(Commit<CeilingKey> commit) { try { return tree.ceilingKey(commit.operation().key()); } finally { commit.close(); } } protected String higherKey(Commit<HigherKey> commit) { try { return tree.higherKey(commit.operation().key()); } finally { commit.close(); } } private Versioned<byte[]> toVersioned(TreeMapEntryValue value) { return value == null ? null : new Versioned<byte[]>(value.value(), value.version()); } private Map.Entry<String, Versioned<byte[]>> toVersionedEntry( Map.Entry<String, TreeMapEntryValue> entry) { //FIXME is this the best type of entry to return? return entry == null ? null : new SimpleImmutableEntry<>( entry.getKey(), toVersioned(entry.getValue())); } private void publish(List<MapEvent<String, byte[]>> events) { listeners.values().forEach(commit -> commit.session() .publish(AtomixConsistentTreeMap.CHANGE_SUBJECT, events)); } @Override public void register(ServerSession session) { } @Override public void unregister(ServerSession session) { closeListener(session.id()); } @Override public void expire(ServerSession session) { closeListener(session.id()); } @Override public void close(ServerSession session) { closeListener(session.id()); } private void closeListener(Long sessionId) { Commit<? extends Listen> commit = listeners.remove(sessionId); if (commit != null) { commit.close(); } } private interface TreeMapEntryValue { byte[] value(); long version(); void discard(); } private class NonTransactionalCommit implements TreeMapEntryValue { private final long version; private final Commit<? extends UpdateAndGet> commit; public NonTransactionalCommit(long version, Commit<? extends UpdateAndGet> commit) { this.version = version; this.commit = commit; } @Override public byte[] value() { return commit.operation().value(); } @Override public long version() { return version; } @Override public void discard() { commit.close(); } } }
[ONOS-6297] Use Raft log indexes as versions in ConsistentTreeMap to ensure consistency across leaders. Change-Id: I816c34b522b7d2a78bad310708436ece01a94aaa
core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapState.java
[ONOS-6297] Use Raft log indexes as versions in ConsistentTreeMap to ensure consistency across leaders.
<ide><path>ore/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapState.java <ide> import com.google.common.collect.Maps; <ide> import com.google.common.collect.Sets; <ide> import io.atomix.copycat.server.Commit; <del>import io.atomix.copycat.server.Snapshottable; <ide> import io.atomix.copycat.server.StateMachineExecutor; <ide> import io.atomix.copycat.server.session.ServerSession; <ide> import io.atomix.copycat.server.session.SessionListener; <del>import io.atomix.copycat.server.storage.snapshot.SnapshotReader; <del>import io.atomix.copycat.server.storage.snapshot.SnapshotWriter; <ide> import io.atomix.resource.ResourceStateMachine; <ide> import org.onlab.util.Match; <ide> import org.onosproject.store.service.MapEvent; <ide> import java.util.Properties; <ide> import java.util.Set; <ide> import java.util.TreeMap; <del>import java.util.concurrent.atomic.AtomicLong; <ide> import java.util.function.Function; <ide> import java.util.stream.Collectors; <ide> <ide> * State machine corresponding to {@link AtomixConsistentTreeMap} backed by a <ide> * {@link TreeMap}. <ide> */ <del>public class AtomixConsistentTreeMapState extends ResourceStateMachine implements SessionListener, Snapshottable { <add>public class AtomixConsistentTreeMapState extends ResourceStateMachine implements SessionListener { <ide> <ide> private final Map<Long, Commit<? extends Listen>> listeners = <ide> Maps.newHashMap(); <ide> private TreeMap<String, TreeMapEntryValue> tree = Maps.newTreeMap(); <ide> private final Set<String> preparedKeys = Sets.newHashSet(); <del> private AtomicLong versionCounter = new AtomicLong(0); <ide> <ide> private Function<Commit<SubMap>, NavigableMap<String, TreeMapEntryValue>> subMapFunction = this::subMap; <ide> private Function<Commit<FirstKey>, String> firstKeyFunction = this::firstKey; <ide> <ide> public AtomixConsistentTreeMapState(Properties properties) { <ide> super(properties); <del> } <del> <del> @Override <del> public void snapshot(SnapshotWriter writer) { <del> writer.writeLong(versionCounter.get()); <del> } <del> <del> @Override <del> public void install(SnapshotReader reader) { <del> versionCounter = new AtomicLong(reader.readLong()); <ide> } <ide> <ide> @Override <ide> } <ide> <ide> byte[] newValue = commit.operation().value(); <del> long newVersion = versionCounter.incrementAndGet(); <add> long newVersion = commit.index(); <ide> Versioned<byte[]> newTreeValue = newValue == null ? null <ide> : new Versioned<byte[]>(newValue, newVersion); <ide>
JavaScript
mit
e5e54d02b4ce17eccfa1861b575d0e79e362e92f
0
alexandernst/angular-multi-select,zhangtiny123/angular-multi-select,jtbdevelopment/angular-multi-select,jtbdevelopment/angular-multi-select,alexandernst/angular-multi-select,zhangtiny123/angular-multi-select
describe('Testing directive in single mode', function() { var scope, element, html, timeout; beforeEach(function (){ //load the module module('angular-multi-select'); //set our view html. html = '<div angular-multi-select ' + 'translation="localLang"' + 'hidden-property="hidden" ' + 'input-model="items" ' + 'output-model="x" ' + 'group-property="sub" ' + 'tick-property="check" ' + 'item-label="{{ icon }}{{ name }}" ' + 'helper-elements="all none reset filter"' + 'selection-mode="single" ' + 'min-search-length="3" ' + 'search-property="name" ' + '></div>'; inject(function($compile, $rootScope, $timeout) { //create a scope (you could just use $rootScope, I suppose) scope = $rootScope; timeout = $timeout; //get the jqLite or jQuery element element = angular.element(html); //compile the element into a function to process the view. $compile(element)($rootScope); element.scope().items = single_test_data; element.scope().localLang = { selected: " seleccionado", selectAll: "Todo", selectNone: "Nada", reset: "Resetear", search: "Escribe aqui para buscar..." }; element.scope().$digest(); $(document.body).append(element); }); }); afterEach(function() { element.remove(); elementn = null; }); it('Should be able to create the directive.', function() { expect(element).not.toBeEmpty(); }); it('Should create the items layer & container', function() { expect(element).toContainElement('div.ams_layer'); expect(element).toContainElement('div.ams_items_container'); }); it('Should create the item label according to the specified in "item-label"', function() { var item = $('.ams_item:not(.ams_group) > .ams_tick').prev(); expect(item).toContainElement("img"); expect(item).toContainText("Chrome"); }); it('Should contain 3 main categories', function() { expect($('div.ams_layer > div')).toHaveLength(2); expect($('div.ams_items_container > ul > li')).toHaveLength(3); expect($('div.ams_items_container > ul > li > div > div')).toContainText("Modern browsers"); }); it("Should handle 'hidden' items correctly", function() { expect($('.ams_item')).toHaveLength(13); }); it("Only 1 element (and all it's parents) should be checked", function() { expect($('.ams_selected')).toHaveLength(3); }); it("Should deselect all when clicked parent group", function() { $(".ams_item > div:contains('Closed Source')").click(); expect($('.ams_selected')).toHaveLength(0); }); it("When a group is clicked, should not mark itself as checked if it contains more than 1 element (even hidden elements block selection!)", function() { $(".ams_item > div:contains('Closed Source')").click(); expect($('.ams_selected')).toHaveLength(0); $(".ams_item > div:contains('Closed Source')").click(); expect($('.ams_selected')).toHaveLength(0); $(".ams_item > div:contains('Open Source')").click(); expect($('.ams_selected')).toHaveLength(0); }); it("Should filter correctly when searching", function() { $('input.inputFilter').val("chro"); $('input.inputFilter').trigger("input"); expect($('.ams_item')).toHaveLength(5); }); it("Should be visible when the button is clicked", function() { $('button.ams_btn').click(); expect('div.ams_layer').toBeVisible(); }); it("Should focus the input when opened", function() { $('button.ams_btn').click(); timeout.flush(); expect($('input.inputFilter')).toBeFocused(); }); it("Should focus elements when using arrows", function() { var event = document.createEvent("Events"); event.initEvent("keydown", true, true); event.which = 40; $('button.ams_btn').click(); scope.$broadcast('angular-multi-select-keydown', { event: event } ); scope.$broadcast('angular-multi-select-keydown', { event: event } ); expect($('.ams_focused')).toHaveLength(1); }); it("Should react to 'select all' by unselecting everything (because we're in single mode)", function() { $('.ams_selectall').click(); expect($('.ams_selected')).toHaveLength(0); }); it("Should react to 'select none'", function() { $('.ams_selectnone').click(); expect($('.ams_selected')).toHaveLength(0); }); it("Should react to 'reset'", function() { $(".ams_item > div:contains('Internet Explorer')").click(); expect($('.ams_selected')).toHaveLength(2); $('.ams_reset').click(); expect($('.ams_selected')).toHaveLength(3); }); it("Should react to 'clear'", function() { $('input.inputFilter').val("chro"); $('input.inputFilter').trigger("input"); expect($('.ams_item')).toHaveLength(5); $('.ams_clear').click(); expect($('.ams_item')).toHaveLength(13); }); it("Should be able to use i18n strings", function() { expect($('.ams_selectall')).toContainHtml("Todo"); expect($('.ams_selectnone')).toContainHtml("Nada"); expect($('.ams_reset')).toContainHtml("Resetear"); expect($('.ams_filter')).toHaveAttr("placeholder", "Escribe aqui para buscar..."); }); }); describe('Testing directive in multi mode', function() { var scope, element, html, timeout; beforeEach(function (){ //load the module module('angular-multi-select'); //set our view html. html = '<div angular-multi-select ' + 'hidden-property="hidden" ' + 'input-model="items" ' + 'output-model="x" ' + 'group-property="sub" ' + 'tick-property="check" ' + 'item-label="{{ name }}" ' + 'helper-elements="all none reset filter"' + 'selection-mode="multi" ' + 'min-search-length="3" ' + 'search-property="name" ' + '></div>'; inject(function($compile, $rootScope, $timeout) { //create a scope (you could just use $rootScope, I suppose) scope = $rootScope; timeout = $timeout; //get the jqLite or jQuery element element = angular.element(html); //compile the element into a function to process the view. $compile(element)($rootScope); element.scope().items = multi_test_data; element.scope().$digest(); $(document.body).append(element); }); }); afterEach(function() { element.remove(); elementn = null; }); it('Should be able to create the directive.', function() { expect(element).not.toBeEmpty(); }); it("4 elements (and all their parents) should be checked", function() { expect($('.ams_selected')).toHaveLength(8); }); it("Should deselect all when clicked parent group", function() { $(".ams_item > div:contains('Open Source')").click(); expect($('.ams_selected', ".ams_item > div:contains('Open Source')" )).toHaveLength(0); }); it("Should select all when a group with no checked children is clicked", function() { $(".ams_item > div:contains('Modern browsers')").click().click(); expect($('.ams_selected', "li:contains('Modern browsers')" )).toHaveLength(7); }); it("Should deselect all when a group is clicked, if all elements are selected", function() { $(".ams_item > div:contains('Modern browsers')").click(); expect($('.ams_selected', "li:contains('Modern browsers')" )).toHaveLength(0); }); it("Should react to 'select all' by selecting everything", function() { $('.ams_selectall').click(); expect($('.ams_selected')).toHaveLength(13); }); it("Should react to 'select none' by unselecting everything", function() { $('.ams_selectnone').click(); expect($('.selected')).toHaveLength(0); }); });
spec/angular-multi-select.spec.js
describe('Testing directive in single mode', function() { var scope, element, html, timeout; beforeEach(function (){ //load the module module('angular-multi-select'); //set our view html. html = '<div angular-multi-select ' + 'hidden-property="hidden" ' + 'input-model="items" ' + 'output-model="x" ' + 'group-property="sub" ' + 'tick-property="check" ' + 'item-label="{{ icon }}{{ name }}" ' + 'helper-elements="all none reset filter"' + 'selection-mode="single" ' + 'min-search-length="3" ' + 'search-property="name" ' + '></div>'; inject(function($compile, $rootScope, $timeout) { //create a scope (you could just use $rootScope, I suppose) scope = $rootScope; timeout = $timeout; //get the jqLite or jQuery element element = angular.element(html); //compile the element into a function to process the view. $compile(element)($rootScope); element.scope().items = single_test_data; element.scope().$digest(); $(document.body).append(element); }); }); afterEach(function() { element.remove(); elementn = null; }); it('Should be able to create the directive.', function() { expect(element).not.toBeEmpty(); }); it('Should create the items layer & container', function() { expect(element).toContainElement('div.ams_layer'); expect(element).toContainElement('div.ams_items_container'); }); it('Should create the item label according to the specified in "item-label"', function() { var item = $('.ams_item:not(.ams_group) > .ams_tick').prev(); expect(item).toContainElement("img"); expect(item).toContainText("Chrome"); }); it('Should contain 3 main categories', function() { expect($('div.ams_layer > div')).toHaveLength(2); expect($('div.ams_items_container > ul > li')).toHaveLength(3); expect($('div.ams_items_container > ul > li > div > div')).toContainText("Modern browsers"); }); it("Should handle 'hidden' items correctly", function() { expect($('.ams_item')).toHaveLength(13); }); it("Only 1 element (and all it's parents) should be checked", function() { expect($('.ams_selected')).toHaveLength(3); }); it("Should deselect all when clicked parent group", function() { $(".ams_item > div:contains('Closed Source')").click(); expect($('.ams_selected')).toHaveLength(0); }); it("When a group is clicked, should not mark itself as checked if it contains more than 1 element (even hidden elements block selection!)", function() { $(".ams_item > div:contains('Closed Source')").click(); expect($('.ams_selected')).toHaveLength(0); $(".ams_item > div:contains('Closed Source')").click(); expect($('.ams_selected')).toHaveLength(0); $(".ams_item > div:contains('Open Source')").click(); expect($('.ams_selected')).toHaveLength(0); }); it("Should filter correctly when searching", function() { $('input.inputFilter').val("chro"); $('input.inputFilter').trigger("input"); expect($('.ams_item')).toHaveLength(5); }); it("Should be visible when the button is clicked", function() { $('button.ams_btn').click(); expect('div.ams_layer').toBeVisible(); }); it("Should focus the input when opened", function() { $('button.ams_btn').click(); timeout.flush(); expect($('input.inputFilter')).toBeFocused(); }); it("Should focus elements when using arrows", function() { var event = document.createEvent("Events"); event.initEvent("keydown", true, true); event.which = 40; $('button.ams_btn').click(); scope.$broadcast('angular-multi-select-keydown', { event: event } ); scope.$broadcast('angular-multi-select-keydown', { event: event } ); expect($('.ams_focused')).toHaveLength(1); }); it("Should react to 'select all' by unselecting everything (because we're in single mode)", function() { $('.ams_selectall').click(); expect($('.ams_selected')).toHaveLength(0); }); it("Should react to 'select none'", function() { $('.ams_selectnone').click(); expect($('.ams_selected')).toHaveLength(0); }); it("Should react to 'reset'", function() { $(".ams_item > div:contains('Internet Explorer')").click(); expect($('.ams_selected')).toHaveLength(2); $('.ams_reset').click(); expect($('.ams_selected')).toHaveLength(3); }); it("Should react to 'clear'", function() { $('input.inputFilter').val("chro"); $('input.inputFilter').trigger("input"); expect($('.ams_item')).toHaveLength(5); $('.ams_clear').click(); expect($('.ams_item')).toHaveLength(13); }); }); describe('Testing directive in multi mode', function() { var scope, element, html, timeout; beforeEach(function (){ //load the module module('angular-multi-select'); //set our view html. html = '<div angular-multi-select ' + 'hidden-property="hidden" ' + 'input-model="items" ' + 'output-model="x" ' + 'group-property="sub" ' + 'tick-property="check" ' + 'item-label="{{ name }}" ' + 'helper-elements="all none reset filter"' + 'selection-mode="multi" ' + 'min-search-length="3" ' + 'search-property="name" ' + '></div>'; inject(function($compile, $rootScope, $timeout) { //create a scope (you could just use $rootScope, I suppose) scope = $rootScope; timeout = $timeout; //get the jqLite or jQuery element element = angular.element(html); //compile the element into a function to process the view. $compile(element)($rootScope); element.scope().items = multi_test_data; element.scope().$digest(); $(document.body).append(element); }); }); afterEach(function() { element.remove(); elementn = null; }); it('Should be able to create the directive.', function() { expect(element).not.toBeEmpty(); }); it("4 elements (and all their parents) should be checked", function() { expect($('.ams_selected')).toHaveLength(8); }); it("Should deselect all when clicked parent group", function() { $(".ams_item > div:contains('Open Source')").click(); expect($('.ams_selected', ".ams_item > div:contains('Open Source')" )).toHaveLength(0); }); it("Should select all when a group with no checked children is clicked", function() { $(".ams_item > div:contains('Modern browsers')").click().click(); expect($('.ams_selected', "li:contains('Modern browsers')" )).toHaveLength(7); }); it("Should deselect all when a group is clicked, if all elements are selected", function() { $(".ams_item > div:contains('Modern browsers')").click(); expect($('.ams_selected', "li:contains('Modern browsers')" )).toHaveLength(0); }); it("Should react to 'select all' by selecting everything", function() { $('.ams_selectall').click(); expect($('.ams_selected')).toHaveLength(13); }); it("Should react to 'select none' by unselecting everything", function() { $('.ams_selectnone').click(); expect($('.selected')).toHaveLength(0); }); });
Fix #26
spec/angular-multi-select.spec.js
Fix #26
<ide><path>pec/angular-multi-select.spec.js <ide> <ide> //set our view html. <ide> html = '<div angular-multi-select ' + <add> 'translation="localLang"' + <ide> 'hidden-property="hidden" ' + <ide> 'input-model="items" ' + <ide> 'output-model="x" ' + <ide> $compile(element)($rootScope); <ide> <ide> element.scope().items = single_test_data; <add> element.scope().localLang = { <add> selected: " seleccionado", <add> selectAll: "Todo", <add> selectNone: "Nada", <add> reset: "Resetear", <add> search: "Escribe aqui para buscar..." <add> }; <ide> element.scope().$digest(); <ide> <ide> $(document.body).append(element); <ide> <ide> $('.ams_clear').click(); <ide> expect($('.ams_item')).toHaveLength(13); <add> }); <add> <add> it("Should be able to use i18n strings", function() { <add> expect($('.ams_selectall')).toContainHtml("Todo"); <add> expect($('.ams_selectnone')).toContainHtml("Nada"); <add> expect($('.ams_reset')).toContainHtml("Resetear"); <add> expect($('.ams_filter')).toHaveAttr("placeholder", "Escribe aqui para buscar..."); <ide> }); <ide> }); <ide>
Java
agpl-3.0
ee1fc1e059003fd4431093b369176c47b7b45705
0
akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow
package org.waterforpeople.mapping.app.web; import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; import org.apache.velocity.runtime.RuntimeServices; import org.apache.velocity.runtime.RuntimeSingleton; import org.apache.velocity.runtime.parser.node.SimpleNode; import org.datanucleus.store.appengine.query.JDOCursorHelper; import org.waterforpeople.mapping.analytics.MapSummarizer; import org.waterforpeople.mapping.analytics.dao.AccessPointStatusSummaryDao; import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary; import org.waterforpeople.mapping.app.gwt.client.device.DeviceDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyAssignmentDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto; import org.waterforpeople.mapping.app.gwt.server.accesspoint.AccessPointManagerServiceImpl; import org.waterforpeople.mapping.app.gwt.server.devicefiles.DeviceFilesServiceImpl; import org.waterforpeople.mapping.app.gwt.server.survey.SurveyAssignmentServiceImpl; import org.waterforpeople.mapping.app.gwt.server.survey.SurveyServiceImpl; import org.waterforpeople.mapping.dao.AccessPointDao; import org.waterforpeople.mapping.dao.CommunityDao; import org.waterforpeople.mapping.dao.DeviceFilesDao; import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao; import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao; import org.waterforpeople.mapping.dao.SurveyContainerDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.dataexport.DeviceFilesReplicationImporter; import org.waterforpeople.mapping.dataexport.SurveyReplicationImporter; import org.waterforpeople.mapping.domain.AccessPoint; import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; import org.waterforpeople.mapping.domain.AccessPoint.Status; import org.waterforpeople.mapping.domain.Community; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.Status.StatusCode; import org.waterforpeople.mapping.domain.SurveyAssignment; import org.waterforpeople.mapping.domain.SurveyAttributeMapping; import org.waterforpeople.mapping.domain.SurveyInstance; import org.waterforpeople.mapping.domain.TechnologyType; import org.waterforpeople.mapping.helper.AccessPointHelper; import org.waterforpeople.mapping.helper.GeoRegionHelper; import org.waterforpeople.mapping.helper.KMLHelper; import com.beoui.geocell.GeocellManager; import com.beoui.geocell.model.Point; import com.gallatinsystems.common.util.ZipUtil; import com.gallatinsystems.device.dao.DeviceDAO; import com.gallatinsystems.device.domain.Device; import com.gallatinsystems.device.domain.Device.DeviceType; import com.gallatinsystems.device.domain.DeviceFiles; import com.gallatinsystems.device.domain.DeviceSurveyJobQueue; import com.gallatinsystems.diagnostics.dao.RemoteStacktraceDao; import com.gallatinsystems.diagnostics.domain.RemoteStacktrace; import com.gallatinsystems.editorial.dao.EditorialPageDao; import com.gallatinsystems.editorial.domain.EditorialPage; import com.gallatinsystems.editorial.domain.EditorialPageContent; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.framework.domain.BaseDomain; import com.gallatinsystems.framework.exceptions.IllegalDeletionException; import com.gallatinsystems.gis.geography.domain.Country; import com.gallatinsystems.gis.map.dao.MapFragmentDao; import com.gallatinsystems.gis.map.domain.Geometry; import com.gallatinsystems.gis.map.domain.MapFragment; import com.gallatinsystems.gis.map.domain.MapFragment.FRAGMENTTYPE; import com.gallatinsystems.gis.map.domain.OGRFeature; import com.gallatinsystems.survey.dao.DeviceSurveyJobQueueDAO; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.QuestionGroupDao; import com.gallatinsystems.survey.dao.QuestionHelpMediaDao; import com.gallatinsystems.survey.dao.QuestionOptionDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.dao.SurveyGroupDAO; import com.gallatinsystems.survey.dao.SurveyTaskUtil; import com.gallatinsystems.survey.dao.TranslationDao; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.Question.Type; import com.gallatinsystems.survey.domain.QuestionGroup; import com.gallatinsystems.survey.domain.QuestionHelpMedia; import com.gallatinsystems.survey.domain.QuestionOption; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.survey.domain.SurveyContainer; import com.gallatinsystems.survey.domain.SurveyGroup; import com.gallatinsystems.survey.domain.SurveyXMLFragment; import com.gallatinsystems.survey.domain.Translation; import com.gallatinsystems.survey.domain.Translation.ParentType; import com.google.appengine.api.datastore.Cursor; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Text; import com.google.appengine.api.labs.taskqueue.Queue; import com.google.appengine.api.labs.taskqueue.QueueFactory; public class TestHarnessServlet extends HttpServlet { private static Logger log = Logger.getLogger(TestHarnessServlet.class .getName()); private static final long serialVersionUID = -5673118002247715049L; @SuppressWarnings("unused") public void doGet(HttpServletRequest req, HttpServletResponse resp) { String action = req.getParameter("action"); if ("testSurveyOrdering".equals(action)) { SurveyGroupDAO sgDao = new SurveyGroupDAO(); SurveyGroup sgItem = sgDao.list("all").get(0); sgItem = sgDao.getByKey(sgItem.getKey().getId(), true); } else if ("loadOGRFeature".equals(action)) { OGRFeature ogrFeature = new OGRFeature(); ogrFeature.setName("clan-21061011"); ogrFeature.setProjectCoordinateSystemIdentifier("World_Mercator"); ogrFeature.setGeoCoordinateSystemIdentifier("GCS_WGS_1984"); ogrFeature.setDatumIdentifier("WGS_1984"); ogrFeature.setSpheroid(6378137D); ogrFeature.setReciprocalOfFlattening(298.257223563); ogrFeature.setCountryCode("LR"); ogrFeature.addBoundingBox(223700.015625, 481399.468750,680781.375000, 945462.437500); Geometry geo = new Geometry(); geo.setType("POLYGON"); String coords = "497974.5625 557051.875,498219.03125 557141.75,498655.34375 557169.4375,499001.65625 557100.1875,499250.96875 556933.9375,499167.875 556615.375,499230.1875 556407.625,499392.78125 556362.75,499385.90625 556279.875,499598.5 556067.3125,499680.25 555952.8125,499218.5625 554988.875,498775.65625 554860.1875,498674.5 554832.5625,498282.0 554734.4375,498020.34375 554554.5625,497709.59375 554374.6875,497614.84375 554374.6875,497519.46875 554369.1875,497297.3125 554359.9375,496852.96875 554355.3125,496621.125 554351.375,496695.75 554454.625,496771.59375 554604.625,496836.3125 554734.0625,496868.65625 554831.125,496847.09375 554863.4375,496760.8125 554863.4375,496663.75 554928.125,496620.625 554992.875,496555.90625 555025.1875,496448.0625 554992.875,496372.5625 555025.1875,496351.0 555133.0625,496415.71875 555197.75,496480.40625 555294.8125,496480.40625 555381.0625,496430.875 555430.75,496446.0625 555547.375,496490.53125 555849.625,496526.09375 556240.75,496721.65625 556596.375,496924.90625 556774.1875,497006.125 556845.25,497281.71875 556978.625,497610.625 556969.6875,497859.53125 556969.6875,497974.5625 557051.875"; for(String item:coords.split(",")){ String[] coord = item.split(" "); geo.addCoordinate(Double.parseDouble(coord[0]),Double.parseDouble(coord[1])); } ogrFeature.setGeometry(geo); ogrFeature.addGeoMeasure("CLNAME", "STRING", "Loisiana Township"); ogrFeature.addGeoMeasure("COUNT", "FLOAT", "1"); BaseDAO<OGRFeature> ogrDao = new BaseDAO<OGRFeature>(OGRFeature.class); ogrDao.save(ogrFeature); try { resp.getWriter().println("OGRFeature: " + ogrFeature.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ("resetLRAP".equals(action)) { try { AccessPointDao apDao = new AccessPointDao(); for (AccessPoint ap : apDao.list("all")) { if ((ap.getCountryCode() == null || ap.getCountryCode() .equals("US")) && (ap.getLatitude() != null && ap.getLongitude() != null)) { if (ap.getLatitude() > 5.0 && ap.getLatitude() < 11) { if (ap.getLongitude() < -9 && ap.getLongitude() > -11) { ap.setCountryCode("LR"); apDao.save(ap); resp.getWriter() .println( "Found " + ap.getCommunityCode() + "mapped to US changing mapping to LR \n"); } } } else if (ap.getCommunityCode() == null) { ap.setCommunityCode(new Random().toString()); apDao.save(ap); resp.getWriter().println( "Found " + ap.getCommunityCode() + "added random community code \n"); } } } catch (IOException e) { log.log(Level.SEVERE, "Could not execute test", e); } } else if ("clearSurveyInstanceQAS".equals(action)) { // QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); // for (QuestionAnswerStore qas : qasDao.list("all")) { // qasDao.delete(qas); // } // SurveyInstanceDAO siDao = new SurveyInstanceDAO(); // for (SurveyInstance si : siDao.list("all")) { // siDao.delete(si); // } AccessPointDao apDao = new AccessPointDao(); for (AccessPoint ap : apDao.list("all")) apDao.delete(ap); } else if ("SurveyInstance".equals(action)) { SurveyInstanceDAO siDao = new SurveyInstanceDAO(); List<SurveyInstance> siList = siDao.listSurveyInstanceBySurveyId( 1362011L, null); Cursor cursor = JDOCursorHelper.getCursor(siList); int i = 0; while (siList.size() > 0) { for (SurveyInstance si : siList) { System.out.println(i++ + " " + si.toString()); String surveyInstanceId = new Long(si.getKey().getId()) .toString(); Queue queue = QueueFactory.getDefaultQueue(); queue.add(url("/app_worker/surveytask").param("action", "reprocessMapSurveyInstance").param("id", surveyInstanceId)); log.info("submiting task for SurveyInstanceId: " + surveyInstanceId); } siList = siDao.listSurveyInstanceBySurveyId(1362011L, cursor.toWebSafeString()); cursor = JDOCursorHelper.getCursor(siList); } System.out.println("finished"); } else if ("rotateImage".equals(action)) { AccessPointManagerServiceImpl apmI = new AccessPointManagerServiceImpl(); String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg"; // String test2 = // "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg"; writeImageToResponse(resp, test1); apmI.setUploadS3Flag(false); writeImageToResponse(resp, apmI.rotateImage(test1)); // apmI.rotateImage(test2); } else if ("clearSurveyGroupGraph".equals(action)) { SurveyGroupDAO sgDao = new SurveyGroupDAO(); sgDao.delete(sgDao.list("all")); SurveyDAO surveyDao = new SurveyDAO(); surveyDao.delete(surveyDao.list("all")); QuestionGroupDao qgDao = new QuestionGroupDao(); qgDao.delete(qgDao.list("all")); QuestionDao qDao = new QuestionDao(); qDao.delete(qDao.list("all")); QuestionHelpMediaDao qhDao = new QuestionHelpMediaDao(); qhDao.delete(qhDao.list("all")); QuestionOptionDao qoDao = new QuestionOptionDao(); qoDao.delete(qoDao.list("all")); TranslationDao tDao = new TranslationDao(); tDao.delete(tDao.list("all")); /* * createSurveyGroupGraph(resp); //SurveyGroupDAO sgDao = new * SurveyGroupDAO(); List<SurveyGroup> sgList = sgDao.list("all"); * Survey survey = sgList.get(0).getSurveyList().get(0); * QuestionAnswerStore qas = new QuestionAnswerStore(); * qas.setArbitratyNumber(1L); * qas.setSurveyId(survey.getKey().getId()); qas.setQuestionID("1"); * qas.setValue("test"); QuestionAnswerStoreDao qasDao = new * QuestionAnswerStoreDao(); qasDao.save(qas); * * * for(SurveyGroup sg: sgList) sgDao.delete(sg); */ } else if ("replicateDeviceFiles".equals(action)) { SurveyInstanceDAO siDao = new SurveyInstanceDAO(); for (SurveyInstance si : siDao.list("all")) { siDao.delete(si); } QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); for (QuestionAnswerStore qas : qasDao.list("all")) { qasDao.delete(qas); } DeviceFilesDao dfDao = new DeviceFilesDao(); for (DeviceFiles df : dfDao.list("all")) { dfDao.delete(df); } DeviceFilesReplicationImporter dfri = new DeviceFilesReplicationImporter(); dfri.executeImport("http://watermapmonitordev.appspot.com", "http://localhost:8888"); Set<String> dfSet = new HashSet<String>(); for (DeviceFiles df : dfDao.list("all")) { dfSet.add(df.getURI()); } DeviceFilesServiceImpl dfsi = new DeviceFilesServiceImpl(); int i = 0; try { resp.getWriter().println( "Found " + dfSet.size() + " distinct files to process"); for (String s : dfSet) { dfsi.reprocessDeviceFile(s); resp.getWriter().println( "submitted " + s + " for reprocessing"); i++; if (i > 10) break; } } catch (IOException e) { log.log(Level.SEVERE, "Could not execute test", e); } } else if ("addDeviceFiles".equals(action)) { DeviceFilesDao dfDao = new DeviceFilesDao(); DeviceFiles df = new DeviceFiles(); df.setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip"); df.setCreatedDateTime(new Date()); df.setPhoneNumber("a4:ed:4e:54:ef:6d"); df.setChecksum("1149406886"); df.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP); DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd"); java.util.Date date = new java.util.Date(); String dateTime = dateFormat.format(date); df.setProcessDate(dateTime); dfDao.save(df); } else if ("testBaseDomain".equals(action)) { SurveyDAO surveyDAO = new SurveyDAO(); String outString = surveyDAO.getForTest(); BaseDAO<AccessPoint> pointDao = new BaseDAO<AccessPoint>( AccessPoint.class); AccessPoint point = new AccessPoint(); point.setLatitude(78d); point.setLongitude(43d); pointDao.save(point); try { resp.getWriter().print(outString); } catch (IOException e) { log.log(Level.SEVERE, "Could not execute test", e); } } else if ("testSaveRegion".equals(action)) { GeoRegionHelper geoHelp = new GeoRegionHelper(); ArrayList<String> regionLines = new ArrayList<String>(); for (int i = 0; i < 10; i++) { StringBuilder builder = new StringBuilder(); builder.append("1,").append("" + i).append(",test,") .append(20 + i + ",").append(30 + i + "\n"); regionLines.add(builder.toString()); } geoHelp.processRegionsSurvey(regionLines); try { resp.getWriter().print("Save complete"); } catch (IOException e) { log.log(Level.SEVERE, "Could not save test region", e); } } else if ("clearAccessPoint".equals(action)) { try { AccessPointDao apDao = new AccessPointDao(); for (AccessPoint ap : apDao.list("all")) { apDao.delete(ap); try { resp.getWriter().print( "Finished Deleting AP: " + ap.toString()); } catch (IOException e) { log.log(Level.SEVERE, "Could not delete ap"); } } resp.getWriter().print("Deleted AccessPoints complete"); BaseDAO<AccessPointStatusSummary> apsDao = new BaseDAO<AccessPointStatusSummary>( AccessPointStatusSummary.class); for (AccessPointStatusSummary item : apsDao.list("all")) { apsDao.delete(item); } resp.getWriter().print("Deleted AccessPointStatusSummary"); MapFragmentDao mfDao = new MapFragmentDao(); for (MapFragment item : mfDao.list("all")) { mfDao.delete(item); } resp.getWriter().print("Cleared MapFragment Table"); } catch (IOException e) { log.log(Level.SEVERE, "Could not clear AP and APStatusSummary", e); } } else if ("loadErrorPoints".equals(action)) { MapFragmentDao mfDao = new MapFragmentDao(); AccessPointDao apDao = new AccessPointDao(); for (int j = 0; j < 1; j++) { Double lat = 0.0; Double lon = 0.0; for (int i = 0; i < 5; i++) { AccessPoint ap = new AccessPoint(); ap.setLatitude(lat); ap.setLongitude(lon); Calendar calendar = Calendar.getInstance(); Date today = new Date(); calendar.setTime(today); calendar.add(Calendar.YEAR, -1 * i); System.out .println("AP: " + ap.getLatitude() + "/" + ap.getLongitude() + "Date: " + calendar.getTime()); ap.setCollectionDate(calendar.getTime()); ap.setAltitude(0.0); ap.setCommunityCode("test" + new Date()); ap.setCommunityName("test" + new Date()); ap.setPhotoURL("http://test.com"); ap.setPointType(AccessPoint.AccessPointType.WATER_POINT); if (i == 0) ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH); else if (i == 1) ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK); else if (i == 2) ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS); else ap.setPointStatus(Status.NO_IMPROVED_SYSTEM); if (i % 2 == 0) ap.setTypeTechnologyString("Kiosk"); else ap.setTypeTechnologyString("Afridev Handpump"); apDao.save(ap); MapSummarizer ms = new MapSummarizer(); // ms.performSummarization("" + ap.getKey().getId(), ""); if (i % 50 == 0) log.log(Level.INFO, "Loaded to " + i); } } try { resp.getWriter().println("Finished loading aps"); } catch (IOException e) { e.printStackTrace(); } } else if ("loadLots".equals(action)) { MapFragmentDao mfDao = new MapFragmentDao(); AccessPointDao apDao = new AccessPointDao(); for (int j = 0; j < 1; j++) { double lat = -15 + (new Random().nextDouble() / 10); double lon = 35 + (new Random().nextDouble() / 10); for (int i = 0; i < 15; i++) { AccessPoint ap = new AccessPoint(); ap.setLatitude(lat); ap.setLongitude(lon); Calendar calendar = Calendar.getInstance(); Date today = new Date(); calendar.setTime(today); calendar.add(Calendar.YEAR, -1 * i); System.out .println("AP: " + ap.getLatitude() + "/" + ap.getLongitude() + "Date: " + calendar.getTime()); // ap.setCollectionDate(calendar.getTime()); ap.setAltitude(0.0); ap.setCommunityCode("test" + new Date()); ap.setCommunityName("test" + new Date()); ap.setPhotoURL("http://waterforpeople.s3.amazonaws.com/images/peru/pc28water.jpg"); ap.setProvideAdequateQuantity(true); ap.setHasSystemBeenDown1DayFlag(false); ap.setMeetGovtQualityStandardFlag(true); ap.setMeetGovtQuantityStandardFlag(false); ap.setCurrentManagementStructurePoint("Community Board"); ap.setDescription("Waterpoint"); ap.setDistrict("test district"); ap.setEstimatedHouseholds(100L); ap.setEstimatedPeoplePerHouse(11L); ap.setFarthestHouseholdfromPoint("Yes"); ap.setNumberOfHouseholdsUsingPoint(100L); ap.setConstructionDateYear("2001"); ap.setCostPer(1.0); ap.setCountryCode("MW"); ap.setConstructionDate(new Date()); ap.setCollectionDate(new Date()); ap.setPhotoName("Water point"); if (i % 2 == 0) ap.setPointType(AccessPoint.AccessPointType.WATER_POINT); else if (i % 3 == 0) ap.setPointType(AccessPoint.AccessPointType.SANITATION_POINT); else ap.setPointType(AccessPoint.AccessPointType.PUBLIC_INSTITUTION); if (i == 0) ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH); else if (i == 1) ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK); else if (i == 2) ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS); else ap.setPointStatus(Status.NO_IMPROVED_SYSTEM); if (i % 2 == 0) ap.setTypeTechnologyString("Kiosk"); else ap.setTypeTechnologyString("Afridev Handpump"); apDao.save(ap); MapSummarizer ms = new MapSummarizer(); // ms.performSummarization("" + ap.getKey().getId(), ""); if (i % 50 == 0) log.log(Level.INFO, "Loaded to " + i); } } try { resp.getWriter().println("Finished loading aps"); } catch (IOException e) { e.printStackTrace(); } } else if ("loadCountries".equals(action)) { Country c = new Country(); c.setIsoAlpha2Code("HN"); c.setName("Honduras"); BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class); countryDAO.save(c); Country c2 = new Country(); c2.setIsoAlpha2Code("MW"); c2.setName("Malawi"); countryDAO.save(c2); } else if ("testAPKml".equals(action)) { MapFragmentDao mfDao = new MapFragmentDao(); BaseDAO<TechnologyType> ttDao = new BaseDAO<TechnologyType>( TechnologyType.class); List<TechnologyType> ttList = ttDao.list("all"); for (TechnologyType tt : ttList) ttDao.delete(tt); TechnologyType tt = new TechnologyType(); tt.setCode("Afridev Handpump"); tt.setName("Afridev Handpump"); ttDao.save(tt); TechnologyType tt2 = new TechnologyType(); tt2.setCode("Kiosk"); tt2.setName("Kiosk"); ttDao.save(tt2); KMLHelper kmlHelper = new KMLHelper(); kmlHelper.buildMap(); List<MapFragment> mfList = mfDao.searchMapFragments("ALL", null, null, null, FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all", null, null); try { for (MapFragment mfItem : mfList) { String contents = ZipUtil .unZip(mfItem.getBlob().getBytes()); log.log(Level.INFO, "Contents Length: " + contents.length()); resp.setContentType("application/vnd.google-earth.kmz+xml"); ServletOutputStream out = resp.getOutputStream(); resp.setHeader("Content-Disposition", "inline; filename=waterforpeoplemapping.kmz;"); out.write(mfItem.getBlob().getBytes()); out.flush(); } } catch (IOException ie) { log.log(Level.SEVERE, "Could not list fragment"); } } else if ("deleteSurveyGraph".equals(action)) { deleteAll(SurveyGroup.class); deleteAll(Survey.class); deleteAll(QuestionGroup.class); deleteAll(Question.class); deleteAll(Translation.class); deleteAll(QuestionOption.class); deleteAll(QuestionHelpMedia.class); try { resp.getWriter().println("Finished deleting survey graph"); } catch (IOException iex) { log.log(Level.SEVERE, "couldn't delete surveyGraph" + iex); } } else if ("saveSurveyGroupRefactor".equals(action)) { SurveyGroupDAO sgDao = new SurveyGroupDAO(); createSurveyGroupGraph(resp); try { List<SurveyGroup> savedSurveyGroups = sgDao.list("all"); for (SurveyGroup sgItem : savedSurveyGroups) { resp.getWriter().println("SG: " + sgItem.getCode()); for (Survey survey : sgItem.getSurveyList()) { resp.getWriter().println( " Survey:" + survey.getName()); for (Map.Entry<Integer, QuestionGroup> entry : survey .getQuestionGroupMap().entrySet()) { resp.getWriter().println( " QuestionGroup: " + entry.getKey() + ":" + entry.getValue().getDesc()); for (Map.Entry<Integer, Question> questionEntry : entry .getValue().getQuestionMap().entrySet()) { resp.getWriter().println( " Question" + questionEntry.getKey() + ":" + questionEntry.getValue() .getText()); for (Map.Entry<Integer, QuestionHelpMedia> qhmEntry : questionEntry .getValue().getQuestionHelpMediaMap() .entrySet()) { resp.getWriter().println( " QuestionHelpMedia" + qhmEntry.getKey() + ":" + qhmEntry.getValue() .getText()); /* * for (Key tKey : qhmEntry.getValue() * .getAltTextKeyList()) { Translation t = * tDao.getByKey(tKey); * resp.getWriter().println( * " QHMAltText" + * t.getLanguageCode() + ":" + t.getText()); * } */ } } } } } } catch (IOException e) { log.log(Level.SEVERE, "Could not save sg"); } } else if ("createAP".equals(action)) { AccessPoint ap = new AccessPoint(); ap.setCollectionDate(new Date()); ap.setCommunityCode(new Random().toString()); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setCountryCode("SZ"); ap.setPointType(AccessPointType.WATER_POINT); AccessPointHelper helper = new AccessPointHelper(); helper.saveAccessPoint(ap); } else if ("createInstance".equals(action)) { SurveyInstance si = new SurveyInstance(); si.setCollectionDate(new Date()); ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>(); QuestionAnswerStore ans = new QuestionAnswerStore(); ans.setQuestionID("q2"); ans.setValue("Geneva"); store.add(ans); si.setQuestionAnswersStore(store); SurveyInstanceDAO dao = new SurveyInstanceDAO(); si = dao.save(si); Queue summQueue = QueueFactory.getQueue("dataSummarization"); summQueue.add(url("/app_worker/datasummarization").param( "objectKey", si.getKey().getId() + "").param("type", "SurveyInstance")); } else if ("createCommunity".equals(action)) { CommunityDao dao = new CommunityDao(); Country c = new Country(); c.setIsoAlpha2Code("CA"); c.setName("Canada"); c.setDisplayName("Canada"); Community comm = new Community(); comm.setCommunityCode("ON"); dao.save(c); comm.setCountryCode("CA"); comm.setLat(54.99); comm.setLon(-74.72); dao.save(comm); c = new Country(); c.setIsoAlpha2Code("US"); c.setName("United States"); c.setDisplayName("Unites States"); comm = new Community(); comm.setCommunityCode("Omaha"); comm.setCountryCode("US"); comm.setLat(34.99); comm.setLon(-74.72); dao.save(c); dao.save(comm); } else if ("addPhone".equals(action)) { String phoneNumber = req.getParameter("phoneNumber"); Device d = new Device(); d.setPhoneNumber(phoneNumber); d.setDeviceType(DeviceType.CELL_PHONE_ANDROID); if (req.getParameter("esn") != null) d.setEsn(req.getParameter("esn")); if (req.getParameter("gallatinSoftwareManifest") != null) d.setGallatinSoftwareManifest(req .getParameter("gallatinSoftwareManifest")); d.setInServiceDate(new Date()); DeviceDAO deviceDao = new DeviceDAO(); deviceDao.save(d); try { resp.getWriter().println("finished adding " + phoneNumber); } catch (Exception e) { e.printStackTrace(); } } else if ("createAPSummary".equals(action)) { AccessPointStatusSummary sum = new AccessPointStatusSummary(); sum.setCommunity("ON"); sum.setCountry("CA"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2000"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao(); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("ON"); sum.setCountry("CA"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2001"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("ON"); sum.setCountry("CA"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2003"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("ON"); sum.setCountry("CA"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2004"); sum.setStatus(AccessPoint.Status.FUNCTIONING_OK); dao.save(sum); sum.setCommunity("NY"); sum.setCountry("US"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2000"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("NY"); sum.setCountry("US"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2001"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("NY"); sum.setCountry("US"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2003"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("NY"); sum.setCountry("US"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2004"); sum.setStatus(AccessPoint.Status.FUNCTIONING_OK); dao.save(sum); } else if ("createApHistory".equals(action)) { GregorianCalendar cal = new GregorianCalendar(); AccessPointHelper apHelper = new AccessPointHelper(); AccessPoint ap = new AccessPoint(); cal.set(Calendar.YEAR, 2000); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(300l); ap.setCostPer(43.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2001); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(317l); ap.setCostPer(40.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2002); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(340l); ap.setCostPer(37.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2003); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_HIGH); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(340l); ap.setCostPer(34.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2004); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(338l); ap.setCostPer(38.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2000); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_HIGH); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(170l); ap.setCostPer(19.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2001); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_HIGH); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(201l); ap.setCostPer(19.00); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2002); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_HIGH); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(211l); ap.setCostPer(17.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2003); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(220l); ap.setCostPer(25.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2004); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(175l); ap.setCostPer(24.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); } else if ("generateGeocells".equals(action)) { AccessPointDao apDao = new AccessPointDao(); List<AccessPoint> apList = apDao.list(null); if (apList != null) { for (AccessPoint ap : apList) { if (ap.getGeocells() == null || ap.getGeocells().size() == 0) { if (ap.getLatitude() != null && ap.getLongitude() != null) { ap.setGeocells(GeocellManager.generateGeoCell(new Point( ap.getLatitude(), ap.getLongitude()))); apDao.save(ap); } } } } } else if ("loadExistingSurvey".equals(action)) { SurveyGroup sg = new SurveyGroup(); sg.setKey(KeyFactory.createKey(SurveyGroup.class.getSimpleName(), 2L)); sg.setName("test" + new Date()); sg.setCode("test" + new Date()); SurveyGroupDAO sgDao = new SurveyGroupDAO(); sgDao.save(sg); Survey s = new Survey(); s.setKey(KeyFactory.createKey(Survey.class.getSimpleName(), 2L)); s.setName("test" + new Date()); s.setSurveyGroupId(sg.getKey().getId()); SurveyDAO surveyDao = new SurveyDAO(); surveyDao.save(s); } else if ("saveAPMapping".equals(action)) { SurveyAttributeMapping mapping = new SurveyAttributeMapping(); mapping.setAttributeName("status"); mapping.setObjectName(AccessPoint.class.getCanonicalName()); mapping.setSurveyId(1L); mapping.setSurveyQuestionId("q1"); SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao(); samDao.save(mapping); } else if ("listAPMapping".equals(action)) { SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao(); List<SurveyAttributeMapping> mappings = samDao .listMappingsBySurvey(1L); if (mappings != null) { System.out.println(mappings.size()); } } else if ("saveSurveyGroup".equals(action)) { try { SurveyGroupDAO sgDao = new SurveyGroupDAO(); List<SurveyGroup> sgList = sgDao.list("all"); for (SurveyGroup sg : sgList) { sgDao.delete(sg); } resp.getWriter().println("Deleted all survey groups"); SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); for (Survey survey : surveyList) { try { surveyDao.delete(survey); } catch (IllegalDeletionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } resp.getWriter().println("Deleted all surveys"); resp.getWriter().println("Deleted all surveysurveygroupassocs"); QuestionGroupDao qgDao = new QuestionGroupDao(); List<QuestionGroup> qgList = qgDao.list("all"); for (QuestionGroup qg : qgList) { qgDao.delete(qg); } resp.getWriter().println("Deleted all question groups"); QuestionDao qDao = new QuestionDao(); List<Question> qList = qDao.list("all"); for (Question q : qList) { try { qDao.delete(q); } catch (IllegalDeletionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } resp.getWriter().println("Deleted all Questions"); QuestionOptionDao qoDao = new QuestionOptionDao(); List<QuestionOption> qoList = qoDao.list("all"); for (QuestionOption qo : qoList) qoDao.delete(qo); resp.getWriter().println("Deleted all QuestionOptions"); resp.getWriter().println("Deleted all questions"); resp.getWriter().println( "Finished deleting and reloading SurveyGroup graph"); } catch (IOException e) { e.printStackTrace(); } } else if ("testPublishSurvey".equals(action)) { try { SurveyGroupDto sgDto = new SurveyServiceImpl() .listSurveyGroups(null, true, false, false).get(0); resp.getWriter().println( "Got Survey Group: " + sgDto.getCode() + " Survey: " + sgDto.getSurveyList().get(0).getKeyId()); SurveyContainerDao scDao = new SurveyContainerDao(); SurveyContainer sc = scDao.findBySurveyId(sgDto.getSurveyList() .get(0).getKeyId()); if (sc != null) { scDao.delete(sc); resp.getWriter().println( "Deleted existing SurveyContainer for: " + sgDto.getSurveyList().get(0).getKeyId()); } resp.getWriter().println( "Result of publishing survey: " + new SurveyServiceImpl().publishSurvey(sgDto .getSurveyList().get(0).getKeyId())); sc = scDao.findBySurveyId(sgDto.getSurveyList().get(0) .getKeyId()); resp.getWriter().println( "Survey Document result from publish: \n\n\n\n" + sc.getSurveyDocument().getValue()); } catch (IOException ex) { ex.printStackTrace(); } } else if ("createTestSurveyForEndToEnd".equals(action)) { createTestSurveyForEndToEnd(); } else if ("deleteSurveyFragments".equals(action)) { deleteAll(SurveyXMLFragment.class); } else if ("migratePIToSchool".equals(action)) { try { resp.getWriter().println( "Has more? " + migratePointType( AccessPointType.PUBLIC_INSTITUTION, AccessPointType.SCHOOL)); } catch (IOException e) { e.printStackTrace(); } } else if ("createDevice".equals(action)) { DeviceDAO devDao = new DeviceDAO(); Device device = new Device(); device.setPhoneNumber("9175667663"); device.setDeviceType(DeviceType.CELL_PHONE_ANDROID); devDao.save(device); } else if ("reprocessSurveys".equals(action)) { try { reprocessSurveys(req.getParameter("date")); } catch (ParseException e) { try { resp.getWriter().println("Couldn't reprocess: " + e); } catch (IOException e1) { e1.printStackTrace(); } } } else if ("importallsurveys".equals(action)) { // Only run in dev hence hardcoding SurveyReplicationImporter sri = new SurveyReplicationImporter(); sri.executeImport("http://watermapmonitordev.appspot.com", "http://localhost:8888"); // sri.executeImport("http://localhost:8888", // "http://localhost:8888"); } else if ("deleteSurveyResponses".equals(action)) { if (req.getParameter("surveyId") == null) { try { resp.getWriter() .println("surveyId is a required parameter"); } catch (IOException e1) { e1.printStackTrace(); } } else { deleteSurveyResponses( Integer.parseInt(req.getParameter("surveyId")), Integer.parseInt(req.getParameter("count"))); } } else if ("fixNameQuestion".equals(action)) { if (req.getParameter("questionId") == null) { try { resp.getWriter().println( "questionId is a required parameter"); } catch (IOException e1) { e1.printStackTrace(); } } else { fixNameQuestion(req.getParameter("questionId")); } } else if ("createSurveyAssignment".equals(action)) { Device device = new Device(); device.setDeviceType(DeviceType.CELL_PHONE_ANDROID); device.setPhoneNumber("1111111111"); device.setInServiceDate(new Date()); BaseDAO<Device> deviceDao = new BaseDAO<Device>(Device.class); deviceDao.save(device); SurveyAssignmentServiceImpl sasi = new SurveyAssignmentServiceImpl(); SurveyAssignmentDto dto = new SurveyAssignmentDto(); SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); SurveyAssignment sa = new SurveyAssignment(); BaseDAO<SurveyAssignment> surveyAssignmentDao = new BaseDAO<SurveyAssignment>( SurveyAssignment.class); sa.setCreatedDateTime(new Date()); sa.setCreateUserId(-1L); ArrayList<Long> deviceList = new ArrayList<Long>(); deviceList.add(device.getKey().getId()); sa.setDeviceIds(deviceList); ArrayList<SurveyDto> surveyDtoList = new ArrayList<SurveyDto>(); for (Survey survey : surveyList) { sa.addSurvey(survey.getKey().getId()); SurveyDto surveyDto = new SurveyDto(); surveyDto.setKeyId(survey.getKey().getId()); surveyDtoList.add(surveyDto); } sa.setStartDate(new Date()); sa.setEndDate(new Date()); sa.setName(new Date().toString()); DeviceDto deviceDto = new DeviceDto(); deviceDto.setKeyId(device.getKey().getId()); deviceDto.setPhoneNumber(device.getPhoneNumber()); ArrayList<DeviceDto> deviceDtoList = new ArrayList<DeviceDto>(); deviceDtoList.add(deviceDto); dto.setDevices(deviceDtoList); dto.setSurveys(surveyDtoList); dto.setEndDate(new Date()); dto.setLanguage("en"); dto.setName("Test Assignment: " + new Date().toString()); dto.setStartDate(new Date()); sasi.saveSurveyAssignment(dto); // sasi.deleteSurveyAssignment(dto); } else if ("populateAssignmentId".equalsIgnoreCase(action)) { populateAssignmentId(Long.parseLong(req .getParameter("assignmentId"))); } else if ("testDSJQDelete".equals(action)) { DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO(); Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, -10); Date then = cal.getTime(); DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue(); dsjq.setDevicePhoneNumber("2019561591"); dsjq.setEffectiveEndDate(then); Random rand = new Random(); dsjq.setAssignmentId(rand.nextLong()); dsjDAO.save(dsjq); DeviceSurveyJobQueue dsjq2 = new DeviceSurveyJobQueue(); dsjq2.setDevicePhoneNumber("2019561591"); cal.add(Calendar.DAY_OF_MONTH, 20); dsjq2.setEffectiveEndDate(cal.getTime()); dsjq2.setAssignmentId(rand.nextLong()); dsjDAO.save(dsjq2); DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO(); List<DeviceSurveyJobQueue> dsjqList = dsjqDao .listAssignmentsWithEarlierExpirationDate(new Date()); for (DeviceSurveyJobQueue item : dsjqList) { SurveyTaskUtil.spawnDeleteTask("deleteDeviceSurveyJobQueue", item.getAssignmentId()); } } else if ("loadDSJ".equals(action)) { SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); for (Survey item : surveyList) { DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO(); Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, -10); Date then = cal.getTime(); DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue(); dsjq.setDevicePhoneNumber("2019561591"); dsjq.setEffectiveEndDate(then); Random rand = new Random(); dsjq.setAssignmentId(rand.nextLong()); dsjq.setSurveyID(item.getKey().getId()); dsjDAO.save(dsjq); } for (int i = 0; i < 20; i++) { DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO(); Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, -10); Date then = cal.getTime(); DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue(); dsjq.setDevicePhoneNumber("2019561591"); dsjq.setEffectiveEndDate(then); Random rand = new Random(); dsjq.setAssignmentId(rand.nextLong()); dsjq.setSurveyID(rand.nextLong()); dsjDAO.save(dsjq); } try { resp.getWriter().println("finished"); } catch (IOException e1) { e1.printStackTrace(); } } else if ("deleteUnusedDSJQueue".equals(action)) { try { SurveyDAO surveyDao = new SurveyDAO(); List<Key> surveyIdList = surveyDao.listSurveyIds(); List<Long> ids = new ArrayList<Long>(); for (Key key : surveyIdList) ids.add(key.getId()); DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO(); List<DeviceSurveyJobQueue> deleteList = new ArrayList<DeviceSurveyJobQueue>(); for (DeviceSurveyJobQueue item : dsjqDao.listAllJobsInQueue()) { Long dsjqSurveyId = item.getSurveyID(); Boolean found = ids.contains(dsjqSurveyId); if (!found) { deleteList.add(item); resp.getWriter().println( "Marking " + item.getId() + " survey: " + item.getSurveyID() + " for deletion"); } } dsjqDao.delete(deleteList); resp.getWriter().println("finished"); } catch (IOException e1) { e1.printStackTrace(); } } else if ("testListTrace".equals(action)) { listStacktrace(); } else if ("createEditorialContent".equals(action)) { createEditorialContent(req.getParameter("pageName")); } else if ("generateEditorialContent".equals(action)) { try { resp.getWriter().print( generateEditorialContent(req.getParameter("pageName"))); } catch (IOException e) { e.printStackTrace(); } } } private String generateEditorialContent(String pageName) { String content = ""; EditorialPageDao dao = new EditorialPageDao(); EditorialPage p = dao.findByTargetPage(pageName); List<EditorialPageContent> contentList = dao.listContentByPage(p .getKey().getId()); try { RuntimeServices runtimeServices = RuntimeSingleton .getRuntimeServices(); StringReader reader = new StringReader(p.getTemplate().getValue()); SimpleNode node = runtimeServices.parse(reader, "dynamicTemplate"); Template template = new Template(); template.setRuntimeServices(runtimeServices); template.setData(node); template.initDocument(); Context ctx = new VelocityContext(); ctx.put("pages", contentList); StringWriter writer = new StringWriter(); template.merge(ctx, writer); content = writer.toString(); } catch (Exception e) { log.log(Level.SEVERE, "Could not initialize velocity", e); } return content; } private void createEditorialContent(String pageName) { EditorialPageDao dao = new EditorialPageDao(); EditorialPage page = new EditorialPage(); page.setTargetFileName(pageName); page.setType("landing"); page.setTemplate(new Text( "<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>")); page = dao.save(page); EditorialPageContent content = new EditorialPageContent(); List<EditorialPageContent> contentList = new ArrayList<EditorialPageContent>(); content.setHeading("Heading 1"); content.setText(new Text("this is some text")); content.setSortOrder(1L); content.setEditorialPageId(page.getKey().getId()); contentList.add(content); content = new EditorialPageContent(); content.setHeading("Heading 2"); content.setText(new Text("this is more text")); content.setSortOrder(2L); content.setEditorialPageId(page.getKey().getId()); contentList.add(content); dao.save(contentList); } private void listStacktrace() { RemoteStacktraceDao traceDao = new RemoteStacktraceDao(); List<RemoteStacktrace> result = null; result = traceDao.listStacktrace(null, null, false, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace(null, null, true, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace("12345", null, true, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace("12345", "12345", true, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace(null, "12345", true, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace("12345", null, false, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace("12345", "12345", false, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace(null, "12345", false, null); if (result != null) { System.out.println(result.size() + ""); } } private void populateAssignmentId(Long assignmentId) { BaseDAO<SurveyAssignment> assignmentDao = new BaseDAO<SurveyAssignment>( SurveyAssignment.class); SurveyAssignment assignment = assignmentDao.getByKey(assignmentId); DeviceSurveyJobQueueDAO jobDao = new DeviceSurveyJobQueueDAO(); if (assignment != null) { for (Long sid : assignment.getSurveyIds()) { jobDao.updateAssignmentIdForSurvey(sid, assignmentId); } } } private void fixNameQuestion(String questionId) { Queue summQueue = QueueFactory.getQueue("dataUpdate"); summQueue.add(url("/app_worker/dataupdate").param("objectKey", questionId + "").param("type", "NameQuestionFix")); } private boolean deleteSurveyResponses(Integer surveyId, Integer count) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<SurveyInstance> instances = dao.listSurveyInstanceBySurvey( new Long(surveyId), count != null ? count : 100); if (instances != null) { for (SurveyInstance instance : instances) { List<QuestionAnswerStore> questions = dao .listQuestionAnswerStore(instance.getKey().getId(), count); if (questions != null) { dao.delete(questions); } dao.delete(instance); } return true; } return false; } private void reprocessSurveys(String date) throws ParseException { SurveyInstanceDAO dao = new SurveyInstanceDAO(); Date startDate = null; if (date != null) { DateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); startDate = sdf.parse(date); List<SurveyInstance> instances = dao.listByDateRange(startDate, null, null); if (instances != null) { AccessPointHelper aph = new AccessPointHelper(); for (SurveyInstance instance : instances) { aph.processSurveyInstance(instance.getKey().getId() + ""); } } } } private boolean migratePointType(AccessPointType source, AccessPointType dest) { AccessPointDao pointDao = new AccessPointDao(); List<AccessPoint> list = pointDao.searchAccessPoints(null, null, null, null, source.toString(), null, null, null, null, null, null); if (list != null && list.size() > 0) { for (AccessPoint point : list) { point.setPointType(dest); pointDao.save(point); } } if (list != null && list.size() == 20) { return true; } else { return false; } } @SuppressWarnings("unchecked") private <T extends BaseDomain> void deleteAll(Class<T> type) { BaseDAO<T> baseDao = new BaseDAO(type); List<T> items = baseDao.list("all"); if (items != null) { for (T item : items) { baseDao.delete(item); } } } private void createTestSurveyForEndToEnd() { SurveyGroupDto sgd = new SurveyGroupDto(); sgd.setCode("E2E Test"); sgd.setDescription("end2end test"); SurveyDto surveyDto = new SurveyDto(); surveyDto.setDescription("e2e test"); SurveyServiceImpl surveySvc = new SurveyServiceImpl(); QuestionGroupDto qgd = new QuestionGroupDto(); qgd.setCode("Question Group 1"); qgd.setDescription("Question Group Desc"); QuestionDto qd = new QuestionDto(); qd.setText("Access Point Name:"); qd.setType(QuestionType.FREE_TEXT); qgd.addQuestion(qd, 0); qd = new QuestionDto(); qd.setText("Location:"); qd.setType(QuestionType.GEO); qgd.addQuestion(qd, 1); qd = new QuestionDto(); qd.setText("Photo"); qd.setType(QuestionType.PHOTO); qgd.addQuestion(qd, 2); surveyDto.addQuestionGroup(qgd); surveyDto.setVersion("Version: 1"); sgd.addSurvey(surveyDto); sgd = surveySvc.save(sgd); System.out.println(sgd.getKeyId()); } private void writeImageToResponse(HttpServletResponse resp, String urlString) { resp.setContentType("image/jpeg"); try { ServletOutputStream out = resp.getOutputStream(); URL url = new URL(urlString); InputStream in = url.openStream(); byte[] buffer = new byte[2048]; int size; while ((size = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, size); } in.close(); out.flush(); } catch (Exception ex) { } } private void writeImageToResponse(HttpServletResponse resp, byte[] imageBytes) { resp.setContentType("image/jpeg"); try { ServletOutputStream out = resp.getOutputStream(); out.write(imageBytes, 0, imageBytes.length); out.flush(); } catch (Exception ex) { } } private void createSurveyGroupGraph(HttpServletResponse resp) { com.gallatinsystems.survey.dao.SurveyGroupDAO sgDao = new com.gallatinsystems.survey.dao.SurveyGroupDAO(); BaseDAO<Translation> tDao = new BaseDAO<Translation>(Translation.class); for (Translation t : tDao.list("all")) tDao.delete(t); // clear out old surveys List<SurveyGroup> sgList = sgDao.list("all"); for (SurveyGroup item : sgList) sgDao.delete(item); try { resp.getWriter().println("Finished clearing surveyGroup table"); } catch (IOException e1) { e1.printStackTrace(); } SurveyDAO surveyDao = new SurveyDAO(); QuestionGroupDao questionGroupDao = new QuestionGroupDao(); QuestionDao questionDao = new QuestionDao(); QuestionOptionDao questionOptionDao = new QuestionOptionDao(); QuestionHelpMediaDao helpDao = new QuestionHelpMediaDao(); for (int i = 0; i < 2; i++) { com.gallatinsystems.survey.domain.SurveyGroup sg = new com.gallatinsystems.survey.domain.SurveyGroup(); sg.setCode(i + ":" + new Date()); sg.setName(i + ":" + new Date()); sg = sgDao.save(sg); for (int j = 0; j < 2; j++) { com.gallatinsystems.survey.domain.Survey survey = new com.gallatinsystems.survey.domain.Survey(); survey.setCode(j + ":" + new Date()); survey.setName(j + ":" + new Date()); survey.setSurveyGroupId(sg.getKey().getId()); survey.setPath(sg.getCode()); survey = surveyDao.save(survey); Translation t = new Translation(); t.setLanguageCode("es"); t.setText(j + ":" + new Date()); t.setParentType(ParentType.SURVEY_NAME); t.setParentId(survey.getKey().getId()); tDao.save(t); survey.addTranslation(t); for (int k = 0; k < 3; k++) { com.gallatinsystems.survey.domain.QuestionGroup qg = new com.gallatinsystems.survey.domain.QuestionGroup(); qg.setName("en:" + j + new Date()); qg.setDesc("en:desc: " + j + new Date()); qg.setCode("en:" + j + new Date()); qg.setSurveyId(survey.getKey().getId()); qg.setOrder(k); qg.setPath(sg.getCode() + "/" + survey.getCode()); qg = questionGroupDao.save(qg); Translation t2 = new Translation(); t2.setLanguageCode("es"); t2.setParentType(ParentType.QUESTION_GROUP_NAME); t2.setText("es:" + k + new Date()); t2.setParentId(qg.getKey().getId()); tDao.save(t2); qg.addTranslation(t2); for (int l = 0; l < 2; l++) { com.gallatinsystems.survey.domain.Question q = new com.gallatinsystems.survey.domain.Question(); q.setType(Type.OPTION); q.setAllowMultipleFlag(false); q.setAllowOtherFlag(false); q.setDependentFlag(false); q.setMandatoryFlag(true); q.setQuestionGroupId(qg.getKey().getId()); q.setOrder(l); q.setText("en:" + l + ":" + new Date()); q.setTip("en:" + l + ":" + new Date()); q.setPath(sg.getCode() + "/" + survey.getCode() + "/" + qg.getCode()); q.setSurveyId(survey.getKey().getId()); q = questionDao.save(q); Translation tq = new Translation(); tq.setLanguageCode("es"); tq.setText("es" + l + ":" + new Date()); tq.setParentType(ParentType.QUESTION_TEXT); tq.setParentId(q.getKey().getId()); tDao.save(tq); q.addTranslation(tq); for (int m = 0; m < 10; m++) { com.gallatinsystems.survey.domain.QuestionOption qo = new com.gallatinsystems.survey.domain.QuestionOption(); qo.setOrder(m); qo.setText(m + ":" + new Date()); qo.setCode(m + ":" + new Date()); qo.setQuestionId(q.getKey().getId()); qo = questionOptionDao.save(qo); Translation tqo = new Translation(); tqo.setLanguageCode("es"); tqo.setText("es:" + m + ":" + new Date()); tqo.setParentType(ParentType.QUESTION_OPTION); tqo.setParentId(qo.getKey().getId()); tDao.save(tqo); qo.addTranslation(tqo); q.addQuestionOption(qo); } for (int n = 0; n < 10; n++) { com.gallatinsystems.survey.domain.QuestionHelpMedia qhm = new com.gallatinsystems.survey.domain.QuestionHelpMedia(); qhm.setText("en:" + n + ":" + new Date()); qhm.setType(QuestionHelpMedia.Type.PHOTO); qhm.setResourceUrl("http://test.com/" + n + ".jpg"); qhm.setQuestionId(q.getKey().getId()); qhm = helpDao.save(qhm); Translation tqhm = new Translation(); tqhm.setLanguageCode("es"); tqhm.setText("es:" + n + ":" + new Date()); tqhm.setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT); tqhm.setParentId(qhm.getKey().getId()); tDao.save(tqhm); qhm.addTranslation(tqhm); q.addHelpMedia(n, qhm); } qg.addQuestion(l, q); } survey.addQuestionGroup(k, qg); } sg.addSurvey(survey); } log.log(Level.INFO, "Finished Saving sg: " + sg.getKey().toString()); } } }
GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
package org.waterforpeople.mapping.app.web; import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; import org.apache.velocity.runtime.RuntimeServices; import org.apache.velocity.runtime.RuntimeSingleton; import org.apache.velocity.runtime.parser.node.SimpleNode; import org.datanucleus.store.appengine.query.JDOCursorHelper; import org.waterforpeople.mapping.analytics.MapSummarizer; import org.waterforpeople.mapping.analytics.dao.AccessPointStatusSummaryDao; import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary; import org.waterforpeople.mapping.app.gwt.client.device.DeviceDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyAssignmentDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType; import org.waterforpeople.mapping.app.gwt.server.accesspoint.AccessPointManagerServiceImpl; import org.waterforpeople.mapping.app.gwt.server.devicefiles.DeviceFilesServiceImpl; import org.waterforpeople.mapping.app.gwt.server.survey.SurveyAssignmentServiceImpl; import org.waterforpeople.mapping.app.gwt.server.survey.SurveyServiceImpl; import org.waterforpeople.mapping.dao.AccessPointDao; import org.waterforpeople.mapping.dao.CommunityDao; import org.waterforpeople.mapping.dao.DeviceFilesDao; import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao; import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao; import org.waterforpeople.mapping.dao.SurveyContainerDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.dataexport.DeviceFilesReplicationImporter; import org.waterforpeople.mapping.dataexport.SurveyReplicationImporter; import org.waterforpeople.mapping.domain.AccessPoint; import org.waterforpeople.mapping.domain.Community; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.SurveyAssignment; import org.waterforpeople.mapping.domain.SurveyAttributeMapping; import org.waterforpeople.mapping.domain.SurveyInstance; import org.waterforpeople.mapping.domain.TechnologyType; import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; import org.waterforpeople.mapping.domain.AccessPoint.Status; import org.waterforpeople.mapping.domain.Status.StatusCode; import org.waterforpeople.mapping.helper.AccessPointHelper; import org.waterforpeople.mapping.helper.GeoRegionHelper; import org.waterforpeople.mapping.helper.KMLHelper; import com.beoui.geocell.GeocellManager; import com.beoui.geocell.model.Point; import com.gallatinsystems.common.util.ZipUtil; import com.gallatinsystems.device.dao.DeviceDAO; import com.gallatinsystems.device.domain.Device; import com.gallatinsystems.device.domain.DeviceFiles; import com.gallatinsystems.device.domain.DeviceSurveyJobQueue; import com.gallatinsystems.device.domain.Device.DeviceType; import com.gallatinsystems.diagnostics.dao.RemoteStacktraceDao; import com.gallatinsystems.diagnostics.domain.RemoteStacktrace; import com.gallatinsystems.editorial.dao.EditorialPageDao; import com.gallatinsystems.editorial.domain.EditorialPage; import com.gallatinsystems.editorial.domain.EditorialPageContent; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.framework.domain.BaseDomain; import com.gallatinsystems.framework.exceptions.IllegalDeletionException; import com.gallatinsystems.gis.geography.domain.Country; import com.gallatinsystems.gis.map.dao.MapFragmentDao; import com.gallatinsystems.gis.map.domain.MapFragment; import com.gallatinsystems.gis.map.domain.MapFragment.FRAGMENTTYPE; import com.gallatinsystems.survey.dao.DeviceSurveyJobQueueDAO; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.QuestionGroupDao; import com.gallatinsystems.survey.dao.QuestionHelpMediaDao; import com.gallatinsystems.survey.dao.QuestionOptionDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.dao.SurveyGroupDAO; import com.gallatinsystems.survey.dao.SurveyTaskUtil; import com.gallatinsystems.survey.dao.TranslationDao; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.QuestionGroup; import com.gallatinsystems.survey.domain.QuestionHelpMedia; import com.gallatinsystems.survey.domain.QuestionOption; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.survey.domain.SurveyContainer; import com.gallatinsystems.survey.domain.SurveyGroup; import com.gallatinsystems.survey.domain.SurveyXMLFragment; import com.gallatinsystems.survey.domain.Translation; import com.gallatinsystems.survey.domain.Question.Type; import com.gallatinsystems.survey.domain.Translation.ParentType; import com.google.appengine.api.datastore.Cursor; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Text; import com.google.appengine.api.labs.taskqueue.Queue; import com.google.appengine.api.labs.taskqueue.QueueFactory; public class TestHarnessServlet extends HttpServlet { private static Logger log = Logger.getLogger(TestHarnessServlet.class .getName()); private static final long serialVersionUID = -5673118002247715049L; @SuppressWarnings("unused") public void doGet(HttpServletRequest req, HttpServletResponse resp) { String action = req.getParameter("action"); if ("testSurveyOrdering".equals(action)) { SurveyGroupDAO sgDao = new SurveyGroupDAO(); SurveyGroup sgItem = sgDao.list("all").get(0); sgItem = sgDao.getByKey(sgItem.getKey().getId(), true); } else if ("resetLRAP".equals(action)) { try { AccessPointDao apDao = new AccessPointDao(); for (AccessPoint ap : apDao.list("all")) { if ((ap.getCountryCode() == null || ap.getCountryCode() .equals("US")) && (ap.getLatitude() != null && ap.getLongitude() != null)) { if (ap.getLatitude() > 5.9 && ap.getLatitude() < 8) { if (ap.getLongitude() < -9 && ap.getLongitude() > -11) { ap.setCountryCode("LR"); apDao.save(ap); resp .getWriter() .println( "Found " + ap.getCommunityCode() + "mapped to US changing mapping to LR"); } } } else if (ap.getCommunityCode() == null) { ap.setCommunityCode(new Random().toString()); apDao.save(ap); resp.getWriter().println( "Found " + ap.getCommunityCode() + "added random community code"); } } } catch (IOException e) { log.log(Level.SEVERE, "Could not execute test", e); } } else if ("clearSurveyInstanceQAS".equals(action)) { // QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); // for (QuestionAnswerStore qas : qasDao.list("all")) { // qasDao.delete(qas); // } // SurveyInstanceDAO siDao = new SurveyInstanceDAO(); // for (SurveyInstance si : siDao.list("all")) { // siDao.delete(si); // } AccessPointDao apDao = new AccessPointDao(); for (AccessPoint ap : apDao.list("all")) apDao.delete(ap); } else if ("SurveyInstance".equals(action)) { SurveyInstanceDAO siDao = new SurveyInstanceDAO(); List<SurveyInstance> siList = siDao.listSurveyInstanceBySurveyId( 1362011L, null); Cursor cursor = JDOCursorHelper.getCursor(siList); int i = 0; while (siList.size() > 0) { for (SurveyInstance si : siList) { System.out.println(i++ + " " + si.toString()); String surveyInstanceId = new Long(si.getKey().getId()) .toString(); Queue queue = QueueFactory.getDefaultQueue(); queue.add(url("/app_worker/surveytask").param("action", "reprocessMapSurveyInstance").param("id", surveyInstanceId)); log.info("submiting task for SurveyInstanceId: " + surveyInstanceId); } siList = siDao.listSurveyInstanceBySurveyId(1362011L, cursor .toWebSafeString()); cursor = JDOCursorHelper.getCursor(siList); } System.out.println("finished"); } else if ("rotateImage".equals(action)) { AccessPointManagerServiceImpl apmI = new AccessPointManagerServiceImpl(); String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg"; // String test2 = // "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg"; writeImageToResponse(resp, test1); apmI.setUploadS3Flag(false); writeImageToResponse(resp, apmI.rotateImage(test1)); // apmI.rotateImage(test2); } else if ("clearSurveyGroupGraph".equals(action)) { SurveyGroupDAO sgDao = new SurveyGroupDAO(); sgDao.delete(sgDao.list("all")); SurveyDAO surveyDao = new SurveyDAO(); surveyDao.delete(surveyDao.list("all")); QuestionGroupDao qgDao = new QuestionGroupDao(); qgDao.delete(qgDao.list("all")); QuestionDao qDao = new QuestionDao(); qDao.delete(qDao.list("all")); QuestionHelpMediaDao qhDao = new QuestionHelpMediaDao(); qhDao.delete(qhDao.list("all")); QuestionOptionDao qoDao = new QuestionOptionDao(); qoDao.delete(qoDao.list("all")); TranslationDao tDao = new TranslationDao(); tDao.delete(tDao.list("all")); /* * createSurveyGroupGraph(resp); //SurveyGroupDAO sgDao = new * SurveyGroupDAO(); List<SurveyGroup> sgList = sgDao.list("all"); * Survey survey = sgList.get(0).getSurveyList().get(0); * QuestionAnswerStore qas = new QuestionAnswerStore(); * qas.setArbitratyNumber(1L); * qas.setSurveyId(survey.getKey().getId()); qas.setQuestionID("1"); * qas.setValue("test"); QuestionAnswerStoreDao qasDao = new * QuestionAnswerStoreDao(); qasDao.save(qas); * * * for(SurveyGroup sg: sgList) sgDao.delete(sg); */ } else if ("replicateDeviceFiles".equals(action)) { SurveyInstanceDAO siDao = new SurveyInstanceDAO(); for (SurveyInstance si : siDao.list("all")) { siDao.delete(si); } QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); for (QuestionAnswerStore qas : qasDao.list("all")) { qasDao.delete(qas); } DeviceFilesDao dfDao = new DeviceFilesDao(); for (DeviceFiles df : dfDao.list("all")) { dfDao.delete(df); } DeviceFilesReplicationImporter dfri = new DeviceFilesReplicationImporter(); dfri.executeImport("http://watermapmonitordev.appspot.com", "http://localhost:8888"); Set<String> dfSet = new HashSet<String>(); for (DeviceFiles df : dfDao.list("all")) { dfSet.add(df.getURI()); } DeviceFilesServiceImpl dfsi = new DeviceFilesServiceImpl(); int i = 0; try { resp.getWriter().println( "Found " + dfSet.size() + " distinct files to process"); for (String s : dfSet) { dfsi.reprocessDeviceFile(s); resp.getWriter().println( "submitted " + s + " for reprocessing"); i++; if (i > 10) break; } } catch (IOException e) { log.log(Level.SEVERE, "Could not execute test", e); } } else if ("addDeviceFiles".equals(action)) { DeviceFilesDao dfDao = new DeviceFilesDao(); DeviceFiles df = new DeviceFiles(); df .setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip"); df.setCreatedDateTime(new Date()); df.setPhoneNumber("a4:ed:4e:54:ef:6d"); df.setChecksum("1149406886"); df.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP); DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd"); java.util.Date date = new java.util.Date(); String dateTime = dateFormat.format(date); df.setProcessDate(dateTime); dfDao.save(df); } else if ("testBaseDomain".equals(action)) { SurveyDAO surveyDAO = new SurveyDAO(); String outString = surveyDAO.getForTest(); BaseDAO<AccessPoint> pointDao = new BaseDAO<AccessPoint>( AccessPoint.class); AccessPoint point = new AccessPoint(); point.setLatitude(78d); point.setLongitude(43d); pointDao.save(point); try { resp.getWriter().print(outString); } catch (IOException e) { log.log(Level.SEVERE, "Could not execute test", e); } } else if ("testSaveRegion".equals(action)) { GeoRegionHelper geoHelp = new GeoRegionHelper(); ArrayList<String> regionLines = new ArrayList<String>(); for (int i = 0; i < 10; i++) { StringBuilder builder = new StringBuilder(); builder.append("1,").append("" + i).append(",test,").append( 20 + i + ",").append(30 + i + "\n"); regionLines.add(builder.toString()); } geoHelp.processRegionsSurvey(regionLines); try { resp.getWriter().print("Save complete"); } catch (IOException e) { log.log(Level.SEVERE, "Could not save test region", e); } } else if ("clearAccessPoint".equals(action)) { try { AccessPointDao apDao = new AccessPointDao(); for (AccessPoint ap : apDao.list("all")) { apDao.delete(ap); try { resp.getWriter().print( "Finished Deleting AP: " + ap.toString()); } catch (IOException e) { log.log(Level.SEVERE, "Could not delete ap"); } } resp.getWriter().print("Deleted AccessPoints complete"); BaseDAO<AccessPointStatusSummary> apsDao = new BaseDAO<AccessPointStatusSummary>( AccessPointStatusSummary.class); for (AccessPointStatusSummary item : apsDao.list("all")) { apsDao.delete(item); } resp.getWriter().print("Deleted AccessPointStatusSummary"); MapFragmentDao mfDao = new MapFragmentDao(); for (MapFragment item : mfDao.list("all")) { mfDao.delete(item); } resp.getWriter().print("Cleared MapFragment Table"); } catch (IOException e) { log.log(Level.SEVERE, "Could not clear AP and APStatusSummary", e); } } else if ("loadErrorPoints".equals(action)) { MapFragmentDao mfDao = new MapFragmentDao(); AccessPointDao apDao = new AccessPointDao(); for (int j = 0; j < 1; j++) { Double lat = 0.0; Double lon = 0.0; for (int i = 0; i < 5; i++) { AccessPoint ap = new AccessPoint(); ap.setLatitude(lat); ap.setLongitude(lon); Calendar calendar = Calendar.getInstance(); Date today = new Date(); calendar.setTime(today); calendar.add(Calendar.YEAR, -1 * i); System.out .println("AP: " + ap.getLatitude() + "/" + ap.getLongitude() + "Date: " + calendar.getTime()); ap.setCollectionDate(calendar.getTime()); ap.setAltitude(0.0); ap.setCommunityCode("test" + new Date()); ap.setCommunityName("test" + new Date()); ap.setPhotoURL("http://test.com"); ap.setPointType(AccessPoint.AccessPointType.WATER_POINT); if (i == 0) ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH); else if (i == 1) ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK); else if (i == 2) ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS); else ap.setPointStatus(Status.NO_IMPROVED_SYSTEM); if (i % 2 == 0) ap.setTypeTechnologyString("Kiosk"); else ap.setTypeTechnologyString("Afridev Handpump"); apDao.save(ap); MapSummarizer ms = new MapSummarizer(); // ms.performSummarization("" + ap.getKey().getId(), ""); if (i % 50 == 0) log.log(Level.INFO, "Loaded to " + i); } } try { resp.getWriter().println("Finished loading aps"); } catch (IOException e) { e.printStackTrace(); } } else if ("loadLots".equals(action)) { MapFragmentDao mfDao = new MapFragmentDao(); AccessPointDao apDao = new AccessPointDao(); for (int j = 0; j < 1; j++) { double lat = -15 + (new Random().nextDouble() / 10); double lon = 35 + (new Random().nextDouble() / 10); for (int i = 0; i < 15; i++) { AccessPoint ap = new AccessPoint(); ap.setLatitude(lat); ap.setLongitude(lon); Calendar calendar = Calendar.getInstance(); Date today = new Date(); calendar.setTime(today); calendar.add(Calendar.YEAR, -1 * i); System.out .println("AP: " + ap.getLatitude() + "/" + ap.getLongitude() + "Date: " + calendar.getTime()); // ap.setCollectionDate(calendar.getTime()); ap.setAltitude(0.0); ap.setCommunityCode("test" + new Date()); ap.setCommunityName("test" + new Date()); ap .setPhotoURL("http://waterforpeople.s3.amazonaws.com/images/peru/pc28water.jpg"); ap.setProvideAdequateQuantity(true); ap.setHasSystemBeenDown1DayFlag(false); ap.setMeetGovtQualityStandardFlag(true); ap.setMeetGovtQuantityStandardFlag(false); ap.setCurrentManagementStructurePoint("Community Board"); ap.setDescription("Waterpoint"); ap.setDistrict("test district"); ap.setEstimatedHouseholds(100L); ap.setEstimatedPeoplePerHouse(11L); ap.setFarthestHouseholdfromPoint("Yes"); ap.setNumberOfHouseholdsUsingPoint(100L); ap.setConstructionDateYear("2001"); ap.setCostPer(1.0); ap.setCountryCode("MW"); ap.setConstructionDate(new Date()); ap.setCollectionDate(new Date()); ap.setPhotoName("Water point"); if (i % 2 == 0) ap .setPointType(AccessPoint.AccessPointType.WATER_POINT); else if (i % 3 == 0) ap .setPointType(AccessPoint.AccessPointType.SANITATION_POINT); else ap .setPointType(AccessPoint.AccessPointType.PUBLIC_INSTITUTION); if (i == 0) ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH); else if (i == 1) ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK); else if (i == 2) ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS); else ap.setPointStatus(Status.NO_IMPROVED_SYSTEM); if (i % 2 == 0) ap.setTypeTechnologyString("Kiosk"); else ap.setTypeTechnologyString("Afridev Handpump"); apDao.save(ap); MapSummarizer ms = new MapSummarizer(); // ms.performSummarization("" + ap.getKey().getId(), ""); if (i % 50 == 0) log.log(Level.INFO, "Loaded to " + i); } } try { resp.getWriter().println("Finished loading aps"); } catch (IOException e) { e.printStackTrace(); } } else if ("loadCountries".equals(action)) { Country c = new Country(); c.setIsoAlpha2Code("HN"); c.setName("Honduras"); BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class); countryDAO.save(c); Country c2 = new Country(); c2.setIsoAlpha2Code("MW"); c2.setName("Malawi"); countryDAO.save(c2); } else if ("testAPKml".equals(action)) { MapFragmentDao mfDao = new MapFragmentDao(); BaseDAO<TechnologyType> ttDao = new BaseDAO<TechnologyType>( TechnologyType.class); List<TechnologyType> ttList = ttDao.list("all"); for (TechnologyType tt : ttList) ttDao.delete(tt); TechnologyType tt = new TechnologyType(); tt.setCode("Afridev Handpump"); tt.setName("Afridev Handpump"); ttDao.save(tt); TechnologyType tt2 = new TechnologyType(); tt2.setCode("Kiosk"); tt2.setName("Kiosk"); ttDao.save(tt2); KMLHelper kmlHelper = new KMLHelper(); kmlHelper.buildMap(); List<MapFragment> mfList = mfDao.searchMapFragments("ALL", null, null, null, FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all", null, null); try { for (MapFragment mfItem : mfList) { String contents = ZipUtil .unZip(mfItem.getBlob().getBytes()); log .log(Level.INFO, "Contents Length: " + contents.length()); resp.setContentType("application/vnd.google-earth.kmz+xml"); ServletOutputStream out = resp.getOutputStream(); resp.setHeader("Content-Disposition", "inline; filename=waterforpeoplemapping.kmz;"); out.write(mfItem.getBlob().getBytes()); out.flush(); } } catch (IOException ie) { log.log(Level.SEVERE, "Could not list fragment"); } } else if ("deleteSurveyGraph".equals(action)) { deleteAll(SurveyGroup.class); deleteAll(Survey.class); deleteAll(QuestionGroup.class); deleteAll(Question.class); deleteAll(Translation.class); deleteAll(QuestionOption.class); deleteAll(QuestionHelpMedia.class); try { resp.getWriter().println("Finished deleting survey graph"); } catch (IOException iex) { log.log(Level.SEVERE, "couldn't delete surveyGraph" + iex); } } else if ("saveSurveyGroupRefactor".equals(action)) { SurveyGroupDAO sgDao = new SurveyGroupDAO(); createSurveyGroupGraph(resp); try { List<SurveyGroup> savedSurveyGroups = sgDao.list("all"); for (SurveyGroup sgItem : savedSurveyGroups) { resp.getWriter().println("SG: " + sgItem.getCode()); for (Survey survey : sgItem.getSurveyList()) { resp.getWriter().println( " Survey:" + survey.getName()); for (Map.Entry<Integer, QuestionGroup> entry : survey .getQuestionGroupMap().entrySet()) { resp.getWriter().println( " QuestionGroup: " + entry.getKey() + ":" + entry.getValue().getDesc()); for (Map.Entry<Integer, Question> questionEntry : entry .getValue().getQuestionMap().entrySet()) { resp.getWriter().println( " Question" + questionEntry.getKey() + ":" + questionEntry.getValue() .getText()); for (Map.Entry<Integer, QuestionHelpMedia> qhmEntry : questionEntry .getValue().getQuestionHelpMediaMap() .entrySet()) { resp.getWriter().println( " QuestionHelpMedia" + qhmEntry.getKey() + ":" + qhmEntry.getValue() .getText()); /* * for (Key tKey : qhmEntry.getValue() * .getAltTextKeyList()) { Translation t = * tDao.getByKey(tKey); * resp.getWriter().println( * " QHMAltText" + * t.getLanguageCode() + ":" + t.getText()); * } */ } } } } } } catch (IOException e) { log.log(Level.SEVERE, "Could not save sg"); } } else if ("createAP".equals(action)) { AccessPoint ap = new AccessPoint(); ap.setCollectionDate(new Date()); ap.setCommunityCode(new Random().toString()); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setCountryCode("SZ"); ap.setPointType(AccessPointType.WATER_POINT); AccessPointHelper helper = new AccessPointHelper(); helper.saveAccessPoint(ap); } else if ("createInstance".equals(action)) { SurveyInstance si = new SurveyInstance(); si.setCollectionDate(new Date()); ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>(); QuestionAnswerStore ans = new QuestionAnswerStore(); ans.setQuestionID("q2"); ans.setValue("Geneva"); store.add(ans); si.setQuestionAnswersStore(store); SurveyInstanceDAO dao = new SurveyInstanceDAO(); si = dao.save(si); Queue summQueue = QueueFactory.getQueue("dataSummarization"); summQueue.add(url("/app_worker/datasummarization").param( "objectKey", si.getKey().getId() + "").param("type", "SurveyInstance")); } else if ("createCommunity".equals(action)) { CommunityDao dao = new CommunityDao(); Country c = new Country(); c.setIsoAlpha2Code("CA"); c.setName("Canada"); c.setDisplayName("Canada"); Community comm = new Community(); comm.setCommunityCode("ON"); dao.save(c); comm.setCountryCode("CA"); comm.setLat(54.99); comm.setLon(-74.72); dao.save(comm); c = new Country(); c.setIsoAlpha2Code("US"); c.setName("United States"); c.setDisplayName("Unites States"); comm = new Community(); comm.setCommunityCode("Omaha"); comm.setCountryCode("US"); comm.setLat(34.99); comm.setLon(-74.72); dao.save(c); dao.save(comm); } else if ("addPhone".equals(action)) { String phoneNumber = req.getParameter("phoneNumber"); Device d = new Device(); d.setPhoneNumber(phoneNumber); d.setDeviceType(DeviceType.CELL_PHONE_ANDROID); if (req.getParameter("esn") != null) d.setEsn(req.getParameter("esn")); if (req.getParameter("gallatinSoftwareManifest") != null) d.setGallatinSoftwareManifest(req .getParameter("gallatinSoftwareManifest")); d.setInServiceDate(new Date()); DeviceDAO deviceDao = new DeviceDAO(); deviceDao.save(d); try { resp.getWriter().println("finished adding " + phoneNumber); } catch (Exception e) { e.printStackTrace(); } } else if ("createAPSummary".equals(action)) { AccessPointStatusSummary sum = new AccessPointStatusSummary(); sum.setCommunity("ON"); sum.setCountry("CA"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2000"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao(); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("ON"); sum.setCountry("CA"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2001"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("ON"); sum.setCountry("CA"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2003"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("ON"); sum.setCountry("CA"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2004"); sum.setStatus(AccessPoint.Status.FUNCTIONING_OK); dao.save(sum); sum.setCommunity("NY"); sum.setCountry("US"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2000"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("NY"); sum.setCountry("US"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2001"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("NY"); sum.setCountry("US"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2003"); sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH); dao.save(sum); sum = new AccessPointStatusSummary(); sum.setCommunity("NY"); sum.setCountry("US"); sum.setType(AccessPointType.WATER_POINT.toString()); sum.setYear("2004"); sum.setStatus(AccessPoint.Status.FUNCTIONING_OK); dao.save(sum); } else if ("createApHistory".equals(action)) { GregorianCalendar cal = new GregorianCalendar(); AccessPointHelper apHelper = new AccessPointHelper(); AccessPoint ap = new AccessPoint(); cal.set(Calendar.YEAR, 2000); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(300l); ap.setCostPer(43.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2001); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(317l); ap.setCostPer(40.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2002); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(340l); ap.setCostPer(37.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2003); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_HIGH); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(340l); ap.setCostPer(34.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2004); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Geneva"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(47.3); ap.setLongitude(9d); ap.setNumberOfHouseholdsUsingPoint(338l); ap.setCostPer(38.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2000); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_HIGH); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(170l); ap.setCostPer(19.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2001); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_HIGH); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(201l); ap.setCostPer(19.00); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2002); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_HIGH); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(211l); ap.setCostPer(17.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2003); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(220l); ap.setCostPer(25.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); ap = new AccessPoint(); cal.set(Calendar.YEAR, 2004); ap.setCollectionDate(cal.getTime()); ap.setCommunityCode("Omaha"); ap.setPointStatus(Status.FUNCTIONING_OK); ap.setLatitude(40.87d); ap.setLongitude(-95.2d); ap.setNumberOfHouseholdsUsingPoint(175l); ap.setCostPer(24.20); ap.setPointType(AccessPointType.WATER_POINT); apHelper.saveAccessPoint(ap); } else if ("generateGeocells".equals(action)) { AccessPointDao apDao = new AccessPointDao(); List<AccessPoint> apList = apDao.list(null); if (apList != null) { for (AccessPoint ap : apList) { if (ap.getGeocells() == null || ap.getGeocells().size() == 0) { if (ap.getLatitude() != null && ap.getLongitude() != null) { ap .setGeocells(GeocellManager .generateGeoCell(new Point(ap .getLatitude(), ap .getLongitude()))); apDao.save(ap); } } } } } else if ("loadExistingSurvey".equals(action)) { SurveyGroup sg = new SurveyGroup(); sg.setKey(KeyFactory.createKey(SurveyGroup.class.getSimpleName(), 2L)); sg.setName("test" + new Date()); sg.setCode("test" + new Date()); SurveyGroupDAO sgDao = new SurveyGroupDAO(); sgDao.save(sg); Survey s = new Survey(); s.setKey(KeyFactory.createKey(Survey.class.getSimpleName(), 2L)); s.setName("test" + new Date()); s.setSurveyGroupId(sg.getKey().getId()); SurveyDAO surveyDao = new SurveyDAO(); surveyDao.save(s); } else if ("saveAPMapping".equals(action)) { SurveyAttributeMapping mapping = new SurveyAttributeMapping(); mapping.setAttributeName("status"); mapping.setObjectName(AccessPoint.class.getCanonicalName()); mapping.setSurveyId(1L); mapping.setSurveyQuestionId("q1"); SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao(); samDao.save(mapping); } else if ("listAPMapping".equals(action)) { SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao(); List<SurveyAttributeMapping> mappings = samDao .listMappingsBySurvey(1L); if (mappings != null) { System.out.println(mappings.size()); } } else if ("saveSurveyGroup".equals(action)) { try { SurveyGroupDAO sgDao = new SurveyGroupDAO(); List<SurveyGroup> sgList = sgDao.list("all"); for (SurveyGroup sg : sgList) { sgDao.delete(sg); } resp.getWriter().println("Deleted all survey groups"); SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); for (Survey survey : surveyList) { try { surveyDao.delete(survey); } catch (IllegalDeletionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } resp.getWriter().println("Deleted all surveys"); resp.getWriter().println("Deleted all surveysurveygroupassocs"); QuestionGroupDao qgDao = new QuestionGroupDao(); List<QuestionGroup> qgList = qgDao.list("all"); for (QuestionGroup qg : qgList) { qgDao.delete(qg); } resp.getWriter().println("Deleted all question groups"); QuestionDao qDao = new QuestionDao(); List<Question> qList = qDao.list("all"); for (Question q : qList) { try { qDao.delete(q); } catch (IllegalDeletionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } resp.getWriter().println("Deleted all Questions"); QuestionOptionDao qoDao = new QuestionOptionDao(); List<QuestionOption> qoList = qoDao.list("all"); for (QuestionOption qo : qoList) qoDao.delete(qo); resp.getWriter().println("Deleted all QuestionOptions"); resp.getWriter().println("Deleted all questions"); resp.getWriter().println( "Finished deleting and reloading SurveyGroup graph"); } catch (IOException e) { e.printStackTrace(); } } else if ("testPublishSurvey".equals(action)) { try { SurveyGroupDto sgDto = new SurveyServiceImpl() .listSurveyGroups(null, true, false, false).get(0); resp.getWriter().println( "Got Survey Group: " + sgDto.getCode() + " Survey: " + sgDto.getSurveyList().get(0).getKeyId()); SurveyContainerDao scDao = new SurveyContainerDao(); SurveyContainer sc = scDao.findBySurveyId(sgDto.getSurveyList() .get(0).getKeyId()); if (sc != null) { scDao.delete(sc); resp.getWriter().println( "Deleted existing SurveyContainer for: " + sgDto.getSurveyList().get(0).getKeyId()); } resp.getWriter().println( "Result of publishing survey: " + new SurveyServiceImpl().publishSurvey(sgDto .getSurveyList().get(0).getKeyId())); sc = scDao.findBySurveyId(sgDto.getSurveyList().get(0) .getKeyId()); resp.getWriter().println( "Survey Document result from publish: \n\n\n\n" + sc.getSurveyDocument().getValue()); } catch (IOException ex) { ex.printStackTrace(); } } else if ("createTestSurveyForEndToEnd".equals(action)) { createTestSurveyForEndToEnd(); } else if ("deleteSurveyFragments".equals(action)) { deleteAll(SurveyXMLFragment.class); } else if ("migratePIToSchool".equals(action)) { try { resp.getWriter().println( "Has more? " + migratePointType( AccessPointType.PUBLIC_INSTITUTION, AccessPointType.SCHOOL)); } catch (IOException e) { e.printStackTrace(); } } else if ("createDevice".equals(action)) { DeviceDAO devDao = new DeviceDAO(); Device device = new Device(); device.setPhoneNumber("9175667663"); device.setDeviceType(DeviceType.CELL_PHONE_ANDROID); devDao.save(device); } else if ("reprocessSurveys".equals(action)) { try { reprocessSurveys(req.getParameter("date")); } catch (ParseException e) { try { resp.getWriter().println("Couldn't reprocess: " + e); } catch (IOException e1) { e1.printStackTrace(); } } } else if ("importallsurveys".equals(action)) { // Only run in dev hence hardcoding SurveyReplicationImporter sri = new SurveyReplicationImporter(); sri.executeImport("http://watermapmonitordev.appspot.com", "http://localhost:8888"); // sri.executeImport("http://localhost:8888", // "http://localhost:8888"); } else if ("deleteSurveyResponses".equals(action)) { if (req.getParameter("surveyId") == null) { try { resp.getWriter() .println("surveyId is a required parameter"); } catch (IOException e1) { e1.printStackTrace(); } } else { deleteSurveyResponses(Integer.parseInt(req .getParameter("surveyId")), Integer.parseInt(req .getParameter("count"))); } } else if ("fixNameQuestion".equals(action)) { if (req.getParameter("questionId") == null) { try { resp.getWriter().println( "questionId is a required parameter"); } catch (IOException e1) { e1.printStackTrace(); } } else { fixNameQuestion(req.getParameter("questionId")); } } else if ("createSurveyAssignment".equals(action)) { Device device = new Device(); device.setDeviceType(DeviceType.CELL_PHONE_ANDROID); device.setPhoneNumber("1111111111"); device.setInServiceDate(new Date()); BaseDAO<Device> deviceDao = new BaseDAO<Device>(Device.class); deviceDao.save(device); SurveyAssignmentServiceImpl sasi = new SurveyAssignmentServiceImpl(); SurveyAssignmentDto dto = new SurveyAssignmentDto(); SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); SurveyAssignment sa = new SurveyAssignment(); BaseDAO<SurveyAssignment> surveyAssignmentDao = new BaseDAO<SurveyAssignment>( SurveyAssignment.class); sa.setCreatedDateTime(new Date()); sa.setCreateUserId(-1L); ArrayList<Long> deviceList = new ArrayList<Long>(); deviceList.add(device.getKey().getId()); sa.setDeviceIds(deviceList); ArrayList<SurveyDto> surveyDtoList = new ArrayList<SurveyDto>(); for (Survey survey : surveyList) { sa.addSurvey(survey.getKey().getId()); SurveyDto surveyDto = new SurveyDto(); surveyDto.setKeyId(survey.getKey().getId()); surveyDtoList.add(surveyDto); } sa.setStartDate(new Date()); sa.setEndDate(new Date()); sa.setName(new Date().toString()); DeviceDto deviceDto = new DeviceDto(); deviceDto.setKeyId(device.getKey().getId()); deviceDto.setPhoneNumber(device.getPhoneNumber()); ArrayList<DeviceDto> deviceDtoList = new ArrayList<DeviceDto>(); deviceDtoList.add(deviceDto); dto.setDevices(deviceDtoList); dto.setSurveys(surveyDtoList); dto.setEndDate(new Date()); dto.setLanguage("en"); dto.setName("Test Assignment: " + new Date().toString()); dto.setStartDate(new Date()); sasi.saveSurveyAssignment(dto); // sasi.deleteSurveyAssignment(dto); } else if ("populateAssignmentId".equalsIgnoreCase(action)) { populateAssignmentId(Long.parseLong(req .getParameter("assignmentId"))); } else if ("testDSJQDelete".equals(action)) { DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO(); Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, -10); Date then = cal.getTime(); DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue(); dsjq.setDevicePhoneNumber("2019561591"); dsjq.setEffectiveEndDate(then); Random rand = new Random(); dsjq.setAssignmentId(rand.nextLong()); dsjDAO.save(dsjq); DeviceSurveyJobQueue dsjq2 = new DeviceSurveyJobQueue(); dsjq2.setDevicePhoneNumber("2019561591"); cal.add(Calendar.DAY_OF_MONTH, 20); dsjq2.setEffectiveEndDate(cal.getTime()); dsjq2.setAssignmentId(rand.nextLong()); dsjDAO.save(dsjq2); DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO(); List<DeviceSurveyJobQueue> dsjqList = dsjqDao .listAssignmentsWithEarlierExpirationDate(new Date()); for (DeviceSurveyJobQueue item : dsjqList) { SurveyTaskUtil.spawnDeleteTask("deleteDeviceSurveyJobQueue", item.getAssignmentId()); } } else if ("loadDSJ".equals(action)) { SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); for (Survey item : surveyList) { DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO(); Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, -10); Date then = cal.getTime(); DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue(); dsjq.setDevicePhoneNumber("2019561591"); dsjq.setEffectiveEndDate(then); Random rand = new Random(); dsjq.setAssignmentId(rand.nextLong()); dsjq.setSurveyID(item.getKey().getId()); dsjDAO.save(dsjq); } for (int i = 0; i < 20; i++) { DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO(); Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, -10); Date then = cal.getTime(); DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue(); dsjq.setDevicePhoneNumber("2019561591"); dsjq.setEffectiveEndDate(then); Random rand = new Random(); dsjq.setAssignmentId(rand.nextLong()); dsjq.setSurveyID(rand.nextLong()); dsjDAO.save(dsjq); } try { resp.getWriter().println("finished"); } catch (IOException e1) { e1.printStackTrace(); } } else if ("deleteUnusedDSJQueue".equals(action)) { try { SurveyDAO surveyDao = new SurveyDAO(); List<Key> surveyIdList = surveyDao.listSurveyIds(); List<Long> ids = new ArrayList<Long>(); for (Key key : surveyIdList) ids.add(key.getId()); DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO(); List<DeviceSurveyJobQueue> deleteList = new ArrayList<DeviceSurveyJobQueue>(); for (DeviceSurveyJobQueue item : dsjqDao.listAllJobsInQueue()) { Long dsjqSurveyId = item.getSurveyID(); Boolean found = ids.contains(dsjqSurveyId); if (!found) { deleteList.add(item); resp.getWriter().println( "Marking " + item.getId() + " survey: " + item.getSurveyID() + " for deletion"); } } dsjqDao.delete(deleteList); resp.getWriter().println("finished"); } catch (IOException e1) { e1.printStackTrace(); } } else if ("testListTrace".equals(action)) { listStacktrace(); } else if ("createEditorialContent".equals(action)) { createEditorialContent(req.getParameter("pageName")); } else if ("generateEditorialContent".equals(action)) { try { resp.getWriter().print(generateEditorialContent(req.getParameter("pageName"))); } catch (IOException e) { e.printStackTrace(); } } } private String generateEditorialContent(String pageName) { String content = ""; EditorialPageDao dao = new EditorialPageDao(); EditorialPage p = dao.findByTargetPage(pageName); List<EditorialPageContent> contentList = dao.listContentByPage(p .getKey().getId()); try { RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices(); StringReader reader = new StringReader(p.getTemplate().getValue()); SimpleNode node = runtimeServices.parse(reader, "dynamicTemplate"); Template template = new Template(); template.setRuntimeServices(runtimeServices); template.setData(node); template.initDocument(); Context ctx = new VelocityContext(); ctx.put("pages", contentList); StringWriter writer = new StringWriter(); template.merge(ctx, writer); content = writer.toString(); } catch (Exception e) { log.log(Level.SEVERE, "Could not initialize velocity", e); } return content; } private void createEditorialContent(String pageName) { EditorialPageDao dao = new EditorialPageDao(); EditorialPage page = new EditorialPage(); page.setTargetFileName(pageName); page.setType("landing"); page .setTemplate(new Text("<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>")); page = dao.save(page); EditorialPageContent content = new EditorialPageContent(); List<EditorialPageContent> contentList = new ArrayList<EditorialPageContent>(); content.setHeading("Heading 1"); content.setText(new Text("this is some text")); content.setSortOrder(1L); content.setEditorialPageId(page.getKey().getId()); contentList.add(content); content = new EditorialPageContent(); content.setHeading("Heading 2"); content.setText(new Text("this is more text")); content.setSortOrder(2L); content.setEditorialPageId(page.getKey().getId()); contentList.add(content); dao.save(contentList); } private void listStacktrace() { RemoteStacktraceDao traceDao = new RemoteStacktraceDao(); List<RemoteStacktrace> result = null; result = traceDao.listStacktrace(null, null, false, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace(null, null, true, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace("12345", null, true, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace("12345", "12345", true, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace(null, "12345", true, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace("12345", null, false, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace("12345", "12345", false, null); if (result != null) { System.out.println(result.size() + ""); } result = traceDao.listStacktrace(null, "12345", false, null); if (result != null) { System.out.println(result.size() + ""); } } private void populateAssignmentId(Long assignmentId) { BaseDAO<SurveyAssignment> assignmentDao = new BaseDAO<SurveyAssignment>( SurveyAssignment.class); SurveyAssignment assignment = assignmentDao.getByKey(assignmentId); DeviceSurveyJobQueueDAO jobDao = new DeviceSurveyJobQueueDAO(); if (assignment != null) { for (Long sid : assignment.getSurveyIds()) { jobDao.updateAssignmentIdForSurvey(sid, assignmentId); } } } private void fixNameQuestion(String questionId) { Queue summQueue = QueueFactory.getQueue("dataUpdate"); summQueue.add(url("/app_worker/dataupdate").param("objectKey", questionId + "").param("type", "NameQuestionFix")); } private boolean deleteSurveyResponses(Integer surveyId, Integer count) { SurveyInstanceDAO dao = new SurveyInstanceDAO(); List<SurveyInstance> instances = dao.listSurveyInstanceBySurvey( new Long(surveyId), count != null ? count : 100); if (instances != null) { for (SurveyInstance instance : instances) { List<QuestionAnswerStore> questions = dao .listQuestionAnswerStore(instance.getKey().getId(), count); if (questions != null) { dao.delete(questions); } dao.delete(instance); } return true; } return false; } private void reprocessSurveys(String date) throws ParseException { SurveyInstanceDAO dao = new SurveyInstanceDAO(); Date startDate = null; if (date != null) { DateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); startDate = sdf.parse(date); List<SurveyInstance> instances = dao.listByDateRange(startDate, null, null); if (instances != null) { AccessPointHelper aph = new AccessPointHelper(); for (SurveyInstance instance : instances) { aph.processSurveyInstance(instance.getKey().getId() + ""); } } } } private boolean migratePointType(AccessPointType source, AccessPointType dest) { AccessPointDao pointDao = new AccessPointDao(); List<AccessPoint> list = pointDao.searchAccessPoints(null, null, null, null, source.toString(), null, null, null, null, null, null); if (list != null && list.size() > 0) { for (AccessPoint point : list) { point.setPointType(dest); pointDao.save(point); } } if (list != null && list.size() == 20) { return true; } else { return false; } } @SuppressWarnings("unchecked") private <T extends BaseDomain> void deleteAll(Class<T> type) { BaseDAO<T> baseDao = new BaseDAO(type); List<T> items = baseDao.list("all"); if (items != null) { for (T item : items) { baseDao.delete(item); } } } private void createTestSurveyForEndToEnd() { SurveyGroupDto sgd = new SurveyGroupDto(); sgd.setCode("E2E Test"); sgd.setDescription("end2end test"); SurveyDto surveyDto = new SurveyDto(); surveyDto.setDescription("e2e test"); SurveyServiceImpl surveySvc = new SurveyServiceImpl(); QuestionGroupDto qgd = new QuestionGroupDto(); qgd.setCode("Question Group 1"); qgd.setDescription("Question Group Desc"); QuestionDto qd = new QuestionDto(); qd.setText("Access Point Name:"); qd.setType(QuestionType.FREE_TEXT); qgd.addQuestion(qd, 0); qd = new QuestionDto(); qd.setText("Location:"); qd.setType(QuestionType.GEO); qgd.addQuestion(qd, 1); qd = new QuestionDto(); qd.setText("Photo"); qd.setType(QuestionType.PHOTO); qgd.addQuestion(qd, 2); surveyDto.addQuestionGroup(qgd); surveyDto.setVersion("Version: 1"); sgd.addSurvey(surveyDto); sgd = surveySvc.save(sgd); System.out.println(sgd.getKeyId()); } private void writeImageToResponse(HttpServletResponse resp, String urlString) { resp.setContentType("image/jpeg"); try { ServletOutputStream out = resp.getOutputStream(); URL url = new URL(urlString); InputStream in = url.openStream(); byte[] buffer = new byte[2048]; int size; while ((size = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, size); } in.close(); out.flush(); } catch (Exception ex) { } } private void writeImageToResponse(HttpServletResponse resp, byte[] imageBytes) { resp.setContentType("image/jpeg"); try { ServletOutputStream out = resp.getOutputStream(); out.write(imageBytes, 0, imageBytes.length); out.flush(); } catch (Exception ex) { } } private void createSurveyGroupGraph(HttpServletResponse resp) { com.gallatinsystems.survey.dao.SurveyGroupDAO sgDao = new com.gallatinsystems.survey.dao.SurveyGroupDAO(); BaseDAO<Translation> tDao = new BaseDAO<Translation>(Translation.class); for (Translation t : tDao.list("all")) tDao.delete(t); // clear out old surveys List<SurveyGroup> sgList = sgDao.list("all"); for (SurveyGroup item : sgList) sgDao.delete(item); try { resp.getWriter().println("Finished clearing surveyGroup table"); } catch (IOException e1) { e1.printStackTrace(); } SurveyDAO surveyDao = new SurveyDAO(); QuestionGroupDao questionGroupDao = new QuestionGroupDao(); QuestionDao questionDao = new QuestionDao(); QuestionOptionDao questionOptionDao = new QuestionOptionDao(); QuestionHelpMediaDao helpDao = new QuestionHelpMediaDao(); for (int i = 0; i < 2; i++) { com.gallatinsystems.survey.domain.SurveyGroup sg = new com.gallatinsystems.survey.domain.SurveyGroup(); sg.setCode(i + ":" + new Date()); sg.setName(i + ":" + new Date()); sg = sgDao.save(sg); for (int j = 0; j < 2; j++) { com.gallatinsystems.survey.domain.Survey survey = new com.gallatinsystems.survey.domain.Survey(); survey.setCode(j + ":" + new Date()); survey.setName(j + ":" + new Date()); survey.setSurveyGroupId(sg.getKey().getId()); survey.setPath(sg.getCode()); survey = surveyDao.save(survey); Translation t = new Translation(); t.setLanguageCode("es"); t.setText(j + ":" + new Date()); t.setParentType(ParentType.SURVEY_NAME); t.setParentId(survey.getKey().getId()); tDao.save(t); survey.addTranslation(t); for (int k = 0; k < 3; k++) { com.gallatinsystems.survey.domain.QuestionGroup qg = new com.gallatinsystems.survey.domain.QuestionGroup(); qg.setName("en:" + j + new Date()); qg.setDesc("en:desc: " + j + new Date()); qg.setCode("en:" + j + new Date()); qg.setSurveyId(survey.getKey().getId()); qg.setOrder(k); qg.setPath(sg.getCode() + "/" + survey.getCode()); qg = questionGroupDao.save(qg); Translation t2 = new Translation(); t2.setLanguageCode("es"); t2.setParentType(ParentType.QUESTION_GROUP_NAME); t2.setText("es:" + k + new Date()); t2.setParentId(qg.getKey().getId()); tDao.save(t2); qg.addTranslation(t2); for (int l = 0; l < 2; l++) { com.gallatinsystems.survey.domain.Question q = new com.gallatinsystems.survey.domain.Question(); q.setType(Type.OPTION); q.setAllowMultipleFlag(false); q.setAllowOtherFlag(false); q.setDependentFlag(false); q.setMandatoryFlag(true); q.setQuestionGroupId(qg.getKey().getId()); q.setOrder(l); q.setText("en:" + l + ":" + new Date()); q.setTip("en:" + l + ":" + new Date()); q.setPath(sg.getCode() + "/" + survey.getCode() + "/" + qg.getCode()); q.setSurveyId(survey.getKey().getId()); q = questionDao.save(q); Translation tq = new Translation(); tq.setLanguageCode("es"); tq.setText("es" + l + ":" + new Date()); tq.setParentType(ParentType.QUESTION_TEXT); tq.setParentId(q.getKey().getId()); tDao.save(tq); q.addTranslation(tq); for (int m = 0; m < 10; m++) { com.gallatinsystems.survey.domain.QuestionOption qo = new com.gallatinsystems.survey.domain.QuestionOption(); qo.setOrder(m); qo.setText(m + ":" + new Date()); qo.setCode(m + ":" + new Date()); qo.setQuestionId(q.getKey().getId()); qo = questionOptionDao.save(qo); Translation tqo = new Translation(); tqo.setLanguageCode("es"); tqo.setText("es:" + m + ":" + new Date()); tqo.setParentType(ParentType.QUESTION_OPTION); tqo.setParentId(qo.getKey().getId()); tDao.save(tqo); qo.addTranslation(tqo); q.addQuestionOption(qo); } for (int n = 0; n < 10; n++) { com.gallatinsystems.survey.domain.QuestionHelpMedia qhm = new com.gallatinsystems.survey.domain.QuestionHelpMedia(); qhm.setText("en:" + n + ":" + new Date()); qhm.setType(QuestionHelpMedia.Type.PHOTO); qhm.setResourceUrl("http://test.com/" + n + ".jpg"); qhm.setQuestionId(q.getKey().getId()); qhm = helpDao.save(qhm); Translation tqhm = new Translation(); tqhm.setLanguageCode("es"); tqhm.setText("es:" + n + ":" + new Date()); tqhm .setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT); tqhm.setParentId(qhm.getKey().getId()); tDao.save(tqhm); qhm.addTranslation(tqhm); q.addHelpMedia(n, qhm); } qg.addQuestion(l, q); } survey.addQuestionGroup(k, qg); } sg.addSurvey(survey); } log .log(Level.INFO, "Finished Saving sg: " + sg.getKey().toString()); } } }
loadOGRFeature action
GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
loadOGRFeature action
<ide><path>AE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java <ide> import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary; <ide> import org.waterforpeople.mapping.app.gwt.client.device.DeviceDto; <ide> import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto; <add>import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType; <ide> import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto; <ide> import org.waterforpeople.mapping.app.gwt.client.survey.SurveyAssignmentDto; <ide> import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto; <ide> import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto; <del>import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType; <ide> import org.waterforpeople.mapping.app.gwt.server.accesspoint.AccessPointManagerServiceImpl; <ide> import org.waterforpeople.mapping.app.gwt.server.devicefiles.DeviceFilesServiceImpl; <ide> import org.waterforpeople.mapping.app.gwt.server.survey.SurveyAssignmentServiceImpl; <ide> import org.waterforpeople.mapping.dataexport.DeviceFilesReplicationImporter; <ide> import org.waterforpeople.mapping.dataexport.SurveyReplicationImporter; <ide> import org.waterforpeople.mapping.domain.AccessPoint; <add>import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; <add>import org.waterforpeople.mapping.domain.AccessPoint.Status; <ide> import org.waterforpeople.mapping.domain.Community; <ide> import org.waterforpeople.mapping.domain.QuestionAnswerStore; <add>import org.waterforpeople.mapping.domain.Status.StatusCode; <ide> import org.waterforpeople.mapping.domain.SurveyAssignment; <ide> import org.waterforpeople.mapping.domain.SurveyAttributeMapping; <ide> import org.waterforpeople.mapping.domain.SurveyInstance; <ide> import org.waterforpeople.mapping.domain.TechnologyType; <del>import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; <del>import org.waterforpeople.mapping.domain.AccessPoint.Status; <del>import org.waterforpeople.mapping.domain.Status.StatusCode; <ide> import org.waterforpeople.mapping.helper.AccessPointHelper; <ide> import org.waterforpeople.mapping.helper.GeoRegionHelper; <ide> import org.waterforpeople.mapping.helper.KMLHelper; <ide> import com.gallatinsystems.common.util.ZipUtil; <ide> import com.gallatinsystems.device.dao.DeviceDAO; <ide> import com.gallatinsystems.device.domain.Device; <add>import com.gallatinsystems.device.domain.Device.DeviceType; <ide> import com.gallatinsystems.device.domain.DeviceFiles; <ide> import com.gallatinsystems.device.domain.DeviceSurveyJobQueue; <del>import com.gallatinsystems.device.domain.Device.DeviceType; <ide> import com.gallatinsystems.diagnostics.dao.RemoteStacktraceDao; <ide> import com.gallatinsystems.diagnostics.domain.RemoteStacktrace; <ide> import com.gallatinsystems.editorial.dao.EditorialPageDao; <ide> import com.gallatinsystems.framework.exceptions.IllegalDeletionException; <ide> import com.gallatinsystems.gis.geography.domain.Country; <ide> import com.gallatinsystems.gis.map.dao.MapFragmentDao; <add>import com.gallatinsystems.gis.map.domain.Geometry; <ide> import com.gallatinsystems.gis.map.domain.MapFragment; <ide> import com.gallatinsystems.gis.map.domain.MapFragment.FRAGMENTTYPE; <add>import com.gallatinsystems.gis.map.domain.OGRFeature; <ide> import com.gallatinsystems.survey.dao.DeviceSurveyJobQueueDAO; <ide> import com.gallatinsystems.survey.dao.QuestionDao; <ide> import com.gallatinsystems.survey.dao.QuestionGroupDao; <ide> import com.gallatinsystems.survey.dao.SurveyTaskUtil; <ide> import com.gallatinsystems.survey.dao.TranslationDao; <ide> import com.gallatinsystems.survey.domain.Question; <add>import com.gallatinsystems.survey.domain.Question.Type; <ide> import com.gallatinsystems.survey.domain.QuestionGroup; <ide> import com.gallatinsystems.survey.domain.QuestionHelpMedia; <ide> import com.gallatinsystems.survey.domain.QuestionOption; <ide> import com.gallatinsystems.survey.domain.SurveyGroup; <ide> import com.gallatinsystems.survey.domain.SurveyXMLFragment; <ide> import com.gallatinsystems.survey.domain.Translation; <del>import com.gallatinsystems.survey.domain.Question.Type; <ide> import com.gallatinsystems.survey.domain.Translation.ParentType; <ide> import com.google.appengine.api.datastore.Cursor; <ide> import com.google.appengine.api.datastore.Key; <ide> SurveyGroupDAO sgDao = new SurveyGroupDAO(); <ide> SurveyGroup sgItem = sgDao.list("all").get(0); <ide> sgItem = sgDao.getByKey(sgItem.getKey().getId(), true); <del> <add> } else if ("loadOGRFeature".equals(action)) { <add> OGRFeature ogrFeature = new OGRFeature(); <add> ogrFeature.setName("clan-21061011"); <add> ogrFeature.setProjectCoordinateSystemIdentifier("World_Mercator"); <add> ogrFeature.setGeoCoordinateSystemIdentifier("GCS_WGS_1984"); <add> ogrFeature.setDatumIdentifier("WGS_1984"); <add> ogrFeature.setSpheroid(6378137D); <add> ogrFeature.setReciprocalOfFlattening(298.257223563); <add> ogrFeature.setCountryCode("LR"); <add> ogrFeature.addBoundingBox(223700.015625, 481399.468750,680781.375000, 945462.437500); <add> Geometry geo = new Geometry(); <add> geo.setType("POLYGON"); <add> String coords = "497974.5625 557051.875,498219.03125 557141.75,498655.34375 557169.4375,499001.65625 557100.1875,499250.96875 556933.9375,499167.875 556615.375,499230.1875 556407.625,499392.78125 556362.75,499385.90625 556279.875,499598.5 556067.3125,499680.25 555952.8125,499218.5625 554988.875,498775.65625 554860.1875,498674.5 554832.5625,498282.0 554734.4375,498020.34375 554554.5625,497709.59375 554374.6875,497614.84375 554374.6875,497519.46875 554369.1875,497297.3125 554359.9375,496852.96875 554355.3125,496621.125 554351.375,496695.75 554454.625,496771.59375 554604.625,496836.3125 554734.0625,496868.65625 554831.125,496847.09375 554863.4375,496760.8125 554863.4375,496663.75 554928.125,496620.625 554992.875,496555.90625 555025.1875,496448.0625 554992.875,496372.5625 555025.1875,496351.0 555133.0625,496415.71875 555197.75,496480.40625 555294.8125,496480.40625 555381.0625,496430.875 555430.75,496446.0625 555547.375,496490.53125 555849.625,496526.09375 556240.75,496721.65625 556596.375,496924.90625 556774.1875,497006.125 556845.25,497281.71875 556978.625,497610.625 556969.6875,497859.53125 556969.6875,497974.5625 557051.875"; <add> for(String item:coords.split(",")){ <add> String[] coord = item.split(" "); <add> geo.addCoordinate(Double.parseDouble(coord[0]),Double.parseDouble(coord[1])); <add> } <add> ogrFeature.setGeometry(geo); <add> ogrFeature.addGeoMeasure("CLNAME", "STRING", "Loisiana Township"); <add> ogrFeature.addGeoMeasure("COUNT", "FLOAT", "1"); <add> BaseDAO<OGRFeature> ogrDao = new BaseDAO<OGRFeature>(OGRFeature.class); <add> ogrDao.save(ogrFeature); <add> try { <add> resp.getWriter().println("OGRFeature: " + ogrFeature.toString()); <add> } catch (IOException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> <add> <ide> } else if ("resetLRAP".equals(action)) { <ide> try { <ide> <ide> if ((ap.getCountryCode() == null || ap.getCountryCode() <ide> .equals("US")) <ide> && (ap.getLatitude() != null && ap.getLongitude() != null)) { <del> if (ap.getLatitude() > 5.9 && ap.getLatitude() < 8) { <add> if (ap.getLatitude() > 5.0 && ap.getLatitude() < 11) { <ide> if (ap.getLongitude() < -9 <ide> && ap.getLongitude() > -11) { <ide> ap.setCountryCode("LR"); <ide> apDao.save(ap); <del> resp <del> .getWriter() <add> resp.getWriter() <ide> .println( <ide> "Found " <ide> + ap.getCommunityCode() <del> + "mapped to US changing mapping to LR"); <add> + "mapped to US changing mapping to LR \n"); <ide> <ide> } <ide> } <ide> apDao.save(ap); <ide> resp.getWriter().println( <ide> "Found " + ap.getCommunityCode() <del> + "added random community code"); <add> + "added random community code \n"); <ide> } <ide> } <ide> <ide> log.info("submiting task for SurveyInstanceId: " <ide> + surveyInstanceId); <ide> } <del> siList = siDao.listSurveyInstanceBySurveyId(1362011L, cursor <del> .toWebSafeString()); <add> siList = siDao.listSurveyInstanceBySurveyId(1362011L, <add> cursor.toWebSafeString()); <ide> cursor = JDOCursorHelper.getCursor(siList); <ide> } <ide> System.out.println("finished"); <ide> DeviceFilesDao dfDao = new DeviceFilesDao(); <ide> <ide> DeviceFiles df = new DeviceFiles(); <del> df <del> .setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip"); <add> df.setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip"); <ide> df.setCreatedDateTime(new Date()); <ide> df.setPhoneNumber("a4:ed:4e:54:ef:6d"); <ide> df.setChecksum("1149406886"); <ide> ArrayList<String> regionLines = new ArrayList<String>(); <ide> for (int i = 0; i < 10; i++) { <ide> StringBuilder builder = new StringBuilder(); <del> builder.append("1,").append("" + i).append(",test,").append( <del> 20 + i + ",").append(30 + i + "\n"); <add> builder.append("1,").append("" + i).append(",test,") <add> .append(20 + i + ",").append(30 + i + "\n"); <ide> regionLines.add(builder.toString()); <ide> } <ide> geoHelp.processRegionsSurvey(regionLines); <ide> ap.setAltitude(0.0); <ide> ap.setCommunityCode("test" + new Date()); <ide> ap.setCommunityName("test" + new Date()); <del> ap <del> .setPhotoURL("http://waterforpeople.s3.amazonaws.com/images/peru/pc28water.jpg"); <add> ap.setPhotoURL("http://waterforpeople.s3.amazonaws.com/images/peru/pc28water.jpg"); <ide> ap.setProvideAdequateQuantity(true); <ide> ap.setHasSystemBeenDown1DayFlag(false); <ide> ap.setMeetGovtQualityStandardFlag(true); <ide> ap.setCollectionDate(new Date()); <ide> ap.setPhotoName("Water point"); <ide> if (i % 2 == 0) <del> ap <del> .setPointType(AccessPoint.AccessPointType.WATER_POINT); <add> ap.setPointType(AccessPoint.AccessPointType.WATER_POINT); <ide> else if (i % 3 == 0) <del> ap <del> .setPointType(AccessPoint.AccessPointType.SANITATION_POINT); <add> ap.setPointType(AccessPoint.AccessPointType.SANITATION_POINT); <ide> else <del> ap <del> .setPointType(AccessPoint.AccessPointType.PUBLIC_INSTITUTION); <add> ap.setPointType(AccessPoint.AccessPointType.PUBLIC_INSTITUTION); <ide> if (i == 0) <ide> ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH); <ide> else if (i == 1) <ide> for (MapFragment mfItem : mfList) { <ide> String contents = ZipUtil <ide> .unZip(mfItem.getBlob().getBytes()); <del> log <del> .log(Level.INFO, "Contents Length: " <del> + contents.length()); <add> log.log(Level.INFO, "Contents Length: " + contents.length()); <ide> resp.setContentType("application/vnd.google-earth.kmz+xml"); <ide> ServletOutputStream out = resp.getOutputStream(); <ide> resp.setHeader("Content-Disposition", <ide> || ap.getGeocells().size() == 0) { <ide> if (ap.getLatitude() != null <ide> && ap.getLongitude() != null) { <del> ap <del> .setGeocells(GeocellManager <del> .generateGeoCell(new Point(ap <del> .getLatitude(), ap <del> .getLongitude()))); <add> ap.setGeocells(GeocellManager.generateGeoCell(new Point( <add> ap.getLatitude(), ap.getLongitude()))); <ide> apDao.save(ap); <ide> } <ide> } <ide> } <ide> } else { <ide> <del> deleteSurveyResponses(Integer.parseInt(req <del> .getParameter("surveyId")), Integer.parseInt(req <del> .getParameter("count"))); <add> deleteSurveyResponses( <add> Integer.parseInt(req.getParameter("surveyId")), <add> Integer.parseInt(req.getParameter("count"))); <ide> } <ide> } else if ("fixNameQuestion".equals(action)) { <ide> if (req.getParameter("questionId") == null) { <ide> createEditorialContent(req.getParameter("pageName")); <ide> } else if ("generateEditorialContent".equals(action)) { <ide> try { <del> resp.getWriter().print(generateEditorialContent(req.getParameter("pageName"))); <add> resp.getWriter().print( <add> generateEditorialContent(req.getParameter("pageName"))); <ide> } catch (IOException e) { <ide> e.printStackTrace(); <ide> } <ide> EditorialPageDao dao = new EditorialPageDao(); <ide> EditorialPage p = dao.findByTargetPage(pageName); <ide> List<EditorialPageContent> contentList = dao.listContentByPage(p <del> .getKey().getId()); <add> .getKey().getId()); <ide> <ide> try { <del> RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices(); <del> StringReader reader = new StringReader(p.getTemplate().getValue()); <del> SimpleNode node = runtimeServices.parse(reader, "dynamicTemplate"); <del> Template template = new Template(); <del> template.setRuntimeServices(runtimeServices); <del> template.setData(node); <del> template.initDocument(); <add> RuntimeServices runtimeServices = RuntimeSingleton <add> .getRuntimeServices(); <add> StringReader reader = new StringReader(p.getTemplate().getValue()); <add> SimpleNode node = runtimeServices.parse(reader, "dynamicTemplate"); <add> Template template = new Template(); <add> template.setRuntimeServices(runtimeServices); <add> template.setData(node); <add> template.initDocument(); <ide> Context ctx = new VelocityContext(); <ide> ctx.put("pages", contentList); <ide> StringWriter writer = new StringWriter(); <ide> return content; <ide> } <ide> <del> private void createEditorialContent(String pageName) { <add> private void createEditorialContent(String pageName) { <ide> EditorialPageDao dao = new EditorialPageDao(); <del> <add> <ide> EditorialPage page = new EditorialPage(); <ide> page.setTargetFileName(pageName); <ide> page.setType("landing"); <del> page <del> .setTemplate(new Text("<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>")); <add> page.setTemplate(new Text( <add> "<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>")); <ide> page = dao.save(page); <ide> EditorialPageContent content = new EditorialPageContent(); <ide> List<EditorialPageContent> contentList = new ArrayList<EditorialPageContent>(); <ide> Translation tqhm = new Translation(); <ide> tqhm.setLanguageCode("es"); <ide> tqhm.setText("es:" + n + ":" + new Date()); <del> tqhm <del> .setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT); <add> tqhm.setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT); <ide> tqhm.setParentId(qhm.getKey().getId()); <ide> tDao.save(tqhm); <ide> qhm.addTranslation(tqhm); <ide> } <ide> sg.addSurvey(survey); <ide> } <del> log <del> .log(Level.INFO, "Finished Saving sg: " <del> + sg.getKey().toString()); <add> log.log(Level.INFO, "Finished Saving sg: " + sg.getKey().toString()); <ide> } <ide> } <ide> }
Java
agpl-3.0
0a43fc2e4878676ce69a394beb3d3936a1438f93
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
4dfe2468-2e62-11e5-9284-b827eb9e62be
hello.java
4df8b6e0-2e62-11e5-9284-b827eb9e62be
4dfe2468-2e62-11e5-9284-b827eb9e62be
hello.java
4dfe2468-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>4df8b6e0-2e62-11e5-9284-b827eb9e62be <add>4dfe2468-2e62-11e5-9284-b827eb9e62be
Java
agpl-3.0
54b33985b8607ddaea9e24a31601ee0796eb3b7a
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
07b23b98-2e62-11e5-9284-b827eb9e62be
hello.java
07acd798-2e62-11e5-9284-b827eb9e62be
07b23b98-2e62-11e5-9284-b827eb9e62be
hello.java
07b23b98-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>07acd798-2e62-11e5-9284-b827eb9e62be <add>07b23b98-2e62-11e5-9284-b827eb9e62be
Java
apache-2.0
error: pathspec 'IO/socketBot/src/main/java/ru/matevosyan/client/package-info.java' did not match any file(s) known to git
a5734fb57a56aeb3b9835cde376a7f114f4c9b96
1
VardanMatevosyan/Vardan-Git-Repository,VardanMatevosyan/Vardan-Git-Repository,VardanMatevosyan/Vardan-Git-Repository
/** * Hold Client class. * Created on 14.03.2017. * @since 1.0 * @author Matevosyan Vardan * @version 1.0 */ package ru.matevosyan.client;
IO/socketBot/src/main/java/ru/matevosyan/client/package-info.java
client package info
IO/socketBot/src/main/java/ru/matevosyan/client/package-info.java
client package info
<ide><path>O/socketBot/src/main/java/ru/matevosyan/client/package-info.java <add>/** <add> * Hold Client class. <add> * Created on 14.03.2017. <add> * @since 1.0 <add> * @author Matevosyan Vardan <add> * @version 1.0 <add> */ <add> <add>package ru.matevosyan.client;
Java
unlicense
088b2fa57b69535abf305c4c156536ed4da80144
0
skeeto/ChaosWheel,skeeto/ChaosWheel
/* Copyright (c) 2010 Christopher Wellons <[email protected]> * * Permission to use, copy, modify, and distribute this software for * any purpose with or without fee is hereby granted, provided that * the above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.nullprogram.wheel; import java.util.Vector; import java.util.ArrayDeque; import java.util.Iterator; import java.util.Random; import java.awt.Color; import java.awt.Graphics; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import javax.swing.Timer; import javax.swing.JFrame; import javax.swing.JComponent; /** * Simulates and displays a chaotic water wheel. * * Left-clicking adds a bucket and right-clicking removes a * bucket. The simulation discrete steps are uniform, making this a * bit rudimentary. * * This code is based on a Matlab program written by my friend Michael * Abraham. */ public class ChaosWheel extends JComponent implements MouseListener { private static final long serialVersionUID = 4764158473501226728L; /* Simulation constants. */ private static final int SIZE = 300; // display size in pixels private static final int DELAY = 30; // milliseconds private static final int DEFAULT_BUCKETS = 9; private static final int MIN_BUCKETS = 5; /* Simulation parameters. */ private double radius = 1; // feet private double wheelIntertia = 0.1; // slug * ft ^ 2 private double damping = 2.5; // ft * lbs / radians / sec private double gravity = 32.2; // ft / sec ^ 2 private double bucketFull = 1.0; // slug private double drainRate = 0.3; // slug / sec / slug private double fillRate = 0.33; // slug / sec /* Current state of the wheel. */ private double theta; // radians private double thetadot; // radians / sec private Vector<Double> buckets; // slug private Timer timer; private boolean graphMode; /* Histotic state information. */ private static final int MAX_HISTORY = 1000; private ArrayDeque<Double> rlRatio; // left/right water ratio private ArrayDeque<Double> tbRatio; // top/bottom water ratio private double rlRatioMax = 0; private double rlRatioMin = 0; private double tbRatioMax = 0; private double tbRatioMin = 0; /** * Create a water wheel with the default number of buckets. */ public ChaosWheel() { this(DEFAULT_BUCKETS); } /** * Create a water wheel with a specific number of buckets. * * @param numBuckets number of buckets. */ public ChaosWheel(final int numBuckets) { Random rng = new Random(); theta = rng.nextDouble() * 2d * Math.PI; thetadot = (rng.nextDouble() - 0.5); buckets = new Vector<Double>(); for (int i = 0; i < numBuckets; i++) { buckets.add(0d); } rlRatio = new ArrayDeque<Double>(); tbRatio = new ArrayDeque<Double>(); setPreferredSize(new Dimension(SIZE, SIZE)); addMouseListener(this); ActionListener listener = new ActionListener() { public void actionPerformed(final ActionEvent evt) { updateState(DELAY / 1500.0); repaint(); } }; graphMode = false; timer = new Timer(DELAY, listener); } /** * The main function when running standalone. * * @param args command line arguments */ public static void main(final String[] args) { JFrame frame = new JFrame("Lorenz Water Wheel"); ChaosWheel wheel = null; if (args.length == 0) { wheel = new ChaosWheel(); } else { int num = 0; try { num = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.out.println("Argument must be an integer."); System.exit(1); } if (num < MIN_BUCKETS) { System.out.println("Minimum # of buckets: " + MIN_BUCKETS); System.exit(1); } wheel = new ChaosWheel(num); } frame.add(wheel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); wheel.start(); } /** * Draw the water wheel to the display. * * @param g the graphics to draw on */ public final void paintComponent(final Graphics g) { super.paintComponent(g); if (graphMode) { paintGraph(g); return; } /* Draw the buckets. */ double diff = Math.PI * 2d / buckets.size(); int size = Math.min(getWidth(), getHeight()); int bucketSize = size / (int) (buckets.size() / 1.25); int drawRadius = size / 2 - bucketSize; int centerx = size / 2; int centery = size / 2; for (int i = 0; i < buckets.size(); i++) { double angle = i * diff + theta - Math.PI / 2; int x = centerx + (int) (Math.cos(angle) * drawRadius); int y = centery + (int) (Math.sin(angle) * drawRadius); g.setColor(Color.black); g.drawRect(x - bucketSize / 2, y - bucketSize / 2, bucketSize, bucketSize); g.setColor(Color.blue); int height = (int) (bucketSize * buckets.get(i) / bucketFull); g.fillRect(x - bucketSize / 2, y - bucketSize / 2 + (bucketSize - height), bucketSize, height); } } /** * Paint a graph of historical data. * * @param g graphics to be painted */ private void paintGraph(final Graphics g) { if (rlRatio.size() < 2) { return; } g.setColor(Color.black); Iterator<Double> rlit = rlRatio.iterator(); Iterator<Double> tbit = tbRatio.iterator(); Double rlLast = rlit.next(); Double tbLast = tbit.next(); while (rlit.hasNext()) { Double rl = rlit.next(); Double tb = tbit.next(); int x0 = (int) (rlLast / (rlRatioMax - rlRatioMin) * getWidth()); int y0 = (int) (tbLast / (tbRatioMax - tbRatioMin) * getHeight()); int x1 = (int) (rl / (rlRatioMax - rlRatioMin) * getWidth()); int y1 = (int) (tb / (tbRatioMax - tbRatioMin) * getHeight()); g.drawLine(x0, y0, x1, y1); rlLast = rl; tbLast = tb; } } /** * Start running the wheel simulation. */ public final void start() { timer.start(); } /** * Tell the wheel to stop running. */ public final void stop() { timer.stop(); } /** * Update the state by the given amount of seconds. * * @param tdot number of seconds to update by. */ public final void updateState(final double tdot) { /* Store the original system state */ double thetaOrig = theta; double thetadotOrig = thetadot; Vector<Double> bucketsOrig = new Vector<Double>(buckets); /* These are variables needed for intermediate steps in RK4 */ double dt = 0.0; double rateWeight = 1.0; /* Time derivatives of states */ double ddtTheta = 0.0; double ddtThetadot = 0.0; Vector<Double> ddtBuckets = new Vector<Double>(); for (int i = 0; i < buckets.size(); i++) { ddtBuckets.add(0d); } /* Total derivative approximations */ double ddtThetaTotal = 0.0; double ddtThetadotTotal = 0.0; Vector<Double> ddtBucketsTotal = new Vector<Double>(); for (int i = 0; i < buckets.size(); i++) { ddtBucketsTotal.add(0.0); } /* RK4 Integration */ for (int rk4idx = 1; rk4idx <= 4; rk4idx++) { if (rk4idx > 1) { rateWeight = 2.0; dt = tdot / 2.0; } else if (rk4idx == 4) { rateWeight = 1.0; dt = tdot; } /* System states to be used in this RK4 step */ theta = thetaOrig + dt * ddtTheta; while (theta < 0) { theta += Math.PI * 2; } while (theta > Math.PI * 2) { theta -= Math.PI * 2; } thetadot = thetadotOrig + dt * ddtThetadot; for (int i = 0; i < buckets.size(); i++) { double val = bucketsOrig.get(i) + dt * ddtBuckets.get(i); buckets.set(i, Math.min(bucketFull, Math.max(0, val))); } /* Differential equation for ddtTheta (kinematics) */ ddtTheta = thetadot; /* Calculate inertia */ double inertia = wheelIntertia; for (int i = 0; i < buckets.size(); i++) { inertia += buckets.get(i) * radius * radius; } /* Calculate torque */ double torque = -1 * (damping * thetadot); double diff = Math.PI * 2d / buckets.size(); for (int i = 0; i < buckets.size(); i++) { torque += buckets.get(i) * radius * gravity * Math.sin(theta + diff * i); } /* Differential equation for ddtThetadot (physics) */ ddtThetadot = torque / inertia; /* Differential equation for ddtBuckets (drain rate equation) */ for (int i = 0; i < buckets.size(); i++) { ddtBuckets.set(i, buckets.get(i) * -drainRate + inflow(theta + diff * i)); } /* Log the derivative approximations */ ddtThetaTotal += ddtTheta * rateWeight; ddtThetadotTotal += ddtThetadot * rateWeight; for (int i = 0; i < ddtBucketsTotal.size(); i++) { ddtBucketsTotal.set(i, ddtBucketsTotal.get(i) + ddtBuckets.get(i) * rateWeight); } } /* End of RK4 for loop */ /* Update the system state. * THIS is where time actually moves forward. */ theta = thetaOrig + 1.0 / 6.0 * ddtThetaTotal * tdot; thetadot = thetadotOrig + 1.0 / 6.0 * ddtThetadotTotal * tdot; for (int i = 0; i < ddtBucketsTotal.size(); i++) { double val = buckets.get(i) + 1d / 6d * ddtBucketsTotal.get(i) * tdot; buckets.set(i, Math.min(bucketFull, Math.max(0, val))); } logState(); } /** * Append some info about the current wheel state to the log. */ private void logState() { double left = 0; double right = 0; double top = 0; double bottom = 0; double diff = Math.PI * 2d / buckets.size(); for (int i = 0; i < buckets.size(); i++) { double angle = theta + diff * i; if (Math.cos(angle) > 0) { right += buckets.get(i); } left += buckets.get(i); if (Math.sin(angle) > 0) { top += buckets.get(i); } bottom += buckets.get(i); } double rl = left / right; double tb = top / bottom; rlRatioMax = Math.max(rl, rlRatioMax); tbRatioMax = Math.max(tb, tbRatioMax); rlRatioMin = Math.min(rl, rlRatioMin); tbRatioMin = Math.min(tb, tbRatioMin); rlRatio.add(rl); tbRatio.add(tb); if (rlRatio.size() > MAX_HISTORY) { rl = rlRatio.remove(); tb = tbRatio.remove(); } } /** * The fill rate for a bucket at the given position. * * @param angle position of the bucket * @return fill rate of the bucket (slugs / sec) */ private double inflow(final double angle) { double lim = Math.abs(Math.cos(Math.PI * 2d / buckets.size())); if (Math.cos(angle) > lim) { return fillRate / 2d * (Math.cos(buckets.size() * Math.atan2(Math.tan(angle), 1) / 2d) + 1); } else { return 0; } } /** * Add one bucket to the display. */ private void addBucket() { buckets.add(0d); } /** * Remove one bucket from the display. */ private void removeBucket() { if (buckets.size() > MIN_BUCKETS) { buckets.remove(0); } } /** {@inheritDoc} */ public final void mouseReleased(final MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON1: addBucket(); break; case MouseEvent.BUTTON2: graphMode ^= true; break; case MouseEvent.BUTTON3: removeBucket(); break; default: /* do nothing */ break; } } /** {@inheritDoc} */ public void mouseExited(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mouseEntered(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mouseClicked(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mousePressed(final MouseEvent e) { /* Do nothing */ } }
src/com/nullprogram/wheel/ChaosWheel.java
/* Copyright (c) 2010 Christopher Wellons <[email protected]> * * Permission to use, copy, modify, and distribute this software for * any purpose with or without fee is hereby granted, provided that * the above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.nullprogram.wheel; import java.util.Vector; import java.util.ArrayDeque; import java.util.Iterator; import java.util.Random; import java.awt.Color; import java.awt.Graphics; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import javax.swing.Timer; import javax.swing.JFrame; import javax.swing.JComponent; /** * Simulates and displays a chaotic water wheel. * * Left-clicking adds a bucket and right-clicking removes a * bucket. The simulation discrete steps are uniform, making this a * bit rudimentary. * * This code is based on a Matlab program written by my friend Michael * Abraham. */ public class ChaosWheel extends JComponent implements MouseListener { private static final long serialVersionUID = 4764158473501226728L; /* Simulation constants. */ private static final int SIZE = 300; // display size in pixels private static final int DELAY = 30; // milliseconds private static final int DEFAULT_BUCKETS = 9; private static final int MIN_BUCKETS = 5; /* Simulation parameters. */ private double radius = 1; // feet private double wheelIntertia = 0.1; // slug * ft ^ 2 private double damping = 2.5; // ft * lbs / radians / sec private double gravity = 32.2; // ft / sec ^ 2 private double bucketFull = 1.0; // slug private double drainRate = 0.3; // slug / sec / slug private double fillRate = 0.33; // slug / sec /* Current state of the wheel. */ private double theta; // radians private double thetadot; // radians / sec private Vector<Double> buckets; // slug private Timer timer; private boolean graphMode; /* Histotic state information. */ private static final int MAX_HISTORY = 1000; private ArrayDeque<Double> rlRatio; // left/right water ratio private ArrayDeque<Double> tbRatio; // top/bottom water ratio private double rlRatioMax = 0; private double rlRatioMin = 0; private double tbRatioMax = 0; private double tbRatioMin = 0; /** * Create a water wheel with the default number of buckets. */ public ChaosWheel() { this(DEFAULT_BUCKETS); } /** * Create a water wheel with a specific number of buckets. * * @param numBuckets number of buckets. */ public ChaosWheel(final int numBuckets) { Random rng = new Random(); theta = rng.nextDouble() * 2d * Math.PI; thetadot = (rng.nextDouble() - 0.5); buckets = new Vector<Double>(); for (int i = 0; i < numBuckets; i++) { buckets.add(0d); } rlRatio = new ArrayDeque<Double>(); tbRatio = new ArrayDeque<Double>(); setPreferredSize(new Dimension(SIZE, SIZE)); addMouseListener(this); ActionListener listener = new ActionListener() { public void actionPerformed(final ActionEvent evt) { updateState(DELAY / 1500.0); repaint(); } }; graphMode = false; timer = new Timer(DELAY, listener); } /** * The main function when running standalone. * * @param args command line arguments */ public static void main(final String[] args) { JFrame frame = new JFrame("Lorenz Water Wheel"); ChaosWheel wheel = null; if (args.length == 0) { wheel = new ChaosWheel(); } else { int num = 0; try { num = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.out.println("Argument must be an integer."); System.exit(1); } if (num < MIN_BUCKETS) { System.out.println("Minimum # of buckets: " + MIN_BUCKETS); System.exit(1); } wheel = new ChaosWheel(num); } frame.add(wheel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); wheel.start(); } /** * Draw the water wheel to the display. * * @param g the graphics to draw on */ public final void paintComponent(final Graphics g) { super.paintComponent(g); if (graphMode) { paintGraph(g); return; } /* Draw the buckets. */ double diff = Math.PI * 2d / buckets.size(); int size = Math.min(getWidth(), getHeight()); int bucketSize = size / (int) (buckets.size() / 1.25); int drawRadius = size / 2 - bucketSize; int centerx = size / 2; int centery = size / 2; for (int i = 0; i < buckets.size(); i++) { double angle = i * diff + theta - Math.PI / 2; int x = centerx + (int) (Math.cos(angle) * drawRadius); int y = centery + (int) (Math.sin(angle) * drawRadius); g.setColor(Color.black); g.drawRect(x - bucketSize / 2, y - bucketSize / 2, bucketSize, bucketSize); g.setColor(Color.blue); int height = (int) (bucketSize * buckets.get(i) / bucketFull); g.fillRect(x - bucketSize / 2, y - bucketSize / 2 + (bucketSize - height), bucketSize, height); } } /** * Paint a graph of historical data. * * @param g graphics to be painted */ private void paintGraph(final Graphics g) { if (rlRatio.size() < 2) { return; } g.setColor(Color.black); Iterator<Double> rlit = rlRatio.iterator(); Iterator<Double> tbit = tbRatio.iterator(); Double rlLast = rlit.next(); Double tbLast = tbit.next(); while (rlit.hasNext()) { Double rl = rlit.next(); Double tb = tbit.next(); int x0 = (int) (rlLast / (rlRatioMax - rlRatioMin) * getWidth()); int y0 = (int) (tbLast / (tbRatioMax - tbRatioMin) * getHeight()); int x1 = (int) (rl / (rlRatioMax - rlRatioMin) * getWidth()); int y1 = (int) (tb / (tbRatioMax - tbRatioMin) * getHeight()); g.drawLine(x0, y0, x1, y1); rlLast = rl; tbLast = tb; } } /** * Start running the wheel simulation. */ public final void start() { timer.start(); } /** * Tell the wheel to stop running. */ public final void stop() { timer.stop(); } /** * Update the state by the given amount of seconds. * * @param tdot number of seconds to update by. */ public final void updateState(final double tdot) { /* Store the original system state */ double thetaOrig = theta; double thetadotOrig = thetadot; Vector<Double> bucketsOrig = new Vector<Double>(buckets); /* These are variables needed for intermediate steps in RK4 */ double dt = 0.0; double rateWeight = 1.0; /* Time derivatives of states */ double ddtTheta = 0.0; double ddtThetadot = 0.0; Vector<Double> ddtBuckets = new Vector<Double>(); for (int i = 0; i < buckets.size(); i++) { ddtBuckets.add(0d); } /* Total derivative approximations */ double ddtThetaTotal = 0.0; double ddtThetadotTotal = 0.0; Vector<Double> ddtBucketsTotal = new Vector<Double>(); for (int i = 0; i < buckets.size(); i++) { ddtBucketsTotal.add(0.0); } /* RK4 Integration */ for (int rk4idx = 1; rk4idx <= 4; rk4idx++) { if (rk4idx > 1) { rateWeight = 2.0; dt = tdot / 2.0; } else if (rk4idx == 4) { rateWeight = 1.0; dt = tdot; } /* System states to be used in this RK4 step */ theta = thetaOrig + dt * ddtTheta; while (theta < 0) { theta += Math.PI * 2; } while (theta > Math.PI * 2) { theta -= Math.PI * 2; } thetadot = thetadotOrig + dt * ddtThetadot; for (int i = 0; i < buckets.size(); i++) { double val = bucketsOrig.get(i) + dt * ddtBuckets.get(i); buckets.set(i, Math.min(bucketFull, Math.max(0, val))); } /* Differential equation for ddtTheta (kinematics) */ ddtTheta = thetadot; /* Calculate inertia */ double inertia = wheelIntertia; for (int i = 0; i < buckets.size(); i++) { inertia += buckets.get(i) * radius * radius; } /* Calculate torque */ double torque = -1 * (damping * thetadot); double diff = Math.PI * 2d / buckets.size(); for (int i = 0; i < buckets.size(); i++) { torque += buckets.get(i) * radius * gravity * Math.sin(theta + diff * i); } /* Differential equation for ddtThetadot (physics) */ ddtThetadot = torque / inertia; /* Differential equation for ddtBuckets (drain rate equation) */ for (int i = 0; i < buckets.size(); i++) { ddtBuckets.set(i, buckets.get(i) * -drainRate + inflow(theta + diff * i)); } /* Log the derivative approximations */ ddtThetaTotal += ddtTheta * rateWeight; ddtThetadotTotal += ddtThetadot * rateWeight; for (int i = 0; i < ddtBucketsTotal.size(); i++) { ddtBucketsTotal.set(i, ddtBucketsTotal.get(i) + ddtBuckets.get(i) * rateWeight); } } /* End of RK4 for loop */ /* Update the system state. * THIS is where time actually moves forward. */ theta = thetaOrig + 1.0 / 6.0 * ddtThetaTotal * tdot; thetadot = thetadotOrig + 1.0 / 6.0 * ddtThetadotTotal * tdot; for (int i = 0; i < ddtBucketsTotal.size(); i++) { double val = buckets.get(i) + 1d / 6d * ddtBucketsTotal.get(i) * tdot; buckets.set(i, Math.min(bucketFull, Math.max(0, val))); } logState(); } /** * Append some info about the current wheel state to the log. */ private void logState() { double left = 0; double right = 0; double top = 0; double bottom = 0; double diff = Math.PI * 2d / buckets.size(); for (int i = 0; i < buckets.size(); i++) { double angle = theta + diff * i; if (Math.cos(angle) > 0) { right += buckets.get(i); } left += buckets.get(i); if (Math.sin(angle) > 0) { top += buckets.get(i); } bottom += buckets.get(i); } double rl = left / right; double tb = top / bottom; rlRatioMax = Math.max(rl, rlRatioMax); tbRatioMax = Math.max(tb, tbRatioMax); rlRatioMin = Math.min(rl, rlRatioMin); tbRatioMin = Math.min(tb, tbRatioMin); rlRatio.add(rl); tbRatio.add(tb); if (rlRatio.size() > MAX_HISTORY) { rl = rlRatio.remove(); tb = tbRatio.remove(); } } /** * The fill rate for a bucket at the given position. * * @param angle position of the bucket * @return fill rate of the bucket (slugs / sec) */ private double inflow(final double angle) { double lim = Math.abs(Math.cos(Math.PI * 2d / buckets.size())); if (Math.cos(angle) > lim) { return fillRate / 2d * (Math.cos(buckets.size() * Math.atan2(Math.tan(angle), 1) / 2d) + 1); } else { return 0; } } /** * Add one bucket to the display. */ private void addBucket() { buckets.add(0d); } /** * Remove one bucket from the display. */ private void removeBucket() { if (buckets.size() > MIN_BUCKETS) { buckets.remove(0); } } /** {@inheritDoc} */ public final void mouseReleased(final MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON1: addBucket(); break; case MouseEvent.BUTTON2: graphMode ^= true; break; case MouseEvent.BUTTON3: removeBucket(); break; default: /* do nothing */ break; } } /** {@inheritDoc} */ public void mouseExited(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mouseEntered(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mouseClicked(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mousePressed(final MouseEvent e) { /* Do nothing */ } }
Ran the indenter on the code.
src/com/nullprogram/wheel/ChaosWheel.java
Ran the indenter on the code.
<ide><path>rc/com/nullprogram/wheel/ChaosWheel.java <ide> thetadot = thetadotOrig + 1.0 / 6.0 * ddtThetadotTotal * tdot; <ide> for (int i = 0; i < ddtBucketsTotal.size(); i++) { <ide> double val = buckets.get(i) <del> + 1d / 6d * ddtBucketsTotal.get(i) * tdot; <add> + 1d / 6d * ddtBucketsTotal.get(i) * tdot; <ide> buckets.set(i, Math.min(bucketFull, Math.max(0, val))); <ide> } <ide>
Java
apache-2.0
ed4dfba26be2074d374ad210098dc9901d4276dd
0
jdanekrh/jms-reproducers,jdanekrh/jms-reproducers
/* * 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.activemq.artemis.tests.integration.amqp; import org.apache.activemq.JMSClientTestSupport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jms.*; import java.util.Enumeration; import static org.junit.Assert.*; @RunWith(Parameterized.class) public class JMSMessageConsumerTest extends JMSClientTestSupport { protected static final Logger LOG = LoggerFactory.getLogger(JMSMessageConsumerTest.class); @SuppressWarnings("rawtypes") @Test(timeout = 30000) public void testSelectorsWithJMSPriority() throws Exception { Connection connection = createConnection(); connection.start(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue("testSelectorsWithJMSPriority_" + randomSuffix); MessageProducer p = session.createProducer(queue); TextMessage message = session.createTextMessage(); message.setText("hello"); p.send(message, DeliveryMode.PERSISTENT, 5, 0); message = session.createTextMessage(); message.setText("hello + 9"); p.send(message, DeliveryMode.PERSISTENT, 9, 0); Thread.sleep(2000); QueueBrowser browser = session.createBrowser(queue); Enumeration enumeration = browser.getEnumeration(); int count = 0; while (enumeration.hasMoreElements()) { Message m = (Message) enumeration.nextElement(); assertTrue(m instanceof TextMessage); count++; } assertEquals(2, count); MessageConsumer consumer = session.createConsumer(queue, "JMSPriority > 8"); Message msg = consumer.receive(2000); assertNotNull(msg); assertTrue(msg instanceof TextMessage); assertEquals("hello + 9", ((TextMessage) msg).getText()); } finally { connection.close(); } } @Test(timeout = 60000) public void testJMSSelectorFiltersJMSMessageID() throws Exception { Connection connection = createConnection(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue("testJMSSelectorFiltersJMSMessageID_" + randomSuffix); MessageProducer producer = session.createProducer(queue); // Send one to receive TextMessage message = session.createTextMessage(); producer.send(message); // Send another to filter producer.send(session.createTextMessage()); connection.start(); // First one should make it through MessageConsumer messageConsumer = session.createConsumer(queue, "JMSMessageID = '" + message.getJMSMessageID() + "'"); TextMessage m = (TextMessage) messageConsumer.receive(5000); assertNotNull(m); assertEquals(message.getJMSMessageID(), m.getJMSMessageID()); // The second one should not be received. assertNull(messageConsumer.receive(1000)); } finally { connection.close(); } } }
src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSMessageConsumerTest.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.activemq.artemis.tests.integration.amqp; import org.apache.activemq.JMSClientTestSupport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jms.*; import java.util.Enumeration; import static org.junit.Assert.*; @RunWith(Parameterized.class) public class JMSMessageConsumerTest extends JMSClientTestSupport { protected static final Logger LOG = LoggerFactory.getLogger(JMSMessageConsumerTest.class); @SuppressWarnings("rawtypes") @Test(timeout = 30000) public void testSelectorsWithJMSPriority() throws Exception { Connection connection = createConnection(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue("testSelectorsWithJMSPriority_" + randomSuffix); MessageProducer p = session.createProducer(queue); TextMessage message = session.createTextMessage(); message.setText("hello"); p.send(message, DeliveryMode.PERSISTENT, 5, 0); message = session.createTextMessage(); message.setText("hello + 9"); p.send(message, DeliveryMode.PERSISTENT, 9, 0); QueueBrowser browser = session.createBrowser(queue); Enumeration enumeration = browser.getEnumeration(); int count = 0; while (enumeration.hasMoreElements()) { Message m = (Message) enumeration.nextElement(); assertTrue(m instanceof TextMessage); count++; } assertEquals(2, count); MessageConsumer consumer = session.createConsumer(queue, "JMSPriority > 8"); Message msg = consumer.receive(2000); assertNotNull(msg); assertTrue(msg instanceof TextMessage); assertEquals("hello + 9", ((TextMessage) msg).getText()); } finally { connection.close(); } } @Test(timeout = 60000) public void testJMSSelectorFiltersJMSMessageID() throws Exception { Connection connection = createConnection(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue("testJMSSelectorFiltersJMSMessageID_" + randomSuffix); MessageProducer producer = session.createProducer(queue); // Send one to receive TextMessage message = session.createTextMessage(); producer.send(message); // Send another to filter producer.send(session.createTextMessage()); connection.start(); // First one should make it through MessageConsumer messageConsumer = session.createConsumer(queue, "JMSMessageID = '" + message.getJMSMessageID() + "'"); TextMessage m = (TextMessage) messageConsumer.receive(5000); assertNotNull(m); assertEquals(message.getJMSMessageID(), m.getJMSMessageID()); // The second one should not be received. assertNull(messageConsumer.receive(1000)); } finally { connection.close(); } } }
fixup for JMSMessageConsumerTest the upstream suite starts up the connection, I need to do it myself terrible situation writing tests that are supposed to fail, one never knows when they really are supposed to, and when it is fail fail... The extra sleep is for OpenWire, it may miss a message in browsing
src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSMessageConsumerTest.java
fixup for JMSMessageConsumerTest
<ide><path>rc/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSMessageConsumerTest.java <ide> @Test(timeout = 30000) <ide> public void testSelectorsWithJMSPriority() throws Exception { <ide> Connection connection = createConnection(); <add> connection.start(); <ide> <ide> try { <ide> Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); <ide> message = session.createTextMessage(); <ide> message.setText("hello + 9"); <ide> p.send(message, DeliveryMode.PERSISTENT, 9, 0); <add> <add> Thread.sleep(2000); <ide> <ide> QueueBrowser browser = session.createBrowser(queue); <ide> Enumeration enumeration = browser.getEnumeration();
Java
bsd-3-clause
26e7a6fcb9bfcd9ac467480e55c4d6419381ced9
0
FlanFlanagan/cyclist2,cyclus/cyclist2
package edu.utexas.cycic; import java.io.FileReader; import java.io.Reader; import java.io.StringReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Pattern; import org.apache.log4j.Logger; import edu.utah.sci.cyclist.Cyclist; import edu.utah.sci.cyclist.core.Resources1; import edu.utah.sci.cyclist.core.event.dnd.DnD; import edu.utah.sci.cyclist.core.ui.components.ViewBase; import edu.utah.sci.cyclist.core.util.AwesomeIcon; import edu.utah.sci.cyclist.core.util.GlyphRegistry; import edu.utah.sci.cyclist.core.controller.CyclistController; import edu.utah.sci.cyclist.core.model.CyclusJob; import edu.utah.sci.cyclist.core.model.CyclusJob.Status; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javax.imageio.ImageIO; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.swing.AbstractAction; import javafx.geometry.Insets; import javafx.scene.SnapshotParameters; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.ColorPicker; import javafx.scene.control.ComboBox; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.image.WritableImage; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.TextAlignment; import javafx.stage.FileChooser; import javafx.stage.Window; public class Cycic extends ViewBase{ static Logger log = Logger.getLogger(Cycic.class); /** * Function for building the CYCIC Pane and GridPane of this view. */ public Cycic(){ super(); if (monthList.size() == 0){ months(); } if (CycicScenarios.cycicScenarios.size() < 1){ DataArrays scenario = new DataArrays(); workingScenario = scenario; CycicScenarios.cycicScenarios.add(scenario); } init(); } /** * */ public static final String TITLE = "Cycic"; static Pane pane = new Pane(); Pane nodesPane = new Pane(); static facilityNode workingNode = null; static DataArrays workingScenario; static boolean marketHideBool = true; static Window window; static ToggleGroup opSwitch = new ToggleGroup(); static ToggleButton localToggle = new ToggleButton("Local"); static ToggleButton remoteToggle = new ToggleButton("Remote"); static CyclusJob _remoteDashA; private static Object monitor = new Object(); private static String currentSkin = "Default Skin"; /** * */ static GridPane simInfo = new GridPane(){ { setHgap(4); setVgap(4); setPadding(new Insets(10, 10, 10, 10)); } }; /** * */ static VBox simDetailBox = new VBox(){ { getChildren().add(simInfo); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; /** * */ static GridPane commodGrid = new GridPane(){ { setVgap(5); setHgap(5); } }; /** * */ static Button addNewCommod = new Button(){ { setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ addNewCommodity(); } }); setText("+"); setStyle("-fx-font-size: 12;"); } }; static VBox commodBox = new VBox(){ { getChildren().add(new HBox(){ { getChildren().add(new Label(){ { setText("Simulation Commodities"); setTooltip(new Tooltip("Commodities facilitate the transfer of materials from one facility to another." + "Facilities with the same commodities are allowed to trade with each other.")); setFont(new Font("Times", 16)); } }); getChildren().add(addNewCommod); setSpacing(5); } }); getChildren().add(commodGrid); setPadding(new Insets(10, 10, 10, 10)); setSpacing(5); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; GridPane archetypeGrid = new GridPane(){ { add(new Label(){ { setText("Add Available Archetypes"); setTooltip(new Tooltip("Use the drop down menu to select archetypes to add to the simulation.")); setFont(new Font("Times", 16)); } }, 0, 0); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); setVgap(5); setHgap(10); setPadding(new Insets(10, 10, 10, 10)); } }; private void updateLinkColor(){ ColorPicker cP = new ColorPicker(); cP.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ for(nodeLink node: DataArrays.Links){ node.line.updateColor(cP.getValue()); } } }); Dialog dg = new Dialog(); ButtonType loginButtonType = new ButtonType("Ok", ButtonData.OK_DONE); dg.getDialogPane().setContent(cP); dg.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL); dg.setResizable(true); dg.show(); } private void updateBgColor(){ ColorPicker cP = new ColorPicker(); cP.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ String background = "-fx-background-color: #"; background += cP.getValue().toString().substring(2, 8); pane.setStyle(background); } }); Dialog dg = new Dialog(); ButtonType loginButtonType = new ButtonType("Ok", ButtonData.OK_DONE); dg.getDialogPane().setContent(cP); dg.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL); dg.setResizable(true); dg.show(); } private void setSkin() { if(currentSkin.equalsIgnoreCase("Default Skin")){ for(int j = 0; j < DataArrays.FacilityNodes.size(); j++){ DataArrays.FacilityNodes.get(j).cycicCircle.image.setVisible(false); DataArrays.FacilityNodes.get(j).cycicCircle.setOpacity(100); } } else { for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ skinSet skin = DataArrays.visualizationSkins.get(i); if(skin.name.equalsIgnoreCase(currentSkin)){ for(int j = 0; j < DataArrays.FacilityNodes.size(); j++){ DataArrays.FacilityNodes.get(j).cycicCircle.image.setImage(skin.images.getOrDefault(DataArrays.FacilityNodes.get(j).niche, skin.images.get("facility"))); DataArrays.FacilityNodes.get(j).cycicCircle.image.setVisible(true); DataArrays.FacilityNodes.get(j).cycicCircle.setOpacity(0); } } } } } /** * Initiates the Pane and GridPane. */ private void init(){ Resources1 resource = new Resources1(); File file = new File(resource.getCurrentPath()); String path = "/" + file.getParent(); try { defaultJsonReader(path); log.info("Meta data loaded for default archetypes. If you wish to add others, please use the DISCOVER ARCHETYPES button. Thanks!"); } catch (IOException e1) { log.warn("Could not read default meta data. Please use DISCOVER ARCHETYPES button. Thanks!"); } final ContextMenu paneMenu = new ContextMenu(); MenuItem linkColor = new MenuItem("Change Link Color..."); linkColor.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ updateLinkColor(); } }); MenuItem bgColor = new MenuItem("Change Background Color..."); bgColor.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ updateBgColor(); } }); DataArrays.visualizationSkins.add(XMLReader.SC2); DataArrays.visualizationSkins.add(XMLReader.loadSkin(path)); Menu skinMenu = new Menu("Change skin"); MenuItem defSkin = new MenuItem("Default Skin"); defSkin.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ currentSkin = "Default Skin"; setSkin(); } }); skinMenu.getItems().add(defSkin); for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ final String skinName = DataArrays.visualizationSkins.get(i).name; if (skinName.equals("DSARR")) { currentSkin = skinName; } MenuItem item = new MenuItem(skinName); item.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ currentSkin = skinName; setSkin(); } }); skinMenu.getItems().add(item); } MenuItem imageExport = new MenuItem("Save fuel cycle diagram"); imageExport.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ export(); } }); paneMenu.getItems().addAll(linkColor,bgColor,skinMenu,new SeparatorMenuItem(), imageExport); pane.setOnMouseClicked(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ if(e.getButton().equals(MouseButton.SECONDARY)){ paneMenu.show(pane,e.getScreenX(),e.getScreenY()); } } }); pane.setOnDragOver(new EventHandler <DragEvent>(){ public void handle(DragEvent event){ event.acceptTransferModes(TransferMode.ANY); } }); pane.setOnDragDropped(new EventHandler<DragEvent>(){ public void handle(DragEvent event){ if(event.getDragboard().hasContent(DnD.VALUE_FORMAT)){ facilityNode facility = new facilityNode(); facility.facilityType = event.getDragboard().getContent(DnD.VALUE_FORMAT).toString(); facility.facilityType.trim(); for (int i = 0; i < DataArrays.simFacilities.size(); i++){ if(DataArrays.simFacilities.get(i).facilityName.equalsIgnoreCase(facility.facilityType)){ facility.facilityStructure = DataArrays.simFacilities.get(i).facStruct; facility.niche = DataArrays.simFacilities.get(i).niche; facility.archetype = DataArrays.simFacilities.get(i).facilityArch; } } event.consume(); facility.name = ""; facility.cycicCircle = CycicCircles.addNode((String)facility.name, facility); facility.cycicCircle.setCenterX(event.getX()); facility.cycicCircle.setCenterY(event.getY()); facility.cycicCircle.text.setLayoutX(event.getX()-facility.cycicCircle.getRadius()*0.7); facility.cycicCircle.text.setLayoutY(event.getY()-facility.cycicCircle.getRadius()*0.6); facility.cycicCircle.menu.setLayoutX(event.getX()); facility.cycicCircle.menu.setLayoutY(event.getY()); for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ if(DataArrays.visualizationSkins.get(i).name.equalsIgnoreCase(currentSkin)){ facility.cycicCircle.image.setImage(DataArrays.visualizationSkins.get(i).images.getOrDefault(facility.niche,DataArrays.visualizationSkins.get(i).images.get("facility"))); facility.cycicCircle.image.setVisible(true); facility.cycicCircle.setOpacity(0); } } facility.cycicCircle.image.setLayoutX(facility.cycicCircle.getCenterX()-60); facility.cycicCircle.image.setLayoutY(facility.cycicCircle.getCenterY()-60); facility.sorterCircle = SorterCircles.addNode((String)facility.name, facility, facility); FormBuilderFunctions.formArrayBuilder(facility.facilityStructure, facility.facilityData); } else { event.consume(); } } }); setTitle(TITLE); setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ CycicScenarios.workingCycicScenario = workingScenario; } }); VBox cycicBox = new VBox(); cycicBox.autosize(); pane.autosize(); pane.setId("cycicPane"); pane.setPrefSize(1000, 600); pane.setStyle("-fx-background-color: white;"); // Temp Toolbar // final GridPane grid = new GridPane(); grid.setStyle("-fx-background-color: #d6d6d6;" + "-fx-font-size: 14;"); grid.setHgap(10); grid.setVgap(5); createArchetypeBar(grid); // Adding a new Facility // Label scenetitle1 = new Label("Add Prototype"); grid.add(scenetitle1, 0, 0); Label facName = new Label("Name"); grid.add(facName, 1, 0); // Name Field final TextField facNameField = new TextField(); grid.add(facNameField, 2, 0); // Facility Type final ComboBox<String> structureCB = new ComboBox<String>(); structureCB.setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent m){ structureCB.getItems().clear(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ structureCB.getItems().add((String) DataArrays.simFacilities.get(i).facilityName); } } }); structureCB.setPromptText("Select Facility Archetype"); grid.add(structureCB, 3, 0); //Submit Button Button submit1 = new Button("Add"); submit1.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent event){ if (structureCB.getValue() == null){ return; } facilityNode tempNode = new facilityNode(); tempNode.facilityType = structureCB.getValue(); for (int i = 0; i < DataArrays.simFacilities.size(); i++){ if (DataArrays.simFacilities.get(i).facilityName == structureCB.getValue()){ tempNode.facilityStructure = DataArrays.simFacilities.get(i).facStruct; } } tempNode.name = facNameField.getText(); tempNode.cycicCircle = CycicCircles.addNode((String)tempNode.name, tempNode); tempNode.sorterCircle = SorterCircles.addNode((String)tempNode.name, tempNode, tempNode); FormBuilderFunctions.formArrayBuilder(tempNode.facilityStructure, tempNode.facilityData); } }); grid.add(submit1, 4, 0); ScrollPane scroll = new ScrollPane(); scroll.setMinHeight(120); scroll.setContent(nodesPane); opSwitch.getToggles().clear(); opSwitch.getToggles().addAll(localToggle, remoteToggle); try { Process readproc = Runtime.getRuntime().exec("cyclus -V"); new BufferedReader(new InputStreamReader(readproc.getInputStream())); localToggle.setSelected(true); } catch (RuntimeException | IOException e) { localToggle.setSelected(false); remoteToggle.setSelected(true); }; grid.add(localToggle, 7, 0); grid.add(remoteToggle, 8, 0); cycicBox.getChildren().addAll(grid, scroll, pane); HBox mainView = new HBox(){ { setSpacing(5); } }; details(); VBox sideView = new VBox(){ { setSpacing(5); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; sideView.getChildren().addAll(simDetailBox, archetypeGrid, commodBox); mainView.getChildren().addAll(sideView, cycicBox); setContent(mainView); } /** * */ public void retrieveSchema(String rawMetadata) { // rawMetadata is a JSON string. Reader metaReader = new StringReader(rawMetadata); JsonReader metaJsonReader = Json.createReader(metaReader); JsonObject metadata = metaJsonReader.readObject(); metaJsonReader.close(); JsonObject schemas = metadata.getJsonObject("schema"); JsonObject annotations = metadata.getJsonObject("annotations"); DataArrays.simFacilities.clear(); DataArrays.simRegions.clear(); DataArrays.simInstitutions.clear(); for(javax.json.JsonString specVal : metadata.getJsonArray("specs").getValuesAs(JsonString.class)){ String spec = specVal.getString(); boolean test = true; for(int j = 0; j < XMLReader.blackList.size(); j++){ if(spec.equalsIgnoreCase(XMLReader.blackList.get(j))){ test = false; } } if(test == false){ continue; } String schema = schemas.getString(spec); String pattern1 = "<!--.*?-->"; Pattern p = Pattern.compile(pattern1, Pattern.DOTALL); schema = p.matcher(schema).replaceAll(""); if(schema.length() > 12){ if(!schema.substring(0, 12).equals("<interleave>")){ schema = "<interleave>" + schema + "</interleave>"; } } JsonObject anno = annotations.getJsonObject(spec); switch(anno.getString("entity")){ case "facility": log.info("Adding archetype "+spec); facilityStructure node = new facilityStructure(); node.facAnnotations = anno.toString(); node.facilityArch = spec; node.niche = anno.getString("niche", "facility"); JsonObject facVars = anno.getJsonObject("vars"); ArrayList<Object> facArray = new ArrayList<Object>(); node.facStruct = XMLReader.nodeBuilder(facVars, facArray, XMLReader.readSchema_new(schema)); node.facilityName = spec.replace(":", " "); DataArrays.simFacilities.add(node); break; case "region": log.info("Adding archetype "+spec); regionStructure rNode = new regionStructure(); rNode.regionAnnotations = anno.toString(); rNode.regionArch = spec; JsonObject regionVars = anno.getJsonObject("vars"); ArrayList<Object> regionArray = new ArrayList<Object>(); rNode.regionStruct = XMLReader.nodeBuilder(regionVars, regionArray, XMLReader.readSchema_new(schema)); rNode.regionName = spec.replace(":", " "); DataArrays.simRegions.add(rNode); break; case "institution": log.info("Adding archetype "+spec); institutionStructure iNode = new institutionStructure(); iNode.institArch = spec; iNode.institAnnotations = anno.toString(); JsonObject instVars = anno.getJsonObject("vars"); ArrayList<Object> instArray = new ArrayList<Object>(); iNode.institStruct = XMLReader.nodeBuilder(instVars, instArray, XMLReader.readSchema_new(schema)); iNode.institName = spec.replace(":", " "); DataArrays.simInstitutions.add(iNode); break; default: log.error(spec+" is not of the 'facility', 'region' or 'institution' type. " + "Please check the entity value in the archetype annotation."); break; }; } log.info("Schema discovery complete"); } /** * * @param circle * @param i * @param name */ public void buildDnDCircle(FacilityCircle circle, int i, String name){ circle.setRadius(40); circle.setStroke(Color.BLACK); circle.rgbColor=VisFunctions.stringToColor(name); circle.setFill(Color.rgb(circle.rgbColor.get(0),circle.rgbColor.get(1),circle.rgbColor.get(2))); circle.setCenterX(45+(i*90)); circle.setCenterY(50); circle.text.setText(name.split(" ")[2]); circle.text.setWrapText(true); circle.text.setMaxWidth(60); circle.text.setLayoutX(circle.getCenterX()-circle.getRadius()*0.7); circle.text.setLayoutY(circle.getCenterY()-circle.getRadius()*0.6); circle.text.setTextAlignment(TextAlignment.CENTER); circle.text.setMouseTransparent(true); circle.text.setMaxWidth(circle.getRadius()*1.4); circle.text.setMaxHeight(circle.getRadius()*1.2); circle.setOnDragDetected(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ Dragboard db = circle.startDragAndDrop(TransferMode.COPY); ClipboardContent content = new ClipboardContent(); content.put(DnD.VALUE_FORMAT, name); db.setContent(content); e.consume(); } }); } /** * */ public static void buildCommodPane(){ commodGrid.getChildren().clear(); for (int i = 0; i < Cycic.workingScenario.CommoditiesList.size(); i++){ CommodityNode commod = Cycic.workingScenario.CommoditiesList.get(i); TextField commodity = new TextField(); commodity.setText(commod.name.getText()); commodGrid.add(commodity, 0, i ); final int index = i; commodity.setPromptText("Enter Commodity Name"); commodity.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commod.name.setText(newValue); } }); commodGrid.add(new Label("Priority"), 1, index); TextField priority = VisFunctions.numberField(); priority.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commod.priority = Double.parseDouble(newValue); } }); priority.setPromptText("Enter Commodity Prioirty"); priority.setText("1"); commodGrid.add(priority, 2, index); Button removeCommod = new Button(); removeCommod.setGraphic(GlyphRegistry.get(AwesomeIcon.TRASH_ALT, "10px")); removeCommod.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ String commod = Cycic.workingScenario.CommoditiesList.get(index).name.getText(); Cycic.workingScenario.CommoditiesList.remove(index); for(facilityNode facility: DataArrays.FacilityNodes){ for(int i =0; i < facility.cycicCircle.incommods.size(); i++){ if(facility.cycicCircle.incommods.get(i) == commod){ facility.cycicCircle.incommods.remove(i); } } for(int i =0; i < facility.cycicCircle.outcommods.size(); i++){ if(facility.cycicCircle.outcommods.get(i) == commod){ facility.cycicCircle.outcommods.remove(i); } } } VisFunctions.redrawPane(); buildCommodPane(); } }); commodGrid.add(removeCommod, 3, index); } } /** * Adds a new TextField to the commodity GridPane tied to a new commodity in the * simulation. */ static public void addNewCommodity(){ CommodityNode commodity = new CommodityNode(); commodity.name.setText(""); Cycic.workingScenario.CommoditiesList.add(commodity); TextField newCommod = new TextField(); newCommod.autosize(); newCommod.setPromptText("Enter Commodity Name"); newCommod.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commodity.name.setText(newValue); } }); buildCommodPane(); } HashMap<String, String> months = new HashMap<String, String>(); ArrayList<String> monthList = new ArrayList<String>(); /** * Quick hack to convert months into their integer values. * i.e. January = 0, Feb = 1, etc... */ public void months(){ Cycic.workingScenario.simulationData.startMonth = "0"; monthList.add("January"); monthList.add("February"); monthList.add("March"); monthList.add("April"); monthList.add("May"); monthList.add("June"); monthList.add("July"); monthList.add("August"); monthList.add("September"); monthList.add("October"); monthList.add("November"); monthList.add("December"); months.put("January", "1"); months.put("Febuary", "2"); months.put("March", "3"); months.put("April", "4"); months.put("May", "5"); months.put("June", "6"); months.put("July", "7"); months.put("August", "8"); months.put("September", "9"); months.put("October", "10"); months.put("November", "11"); months.put("December", "12"); } public void details(){ Label simDets = new Label("Simulation Details"); simDets.setTooltip(new Tooltip("The top level details of the simulation.")); simDets.setFont(new Font("Times", 16)); simInfo.add(simDets, 0, 0); TextField duration = VisFunctions.numberField(); duration.setMaxWidth(150); duration.setPromptText("Length of Simulation"); duration.setText(Cycic.workingScenario.simulationData.duration); Cycic.workingScenario.simulationData.duration = "0"; duration.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.duration = newValue; } }); simInfo.add(new Label("Duration (Months)"), 0, 1); simInfo.add(duration, 1, 1); final ComboBox<String> startMonth = new ComboBox<String>(); startMonth.setValue(months.get(Cycic.workingScenario.simulationData.startMonth)); for(int i = 0; i < 12; i++ ){ startMonth.getItems().add(monthList.get(i)); } Cycic.workingScenario.simulationData.startMonth = "1"; startMonth.setValue(monthList.get(Integer.parseInt(Cycic.workingScenario.simulationData.startMonth))); startMonth.valueProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.startMonth = months.get(newValue); } }); startMonth.setPromptText("Select Month"); simInfo.add(new Label("Start Month"), 0, 2); simInfo.add(startMonth, 1, 2); TextField startYear = VisFunctions.numberField(); startYear.setText(Cycic.workingScenario.simulationData.startYear); Cycic.workingScenario.simulationData.startYear = "0"; startYear.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.startYear = newValue; } }); startYear.setPromptText("Starting Year"); startYear.setMaxWidth(150); simInfo.add(new Label("Start Year"), 0, 3); simInfo.add(startYear, 1, 3); TextArea description = new TextArea(); description.setMaxSize(250, 50); description.setWrapText(true); description.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.description = newValue; } }); simInfo.add(new Label("Description"), 0, 4); simInfo.add(description, 1, 4); TextArea notes = new TextArea(); notes.setMaxSize(250, 50); notes.setWrapText(true); notes.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.notes = newValue; } }); simInfo.add(new Label("Notes"), 0, 5); simInfo.add(notes, 1, 5); // Prints the Cyclus input associated with this simulator. Button output = new Button("Generate Cyclus Input"); output.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent event){ if(OutPut.inputTest()){ FileChooser fileChooser = new FileChooser(); //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XML files (*.xml)", "*.xml"); fileChooser.getExtensionFilters().add(extFilter); fileChooser.setTitle("Please save as Cyclus input file."); fileChooser.setInitialFileName("*.xml"); //Show save file dialog File file = fileChooser.showSaveDialog(window); OutPut.output(file); } } }); simInfo.add(output, 0, 6); Button runCyclus = new Button("Run Cyclus!"); runCyclus.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ if(!OutPut.inputTest()){ log.info("Cyclus Input Not Well Formed!"); return; // safety dance } if (localToggle.isSelected()) { // local execution String tempHash = Integer.toString(OutPut.xmlStringGen().hashCode()); String cycicTemp = "cycic"+tempHash; try { File temp = File.createTempFile(cycicTemp, ".xml"); FileWriter fileOutput = new FileWriter(temp); new BufferedWriter(fileOutput); Process p = Runtime.getRuntime().exec("cyclus -o "+cycicTemp +".sqlite "+cycicTemp); p.waitFor(); String line = null; BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { log.info(line); } input.close(); log.info("Cyclus run complete"); } catch (Exception e1) { e1.printStackTrace(); } } else { // remote execution String cycicXml = OutPut.xmlStringGen(); CyclistController._cyclusService.submit(cycicXml); } } });; simInfo.add(runCyclus, 1,6); } public void createArchetypeBar(GridPane grid){ ComboBox<String> archetypes = new ComboBox<String>(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ archetypes.getItems().add(DataArrays.simFacilities.get(i).facilityName); } archetypes.setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ archetypes.getItems().clear(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ archetypes.getItems().add(DataArrays.simFacilities.get(i).facilityName); } } }); archetypes.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ for(int i = 0; i < DataArrays.simFacilities.size(); i++){ if(DataArrays.simFacilities.get(i).facilityName.equalsIgnoreCase(archetypes.getValue())){ if(DataArrays.simFacilities.get(i).loaded == true){ return; } facilityStructure test = DataArrays.simFacilities.get(i); new StringBuilder(); try { test.loaded = true; FacilityCircle circle = new FacilityCircle(); int pos = 0; for(int k = 0; k < DataArrays.simFacilities.size(); k++){ if(DataArrays.simFacilities.get(k).loaded == true){ pos+=1; } } buildDnDCircle(circle, pos-1, test.facilityName); nodesPane.getChildren().addAll(circle,circle.text); } catch (Exception eq) { } } } } }); Button cyclusDashM = new Button("Discover Archetypes"); cyclusDashM.setTooltip(new Tooltip("Use this button to search for all local Cyclus modules.")); cyclusDashM.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ if (localToggle.isSelected()) { // Local metadata collection try { Process readproc = Runtime.getRuntime().exec("cyclus -m"); BufferedReader metaBuf = new BufferedReader(new InputStreamReader(readproc.getInputStream())); String line=null; String metadata = new String(); while ((line = metaBuf.readLine()) != null) {metadata += line;} metaBuf.close(); retrieveSchema(metadata); } catch (IOException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } } else { // Remote metadata collection CyclistController._cyclusService.submitCmd("cyclus", "-m"); _remoteDashA = CyclistController._cyclusService.latestJob(); _remoteDashA.statusProperty() .addListener(new ChangeListener<CyclusJob.Status>() { @Override public void changed(ObservableValue<? extends Status> observable, Status oldValue, Status newValue) { if (newValue == Status.READY) { retrieveSchema(_remoteDashA.getStdout()); } } }); } } }); archetypeGrid.add(cyclusDashM, 1, 0); archetypeGrid.add(new Label("Add Archetype to Simulation"), 0, 1); archetypeGrid.add(archetypes, 1, 1); } private void export() { FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().add( new FileChooser.ExtensionFilter("Image file (png, jpg, gif)", "*.png", "*.jpg", "'*.gif") ); File file = chooser.showSaveDialog(Cyclist.cyclistStage); if (file != null) { WritableImage image = pane.snapshot(new SnapshotParameters(), null); String name = file.getName(); String ext = name.substring(name.indexOf(".")+1, name.length()); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), ext, file); } catch (IOException e) { log.error("Error writing image to file: "+e.getMessage()); } } else { System.out.println("File did not generate correctly."); } } private void defaultJsonReader(String path) throws IOException{ BufferedReader reader = new BufferedReader( new FileReader (path + "/default-metadata.json")); String line = null; StringBuilder stringBuilder = new StringBuilder(); String ls = System.getProperty("line.separator"); while( ( line = reader.readLine() ) != null ) { stringBuilder.append( line ); stringBuilder.append( ls ); } reader.close(); retrieveSchema(stringBuilder.toString()); } }
cyclist/src/edu/utexas/cycic/Cycic.java
package edu.utexas.cycic; import java.io.FileReader; import java.io.Reader; import java.io.StringReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Pattern; import org.apache.log4j.Logger; import edu.utah.sci.cyclist.Cyclist; import edu.utah.sci.cyclist.core.Resources1; import edu.utah.sci.cyclist.core.event.dnd.DnD; import edu.utah.sci.cyclist.core.ui.components.ViewBase; import edu.utah.sci.cyclist.core.util.AwesomeIcon; import edu.utah.sci.cyclist.core.util.GlyphRegistry; import edu.utah.sci.cyclist.core.controller.CyclistController; import edu.utah.sci.cyclist.core.model.CyclusJob; import edu.utah.sci.cyclist.core.model.CyclusJob.Status; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javax.imageio.ImageIO; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonString; import javax.swing.AbstractAction; import javafx.geometry.Insets; import javafx.scene.SnapshotParameters; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.ColorPicker; import javafx.scene.control.ComboBox; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.image.WritableImage; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.TextAlignment; import javafx.stage.FileChooser; import javafx.stage.Window; public class Cycic extends ViewBase{ static Logger log = Logger.getLogger(Cycic.class); /** * Function for building the CYCIC Pane and GridPane of this view. */ public Cycic(){ super(); if (monthList.size() == 0){ months(); } if (CycicScenarios.cycicScenarios.size() < 1){ DataArrays scenario = new DataArrays(); workingScenario = scenario; CycicScenarios.cycicScenarios.add(scenario); } init(); } /** * */ public static final String TITLE = "Cycic"; static Pane pane = new Pane(); Pane nodesPane = new Pane(); static facilityNode workingNode = null; static DataArrays workingScenario; static boolean marketHideBool = true; static Window window; static ToggleGroup opSwitch = new ToggleGroup(); static ToggleButton localToggle = new ToggleButton("Local"); static ToggleButton remoteToggle = new ToggleButton("Remote"); static CyclusJob _remoteDashA; private static Object monitor = new Object(); private static String currentSkin = "Default Skin"; /** * */ static GridPane simInfo = new GridPane(){ { setHgap(4); setVgap(4); setPadding(new Insets(10, 10, 10, 10)); } }; /** * */ static VBox simDetailBox = new VBox(){ { getChildren().add(simInfo); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; /** * */ static GridPane commodGrid = new GridPane(){ { setVgap(5); setHgap(5); } }; /** * */ static Button addNewCommod = new Button(){ { setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ addNewCommodity(); } }); setText("+"); setStyle("-fx-font-size: 12;"); } }; static VBox commodBox = new VBox(){ { getChildren().add(new HBox(){ { getChildren().add(new Label(){ { setText("Simulation Commodities"); setTooltip(new Tooltip("Commodities facilitate the transfer of materials from one facility to another." + "Facilities with the same commodities are allowed to trade with each other.")); setFont(new Font("Times", 16)); } }); getChildren().add(addNewCommod); setSpacing(5); } }); getChildren().add(commodGrid); setPadding(new Insets(10, 10, 10, 10)); setSpacing(5); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; GridPane archetypeGrid = new GridPane(){ { add(new Label(){ { setText("Add Available Archetypes"); setTooltip(new Tooltip("Use the drop down menu to select archetypes to add to the simulation.")); setFont(new Font("Times", 16)); } }, 0, 0); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); setVgap(5); setHgap(10); setPadding(new Insets(10, 10, 10, 10)); } }; private void updateLinkColor(){ ColorPicker cP = new ColorPicker(); cP.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ for(nodeLink node: DataArrays.Links){ node.line.updateColor(cP.getValue()); } } }); Dialog dg = new Dialog(); ButtonType loginButtonType = new ButtonType("Ok", ButtonData.OK_DONE); dg.getDialogPane().setContent(cP); dg.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL); dg.setResizable(true); dg.show(); } private void updateBgColor(){ ColorPicker cP = new ColorPicker(); cP.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ String background = "-fx-background-color: #"; background += cP.getValue().toString().substring(2, 8); pane.setStyle(background); } }); Dialog dg = new Dialog(); ButtonType loginButtonType = new ButtonType("Ok", ButtonData.OK_DONE); dg.getDialogPane().setContent(cP); dg.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL); dg.setResizable(true); dg.show(); } private void setSkin() { if(currentSkin.equalsIgnoreCase("Default Skin")){ for(int j = 0; j < DataArrays.FacilityNodes.size(); j++){ DataArrays.FacilityNodes.get(j).cycicCircle.image.setVisible(false); DataArrays.FacilityNodes.get(j).cycicCircle.setOpacity(100); } } else { for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ skinSet skin = DataArrays.visualizationSkins.get(i); if(skin.name.equalsIgnoreCase(currentSkin)){ for(int j = 0; j < DataArrays.FacilityNodes.size(); j++){ DataArrays.FacilityNodes.get(j).cycicCircle.image.setImage(skin.images.getOrDefault(DataArrays.FacilityNodes.get(j).niche, skin.images.get("facility"))); DataArrays.FacilityNodes.get(j).cycicCircle.image.setVisible(true); DataArrays.FacilityNodes.get(j).cycicCircle.setOpacity(0); } } } } } /** * Initiates the Pane and GridPane. */ private void init(){ Resources1 resource = new Resources1(); File file = new File(resource.getCurrentPath()); String path = "/" + file.getParent(); try { defaultJsonReader(path); log.info("Meta data loaded for default archetypes. If you wish to add others, please use the DISCOVER ARCHETYPES button. Thanks!"); } catch (IOException e1) { log.warn("Could not read default meta data. Please use DISCOVER ARCHETYPES button. Thanks!"); } final ContextMenu paneMenu = new ContextMenu(); MenuItem linkColor = new MenuItem("Change Link Color..."); linkColor.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ updateLinkColor(); } }); MenuItem bgColor = new MenuItem("Change Background Color..."); bgColor.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ updateBgColor(); } }); DataArrays.visualizationSkins.add(XMLReader.SC2); DataArrays.visualizationSkins.add(XMLReader.loadSkin(path)); Menu skinMenu = new Menu("Change skin"); MenuItem defSkin = new MenuItem("Default Skin"); defSkin.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ currentSkin = "Default Skin"; setSkin(); } }); skinMenu.getItems().add(defSkin); for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ final String skinName = DataArrays.visualizationSkins.get(i).name; MenuItem item = new MenuItem(skinName); item.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ currentSkin = skinName; setSkin(); } }); skinMenu.getItems().add(item); } MenuItem imageExport = new MenuItem("Save fuel cycle diagram"); imageExport.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ export(); } }); paneMenu.getItems().addAll(linkColor,bgColor,skinMenu,new SeparatorMenuItem(), imageExport); pane.setOnMouseClicked(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ if(e.getButton().equals(MouseButton.SECONDARY)){ paneMenu.show(pane,e.getScreenX(),e.getScreenY()); } } }); pane.setOnDragOver(new EventHandler <DragEvent>(){ public void handle(DragEvent event){ event.acceptTransferModes(TransferMode.ANY); } }); pane.setOnDragDropped(new EventHandler<DragEvent>(){ public void handle(DragEvent event){ if(event.getDragboard().hasContent(DnD.VALUE_FORMAT)){ facilityNode facility = new facilityNode(); facility.facilityType = event.getDragboard().getContent(DnD.VALUE_FORMAT).toString(); facility.facilityType.trim(); for (int i = 0; i < DataArrays.simFacilities.size(); i++){ if(DataArrays.simFacilities.get(i).facilityName.equalsIgnoreCase(facility.facilityType)){ facility.facilityStructure = DataArrays.simFacilities.get(i).facStruct; facility.niche = DataArrays.simFacilities.get(i).niche; facility.archetype = DataArrays.simFacilities.get(i).facilityArch; } } event.consume(); facility.name = ""; facility.cycicCircle = CycicCircles.addNode((String)facility.name, facility); facility.cycicCircle.setCenterX(event.getX()); facility.cycicCircle.setCenterY(event.getY()); facility.cycicCircle.text.setLayoutX(event.getX()-facility.cycicCircle.getRadius()*0.7); facility.cycicCircle.text.setLayoutY(event.getY()-facility.cycicCircle.getRadius()*0.6); facility.cycicCircle.menu.setLayoutX(event.getX()); facility.cycicCircle.menu.setLayoutY(event.getY()); for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ if(DataArrays.visualizationSkins.get(i).name.equalsIgnoreCase(currentSkin)){ facility.cycicCircle.image.setImage(DataArrays.visualizationSkins.get(i).images.getOrDefault(facility.niche,DataArrays.visualizationSkins.get(i).images.get("facility"))); facility.cycicCircle.image.setVisible(true); facility.cycicCircle.setOpacity(0); } } facility.cycicCircle.image.setLayoutX(facility.cycicCircle.getCenterX()-60); facility.cycicCircle.image.setLayoutY(facility.cycicCircle.getCenterY()-60); facility.sorterCircle = SorterCircles.addNode((String)facility.name, facility, facility); FormBuilderFunctions.formArrayBuilder(facility.facilityStructure, facility.facilityData); } else { event.consume(); } } }); setTitle(TITLE); setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ CycicScenarios.workingCycicScenario = workingScenario; } }); VBox cycicBox = new VBox(); cycicBox.autosize(); pane.autosize(); pane.setId("cycicPane"); pane.setPrefSize(1000, 600); pane.setStyle("-fx-background-color: white;"); // Temp Toolbar // final GridPane grid = new GridPane(); grid.setStyle("-fx-background-color: #d6d6d6;" + "-fx-font-size: 14;"); grid.setHgap(10); grid.setVgap(5); createArchetypeBar(grid); // Adding a new Facility // Label scenetitle1 = new Label("Add Prototype"); grid.add(scenetitle1, 0, 0); Label facName = new Label("Name"); grid.add(facName, 1, 0); // Name Field final TextField facNameField = new TextField(); grid.add(facNameField, 2, 0); // Facility Type final ComboBox<String> structureCB = new ComboBox<String>(); structureCB.setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent m){ structureCB.getItems().clear(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ structureCB.getItems().add((String) DataArrays.simFacilities.get(i).facilityName); } } }); structureCB.setPromptText("Select Facility Archetype"); grid.add(structureCB, 3, 0); //Submit Button Button submit1 = new Button("Add"); submit1.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent event){ if (structureCB.getValue() == null){ return; } facilityNode tempNode = new facilityNode(); tempNode.facilityType = structureCB.getValue(); for (int i = 0; i < DataArrays.simFacilities.size(); i++){ if (DataArrays.simFacilities.get(i).facilityName == structureCB.getValue()){ tempNode.facilityStructure = DataArrays.simFacilities.get(i).facStruct; } } tempNode.name = facNameField.getText(); tempNode.cycicCircle = CycicCircles.addNode((String)tempNode.name, tempNode); tempNode.sorterCircle = SorterCircles.addNode((String)tempNode.name, tempNode, tempNode); FormBuilderFunctions.formArrayBuilder(tempNode.facilityStructure, tempNode.facilityData); } }); grid.add(submit1, 4, 0); ScrollPane scroll = new ScrollPane(); scroll.setMinHeight(120); scroll.setContent(nodesPane); opSwitch.getToggles().clear(); opSwitch.getToggles().addAll(localToggle, remoteToggle); try { Process readproc = Runtime.getRuntime().exec("cyclus -V"); new BufferedReader(new InputStreamReader(readproc.getInputStream())); localToggle.setSelected(true); } catch (RuntimeException | IOException e) { localToggle.setSelected(false); remoteToggle.setSelected(true); }; grid.add(localToggle, 7, 0); grid.add(remoteToggle, 8, 0); cycicBox.getChildren().addAll(grid, scroll, pane); HBox mainView = new HBox(){ { setSpacing(5); } }; details(); VBox sideView = new VBox(){ { setSpacing(5); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; sideView.getChildren().addAll(simDetailBox, archetypeGrid, commodBox); mainView.getChildren().addAll(sideView, cycicBox); setContent(mainView); } /** * */ public void retrieveSchema(String rawMetadata) { // rawMetadata is a JSON string. Reader metaReader = new StringReader(rawMetadata); JsonReader metaJsonReader = Json.createReader(metaReader); JsonObject metadata = metaJsonReader.readObject(); metaJsonReader.close(); JsonObject schemas = metadata.getJsonObject("schema"); JsonObject annotations = metadata.getJsonObject("annotations"); DataArrays.simFacilities.clear(); DataArrays.simRegions.clear(); DataArrays.simInstitutions.clear(); for(javax.json.JsonString specVal : metadata.getJsonArray("specs").getValuesAs(JsonString.class)){ String spec = specVal.getString(); boolean test = true; for(int j = 0; j < XMLReader.blackList.size(); j++){ if(spec.equalsIgnoreCase(XMLReader.blackList.get(j))){ test = false; } } if(test == false){ continue; } String schema = schemas.getString(spec); String pattern1 = "<!--.*?-->"; Pattern p = Pattern.compile(pattern1, Pattern.DOTALL); schema = p.matcher(schema).replaceAll(""); if(schema.length() > 12){ if(!schema.substring(0, 12).equals("<interleave>")){ schema = "<interleave>" + schema + "</interleave>"; } } JsonObject anno = annotations.getJsonObject(spec); switch(anno.getString("entity")){ case "facility": log.info("Adding archetype "+spec); facilityStructure node = new facilityStructure(); node.facAnnotations = anno.toString(); node.facilityArch = spec; node.niche = anno.getString("niche", "facility"); JsonObject facVars = anno.getJsonObject("vars"); ArrayList<Object> facArray = new ArrayList<Object>(); node.facStruct = XMLReader.nodeBuilder(facVars, facArray, XMLReader.readSchema_new(schema)); node.facilityName = spec.replace(":", " "); DataArrays.simFacilities.add(node); break; case "region": log.info("Adding archetype "+spec); regionStructure rNode = new regionStructure(); rNode.regionAnnotations = anno.toString(); rNode.regionArch = spec; JsonObject regionVars = anno.getJsonObject("vars"); ArrayList<Object> regionArray = new ArrayList<Object>(); rNode.regionStruct = XMLReader.nodeBuilder(regionVars, regionArray, XMLReader.readSchema_new(schema)); rNode.regionName = spec.replace(":", " "); DataArrays.simRegions.add(rNode); break; case "institution": log.info("Adding archetype "+spec); institutionStructure iNode = new institutionStructure(); iNode.institArch = spec; iNode.institAnnotations = anno.toString(); JsonObject instVars = anno.getJsonObject("vars"); ArrayList<Object> instArray = new ArrayList<Object>(); iNode.institStruct = XMLReader.nodeBuilder(instVars, instArray, XMLReader.readSchema_new(schema)); iNode.institName = spec.replace(":", " "); DataArrays.simInstitutions.add(iNode); break; default: log.error(spec+" is not of the 'facility', 'region' or 'institution' type. " + "Please check the entity value in the archetype annotation."); break; }; } log.info("Schema discovery complete"); } /** * * @param circle * @param i * @param name */ public void buildDnDCircle(FacilityCircle circle, int i, String name){ circle.setRadius(40); circle.setStroke(Color.BLACK); circle.rgbColor=VisFunctions.stringToColor(name); circle.setFill(Color.rgb(circle.rgbColor.get(0),circle.rgbColor.get(1),circle.rgbColor.get(2))); circle.setCenterX(45+(i*90)); circle.setCenterY(50); circle.text.setText(name.split(" ")[2]); circle.text.setWrapText(true); circle.text.setMaxWidth(60); circle.text.setLayoutX(circle.getCenterX()-circle.getRadius()*0.7); circle.text.setLayoutY(circle.getCenterY()-circle.getRadius()*0.6); circle.text.setTextAlignment(TextAlignment.CENTER); circle.text.setMouseTransparent(true); circle.text.setMaxWidth(circle.getRadius()*1.4); circle.text.setMaxHeight(circle.getRadius()*1.2); circle.setOnDragDetected(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ Dragboard db = circle.startDragAndDrop(TransferMode.COPY); ClipboardContent content = new ClipboardContent(); content.put(DnD.VALUE_FORMAT, name); db.setContent(content); e.consume(); } }); } /** * */ public static void buildCommodPane(){ commodGrid.getChildren().clear(); for (int i = 0; i < Cycic.workingScenario.CommoditiesList.size(); i++){ CommodityNode commod = Cycic.workingScenario.CommoditiesList.get(i); TextField commodity = new TextField(); commodity.setText(commod.name.getText()); commodGrid.add(commodity, 0, i ); final int index = i; commodity.setPromptText("Enter Commodity Name"); commodity.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commod.name.setText(newValue); } }); commodGrid.add(new Label("Priority"), 1, index); TextField priority = VisFunctions.numberField(); priority.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commod.priority = Double.parseDouble(newValue); } }); priority.setPromptText("Enter Commodity Prioirty"); priority.setText("1"); commodGrid.add(priority, 2, index); Button removeCommod = new Button(); removeCommod.setGraphic(GlyphRegistry.get(AwesomeIcon.TRASH_ALT, "10px")); removeCommod.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ String commod = Cycic.workingScenario.CommoditiesList.get(index).name.getText(); Cycic.workingScenario.CommoditiesList.remove(index); for(facilityNode facility: DataArrays.FacilityNodes){ for(int i =0; i < facility.cycicCircle.incommods.size(); i++){ if(facility.cycicCircle.incommods.get(i) == commod){ facility.cycicCircle.incommods.remove(i); } } for(int i =0; i < facility.cycicCircle.outcommods.size(); i++){ if(facility.cycicCircle.outcommods.get(i) == commod){ facility.cycicCircle.outcommods.remove(i); } } } VisFunctions.redrawPane(); buildCommodPane(); } }); commodGrid.add(removeCommod, 3, index); } } /** * Adds a new TextField to the commodity GridPane tied to a new commodity in the * simulation. */ static public void addNewCommodity(){ CommodityNode commodity = new CommodityNode(); commodity.name.setText(""); Cycic.workingScenario.CommoditiesList.add(commodity); TextField newCommod = new TextField(); newCommod.autosize(); newCommod.setPromptText("Enter Commodity Name"); newCommod.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commodity.name.setText(newValue); } }); buildCommodPane(); } HashMap<String, String> months = new HashMap<String, String>(); ArrayList<String> monthList = new ArrayList<String>(); /** * Quick hack to convert months into their integer values. * i.e. January = 0, Feb = 1, etc... */ public void months(){ Cycic.workingScenario.simulationData.startMonth = "0"; monthList.add("January"); monthList.add("February"); monthList.add("March"); monthList.add("April"); monthList.add("May"); monthList.add("June"); monthList.add("July"); monthList.add("August"); monthList.add("September"); monthList.add("October"); monthList.add("November"); monthList.add("December"); months.put("January", "1"); months.put("Febuary", "2"); months.put("March", "3"); months.put("April", "4"); months.put("May", "5"); months.put("June", "6"); months.put("July", "7"); months.put("August", "8"); months.put("September", "9"); months.put("October", "10"); months.put("November", "11"); months.put("December", "12"); } public void details(){ Label simDets = new Label("Simulation Details"); simDets.setTooltip(new Tooltip("The top level details of the simulation.")); simDets.setFont(new Font("Times", 16)); simInfo.add(simDets, 0, 0); TextField duration = VisFunctions.numberField(); duration.setMaxWidth(150); duration.setPromptText("Length of Simulation"); duration.setText(Cycic.workingScenario.simulationData.duration); Cycic.workingScenario.simulationData.duration = "0"; duration.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.duration = newValue; } }); simInfo.add(new Label("Duration (Months)"), 0, 1); simInfo.add(duration, 1, 1); final ComboBox<String> startMonth = new ComboBox<String>(); startMonth.setValue(months.get(Cycic.workingScenario.simulationData.startMonth)); for(int i = 0; i < 12; i++ ){ startMonth.getItems().add(monthList.get(i)); } Cycic.workingScenario.simulationData.startMonth = "1"; startMonth.setValue(monthList.get(Integer.parseInt(Cycic.workingScenario.simulationData.startMonth))); startMonth.valueProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.startMonth = months.get(newValue); } }); startMonth.setPromptText("Select Month"); simInfo.add(new Label("Start Month"), 0, 2); simInfo.add(startMonth, 1, 2); TextField startYear = VisFunctions.numberField(); startYear.setText(Cycic.workingScenario.simulationData.startYear); Cycic.workingScenario.simulationData.startYear = "0"; startYear.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.startYear = newValue; } }); startYear.setPromptText("Starting Year"); startYear.setMaxWidth(150); simInfo.add(new Label("Start Year"), 0, 3); simInfo.add(startYear, 1, 3); TextArea description = new TextArea(); description.setMaxSize(250, 50); description.setWrapText(true); description.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.description = newValue; } }); simInfo.add(new Label("Description"), 0, 4); simInfo.add(description, 1, 4); TextArea notes = new TextArea(); notes.setMaxSize(250, 50); notes.setWrapText(true); notes.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.notes = newValue; } }); simInfo.add(new Label("Notes"), 0, 5); simInfo.add(notes, 1, 5); // Prints the Cyclus input associated with this simulator. Button output = new Button("Generate Cyclus Input"); output.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent event){ if(OutPut.inputTest()){ FileChooser fileChooser = new FileChooser(); //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XML files (*.xml)", "*.xml"); fileChooser.getExtensionFilters().add(extFilter); fileChooser.setTitle("Please save as Cyclus input file."); fileChooser.setInitialFileName("*.xml"); //Show save file dialog File file = fileChooser.showSaveDialog(window); OutPut.output(file); } } }); simInfo.add(output, 0, 6); Button runCyclus = new Button("Run Cyclus!"); runCyclus.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ if(!OutPut.inputTest()){ log.info("Cyclus Input Not Well Formed!"); return; // safety dance } if (localToggle.isSelected()) { // local execution String tempHash = Integer.toString(OutPut.xmlStringGen().hashCode()); String cycicTemp = "cycic"+tempHash; try { File temp = File.createTempFile(cycicTemp, ".xml"); FileWriter fileOutput = new FileWriter(temp); new BufferedWriter(fileOutput); Process p = Runtime.getRuntime().exec("cyclus -o "+cycicTemp +".sqlite "+cycicTemp); p.waitFor(); String line = null; BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { log.info(line); } input.close(); log.info("Cyclus run complete"); } catch (Exception e1) { e1.printStackTrace(); } } else { // remote execution String cycicXml = OutPut.xmlStringGen(); CyclistController._cyclusService.submit(cycicXml); } } });; simInfo.add(runCyclus, 1,6); } public void createArchetypeBar(GridPane grid){ ComboBox<String> archetypes = new ComboBox<String>(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ archetypes.getItems().add(DataArrays.simFacilities.get(i).facilityName); } archetypes.setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ archetypes.getItems().clear(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ archetypes.getItems().add(DataArrays.simFacilities.get(i).facilityName); } } }); archetypes.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ for(int i = 0; i < DataArrays.simFacilities.size(); i++){ if(DataArrays.simFacilities.get(i).facilityName.equalsIgnoreCase(archetypes.getValue())){ if(DataArrays.simFacilities.get(i).loaded == true){ return; } facilityStructure test = DataArrays.simFacilities.get(i); new StringBuilder(); try { test.loaded = true; FacilityCircle circle = new FacilityCircle(); int pos = 0; for(int k = 0; k < DataArrays.simFacilities.size(); k++){ if(DataArrays.simFacilities.get(k).loaded == true){ pos+=1; } } buildDnDCircle(circle, pos-1, test.facilityName); nodesPane.getChildren().addAll(circle,circle.text); } catch (Exception eq) { } } } } }); Button cyclusDashM = new Button("Discover Archetypes"); cyclusDashM.setTooltip(new Tooltip("Use this button to search for all local Cyclus modules.")); cyclusDashM.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ if (localToggle.isSelected()) { // Local metadata collection try { Process readproc = Runtime.getRuntime().exec("cyclus -m"); BufferedReader metaBuf = new BufferedReader(new InputStreamReader(readproc.getInputStream())); String line=null; String metadata = new String(); while ((line = metaBuf.readLine()) != null) {metadata += line;} metaBuf.close(); retrieveSchema(metadata); } catch (IOException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } } else { // Remote metadata collection CyclistController._cyclusService.submitCmd("cyclus", "-m"); _remoteDashA = CyclistController._cyclusService.latestJob(); _remoteDashA.statusProperty() .addListener(new ChangeListener<CyclusJob.Status>() { @Override public void changed(ObservableValue<? extends Status> observable, Status oldValue, Status newValue) { if (newValue == Status.READY) { retrieveSchema(_remoteDashA.getStdout()); } } }); } } }); archetypeGrid.add(cyclusDashM, 1, 0); archetypeGrid.add(new Label("Add Archetype to Simulation"), 0, 1); archetypeGrid.add(archetypes, 1, 1); } private void export() { FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().add( new FileChooser.ExtensionFilter("Image file (png, jpg, gif)", "*.png", "*.jpg", "'*.gif") ); File file = chooser.showSaveDialog(Cyclist.cyclistStage); if (file != null) { WritableImage image = pane.snapshot(new SnapshotParameters(), null); String name = file.getName(); String ext = name.substring(name.indexOf(".")+1, name.length()); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), ext, file); } catch (IOException e) { log.error("Error writing image to file: "+e.getMessage()); } } else { System.out.println("File did not generate correctly."); } } private void defaultJsonReader(String path) throws IOException{ BufferedReader reader = new BufferedReader( new FileReader (path + "/default-metadata.json")); String line = null; StringBuilder stringBuilder = new StringBuilder(); String ls = System.getProperty("line.separator"); while( ( line = reader.readLine() ) != null ) { stringBuilder.append( line ); stringBuilder.append( ls ); } reader.close(); retrieveSchema(stringBuilder.toString()); } }
Kludge to choose DSARR as default, if present
cyclist/src/edu/utexas/cycic/Cycic.java
Kludge to choose DSARR as default, if present
<ide><path>yclist/src/edu/utexas/cycic/Cycic.java <ide> skinMenu.getItems().add(defSkin); <ide> for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ <ide> final String skinName = DataArrays.visualizationSkins.get(i).name; <add> if (skinName.equals("DSARR")) { <add> currentSkin = skinName; <add> } <ide> MenuItem item = new MenuItem(skinName); <ide> item.setOnAction(new EventHandler<ActionEvent>(){ <ide> public void handle(ActionEvent e){
Java
apache-2.0
188be074e081215d1c22c50cef80dd0b8a197e60
0
ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp
/* 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.ofbiz.order.order; import java.math.BigDecimal; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javolution.util.FastList; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.ObjectType; import org.ofbiz.base.util.StringUtil; import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityComparisonOperator; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityConditionList; import org.ofbiz.entity.condition.EntityExpr; import org.ofbiz.entity.condition.EntityOperator; import org.ofbiz.entity.model.DynamicViewEntity; import org.ofbiz.entity.model.ModelKeyMap; import org.ofbiz.entity.util.EntityListIterator; import org.ofbiz.entity.util.EntityQuery; import org.ofbiz.security.Security; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ServiceUtil; /** * OrderLookupServices */ public class OrderLookupServices { public static final String module = OrderLookupServices.class.getName(); // SCIPIO: this is now a shared implementation static Map<String, Object> findOrders(DispatchContext dctx, Map<String, ? extends Object> context, boolean fullQuery) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Security security = dctx.getSecurity(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Integer viewIndex = (Integer) context.get("viewIndex"); Integer viewSize = (Integer) context.get("viewSize"); String showAll = (String) context.get("showAll"); String useEntryDate = (String) context.get("useEntryDate"); Locale locale = (Locale) context.get("locale"); if (showAll == null) { showAll = "N"; } // list of fields to select (initial list) Set<String> fieldsToSelect = new LinkedHashSet<String>(); fieldsToSelect.add("orderId"); fieldsToSelect.add("orderName"); fieldsToSelect.add("statusId"); fieldsToSelect.add("orderTypeId"); fieldsToSelect.add("orderDate"); fieldsToSelect.add("currencyUom"); fieldsToSelect.add("grandTotal"); fieldsToSelect.add("remainingSubTotal"); // sorting by order date newest first List<String> orderBy = UtilMisc.toList("-orderDate", "-orderId"); // list to hold the parameters List<String> paramList = FastList.newInstance(); // list of conditions List<EntityCondition> conditions = FastList.newInstance(); // check security flag for purchase orders boolean canViewPo = security.hasEntityPermission("ORDERMGR", "_PURCHASE_VIEW", userLogin); if (!canViewPo) { conditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.NOT_EQUAL, "PURCHASE_ORDER")); } // dynamic view entity DynamicViewEntity dve = new DynamicViewEntity(); dve.addMemberEntity("OH", "OrderHeader"); dve.addAliasAll("OH", "", null); // no prefix dve.addRelation("one-nofk", "", "OrderType", UtilMisc.toList(new ModelKeyMap("orderTypeId", "orderTypeId"))); dve.addRelation("one-nofk", "", "StatusItem", UtilMisc.toList(new ModelKeyMap("statusId", "statusId"))); // start the lookup String orderId = (String) context.get("orderId"); if (UtilValidate.isNotEmpty(orderId)) { paramList.add("orderId=" + orderId); conditions.add(makeExpr("orderId", orderId)); } // the base order header fields List<String> orderTypeList = UtilGenerics.checkList(context.get("orderTypeId")); if (orderTypeList != null) { List<EntityExpr> orExprs = FastList.newInstance(); for (String orderTypeId : orderTypeList) { paramList.add("orderTypeId=" + orderTypeId); if (!"PURCHASE_ORDER".equals(orderTypeId) || ("PURCHASE_ORDER".equals(orderTypeId) && canViewPo)) { orExprs.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, orderTypeId)); } } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } String orderName = (String) context.get("orderName"); if (UtilValidate.isNotEmpty(orderName)) { paramList.add("orderName=" + orderName); conditions.add(makeExpr("orderName", orderName, true)); } List<String> orderStatusList = UtilGenerics.checkList(context.get("orderStatusId")); if (orderStatusList != null) { List<EntityCondition> orExprs = FastList.newInstance(); for (String orderStatusId : orderStatusList) { paramList.add("orderStatusId=" + orderStatusId); if ("PENDING".equals(orderStatusId)) { List<EntityExpr> pendExprs = FastList.newInstance(); pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_CREATED")); pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_PROCESSING")); pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED")); orExprs.add(EntityCondition.makeCondition(pendExprs, EntityOperator.OR)); } else { orExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, orderStatusId)); } } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } List<String> productStoreList = UtilGenerics.checkList(context.get("productStoreId")); if (productStoreList != null) { List<EntityExpr> orExprs = FastList.newInstance(); for (String productStoreId : productStoreList) { paramList.add("productStoreId=" + productStoreId); orExprs.add(EntityCondition.makeCondition("productStoreId", EntityOperator.EQUALS, productStoreId)); } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } List<String> webSiteList = UtilGenerics.checkList(context.get("orderWebSiteId")); if (webSiteList != null) { List<EntityExpr> orExprs = FastList.newInstance(); for (String webSiteId : webSiteList) { paramList.add("orderWebSiteId=" + webSiteId); orExprs.add(EntityCondition.makeCondition("webSiteId", EntityOperator.EQUALS, webSiteId)); } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } List<String> saleChannelList = UtilGenerics.checkList(context.get("salesChannelEnumId")); if (saleChannelList != null) { List<EntityExpr> orExprs = FastList.newInstance(); for (String salesChannelEnumId : saleChannelList) { paramList.add("salesChannelEnumId=" + salesChannelEnumId); orExprs.add(EntityCondition.makeCondition("salesChannelEnumId", EntityOperator.EQUALS, salesChannelEnumId)); } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } String createdBy = (String) context.get("createdBy"); if (UtilValidate.isNotEmpty(createdBy)) { paramList.add("createdBy=" + createdBy); conditions.add(makeExpr("createdBy", createdBy)); } String terminalId = (String) context.get("terminalId"); if (UtilValidate.isNotEmpty(terminalId)) { paramList.add("terminalId=" + terminalId); conditions.add(makeExpr("terminalId", terminalId)); } String transactionId = (String) context.get("transactionId"); if (UtilValidate.isNotEmpty(transactionId)) { paramList.add("transactionId=" + transactionId); conditions.add(makeExpr("transactionId", transactionId)); } String externalId = (String) context.get("externalId"); if (UtilValidate.isNotEmpty(externalId)) { paramList.add("externalId=" + externalId); conditions.add(makeExpr("externalId", externalId)); } String internalCode = (String) context.get("internalCode"); if (UtilValidate.isNotEmpty(internalCode)) { paramList.add("internalCode=" + internalCode); conditions.add(makeExpr("internalCode", internalCode)); } String dateField = "Y".equals(useEntryDate) ? "entryDate" : "orderDate"; String minDate = (String) context.get("minDate"); if (UtilValidate.isNotEmpty(minDate) && minDate.length() > 8) { minDate = minDate.trim(); if (minDate.length() < 14) minDate = minDate + " " + "00:00:00.000"; paramList.add("minDate=" + minDate); try { Object converted = ObjectType.simpleTypeConvert(minDate, "Timestamp", null, null); if (converted != null) { conditions.add(EntityCondition.makeCondition(dateField, EntityOperator.GREATER_THAN_EQUAL_TO, converted)); } } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); } } String maxDate = (String) context.get("maxDate"); if (UtilValidate.isNotEmpty(maxDate) && maxDate.length() > 8) { maxDate = maxDate.trim(); if (maxDate.length() < 14) maxDate = maxDate + " " + "23:59:59.999"; paramList.add("maxDate=" + maxDate); try { Object converted = ObjectType.simpleTypeConvert(maxDate, "Timestamp", null, null); if (converted != null) { conditions.add(EntityCondition.makeCondition("orderDate", EntityOperator.LESS_THAN_EQUAL_TO, converted)); } } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); } } // party (role) fields String userLoginId = (String) context.get("userLoginId"); String partyId = (String) context.get("partyId"); List<String> roleTypeList = UtilGenerics.checkList(context.get("roleTypeId")); // SCIPIO: must track where partyId came from boolean partyIdFromUserLogin = false; if (UtilValidate.isNotEmpty(userLoginId) && UtilValidate.isEmpty(partyId)) { GenericValue ul = null; try { ul = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).cache().queryOne(); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); } if (ul != null) { partyId = ul.getString("partyId"); partyIdFromUserLogin = true; } } String isViewed = (String) context.get("isViewed"); if (UtilValidate.isNotEmpty(isViewed)) { paramList.add("isViewed=" + isViewed); conditions.add(makeExpr("isViewed", isViewed)); } // Shipment Method String shipmentMethod = (String) context.get("shipmentMethod"); if (UtilValidate.isNotEmpty(shipmentMethod)) { String carrierPartyId = shipmentMethod.substring(0, shipmentMethod.indexOf("@")); String ShippingMethodTypeId = shipmentMethod.substring(shipmentMethod.indexOf("@")+1); dve.addMemberEntity("OISG", "OrderItemShipGroup"); dve.addAlias("OISG", "shipmentMethodTypeId"); dve.addAlias("OISG", "carrierPartyId"); dve.addViewLink("OH", "OISG", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); if (UtilValidate.isNotEmpty(carrierPartyId)) { paramList.add("carrierPartyId=" + carrierPartyId); conditions.add(makeExpr("carrierPartyId", carrierPartyId)); } if (UtilValidate.isNotEmpty(ShippingMethodTypeId)) { paramList.add("ShippingMethodTypeId=" + ShippingMethodTypeId); conditions.add(makeExpr("shipmentMethodTypeId", ShippingMethodTypeId)); } } // PaymentGatewayResponse String gatewayAvsResult = (String) context.get("gatewayAvsResult"); String gatewayScoreResult = (String) context.get("gatewayScoreResult"); if (UtilValidate.isNotEmpty(gatewayAvsResult) || UtilValidate.isNotEmpty(gatewayScoreResult)) { dve.addMemberEntity("OPP", "OrderPaymentPreference"); dve.addMemberEntity("PGR", "PaymentGatewayResponse"); dve.addAlias("OPP", "orderPaymentPreferenceId"); dve.addAlias("PGR", "gatewayAvsResult"); dve.addAlias("PGR", "gatewayScoreResult"); dve.addViewLink("OH", "OPP", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); dve.addViewLink("OPP", "PGR", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderPaymentPreferenceId", "orderPaymentPreferenceId"))); } if (UtilValidate.isNotEmpty(gatewayAvsResult)) { paramList.add("gatewayAvsResult=" + gatewayAvsResult); conditions.add(EntityCondition.makeCondition("gatewayAvsResult", gatewayAvsResult)); } if (UtilValidate.isNotEmpty(gatewayScoreResult)) { paramList.add("gatewayScoreResult=" + gatewayScoreResult); conditions.add(EntityCondition.makeCondition("gatewayScoreResult", gatewayScoreResult)); } // add the role data to the view if (roleTypeList != null || partyId != null) { dve.addMemberEntity("OT", "OrderRole"); dve.addAlias("OT", "partyId"); dve.addAlias("OT", "roleTypeId"); dve.addViewLink("OH", "OT", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); } if (UtilValidate.isNotEmpty(partyId)) { // SCIPIO: only append the partyId to paramList if it didn't come from userLoginId if (!partyIdFromUserLogin) { paramList.add("partyId=" + partyId); } fieldsToSelect.add("partyId"); conditions.add(makeExpr("partyId", partyId)); } // SCIPIO: append userLoginId to paramList if (UtilValidate.isNotEmpty(userLoginId)) { paramList.add("userLoginId=" + userLoginId); } if (roleTypeList != null) { fieldsToSelect.add("roleTypeId"); List<EntityExpr> orExprs = FastList.newInstance(); for (String roleTypeId : roleTypeList) { paramList.add("roleTypeId=" + roleTypeId); orExprs.add(makeExpr("roleTypeId", roleTypeId)); } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } // order item fields String correspondingPoId = (String) context.get("correspondingPoId"); String subscriptionId = (String) context.get("subscriptionId"); String productId = (String) context.get("productId"); String budgetId = (String) context.get("budgetId"); String quoteId = (String) context.get("quoteId"); String goodIdentificationTypeId = (String) context.get("goodIdentificationTypeId"); String goodIdentificationIdValue = (String) context.get("goodIdentificationIdValue"); boolean hasGoodIdentification = UtilValidate.isNotEmpty(goodIdentificationTypeId) && UtilValidate.isNotEmpty(goodIdentificationIdValue); if (correspondingPoId != null || subscriptionId != null || productId != null || budgetId != null || quoteId != null || hasGoodIdentification) { dve.addMemberEntity("OI", "OrderItem"); dve.addAlias("OI", "correspondingPoId"); dve.addAlias("OI", "subscriptionId"); dve.addAlias("OI", "productId"); dve.addAlias("OI", "budgetId"); dve.addAlias("OI", "quoteId"); dve.addViewLink("OH", "OI", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); if (hasGoodIdentification) { dve.addMemberEntity("GOODID", "GoodIdentification"); dve.addAlias("GOODID", "goodIdentificationTypeId"); dve.addAlias("GOODID", "idValue"); dve.addViewLink("OI", "GOODID", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("productId", "productId"))); paramList.add("goodIdentificationTypeId=" + goodIdentificationTypeId); conditions.add(makeExpr("goodIdentificationTypeId", goodIdentificationTypeId)); paramList.add("goodIdentificationIdValue=" + goodIdentificationIdValue); conditions.add(makeExpr("idValue", goodIdentificationIdValue)); } } if (UtilValidate.isNotEmpty(correspondingPoId)) { paramList.add("correspondingPoId=" + correspondingPoId); conditions.add(makeExpr("correspondingPoId", correspondingPoId)); } if (UtilValidate.isNotEmpty(subscriptionId)) { paramList.add("subscriptionId=" + subscriptionId); conditions.add(makeExpr("subscriptionId", subscriptionId)); } if (UtilValidate.isNotEmpty(productId)) { paramList.add("productId=" + productId); if (productId.startsWith("%") || productId.startsWith("*") || productId.endsWith("%") || productId.endsWith("*")) { conditions.add(makeExpr("productId", productId)); } else { GenericValue product = null; try { product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne(); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); } if (product != null) { String isVirtual = product.getString("isVirtual"); if (isVirtual != null && "Y".equals(isVirtual)) { List<EntityExpr> orExprs = FastList.newInstance(); orExprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId)); Map<String, Object> varLookup = null; try { varLookup = dispatcher.runSync("getAllProductVariants", UtilMisc.toMap("productId", productId)); } catch (GenericServiceException e) { Debug.logWarning(e.getMessage(), module); } List<GenericValue> variants = UtilGenerics.checkList(varLookup.get("assocProducts")); if (variants != null) { for (GenericValue v : variants) { orExprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, v.getString("productIdTo"))); } } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } else { conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId)); } } else { String failMsg = UtilProperties.getMessage("OrderErrorUiLabels", "OrderFindOrderProductInvalid", UtilMisc.toMap("productId", productId), locale); return ServiceUtil.returnFailure(failMsg); } } } if (UtilValidate.isNotEmpty(budgetId)) { paramList.add("budgetId=" + budgetId); conditions.add(makeExpr("budgetId", budgetId)); } if (UtilValidate.isNotEmpty(quoteId)) { paramList.add("quoteId=" + quoteId); conditions.add(makeExpr("quoteId", quoteId)); } // payment preference fields String billingAccountId = (String) context.get("billingAccountId"); String finAccountId = (String) context.get("finAccountId"); String cardNumber = (String) context.get("cardNumber"); String accountNumber = (String) context.get("accountNumber"); String paymentStatusId = (String) context.get("paymentStatusId"); if (UtilValidate.isNotEmpty(paymentStatusId)) { paramList.add("paymentStatusId=" + paymentStatusId); conditions.add(makeExpr("paymentStatusId", paymentStatusId)); } if (finAccountId != null || cardNumber != null || accountNumber != null || paymentStatusId != null) { dve.addMemberEntity("OP", "OrderPaymentPreference"); dve.addAlias("OP", "finAccountId"); dve.addAlias("OP", "paymentMethodId"); dve.addAlias("OP", "paymentStatusId", "statusId", null, false, false, null); dve.addViewLink("OH", "OP", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); } // search by billing account ID if (UtilValidate.isNotEmpty(billingAccountId)) { paramList.add("billingAccountId=" + billingAccountId); conditions.add(makeExpr("billingAccountId", billingAccountId)); } // search by fin account ID if (UtilValidate.isNotEmpty(finAccountId)) { paramList.add("finAccountId=" + finAccountId); conditions.add(makeExpr("finAccountId", finAccountId)); } // search by card number if (UtilValidate.isNotEmpty(cardNumber)) { dve.addMemberEntity("CC", "CreditCard"); dve.addAlias("CC", "cardNumber"); dve.addViewLink("OP", "CC", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("paymentMethodId", "paymentMethodId"))); paramList.add("cardNumber=" + cardNumber); conditions.add(makeExpr("cardNumber", cardNumber)); } // search by eft account number if (UtilValidate.isNotEmpty(accountNumber)) { dve.addMemberEntity("EF", "EftAccount"); dve.addAlias("EF", "accountNumber"); dve.addViewLink("OP", "EF", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("paymentMethodId", "paymentMethodId"))); paramList.add("accountNumber=" + accountNumber); conditions.add(makeExpr("accountNumber", accountNumber)); } // shipment/inventory item String inventoryItemId = (String) context.get("inventoryItemId"); String softIdentifier = (String) context.get("softIdentifier"); String serialNumber = (String) context.get("serialNumber"); String shipmentId = (String) context.get("shipmentId"); if (shipmentId != null || inventoryItemId != null || softIdentifier != null || serialNumber != null) { dve.addMemberEntity("II", "ItemIssuance"); dve.addAlias("II", "shipmentId"); dve.addAlias("II", "inventoryItemId"); dve.addViewLink("OH", "II", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); if (softIdentifier != null || serialNumber != null) { dve.addMemberEntity("IV", "InventoryItem"); dve.addAlias("IV", "softIdentifier"); dve.addAlias("IV", "serialNumber"); dve.addViewLink("II", "IV", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("inventoryItemId", "inventoryItemId"))); } } if (UtilValidate.isNotEmpty(inventoryItemId)) { paramList.add("inventoryItemId=" + inventoryItemId); conditions.add(makeExpr("inventoryItemId", inventoryItemId)); } if (UtilValidate.isNotEmpty(softIdentifier)) { paramList.add("softIdentifier=" + softIdentifier); conditions.add(makeExpr("softIdentifier", softIdentifier, true)); } if (UtilValidate.isNotEmpty(serialNumber)) { paramList.add("serialNumber=" + serialNumber); conditions.add(makeExpr("serialNumber", serialNumber, true)); } if (UtilValidate.isNotEmpty(shipmentId)) { paramList.add("shipmentId=" + shipmentId); conditions.add(makeExpr("shipmentId", shipmentId)); } // back order checking String hasBackOrders = (String) context.get("hasBackOrders"); if (UtilValidate.isNotEmpty(hasBackOrders)) { dve.addMemberEntity("IR", "OrderItemShipGrpInvRes"); dve.addAlias("IR", "quantityNotAvailable"); dve.addViewLink("OH", "IR", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); paramList.add("hasBackOrders=" + hasBackOrders); if ("Y".equals(hasBackOrders)) { conditions.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.NOT_EQUAL, null)); conditions.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.GREATER_THAN, BigDecimal.ZERO)); } else if ("N".equals(hasBackOrders)) { List<EntityExpr> orExpr = FastList.newInstance(); orExpr.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.EQUALS, null)); orExpr.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.EQUALS, BigDecimal.ZERO)); conditions.add(EntityCondition.makeCondition(orExpr, EntityOperator.OR)); } } // Get all orders according to specific ship to country with "Only Include" or "Do not Include". String countryGeoId = (String) context.get("countryGeoId"); String includeCountry = (String) context.get("includeCountry"); if (UtilValidate.isNotEmpty(countryGeoId) && UtilValidate.isNotEmpty(includeCountry)) { paramList.add("countryGeoId=" + countryGeoId); paramList.add("includeCountry=" + includeCountry); // add condition to dynamic view dve.addMemberEntity("OCM", "OrderContactMech"); dve.addMemberEntity("PA", "PostalAddress"); dve.addAlias("OCM", "contactMechId"); dve.addAlias("OCM", "contactMechPurposeTypeId"); dve.addAlias("PA", "countryGeoId"); dve.addViewLink("OH", "OCM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId")); dve.addViewLink("OCM", "PA", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId")); EntityConditionList<EntityExpr> exprs = null; if ("Y".equals(includeCountry)) { exprs = EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition("contactMechPurposeTypeId", "SHIPPING_LOCATION"), EntityCondition.makeCondition("countryGeoId", countryGeoId)), EntityOperator.AND); } else { exprs = EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition("contactMechPurposeTypeId", "SHIPPING_LOCATION"), EntityCondition.makeCondition("countryGeoId", EntityOperator.NOT_EQUAL, countryGeoId)), EntityOperator.AND); } conditions.add(exprs); } // create the main condition EntityCondition cond = null; if (conditions.size() > 0 || showAll.equalsIgnoreCase("Y")) { cond = EntityCondition.makeCondition(conditions, EntityOperator.AND); } if (Debug.verboseOn()) { Debug.logInfo("Find order query: " + cond.toString(), module); } List<GenericValue> orderList = FastList.newInstance(); int orderCount = 0; // SCIPIO: only if not full query int lowIndex; int highIndex; if (!fullQuery) { // get the index for the partial list lowIndex = (((viewIndex.intValue() - 1) * viewSize.intValue()) + 1); highIndex = viewIndex.intValue() * viewSize.intValue(); } else { lowIndex = 0; highIndex = 0; } if (cond != null) { EntityListIterator eli = null; try { EntityQuery eqy; // do the lookup eqy = EntityQuery.use(delegator) .select(fieldsToSelect) .from(dve) .where(cond) .orderBy(orderBy) .distinct(); // set distinct on so we only get one row per order // SCIPIO: only max rows if not limited if (!fullQuery) { eqy = eqy.maxRows(highIndex); } eli = eqy.cursorScrollInsensitive().queryIterator(); orderCount = eli.getResultsSizeAfterPartialList(); // get the partial list for this page // SCIPIO: support full query if (fullQuery) { orderList = eli.getCompleteList(); } else { eli.beforeFirst(); if (orderCount > viewSize.intValue()) { orderList = eli.getPartialList(lowIndex, viewSize.intValue()); } else if (orderCount > 0) { orderList = eli.getCompleteList(); } if (highIndex > orderCount) { highIndex = orderCount; } } } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } finally { if (eli != null) { try { eli.close(); } catch (GenericEntityException e) { Debug.logWarning(e, e.getMessage(), module); } } } } // create the result map Map<String, Object> result = ServiceUtil.returnSuccess(); // filter out requested inventory problems filterInventoryProblems(context, result, orderList, paramList); // format the param list // Scipio: FIXME: The paramlist should not be escaped this early; it should be escaped by Freemarker String paramString = StringUtil.join(paramList, "&amp;"); // SCIPIO: only if not full query if (!fullQuery) { result.put("highIndex", Integer.valueOf(highIndex)); result.put("lowIndex", Integer.valueOf(lowIndex)); result.put("viewIndex", viewIndex); result.put("viewSize", viewSize); } result.put("showAll", showAll); result.put("paramList", (paramString != null? paramString: "")); result.put("orderList", orderList); result.put("orderListSize", Integer.valueOf(orderCount)); return result; } /** * SCIPIO: stock findOrders service. */ public static Map<String, Object> findOrders(DispatchContext dctx, Map<String, ? extends Object> context) { return findOrders(dctx, context, false); } /** * SCIPIO: findOrders without view size limitations. * */ public static Map<String, Object> findOrdersFull(DispatchContext dctx, Map<String, ? extends Object> context) { return findOrders(dctx, context, true); } public static void filterInventoryProblems(Map<String, ? extends Object> context, Map<String, Object> result, List<GenericValue> orderList, List<String> paramList) { List<String> filterInventoryProblems = FastList.newInstance(); String doFilter = (String) context.get("filterInventoryProblems"); if (doFilter == null) { doFilter = "N"; } // SCIPIO: must add param to list even if no results! if ("Y".equals(doFilter)) { paramList.add("filterInventoryProblems=Y"); } if ("Y".equals(doFilter) && orderList.size() > 0) { //paramList.add("filterInventoryProblems=Y"); for (GenericValue orderHeader : orderList) { OrderReadHelper orh = new OrderReadHelper(orderHeader); BigDecimal backorderQty = orh.getOrderBackorderQuantity(); if (backorderQty.compareTo(BigDecimal.ZERO) == 1) { filterInventoryProblems.add(orh.getOrderId()); } } } List<String> filterPOsOpenPastTheirETA = FastList.newInstance(); List<String> filterPOsWithRejectedItems = FastList.newInstance(); List<String> filterPartiallyReceivedPOs = FastList.newInstance(); String filterPOReject = (String) context.get("filterPOsWithRejectedItems"); String filterPOPast = (String) context.get("filterPOsOpenPastTheirETA"); String filterPartRec = (String) context.get("filterPartiallyReceivedPOs"); if (filterPOReject == null) { filterPOReject = "N"; } if (filterPOPast == null) { filterPOPast = "N"; } if (filterPartRec == null) { filterPartRec = "N"; } boolean doPoFilter = false; if ("Y".equals(filterPOReject)) { paramList.add("filterPOsWithRejectedItems=Y"); doPoFilter = true; } if ("Y".equals(filterPOPast)) { paramList.add("filterPOsOpenPastTheirETA=Y"); doPoFilter = true; } if ("Y".equals(filterPartRec)) { paramList.add("filterPartiallyReceivedPOs=Y"); doPoFilter = true; } if (doPoFilter && orderList.size() > 0) { for (GenericValue orderHeader : orderList) { OrderReadHelper orh = new OrderReadHelper(orderHeader); String orderType = orh.getOrderTypeId(); String orderId = orh.getOrderId(); if ("PURCHASE_ORDER".equals(orderType)) { if ("Y".equals(filterPOReject) && orh.getRejectedOrderItems()) { filterPOsWithRejectedItems.add(orderId); } else if ("Y".equals(filterPOPast) && orh.getPastEtaOrderItems(orderId)) { filterPOsOpenPastTheirETA.add(orderId); } else if ("Y".equals(filterPartRec) && orh.getPartiallyReceivedItems()) { filterPartiallyReceivedPOs.add(orderId); } } } } result.put("filterInventoryProblemsList", filterInventoryProblems); result.put("filterPOsWithRejectedItemsList", filterPOsWithRejectedItems); result.put("filterPOsOpenPastTheirETAList", filterPOsOpenPastTheirETA); result.put("filterPartiallyReceivedPOsList", filterPartiallyReceivedPOs); } protected static EntityExpr makeExpr(String fieldName, String value) { return makeExpr(fieldName, value, false); } protected static EntityExpr makeExpr(String fieldName, String value, boolean forceLike) { EntityComparisonOperator<?, ?> op = forceLike ? EntityOperator.LIKE : EntityOperator.EQUALS; if (value.startsWith("*")) { op = EntityOperator.LIKE; value = "%" + value.substring(1); } else if (value.startsWith("%")) { op = EntityOperator.LIKE; } if (value.endsWith("*")) { op = EntityOperator.LIKE; value = value.substring(0, value.length() - 1) + "%"; } else if (value.endsWith("%")) { op = EntityOperator.LIKE; } if (forceLike) { if (!value.startsWith("%")) { value = "%" + value; } if (!value.endsWith("%")) { value = value + "%"; } } return EntityCondition.makeCondition(fieldName, op, value); } }
applications/order/src/org/ofbiz/order/order/OrderLookupServices.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.ofbiz.order.order; import java.math.BigDecimal; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javolution.util.FastList; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.ObjectType; import org.ofbiz.base.util.StringUtil; import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityComparisonOperator; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityConditionList; import org.ofbiz.entity.condition.EntityExpr; import org.ofbiz.entity.condition.EntityOperator; import org.ofbiz.entity.model.DynamicViewEntity; import org.ofbiz.entity.model.ModelKeyMap; import org.ofbiz.entity.util.EntityListIterator; import org.ofbiz.entity.util.EntityQuery; import org.ofbiz.security.Security; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ServiceUtil; /** * OrderLookupServices */ public class OrderLookupServices { public static final String module = OrderLookupServices.class.getName(); // SCIPIO: this is now a shared implementation static Map<String, Object> findOrders(DispatchContext dctx, Map<String, ? extends Object> context, boolean fullQuery) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Security security = dctx.getSecurity(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Integer viewIndex = (Integer) context.get("viewIndex"); Integer viewSize = (Integer) context.get("viewSize"); String showAll = (String) context.get("showAll"); String useEntryDate = (String) context.get("useEntryDate"); Locale locale = (Locale) context.get("locale"); if (showAll == null) { showAll = "N"; } // list of fields to select (initial list) Set<String> fieldsToSelect = new LinkedHashSet<String>(); fieldsToSelect.add("orderId"); fieldsToSelect.add("orderName"); fieldsToSelect.add("statusId"); fieldsToSelect.add("orderTypeId"); fieldsToSelect.add("orderDate"); fieldsToSelect.add("currencyUom"); fieldsToSelect.add("grandTotal"); fieldsToSelect.add("remainingSubTotal"); // sorting by order date newest first List<String> orderBy = UtilMisc.toList("-orderDate", "-orderId"); // list to hold the parameters List<String> paramList = FastList.newInstance(); // list of conditions List<EntityCondition> conditions = FastList.newInstance(); // check security flag for purchase orders boolean canViewPo = security.hasEntityPermission("ORDERMGR", "_PURCHASE_VIEW", userLogin); if (!canViewPo) { conditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.NOT_EQUAL, "PURCHASE_ORDER")); } // dynamic view entity DynamicViewEntity dve = new DynamicViewEntity(); dve.addMemberEntity("OH", "OrderHeader"); dve.addAliasAll("OH", "", null); // no prefix dve.addRelation("one-nofk", "", "OrderType", UtilMisc.toList(new ModelKeyMap("orderTypeId", "orderTypeId"))); dve.addRelation("one-nofk", "", "StatusItem", UtilMisc.toList(new ModelKeyMap("statusId", "statusId"))); // start the lookup String orderId = (String) context.get("orderId"); if (UtilValidate.isNotEmpty(orderId)) { paramList.add("orderId=" + orderId); conditions.add(makeExpr("orderId", orderId)); } // the base order header fields List<String> orderTypeList = UtilGenerics.checkList(context.get("orderTypeId")); if (orderTypeList != null) { List<EntityExpr> orExprs = FastList.newInstance(); for (String orderTypeId : orderTypeList) { paramList.add("orderTypeId=" + orderTypeId); if (!"PURCHASE_ORDER".equals(orderTypeId) || ("PURCHASE_ORDER".equals(orderTypeId) && canViewPo)) { orExprs.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, orderTypeId)); } } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } String orderName = (String) context.get("orderName"); if (UtilValidate.isNotEmpty(orderName)) { paramList.add("orderName=" + orderName); conditions.add(makeExpr("orderName", orderName, true)); } List<String> orderStatusList = UtilGenerics.checkList(context.get("orderStatusId")); if (orderStatusList != null) { List<EntityCondition> orExprs = FastList.newInstance(); for (String orderStatusId : orderStatusList) { paramList.add("orderStatusId=" + orderStatusId); if ("PENDING".equals(orderStatusId)) { List<EntityExpr> pendExprs = FastList.newInstance(); pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_CREATED")); pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_PROCESSING")); pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED")); orExprs.add(EntityCondition.makeCondition(pendExprs, EntityOperator.OR)); } else { orExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, orderStatusId)); } } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } List<String> productStoreList = UtilGenerics.checkList(context.get("productStoreId")); if (productStoreList != null) { List<EntityExpr> orExprs = FastList.newInstance(); for (String productStoreId : productStoreList) { paramList.add("productStoreId=" + productStoreId); orExprs.add(EntityCondition.makeCondition("productStoreId", EntityOperator.EQUALS, productStoreId)); } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } List<String> webSiteList = UtilGenerics.checkList(context.get("orderWebSiteId")); if (webSiteList != null) { List<EntityExpr> orExprs = FastList.newInstance(); for (String webSiteId : webSiteList) { paramList.add("orderWebSiteId=" + webSiteId); orExprs.add(EntityCondition.makeCondition("webSiteId", EntityOperator.EQUALS, webSiteId)); } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } List<String> saleChannelList = UtilGenerics.checkList(context.get("salesChannelEnumId")); if (saleChannelList != null) { List<EntityExpr> orExprs = FastList.newInstance(); for (String salesChannelEnumId : saleChannelList) { paramList.add("salesChannelEnumId=" + salesChannelEnumId); orExprs.add(EntityCondition.makeCondition("salesChannelEnumId", EntityOperator.EQUALS, salesChannelEnumId)); } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } String createdBy = (String) context.get("createdBy"); if (UtilValidate.isNotEmpty(createdBy)) { paramList.add("createdBy=" + createdBy); conditions.add(makeExpr("createdBy", createdBy)); } String terminalId = (String) context.get("terminalId"); if (UtilValidate.isNotEmpty(terminalId)) { paramList.add("terminalId=" + terminalId); conditions.add(makeExpr("terminalId", terminalId)); } String transactionId = (String) context.get("transactionId"); if (UtilValidate.isNotEmpty(transactionId)) { paramList.add("transactionId=" + transactionId); conditions.add(makeExpr("transactionId", transactionId)); } String externalId = (String) context.get("externalId"); if (UtilValidate.isNotEmpty(externalId)) { paramList.add("externalId=" + externalId); conditions.add(makeExpr("externalId", externalId)); } String internalCode = (String) context.get("internalCode"); if (UtilValidate.isNotEmpty(internalCode)) { paramList.add("internalCode=" + internalCode); conditions.add(makeExpr("internalCode", internalCode)); } String dateField = "Y".equals(useEntryDate) ? "entryDate" : "orderDate"; String minDate = (String) context.get("minDate"); if (UtilValidate.isNotEmpty(minDate) && minDate.length() > 8) { minDate = minDate.trim(); if (minDate.length() < 14) minDate = minDate + " " + "00:00:00.000"; paramList.add("minDate=" + minDate); try { Object converted = ObjectType.simpleTypeConvert(minDate, "Timestamp", null, null); if (converted != null) { conditions.add(EntityCondition.makeCondition(dateField, EntityOperator.GREATER_THAN_EQUAL_TO, converted)); } } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); } } String maxDate = (String) context.get("maxDate"); if (UtilValidate.isNotEmpty(maxDate) && maxDate.length() > 8) { maxDate = maxDate.trim(); if (maxDate.length() < 14) maxDate = maxDate + " " + "23:59:59.999"; paramList.add("maxDate=" + maxDate); try { Object converted = ObjectType.simpleTypeConvert(maxDate, "Timestamp", null, null); if (converted != null) { conditions.add(EntityCondition.makeCondition("orderDate", EntityOperator.LESS_THAN_EQUAL_TO, converted)); } } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); } } // party (role) fields String userLoginId = (String) context.get("userLoginId"); String partyId = (String) context.get("partyId"); List<String> roleTypeList = UtilGenerics.checkList(context.get("roleTypeId")); if (UtilValidate.isNotEmpty(userLoginId) && UtilValidate.isEmpty(partyId)) { GenericValue ul = null; try { ul = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).cache().queryOne(); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); } if (ul != null) { partyId = ul.getString("partyId"); } } String isViewed = (String) context.get("isViewed"); if (UtilValidate.isNotEmpty(isViewed)) { paramList.add("isViewed=" + isViewed); conditions.add(makeExpr("isViewed", isViewed)); } // Shipment Method String shipmentMethod = (String) context.get("shipmentMethod"); if (UtilValidate.isNotEmpty(shipmentMethod)) { String carrierPartyId = shipmentMethod.substring(0, shipmentMethod.indexOf("@")); String ShippingMethodTypeId = shipmentMethod.substring(shipmentMethod.indexOf("@")+1); dve.addMemberEntity("OISG", "OrderItemShipGroup"); dve.addAlias("OISG", "shipmentMethodTypeId"); dve.addAlias("OISG", "carrierPartyId"); dve.addViewLink("OH", "OISG", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); if (UtilValidate.isNotEmpty(carrierPartyId)) { paramList.add("carrierPartyId=" + carrierPartyId); conditions.add(makeExpr("carrierPartyId", carrierPartyId)); } if (UtilValidate.isNotEmpty(ShippingMethodTypeId)) { paramList.add("ShippingMethodTypeId=" + ShippingMethodTypeId); conditions.add(makeExpr("shipmentMethodTypeId", ShippingMethodTypeId)); } } // PaymentGatewayResponse String gatewayAvsResult = (String) context.get("gatewayAvsResult"); String gatewayScoreResult = (String) context.get("gatewayScoreResult"); if (UtilValidate.isNotEmpty(gatewayAvsResult) || UtilValidate.isNotEmpty(gatewayScoreResult)) { dve.addMemberEntity("OPP", "OrderPaymentPreference"); dve.addMemberEntity("PGR", "PaymentGatewayResponse"); dve.addAlias("OPP", "orderPaymentPreferenceId"); dve.addAlias("PGR", "gatewayAvsResult"); dve.addAlias("PGR", "gatewayScoreResult"); dve.addViewLink("OH", "OPP", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); dve.addViewLink("OPP", "PGR", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderPaymentPreferenceId", "orderPaymentPreferenceId"))); } if (UtilValidate.isNotEmpty(gatewayAvsResult)) { paramList.add("gatewayAvsResult=" + gatewayAvsResult); conditions.add(EntityCondition.makeCondition("gatewayAvsResult", gatewayAvsResult)); } if (UtilValidate.isNotEmpty(gatewayScoreResult)) { paramList.add("gatewayScoreResult=" + gatewayScoreResult); conditions.add(EntityCondition.makeCondition("gatewayScoreResult", gatewayScoreResult)); } // add the role data to the view if (roleTypeList != null || partyId != null) { dve.addMemberEntity("OT", "OrderRole"); dve.addAlias("OT", "partyId"); dve.addAlias("OT", "roleTypeId"); dve.addViewLink("OH", "OT", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); } if (UtilValidate.isNotEmpty(partyId)) { paramList.add("partyId=" + partyId); fieldsToSelect.add("partyId"); conditions.add(makeExpr("partyId", partyId)); } if (roleTypeList != null) { fieldsToSelect.add("roleTypeId"); List<EntityExpr> orExprs = FastList.newInstance(); for (String roleTypeId : roleTypeList) { paramList.add("roleTypeId=" + roleTypeId); orExprs.add(makeExpr("roleTypeId", roleTypeId)); } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } // order item fields String correspondingPoId = (String) context.get("correspondingPoId"); String subscriptionId = (String) context.get("subscriptionId"); String productId = (String) context.get("productId"); String budgetId = (String) context.get("budgetId"); String quoteId = (String) context.get("quoteId"); String goodIdentificationTypeId = (String) context.get("goodIdentificationTypeId"); String goodIdentificationIdValue = (String) context.get("goodIdentificationIdValue"); boolean hasGoodIdentification = UtilValidate.isNotEmpty(goodIdentificationTypeId) && UtilValidate.isNotEmpty(goodIdentificationIdValue); if (correspondingPoId != null || subscriptionId != null || productId != null || budgetId != null || quoteId != null || hasGoodIdentification) { dve.addMemberEntity("OI", "OrderItem"); dve.addAlias("OI", "correspondingPoId"); dve.addAlias("OI", "subscriptionId"); dve.addAlias("OI", "productId"); dve.addAlias("OI", "budgetId"); dve.addAlias("OI", "quoteId"); dve.addViewLink("OH", "OI", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); if (hasGoodIdentification) { dve.addMemberEntity("GOODID", "GoodIdentification"); dve.addAlias("GOODID", "goodIdentificationTypeId"); dve.addAlias("GOODID", "idValue"); dve.addViewLink("OI", "GOODID", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("productId", "productId"))); paramList.add("goodIdentificationTypeId=" + goodIdentificationTypeId); conditions.add(makeExpr("goodIdentificationTypeId", goodIdentificationTypeId)); paramList.add("goodIdentificationIdValue=" + goodIdentificationIdValue); conditions.add(makeExpr("idValue", goodIdentificationIdValue)); } } if (UtilValidate.isNotEmpty(correspondingPoId)) { paramList.add("correspondingPoId=" + correspondingPoId); conditions.add(makeExpr("correspondingPoId", correspondingPoId)); } if (UtilValidate.isNotEmpty(subscriptionId)) { paramList.add("subscriptionId=" + subscriptionId); conditions.add(makeExpr("subscriptionId", subscriptionId)); } if (UtilValidate.isNotEmpty(productId)) { paramList.add("productId=" + productId); if (productId.startsWith("%") || productId.startsWith("*") || productId.endsWith("%") || productId.endsWith("*")) { conditions.add(makeExpr("productId", productId)); } else { GenericValue product = null; try { product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne(); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); } if (product != null) { String isVirtual = product.getString("isVirtual"); if (isVirtual != null && "Y".equals(isVirtual)) { List<EntityExpr> orExprs = FastList.newInstance(); orExprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId)); Map<String, Object> varLookup = null; try { varLookup = dispatcher.runSync("getAllProductVariants", UtilMisc.toMap("productId", productId)); } catch (GenericServiceException e) { Debug.logWarning(e.getMessage(), module); } List<GenericValue> variants = UtilGenerics.checkList(varLookup.get("assocProducts")); if (variants != null) { for (GenericValue v : variants) { orExprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, v.getString("productIdTo"))); } } conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR)); } else { conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId)); } } else { String failMsg = UtilProperties.getMessage("OrderErrorUiLabels", "OrderFindOrderProductInvalid", UtilMisc.toMap("productId", productId), locale); return ServiceUtil.returnFailure(failMsg); } } } if (UtilValidate.isNotEmpty(budgetId)) { paramList.add("budgetId=" + budgetId); conditions.add(makeExpr("budgetId", budgetId)); } if (UtilValidate.isNotEmpty(quoteId)) { paramList.add("quoteId=" + quoteId); conditions.add(makeExpr("quoteId", quoteId)); } // payment preference fields String billingAccountId = (String) context.get("billingAccountId"); String finAccountId = (String) context.get("finAccountId"); String cardNumber = (String) context.get("cardNumber"); String accountNumber = (String) context.get("accountNumber"); String paymentStatusId = (String) context.get("paymentStatusId"); if (UtilValidate.isNotEmpty(paymentStatusId)) { paramList.add("paymentStatusId=" + paymentStatusId); conditions.add(makeExpr("paymentStatusId", paymentStatusId)); } if (finAccountId != null || cardNumber != null || accountNumber != null || paymentStatusId != null) { dve.addMemberEntity("OP", "OrderPaymentPreference"); dve.addAlias("OP", "finAccountId"); dve.addAlias("OP", "paymentMethodId"); dve.addAlias("OP", "paymentStatusId", "statusId", null, false, false, null); dve.addViewLink("OH", "OP", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); } // search by billing account ID if (UtilValidate.isNotEmpty(billingAccountId)) { paramList.add("billingAccountId=" + billingAccountId); conditions.add(makeExpr("billingAccountId", billingAccountId)); } // search by fin account ID if (UtilValidate.isNotEmpty(finAccountId)) { paramList.add("finAccountId=" + finAccountId); conditions.add(makeExpr("finAccountId", finAccountId)); } // search by card number if (UtilValidate.isNotEmpty(cardNumber)) { dve.addMemberEntity("CC", "CreditCard"); dve.addAlias("CC", "cardNumber"); dve.addViewLink("OP", "CC", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("paymentMethodId", "paymentMethodId"))); paramList.add("cardNumber=" + cardNumber); conditions.add(makeExpr("cardNumber", cardNumber)); } // search by eft account number if (UtilValidate.isNotEmpty(accountNumber)) { dve.addMemberEntity("EF", "EftAccount"); dve.addAlias("EF", "accountNumber"); dve.addViewLink("OP", "EF", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("paymentMethodId", "paymentMethodId"))); paramList.add("accountNumber=" + accountNumber); conditions.add(makeExpr("accountNumber", accountNumber)); } // shipment/inventory item String inventoryItemId = (String) context.get("inventoryItemId"); String softIdentifier = (String) context.get("softIdentifier"); String serialNumber = (String) context.get("serialNumber"); String shipmentId = (String) context.get("shipmentId"); if (shipmentId != null || inventoryItemId != null || softIdentifier != null || serialNumber != null) { dve.addMemberEntity("II", "ItemIssuance"); dve.addAlias("II", "shipmentId"); dve.addAlias("II", "inventoryItemId"); dve.addViewLink("OH", "II", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); if (softIdentifier != null || serialNumber != null) { dve.addMemberEntity("IV", "InventoryItem"); dve.addAlias("IV", "softIdentifier"); dve.addAlias("IV", "serialNumber"); dve.addViewLink("II", "IV", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("inventoryItemId", "inventoryItemId"))); } } if (UtilValidate.isNotEmpty(inventoryItemId)) { paramList.add("inventoryItemId=" + inventoryItemId); conditions.add(makeExpr("inventoryItemId", inventoryItemId)); } if (UtilValidate.isNotEmpty(softIdentifier)) { paramList.add("softIdentifier=" + softIdentifier); conditions.add(makeExpr("softIdentifier", softIdentifier, true)); } if (UtilValidate.isNotEmpty(serialNumber)) { paramList.add("serialNumber=" + serialNumber); conditions.add(makeExpr("serialNumber", serialNumber, true)); } if (UtilValidate.isNotEmpty(shipmentId)) { paramList.add("shipmentId=" + shipmentId); conditions.add(makeExpr("shipmentId", shipmentId)); } // back order checking String hasBackOrders = (String) context.get("hasBackOrders"); if (UtilValidate.isNotEmpty(hasBackOrders)) { dve.addMemberEntity("IR", "OrderItemShipGrpInvRes"); dve.addAlias("IR", "quantityNotAvailable"); dve.addViewLink("OH", "IR", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId"))); paramList.add("hasBackOrders=" + hasBackOrders); if ("Y".equals(hasBackOrders)) { conditions.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.NOT_EQUAL, null)); conditions.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.GREATER_THAN, BigDecimal.ZERO)); } else if ("N".equals(hasBackOrders)) { List<EntityExpr> orExpr = FastList.newInstance(); orExpr.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.EQUALS, null)); orExpr.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.EQUALS, BigDecimal.ZERO)); conditions.add(EntityCondition.makeCondition(orExpr, EntityOperator.OR)); } } // Get all orders according to specific ship to country with "Only Include" or "Do not Include". String countryGeoId = (String) context.get("countryGeoId"); String includeCountry = (String) context.get("includeCountry"); if (UtilValidate.isNotEmpty(countryGeoId) && UtilValidate.isNotEmpty(includeCountry)) { paramList.add("countryGeoId=" + countryGeoId); paramList.add("includeCountry=" + includeCountry); // add condition to dynamic view dve.addMemberEntity("OCM", "OrderContactMech"); dve.addMemberEntity("PA", "PostalAddress"); dve.addAlias("OCM", "contactMechId"); dve.addAlias("OCM", "contactMechPurposeTypeId"); dve.addAlias("PA", "countryGeoId"); dve.addViewLink("OH", "OCM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId")); dve.addViewLink("OCM", "PA", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId")); EntityConditionList<EntityExpr> exprs = null; if ("Y".equals(includeCountry)) { exprs = EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition("contactMechPurposeTypeId", "SHIPPING_LOCATION"), EntityCondition.makeCondition("countryGeoId", countryGeoId)), EntityOperator.AND); } else { exprs = EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition("contactMechPurposeTypeId", "SHIPPING_LOCATION"), EntityCondition.makeCondition("countryGeoId", EntityOperator.NOT_EQUAL, countryGeoId)), EntityOperator.AND); } conditions.add(exprs); } // create the main condition EntityCondition cond = null; if (conditions.size() > 0 || showAll.equalsIgnoreCase("Y")) { cond = EntityCondition.makeCondition(conditions, EntityOperator.AND); } if (Debug.verboseOn()) { Debug.logInfo("Find order query: " + cond.toString(), module); } List<GenericValue> orderList = FastList.newInstance(); int orderCount = 0; // SCIPIO: only if not full query int lowIndex; int highIndex; if (!fullQuery) { // get the index for the partial list lowIndex = (((viewIndex.intValue() - 1) * viewSize.intValue()) + 1); highIndex = viewIndex.intValue() * viewSize.intValue(); } else { lowIndex = 0; highIndex = 0; } if (cond != null) { EntityListIterator eli = null; try { EntityQuery eqy; // do the lookup eqy = EntityQuery.use(delegator) .select(fieldsToSelect) .from(dve) .where(cond) .orderBy(orderBy) .distinct(); // set distinct on so we only get one row per order // SCIPIO: only max rows if not limited if (!fullQuery) { eqy = eqy.maxRows(highIndex); } eli = eqy.cursorScrollInsensitive().queryIterator(); orderCount = eli.getResultsSizeAfterPartialList(); // get the partial list for this page // SCIPIO: support full query if (fullQuery) { orderList = eli.getCompleteList(); } else { eli.beforeFirst(); if (orderCount > viewSize.intValue()) { orderList = eli.getPartialList(lowIndex, viewSize.intValue()); } else if (orderCount > 0) { orderList = eli.getCompleteList(); } if (highIndex > orderCount) { highIndex = orderCount; } } } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } finally { if (eli != null) { try { eli.close(); } catch (GenericEntityException e) { Debug.logWarning(e, e.getMessage(), module); } } } } // create the result map Map<String, Object> result = ServiceUtil.returnSuccess(); // filter out requested inventory problems filterInventoryProblems(context, result, orderList, paramList); // format the param list // Scipio: FIXME: The paramlist should not be escaped this early; it should be escaped by Freemarker String paramString = StringUtil.join(paramList, "&amp;"); // SCIPIO: only if not full query if (!fullQuery) { result.put("highIndex", Integer.valueOf(highIndex)); result.put("lowIndex", Integer.valueOf(lowIndex)); result.put("viewIndex", viewIndex); result.put("viewSize", viewSize); } result.put("showAll", showAll); result.put("paramList", (paramString != null? paramString: "")); result.put("orderList", orderList); result.put("orderListSize", Integer.valueOf(orderCount)); return result; } /** * SCIPIO: stock findOrders service. */ public static Map<String, Object> findOrders(DispatchContext dctx, Map<String, ? extends Object> context) { return findOrders(dctx, context, false); } /** * SCIPIO: findOrders without view size limitations. * */ public static Map<String, Object> findOrdersFull(DispatchContext dctx, Map<String, ? extends Object> context) { return findOrders(dctx, context, true); } public static void filterInventoryProblems(Map<String, ? extends Object> context, Map<String, Object> result, List<GenericValue> orderList, List<String> paramList) { List<String> filterInventoryProblems = FastList.newInstance(); String doFilter = (String) context.get("filterInventoryProblems"); if (doFilter == null) { doFilter = "N"; } // SCIPIO: must add param to list even if no results! if ("Y".equals(doFilter)) { paramList.add("filterInventoryProblems=Y"); } if ("Y".equals(doFilter) && orderList.size() > 0) { //paramList.add("filterInventoryProblems=Y"); for (GenericValue orderHeader : orderList) { OrderReadHelper orh = new OrderReadHelper(orderHeader); BigDecimal backorderQty = orh.getOrderBackorderQuantity(); if (backorderQty.compareTo(BigDecimal.ZERO) == 1) { filterInventoryProblems.add(orh.getOrderId()); } } } List<String> filterPOsOpenPastTheirETA = FastList.newInstance(); List<String> filterPOsWithRejectedItems = FastList.newInstance(); List<String> filterPartiallyReceivedPOs = FastList.newInstance(); String filterPOReject = (String) context.get("filterPOsWithRejectedItems"); String filterPOPast = (String) context.get("filterPOsOpenPastTheirETA"); String filterPartRec = (String) context.get("filterPartiallyReceivedPOs"); if (filterPOReject == null) { filterPOReject = "N"; } if (filterPOPast == null) { filterPOPast = "N"; } if (filterPartRec == null) { filterPartRec = "N"; } boolean doPoFilter = false; if ("Y".equals(filterPOReject)) { paramList.add("filterPOsWithRejectedItems=Y"); doPoFilter = true; } if ("Y".equals(filterPOPast)) { paramList.add("filterPOsOpenPastTheirETA=Y"); doPoFilter = true; } if ("Y".equals(filterPartRec)) { paramList.add("filterPartiallyReceivedPOs=Y"); doPoFilter = true; } if (doPoFilter && orderList.size() > 0) { for (GenericValue orderHeader : orderList) { OrderReadHelper orh = new OrderReadHelper(orderHeader); String orderType = orh.getOrderTypeId(); String orderId = orh.getOrderId(); if ("PURCHASE_ORDER".equals(orderType)) { if ("Y".equals(filterPOReject) && orh.getRejectedOrderItems()) { filterPOsWithRejectedItems.add(orderId); } else if ("Y".equals(filterPOPast) && orh.getPastEtaOrderItems(orderId)) { filterPOsOpenPastTheirETA.add(orderId); } else if ("Y".equals(filterPartRec) && orh.getPartiallyReceivedItems()) { filterPartiallyReceivedPOs.add(orderId); } } } } result.put("filterInventoryProblemsList", filterInventoryProblems); result.put("filterPOsWithRejectedItemsList", filterPOsWithRejectedItems); result.put("filterPOsOpenPastTheirETAList", filterPOsOpenPastTheirETA); result.put("filterPartiallyReceivedPOsList", filterPartiallyReceivedPOs); } protected static EntityExpr makeExpr(String fieldName, String value) { return makeExpr(fieldName, value, false); } protected static EntityExpr makeExpr(String fieldName, String value, boolean forceLike) { EntityComparisonOperator<?, ?> op = forceLike ? EntityOperator.LIKE : EntityOperator.EQUALS; if (value.startsWith("*")) { op = EntityOperator.LIKE; value = "%" + value.substring(1); } else if (value.startsWith("%")) { op = EntityOperator.LIKE; } if (value.endsWith("*")) { op = EntityOperator.LIKE; value = value.substring(0, value.length() - 1) + "%"; } else if (value.endsWith("%")) { op = EntityOperator.LIKE; } if (forceLike) { if (!value.startsWith("%")) { value = "%" + value; } if (!value.endsWith("%")) { value = value + "%"; } } return EntityCondition.makeCondition(fieldName, op, value); } }
NoRef/OFBIZ patch: findOrders: fix userLoginId being lost from paramList, better to keep user input, less confusing git-svn-id: 6c0edb9fdd085beb7f3b78cf385b6ddede550bd9@11948 55bbc10b-e964-4c8f-a844-a62c6f7d3c80
applications/order/src/org/ofbiz/order/order/OrderLookupServices.java
NoRef/OFBIZ patch: findOrders: fix userLoginId being lost from paramList, better to keep user input, less confusing
<ide><path>pplications/order/src/org/ofbiz/order/order/OrderLookupServices.java <ide> String partyId = (String) context.get("partyId"); <ide> List<String> roleTypeList = UtilGenerics.checkList(context.get("roleTypeId")); <ide> <add> // SCIPIO: must track where partyId came from <add> boolean partyIdFromUserLogin = false; <add> <ide> if (UtilValidate.isNotEmpty(userLoginId) && UtilValidate.isEmpty(partyId)) { <ide> GenericValue ul = null; <ide> try { <ide> } <ide> if (ul != null) { <ide> partyId = ul.getString("partyId"); <add> partyIdFromUserLogin = true; <ide> } <ide> } <ide> <ide> } <ide> <ide> if (UtilValidate.isNotEmpty(partyId)) { <del> paramList.add("partyId=" + partyId); <add> // SCIPIO: only append the partyId to paramList if it didn't come from userLoginId <add> if (!partyIdFromUserLogin) { <add> paramList.add("partyId=" + partyId); <add> } <ide> fieldsToSelect.add("partyId"); <ide> conditions.add(makeExpr("partyId", partyId)); <add> } <add> <add> // SCIPIO: append userLoginId to paramList <add> if (UtilValidate.isNotEmpty(userLoginId)) { <add> paramList.add("userLoginId=" + userLoginId); <ide> } <ide> <ide> if (roleTypeList != null) {
JavaScript
apache-2.0
985124bbb323a3850ede08b2d4d2c14c222d4daf
0
mbraak/jqTree,hbaptiste/jqTree,mbraak/jqTree,bolster/jqTree,hbaptiste/jqTree,mbraak/jqTree,bolster/jqTree,bolster/jqTree,hbaptiste/jqTree
$(function() { QUnit.config.testTimeout = 5000; /* example data: node1 ---child1 ---child2 -node2 ---child3 */ var example_data = [ { label: 'node1', id: 123, // extra data children: [ { label: 'child1' }, { label: 'child2' } ] }, { label: 'node2', id: 124, children: [ { label: 'child3' } ] } ]; /* example data 2: -main ---c1 ---c2 */ var example_data2 = [ { label: 'main', children: [ { label: 'c1' }, { label: 'c2' } ] } ]; function formatNodes(nodes) { var strings = $.map(nodes, function(node) { return node.name; }); return strings.join(' '); }; function isNodeClosed($node) { return ( ($node.is('li.jqtree-folder.jqtree-closed')) && ($node.find('a:eq(0)').is('a.jqtree-toggler.jqtree-closed')) && ($node.find('ul:eq(0)').is('ul')) ); } function isNodeOpen($node) { return ( ($node.is('li.jqtree-folder')) && ($node.find('a:eq(0)').is('a.jqtree-toggler')) && ($node.find('ul:eq(0)').is('ul')) && (! $node.is('li.jqtree-folder.jqtree-closed')) && (! $node.find('span:eq(0)').is('a.jqtree-toggler.jqtree-closed')) ); } function formatTitles($node) { var titles = $node.find('.jqtree-title').map( function(i, el) { return $(el).text(); } ); return titles.toArray().join(' '); } module("jqtree", { setup: function() { $('body').append('<div id="tree1"></div>'); }, teardown: function() { var $tree = $('#tree1'); $tree.tree('destroy'); $tree.remove(); } }); test("create jqtree from data", function() { $('#tree1').tree({ data: example_data }); equal( $('#tree1').children().length, 1, 'number of children on level 0' ); ok( $('#tree1').children().is('ul.jqtree-tree'), 'first element is ul.jqtree-tree' ); equal( $('#tree1 ul.jqtree-tree > li').length, 2, 'number of children on level 1' ); ok( $('#tree1 ul.jqtree-tree li:eq(0)').is('li.jqtree-folder.jqtree-closed'), 'first child is li.jqtree-folder.jqtree-closed' ); ok( $('#tree1 ul.jqtree-tree li:eq(0) > .jqtree-element > a.jqtree-toggler').is('a.jqtree-toggler.jqtree-closed'), 'button in first folder' ); equal( $('#tree1 ul.jqtree-tree li:eq(0) > .jqtree-element span.jqtree-title').text(), 'node1' ); }); test('toggle', function() { // create tree var $tree = $('#tree1'); var $node1; var node1; $tree.tree({ data: example_data }); $tree.bind( 'tree.open', function(e) { start(); ok(! isNodeClosed($node1), 'node1 is open'); // 2. close node1 $tree.tree('toggle', node1); stop(); } ); $tree.bind( 'tree.close', function(e) { start(); ok(isNodeClosed($node1), 'node1 is closed'); } ); var tree = $tree.tree('getTree'); node1 = tree.children[0]; $node1 = $tree.find('ul.jqtree-tree li:eq(0)'); // node1 is initially closed ok(isNodeClosed($node1), 'node1 is closed'); // 1. open node1 $tree.tree('toggle', node1); stop(); }); test("click event", function() { stop(); // create tree var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true }); $tree.bind('tree.click', function(e) { equal(e.node.name, 'node1'); }); $tree.bind('tree.select', function(e) { start(); equal(e.node.name, 'node1'); }); // click on node1 var $node1 = $tree.find('ul.jqtree-tree li:first'); var $text_span = $node1.find('span:first'); $text_span.click(); }); test('saveState', function() { var $tree = $('#tree1'); var saved_state; function setState(state) { saved_state = state; } function getState() { return saved_state; } function createTree() { $tree.tree({ data: example_data, saveState: true, onSetStateFromStorage: setState, onGetStateFromStorage: getState, selectable: true }); } // create tree createTree(); // nodes are initially closed var tree = $tree.tree('getTree'); tree.iterate(function(node) { ok(! node.is_open, 'jqtree-closed'); return true; }); // open node1 $tree.tree('toggle', tree.children[0]); // node1 is open ok(tree.children[0].is_open, 'node1 is_open'); // select node2 $tree.tree('selectNode', tree.children[1]); // node2 is selected equal( $tree.tree('getSelectedNode').name, 'node2', 'getSelectedNode' ); // create tree again $tree.tree('destroy'); createTree(); tree = $tree.tree('getTree'); ok(tree.children[0].is_open, 'node1 is_open'); ok(! tree.children[1].is_open, 'node2 is closed'); // node2 is selected equal( $tree.tree('getSelectedNode').name, 'node2', 'getSelectedNode' ); }); test('getSelectedNode', function() { var $tree = $('#tree1'); // create tree $tree.tree({ data: example_data, selectable: true }); // there is no node selected equal( $tree.tree('getSelectedNode'), false, 'getSelectedNode' ); // select node1 var tree = $tree.tree('getTree'); var node1 = tree.children[0]; $tree.tree('selectNode', node1); // node1 is selected equal( $tree.tree('getSelectedNode').name, 'node1', 'getSelectedNode' ); }); test("toJson", function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); // 1. call toJson equal( $tree.tree('toJson'), '[{"name":"node1","id":123,"children":'+ '[{"name":"child1"},{"name":"child2"}]},'+ '{"name":"node2","id":124,"children":[{"name":"child3"}]}]' ); // Check that properties 'children', 'parent' and 'element' still exist. var tree = $tree.tree('getTree'); equal(tree.children.length, 2); ok(tree.children[0].parent != undefined, 'parent'); ok($(tree.children[0].element).is('li'), 'element'); }); test('loadData', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data, autoOpen: true }); // first node is 'node1' equal( $tree.find('> ul > li:first .jqtree-element:first > span').text(), 'node1' ); // 1. load new data $tree.tree('loadData', example_data2); // first node is 'main' equal( $tree.find('> ul > li:first .jqtree-element:first > span').text(), 'main' ); // 2. add new nodes to child3 $tree.tree('loadData', example_data); var node2 = $tree.tree('getNodeById', 124); var child3 = node2.children[0]; equal(child3.name, 'child3'); var data = [ { label: 'c4' }, { label: 'c5', children: [ { label: 'c6' } ] } ]; $tree.tree('loadData', data, child3); // first node in html is still 'node1' equal( $tree.find('li:eq(0)').find('.jqtree-element:eq(0) span.jqtree-title').text(), 'node1' ); // Node 'child3' now has a children 'c4' and 'c5' var $child3 = $tree.find('span:contains(child3)'); var $li = $child3.closest('li'); equal( $li.children('ul').children('li:eq(0)').find('.jqtree-element span.jqtree-title').text(), 'c4' ); // Node 'child3' must have toggler button ok($child3.prev().is('a.jqtree-toggler')); }); test('openNode and closeNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node2 = $tree.tree('getNodeByName', 'node2'); equal(node2.name, 'node2'); equal(node2.is_open, undefined); // 1. open node2 $tree.tree('openNode', node2, false); equal(node2.is_open, true); equal(isNodeOpen($(node2.element)), true); // 2. close node2 $tree.tree('closeNode', node2, false); equal(node2.is_open, false); equal(isNodeClosed($(node2.element)), true); // 3. open child1 var node1 = $tree.tree('getNodeByName', 'node1'); var child1 = $tree.tree('getNodeByName', 'child1'); // add a child to child1 so it is a folder $tree.tree('appendNode', 'child1a', child1); // node1 is initialy closed equal(node1.is_open, undefined); // open child1 $tree.tree('openNode', child1, false); // node1 and child1 are now open1 equal(node1.is_open, true); equal(child1.is_open, true); }); test('selectNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true }); var node1 = $tree.tree('getTree').children[0]; var node2 = $tree.tree('getTree').children[1]; var child3 = node2.children[0]; equal(child3.name, 'child3'); equal(node1.is_open, undefined); equal(node2.is_open, undefined); equal(child3.is_open, undefined); // 1. select node 'child3', which is a child of 'node2'; must_open_parents = true $tree.tree('selectNode', child3, true); equal($tree.tree('getSelectedNode').name, 'child3'); equal(node1.is_open, undefined); equal(node2.is_open, true); equal(child3.is_open, undefined); // 2. select node 'node1' $tree.tree('selectNode', node1); equal($tree.tree('getSelectedNode').name, 'node1'); }); test('click toggler', function() { // setup stop(); var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true }); var $title = $tree.find('li:eq(0)').find('> .jqtree-element > span.jqtree-title'); equal($title.text(), 'node1'); var $toggler = $title.prev(); ok($toggler.is('a.jqtree-toggler.jqtree-closed')); $tree.bind('tree.open', function(e) { // 2. handle 'open' event start(); equal(e.node.name, 'node1'); stop(); // 3. click toggler again $toggler.click(); }); $tree.bind('tree.close', function(e) { start(); equal(e.node.name, 'node1'); }); // 1. click toggler of 'node1' $toggler.click(); }); test('getNodeById', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node2 = $tree.tree('getNodeByName', 'node2'); // 1. get 'node2' by id equal( $tree.tree('getNodeById', 124).name, 'node2' ); // 2. get id that does not exist equal($tree.tree('getNodeById', 333), null); // 3. get id by string equal( $tree.tree('getNodeById', '124').name, 'node2' ); // 4. add node with string id; search by int $tree.tree( 'appendNode', { label: 'abc', id: '234' } ); equal( $tree.tree('getNodeById', 234).name, 'abc' ); equal( $tree.tree('getNodeById', '234').name, 'abc' ); // 5. load subtree in node2 var subtree_data = [ { label: 'sub1', id: 200, children: [ {label: 'sub2', id: 201} ] } ]; $tree.tree('loadData', subtree_data, node2); var t = $tree.tree('getTree'); equal( $tree.tree('getNodeById', 200).name, 'sub1' ); equal( $tree.tree('getNodeById', 201).name, 'sub2' ); }); test('autoOpen', function() { var $tree = $('#tree1'); function formatOpenFolders() { var open_nodes = []; $tree.find('li').each(function() { var $li = $(this); if ($li.is('.jqtree-folder') && ! $li.is('.jqtree-closed')) { var label = $li.children('.jqtree-element').find('span').text(); open_nodes.push(label); }; }); return open_nodes.join(';'); } /* -l1n1 (level 0) ----l2n1 (1) ----l2n2 (1) -------l3n1 (2) ----------l4n1 (3) -l1n2 */ var data = [ { label: 'l1n1', children: [ 'l2n1', { label: 'l2n2', children: [ { label: 'l3n1', children: [ 'l4n1' ] } ] } ] }, 'l1n2' ]; // 1. autoOpen is false $tree.tree({ data: data, autoOpen: false }); equal(formatOpenFolders(), ''); $tree.tree('destroy'); // 2. autoOpen is true $tree.tree({ data: data, autoOpen: true }); equal(formatOpenFolders(), 'l1n1;l2n2;l3n1'); $tree.tree('destroy'); // 3. autoOpen level 1 $tree.tree({ data: data, autoOpen: 1 }); equal(formatOpenFolders(), 'l1n1;l2n2'); }); test('onCreateLi', function() { // 1. init tree with onCreateLi var $tree = $('#tree1'); $tree.tree({ data: example_data, onCreateLi: function(node, $li) { var $span = $li.children('.jqtree-element').find('span'); $span.html('_' + node.name + '_'); } }); equal( $tree.find('span:eq(0)').text(), '_node1_' ); }); test('save state', function() { // setup var state = null; // Fake $.cookie plugin for browsers that do not support localstorage $.cookie = function(key, param2, param3) { if (typeof param3 == 'object') { // set state = param2; } else { // get return state; } } // Remove state from localstorage if (typeof localStorage != 'undefined') { localStorage.setItem('my_tree', null); } // 1. init tree var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true, saveState: 'my_tree' }); var tree = $tree.tree('getTree'); equal($tree.tree('getSelectedNode'), false); // 2. select node -> state is saved $tree.tree('selectNode', tree.children[0]); equal($tree.tree('getSelectedNode').name, 'node1'); // 3. init tree again $tree.tree('destroy'); $tree.tree({ data: example_data, selectable: true, saveState: 'my_tree' }); equal($tree.tree('getSelectedNode').name, 'node1'); $.cookie = null; }); test('generate hit areas', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); // 1. get hit areas var node = $tree.tree('getNodeById', 123); var hit_areas = $tree.tree('testGenerateHitAreas', node); var strings = $.map(hit_areas, function(hit_area) { return hit_area.node.name + ' ' + Tree.Position.getName(hit_area.position); }); equal(strings.join(';'), 'node1 none;node2 inside;node2 after'); }); test('removeNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true }); // 1. Remove selected node; node is 'child1' var child1 = $tree.tree('getNodeByName', 'child1'); $tree.tree('selectNode', child1); equal($tree.tree('getSelectedNode').name, 'child1'); $tree.tree('removeNode', child1); equal( formatTitles($tree), 'node1 child2 node2 child3' ); // getSelectedNode must now return false equal($tree.tree('getSelectedNode'), false); // 2. No node is selected; remove child3 $tree.tree('loadData', example_data); var child3 = $tree.tree('getNodeByName', 'child3'); $tree.tree('removeNode', child3); equal( formatTitles($tree), 'node1 child1 child2 node2' ); equal($tree.tree('getSelectedNode'), false); // 3. Remove parent of selected node $tree.tree('loadData', example_data); child1 = $tree.tree('getNodeByName', 'child1'); var node1 = $tree.tree('getNodeByName', 'node1'); $tree.tree('selectNode', child1); $tree.tree('removeNode', node1); // node is unselected equal($tree.tree('getSelectedNode'), false); }); test('appendNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node1 = $tree.tree('getNodeByName', 'node1'); // 1. Add child3 to node1 $tree.tree('appendNode', 'child3', node1); equal( formatTitles($(node1.element)), 'node1 child1 child2 child3' ); // 2. Add child4 to child1 var child1 = $tree.tree('getNodeByName', 'child1'); // Node 'child1' does not have a toggler button equal( $(child1.element).find('> .jqtree-element > .jqtree-toggler').length, 0 ); $tree.tree('appendNode', 'child4', child1); equal(formatTitles($(child1.element)), 'child1 child4'); // Node 'child1' must get a toggler button equal( $(child1.element).find('> .jqtree-element > .jqtree-toggler').length, 1 ); }); test('prependNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node1 = $tree.tree('getNodeByName', 'node1'); // 1. Prepend child0 to node1 $tree.tree('prependNode', 'child0', node1); equal( formatTitles($(node1.element)), 'node1 child0 child1 child2' ); }); test('init event', function() { // setup var $tree = $('#tree1'); $tree.bind('tree.init', function() { start(); // Check that we can call functions in 'tree.init' event equal($tree.tree('getNodeByName', 'node2').name, 'node2'); }); stop(); $tree.tree({ data: example_data }); }); test('updateNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); equal(formatTitles($tree), 'node1 child1 child2 node2 child3'); // -- update label var node2 = $tree.tree('getNodeByName', 'node2'); $tree.tree('updateNode', node2, 'CHANGED'); equal(formatTitles($tree), 'node1 child1 child2 CHANGED child3'); equal(node2.name, 'CHANGED'); // -- update data $tree.tree( 'updateNode', node2, { name: 'xyz', tag1: 'abc' } ); equal(formatTitles($tree), 'node1 child1 child2 xyz child3'); equal(node2.name, 'xyz'); equal(node2.tag1, 'abc'); }); test('moveNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var child1 = $tree.tree('getNodeByName', 'child1'); var child2 = $tree.tree('getNodeByName', 'child2'); var node1 = $tree.tree('getNodeByName', 'node1'); var node2 = $tree.tree('getNodeByName', 'node2'); // -- Move child1 after node2 $tree.tree('moveNode', child1, node2, 'after'); equal(formatTitles($tree), 'node1 child2 node2 child3 child1'); // -- Check that illegal moves are skipped $tree.tree('moveNode', node1, child2, 'inside'); }); test('load on demand', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: [ { id: 1, label: 'node1', load_on_demand: true } ], dataUrl: '/tree/' }); $.mockjax({ url: '*', response: function(options) { equal(options.url, '/tree/'); deepEqual(options.data, { 'node' : 1 }) this.responseText = [ { id: 2, label: 'child1' } ]; } }); // -- open node $tree.bind('tree.refresh', function(e) { start(); equal(formatTitles($tree), 'node1 child1'); }); var node1 = $tree.tree('getNodeByName', 'node1'); equal(formatTitles($tree), 'node1'); $tree.tree('openNode', node1, true); stop(); }); test('addNodeAfter', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node1 = $tree.tree('getNodeByName', 'node1'); // -- add node after node1 $tree.tree('addNodeAfter', 'node3', node1); equal(formatTitles($tree), 'node1 child1 child2 node3 node2 child3'); }); test('addNodeBefore', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node1 = $tree.tree('getNodeByName', 'node1'); // -- add node before node1 var new_node = $tree.tree('addNodeBefore', 'node3', node1); console.log(new_node.name, 'node3') equal(formatTitles($tree), 'node3 node1 child1 child2 node2 child3'); }); test('addParentNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var child3 = $tree.tree('getNodeByName', 'child3'); // -- add parent to child3 $tree.tree('addParentNode', 'node3', child3); equal(formatTitles($tree), 'node1 child1 child2 node2 node3 child3'); }); module("Tree"); test('constructor', function() { // 1. Create node from string var node = new Tree.Node('n1'); equal(node.name, 'n1'); equal(node.children.length, 0); equal(node.parent, null); // 2. Create node from object node = new Tree.Node({ label: 'n2', id: 123, parent: 'abc', // parent must be ignored children: ['c'], // children must be ignored url: '/' }); equal(node.name, 'n2'); equal(node.id, 123); equal(node.url, '/'); equal(node.label, undefined); equal(node.children.length, 0); equal(node.parent, null); }); test("create tree from data", function() { function checkData(tree) { equal( formatNodes(tree.children), 'node1 node2', 'nodes on level 1' ); equal( formatNodes(tree.children[0].children), 'child1 child2', 'children of node1' ); equal( formatNodes(tree.children[1].children), 'child3', 'children of node2' ); equal( tree.children[0].id, 123, 'id' ); } // 1. create tree from example data var tree = new Tree.Tree(); tree.loadFromData(example_data); checkData(tree); // 2. create tree from new data format var data = [ { label: 'node1', id: 123, // extra data children: ['child1', 'child2'] }, { label: 'node2', id: 124, children: ['child3'] } ]; var tree = new Tree.Tree(); tree.loadFromData(data); checkData(tree); }); test("addChild", function() { var tree = new Tree.Tree('tree1'); tree.addChild( new Tree.Node('abc') ); tree.addChild( new Tree.Node('def') ); equal( formatNodes(tree.children), 'abc def', 'children' ); var node = tree.children[0]; equal( node.parent.name, 'tree1', 'parent of node' ); }); test('addChildAtPosition', function() { var tree = new Tree.Tree(); tree.addChildAtPosition(new Tree.Node('abc'), 0); // first tree.addChildAtPosition(new Tree.Node('ghi'), 2); // index 2 does not exist tree.addChildAtPosition(new Tree.Node('def'), 1); tree.addChildAtPosition(new Tree.Node('123'), 0); equal( formatNodes(tree.children), '123 abc def ghi', 'children' ); }); test('removeChild', function() { var tree = new Tree.Tree(); var abc = new Tree.Node({'label': 'abc', 'id': 1}); var def = new Tree.Node({'label': 'def', 'id': 2}); var ghi = new Tree.Node({'label': 'ghi', 'id': 3}); tree.addChild(abc); tree.addChild(def); tree.addChild(ghi); var jkl = new Tree.Node({'label': 'jkl', 'id': 4}); def.addChild(jkl); equal( formatNodes(tree.children), 'abc def ghi', 'children' ); equal(tree.id_mapping[2].name, 'def'); equal(tree.id_mapping[4].name, 'jkl'); // remove 'def' tree.removeChild(def); equal( formatNodes(tree.children), 'abc ghi', 'children' ); equal(tree.id_mapping[2], null); equal(tree.id_mapping[4], null); // remove 'ghi' tree.removeChild(ghi); equal( formatNodes(tree.children), 'abc', 'children' ); // remove 'abc' tree.removeChild(abc); equal( formatNodes(tree.children), '', 'children' ); }); test('getChildIndex', function() { // setup var tree = new Tree.Tree(); var abc = new Tree.Node('abc'); var def = new Tree.Node('def'); var ghi = new Tree.Node('ghi'); tree.addChild(abc); tree.addChild(def); tree.addChild(ghi); // 1. Get child index of 'def' equal(tree.getChildIndex(def), 1); // 2. Get child index of non-existing node equal(tree.getChildIndex(new Tree.Node('xyz')), -1); }); test('hasChildren', function() { var tree = new Tree.Tree(); equal( tree.hasChildren(), false, 'tree without children' ); tree.addChild(new Tree.Node('abc')); equal( tree.hasChildren(), true, 'tree has children' ); }); test('iterate', function() { var tree = new Tree.Tree(); tree.loadFromData(example_data); // iterate over all the nodes var nodes = []; tree.iterate( function(node, level) { nodes.push(node); return true; } ); equal( formatNodes(nodes), 'node1 child1 child2 node2 child3', 'all nodes' ); // iterate over nodes on first level nodes = []; tree.iterate( function(node, level) { nodes.push(node); return false; } ); equal( formatNodes(nodes), 'node1 node2', 'nodes on first level' ); // add child 4 var node3 = tree.getNodeById(124).children[0]; node3.addChild( new Tree.Node('child4') ); // test level parameter nodes = []; tree.iterate( function(node, level) { nodes.push(node.name + ' ' + level); return true; } ); equal( nodes.join(','), 'node1 0,child1 1,child2 1,node2 0,child3 1,child4 2' ); }); test('moveNode', function() { var tree = new Tree.Tree() tree.loadFromData(example_data); /* node1 ---child1 ---child2 node2 ---child3 */ var node1 = tree.children[0]; var node2 = tree.children[1]; var child1 = node1.children[0]; var child2 = node1.children[1]; equal(node2.name, 'node2', 'node2 name'); equal(child2.name, 'child2', 'child2 name'); // move child2 after node2 tree.moveNode(child2, node2, Tree.Position.AFTER); /* node1 ---child1 node2 ---child3 child2 */ equal( formatNodes(tree.children), 'node1 node2 child2', 'tree nodes at first level' ); equal( formatNodes(node1.children), 'child1', 'node1 children' ); // move child1 inside node2 // this means it's the first child tree.moveNode(child1, node2, Tree.Position.INSIDE); /* node1 node2 ---child1 ---child3 child2 */ equal( formatNodes(node2.children), 'child1 child3', 'node2 children' ); equal( formatNodes(node1.children), '', 'node1 has no children' ); // move child2 before child1 tree.moveNode(child2, child1, Tree.Position.BEFORE); /* node1 node2 ---child2 ---child1 ---child3 */ equal( formatNodes(node2.children), 'child2 child1 child3', 'node2 children' ); equal( formatNodes(tree.children), 'node1 node2', 'tree nodes at first level' ); }); test('initFromData', function() { var data = { label: 'main', children: [ 'c1', { label: 'c2', id: 201 } ] }; var node = new Tree.Tree(); node.initFromData(data); equal(node.name, 'main') equal( formatNodes(node.children), 'c1 c2', 'children' ); equal(node.children[1].id, 201); }); test('getData', function() { // 1. empty node var node = new Tree.Tree(); deepEqual(node.getData(), []); // 2.node with data node.loadFromData( [ { label: 'n1', children: [ { label: 'c1' } ] } ] ); deepEqual( node.getData(), [ { name: 'n1', children: [ { name: 'c1' } ] } ] ); }); test('addAfter', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); /* -node1 ---c1 ---c2 -node2 ---c3 */ equal(formatNodes(tree.children), 'node1 node2'); // 1. Add 'node_b' after node2 var node2 = tree.getNodeByName('node2'); node2.addAfter('node_b'); equal(formatNodes(tree.children), 'node1 node2 node_b'); var node_b = tree.getNodeByName('node_b'); equal(node_b.name, 'node_b'); // 2. Add 'node_a' after node1 var node1 = tree.getNodeByName('node1'); node1.addAfter('node_a'); equal(formatNodes(tree.children), 'node1 node_a node2 node_b'); // 3. Add 'node_c' after node_b; new node is an object node_b.addAfter({ label: 'node_c', id: 789 }); var node_c = tree.getNodeByName('node_c'); equal(node_c.id, 789); equal(formatNodes(tree.children), 'node1 node_a node2 node_b node_c'); }); test('addBefore', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); // 1. Add 'node_0' before node1 var node1 = tree.getNodeByName('node1'); node1.addBefore('node0'); equal(formatNodes(tree.children), 'node0 node1 node2'); }); test('addParent', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); // 1. Add node 'root' as parent of node1 // Note that node also becomes a child of 'root' var node1 = tree.getNodeByName('node1'); node1.addParent('root'); var root = tree.getNodeByName('root'); equal(formatNodes(root.children), 'node1 node2'); }); test('remove', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); var child1 = tree.getNodeByName('child1'); var node1 = tree.getNodeByName('node1'); equal(formatNodes(node1.children), 'child1 child2'); equal(child1.parent, node1); // 1. Remove child1 child1.remove(); equal(formatNodes(node1.children), 'child2'); equal(child1.parent, null); }); test('append', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); var node1 = tree.getNodeByName('node1'); // 1. Add child3 to node1 node1.append('child3'); equal(formatNodes(node1.children), 'child1 child2 child3'); }); test('prepend', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); var node1 = tree.getNodeByName('node1'); // 1. Prepend child0 to node1 node1.prepend('child0'); equal(formatNodes(node1.children), 'child0 child1 child2'); }); test('getNodeById', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); // 1. Get node with id 124 var node = tree.getNodeById(124); equal(node.name, 'node2'); // 2. Delete node with id 124 and search again node.remove(); equal(tree.getNodeById(124), null); // 3. Add node with id 456 and search for it var child3 = tree.getNodeByName('child2'); child3.append({ id: 456, label: 'new node' }); node = tree.getNodeById(456); equal(node.name, 'new node'); }); test('getLevel', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); // 1. get level for node1 and child1 equal(tree.getNodeByName('node1').getLevel(), 1); equal(tree.getNodeByName('child1').getLevel(), 2); }); module('util'); test('JSON.stringify', function() { equal(JSON.stringify('abc'), '"abc"'); equal(JSON.stringify(123), '123'); equal(JSON.stringify(true), 'true'); equal(JSON.stringify({abc: 'def'}), '{"abc":"def"}'); equal(JSON.stringify({}), '{}'); equal(JSON.stringify([1, 2, 3]), '[1,2,3]'); equal(JSON.stringify(null), 'null'); equal(JSON.stringify(Number.NEGATIVE_INFINITY), 'null'); // test escapable JSON.stringify("\u200c"); }); test('indexOf', function() { equal(Tree.indexOf([3, 2, 1], 1), 2); equal(Tree._indexOf([3, 2, 1], 1), 2); equal(Tree.indexOf([4, 5, 6], 1), -1); equal(Tree._indexOf([4, 5, 6], 1), -1); }); test('Position.getName', function() { equal(Tree.Position.getName(Tree.Position.BEFORE), 'before'); equal(Tree.Position.getName(Tree.Position.AFTER), 'after'); equal(Tree.Position.getName(Tree.Position.INSIDE), 'inside'); equal(Tree.Position.getName(Tree.Position.NONE), 'none'); }); test('Position.nameToIndex', function() { equal(Tree.Position.nameToIndex('before'), Tree.Position.BEFORE); equal(Tree.Position.nameToIndex('after'), Tree.Position.AFTER); equal(Tree.Position.nameToIndex(''), 0); }); });
test/test.js
$(function() { QUnit.config.testTimeout = 5000; /* example data: node1 ---child1 ---child2 -node2 ---child3 */ var example_data = [ { label: 'node1', id: 123, // extra data children: [ { label: 'child1' }, { label: 'child2' } ] }, { label: 'node2', id: 124, children: [ { label: 'child3' } ] } ]; /* example data 2: -main ---c1 ---c2 */ var example_data2 = [ { label: 'main', children: [ { label: 'c1' }, { label: 'c2' } ] } ]; function formatNodes(nodes) { var strings = $.map(nodes, function(node) { return node.name; }); return strings.join(' '); }; function isNodeClosed($node) { return ( ($node.is('li.jqtree-folder.jqtree-closed')) && ($node.find('a:eq(0)').is('a.jqtree-toggler.jqtree-closed')) && ($node.find('ul:eq(0)').is('ul')) ); } function isNodeOpen($node) { return ( ($node.is('li.jqtree-folder')) && ($node.find('a:eq(0)').is('a.jqtree-toggler')) && ($node.find('ul:eq(0)').is('ul')) && (! $node.is('li.jqtree-folder.jqtree-closed')) && (! $node.find('span:eq(0)').is('a.jqtree-toggler.jqtree-closed')) ); } function formatTitles($node) { var titles = $node.find('.jqtree-title').map( function(i, el) { return $(el).text(); } ); return titles.toArray().join(' '); } module("jqtree", { setup: function() { $('body').append('<div id="tree1"></div>'); }, teardown: function() { var $tree = $('#tree1'); $tree.tree('destroy'); $tree.remove(); } }); test("create jqtree from data", function() { $('#tree1').tree({ data: example_data }); equal( $('#tree1').children().length, 1, 'number of children on level 0' ); ok( $('#tree1').children().is('ul.jqtree-tree'), 'first element is ul.jqtree-tree' ); equal( $('#tree1 ul.jqtree-tree > li').length, 2, 'number of children on level 1' ); ok( $('#tree1 ul.jqtree-tree li:eq(0)').is('li.jqtree-folder.jqtree-closed'), 'first child is li.jqtree-folder.jqtree-closed' ); ok( $('#tree1 ul.jqtree-tree li:eq(0) > .jqtree-element > a.jqtree-toggler').is('a.jqtree-toggler.jqtree-closed'), 'button in first folder' ); equal( $('#tree1 ul.jqtree-tree li:eq(0) > .jqtree-element span.jqtree-title').text(), 'node1' ); }); test('toggle', function() { // create tree var $tree = $('#tree1'); var $node1; var node1; $tree.tree({ data: example_data }); $tree.bind( 'tree.open', function(e) { start(); ok(! isNodeClosed($node1), 'node1 is open'); // 2. close node1 $tree.tree('toggle', node1); stop(); } ); $tree.bind( 'tree.close', function(e) { start(); ok(isNodeClosed($node1), 'node1 is closed'); } ); var tree = $tree.tree('getTree'); node1 = tree.children[0]; $node1 = $tree.find('ul.jqtree-tree li:eq(0)'); // node1 is initially closed ok(isNodeClosed($node1), 'node1 is closed'); // 1. open node1 $tree.tree('toggle', node1); stop(); }); test("click event", function() { stop(); // create tree var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true }); $tree.bind('tree.click', function(e) { equal(e.node.name, 'node1'); }); $tree.bind('tree.select', function(e) { start(); equal(e.node.name, 'node1'); }); // click on node1 var $node1 = $tree.find('ul.jqtree-tree li:first'); var $text_span = $node1.find('span:first'); $text_span.click(); }); test('saveState', function() { var $tree = $('#tree1'); var saved_state; function setState(state) { saved_state = state; } function getState() { return saved_state; } function createTree() { $tree.tree({ data: example_data, saveState: true, onSetStateFromStorage: setState, onGetStateFromStorage: getState, selectable: true }); } // create tree createTree(); // nodes are initially closed var tree = $tree.tree('getTree'); tree.iterate(function(node) { ok(! node.is_open, 'jqtree-closed'); return true; }); // open node1 $tree.tree('toggle', tree.children[0]); // node1 is open ok(tree.children[0].is_open, 'node1 is_open'); // select node2 $tree.tree('selectNode', tree.children[1]); // node2 is selected equal( $tree.tree('getSelectedNode').name, 'node2', 'getSelectedNode' ); // create tree again $tree.tree('destroy'); createTree(); tree = $tree.tree('getTree'); ok(tree.children[0].is_open, 'node1 is_open'); ok(! tree.children[1].is_open, 'node2 is closed'); // node2 is selected equal( $tree.tree('getSelectedNode').name, 'node2', 'getSelectedNode' ); }); test('getSelectedNode', function() { var $tree = $('#tree1'); // create tree $tree.tree({ data: example_data, selectable: true }); // there is no node selected equal( $tree.tree('getSelectedNode'), false, 'getSelectedNode' ); // select node1 var tree = $tree.tree('getTree'); var node1 = tree.children[0]; $tree.tree('selectNode', node1); // node1 is selected equal( $tree.tree('getSelectedNode').name, 'node1', 'getSelectedNode' ); }); test("toJson", function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); // 1. call toJson equal( $tree.tree('toJson'), '[{"name":"node1","id":123,"children":'+ '[{"name":"child1"},{"name":"child2"}]},'+ '{"name":"node2","id":124,"children":[{"name":"child3"}]}]' ); // Check that properties 'children', 'parent' and 'element' still exist. var tree = $tree.tree('getTree'); equal(tree.children.length, 2); ok(tree.children[0].parent != undefined, 'parent'); ok($(tree.children[0].element).is('li'), 'element'); }); test('loadData', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data, autoOpen: true }); // first node is 'node1' equal( $tree.find('> ul > li:first .jqtree-element:first > span').text(), 'node1' ); // 1. load new data $tree.tree('loadData', example_data2); // first node is 'main' equal( $tree.find('> ul > li:first .jqtree-element:first > span').text(), 'main' ); // 2. add new nodes to child3 $tree.tree('loadData', example_data); var node2 = $tree.tree('getNodeById', 124); var child3 = node2.children[0]; equal(child3.name, 'child3'); var data = [ { label: 'c4' }, { label: 'c5', children: [ { label: 'c6' } ] } ]; $tree.tree('loadData', data, child3); // first node in html is still 'node1' equal( $tree.find('li:eq(0)').find('.jqtree-element:eq(0) span.jqtree-title').text(), 'node1' ); // Node 'child3' now has a children 'c4' and 'c5' var $child3 = $tree.find('span:contains(child3)'); var $li = $child3.closest('li'); equal( $li.children('ul').children('li:eq(0)').find('.jqtree-element span.jqtree-title').text(), 'c4' ); // Node 'child3' must have toggler button ok($child3.prev().is('a.jqtree-toggler')); }); test('openNode and closeNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node2 = $tree.tree('getNodeByName', 'node2'); equal(node2.name, 'node2'); equal(node2.is_open, undefined); // 1. open node2 $tree.tree('openNode', node2, false); equal(node2.is_open, true); equal(isNodeOpen($(node2.element)), true); // 2. close node2 $tree.tree('closeNode', node2, false); equal(node2.is_open, false); equal(isNodeClosed($(node2.element)), true); }); test('selectNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true }); var node1 = $tree.tree('getTree').children[0]; var node2 = $tree.tree('getTree').children[1]; var child3 = node2.children[0]; equal(child3.name, 'child3'); equal(node1.is_open, undefined); equal(node2.is_open, undefined); equal(child3.is_open, undefined); // 1. select node 'child3', which is a child of 'node2'; must_open_parents = true $tree.tree('selectNode', child3, true); equal($tree.tree('getSelectedNode').name, 'child3'); equal(node1.is_open, undefined); equal(node2.is_open, true); equal(child3.is_open, undefined); // 2. select node 'node1' $tree.tree('selectNode', node1); equal($tree.tree('getSelectedNode').name, 'node1'); }); test('click toggler', function() { // setup stop(); var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true }); var $title = $tree.find('li:eq(0)').find('> .jqtree-element > span.jqtree-title'); equal($title.text(), 'node1'); var $toggler = $title.prev(); ok($toggler.is('a.jqtree-toggler.jqtree-closed')); $tree.bind('tree.open', function(e) { // 2. handle 'open' event start(); equal(e.node.name, 'node1'); stop(); // 3. click toggler again $toggler.click(); }); $tree.bind('tree.close', function(e) { start(); equal(e.node.name, 'node1'); }); // 1. click toggler of 'node1' $toggler.click(); }); test('getNodeById', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node2 = $tree.tree('getNodeByName', 'node2'); // 1. get 'node2' by id equal( $tree.tree('getNodeById', 124).name, 'node2' ); // 2. get id that does not exist equal($tree.tree('getNodeById', 333), null); // 3. get id by string equal( $tree.tree('getNodeById', '124').name, 'node2' ); // 4. add node with string id; search by int $tree.tree( 'appendNode', { label: 'abc', id: '234' } ); equal( $tree.tree('getNodeById', 234).name, 'abc' ); equal( $tree.tree('getNodeById', '234').name, 'abc' ); // 5. load subtree in node2 var subtree_data = [ { label: 'sub1', id: 200, children: [ {label: 'sub2', id: 201} ] } ]; $tree.tree('loadData', subtree_data, node2); var t = $tree.tree('getTree'); equal( $tree.tree('getNodeById', 200).name, 'sub1' ); equal( $tree.tree('getNodeById', 201).name, 'sub2' ); }); test('autoOpen', function() { var $tree = $('#tree1'); function formatOpenFolders() { var open_nodes = []; $tree.find('li').each(function() { var $li = $(this); if ($li.is('.jqtree-folder') && ! $li.is('.jqtree-closed')) { var label = $li.children('.jqtree-element').find('span').text(); open_nodes.push(label); }; }); return open_nodes.join(';'); } /* -l1n1 (level 0) ----l2n1 (1) ----l2n2 (1) -------l3n1 (2) ----------l4n1 (3) -l1n2 */ var data = [ { label: 'l1n1', children: [ 'l2n1', { label: 'l2n2', children: [ { label: 'l3n1', children: [ 'l4n1' ] } ] } ] }, 'l1n2' ]; // 1. autoOpen is false $tree.tree({ data: data, autoOpen: false }); equal(formatOpenFolders(), ''); $tree.tree('destroy'); // 2. autoOpen is true $tree.tree({ data: data, autoOpen: true }); equal(formatOpenFolders(), 'l1n1;l2n2;l3n1'); $tree.tree('destroy'); // 3. autoOpen level 1 $tree.tree({ data: data, autoOpen: 1 }); equal(formatOpenFolders(), 'l1n1;l2n2'); }); test('onCreateLi', function() { // 1. init tree with onCreateLi var $tree = $('#tree1'); $tree.tree({ data: example_data, onCreateLi: function(node, $li) { var $span = $li.children('.jqtree-element').find('span'); $span.html('_' + node.name + '_'); } }); equal( $tree.find('span:eq(0)').text(), '_node1_' ); }); test('save state', function() { // setup var state = null; // Fake $.cookie plugin for browsers that do not support localstorage $.cookie = function(key, param2, param3) { if (typeof param3 == 'object') { // set state = param2; } else { // get return state; } } // Remove state from localstorage if (typeof localStorage != 'undefined') { localStorage.setItem('my_tree', null); } // 1. init tree var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true, saveState: 'my_tree' }); var tree = $tree.tree('getTree'); equal($tree.tree('getSelectedNode'), false); // 2. select node -> state is saved $tree.tree('selectNode', tree.children[0]); equal($tree.tree('getSelectedNode').name, 'node1'); // 3. init tree again $tree.tree('destroy'); $tree.tree({ data: example_data, selectable: true, saveState: 'my_tree' }); equal($tree.tree('getSelectedNode').name, 'node1'); $.cookie = null; }); test('generate hit areas', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); // 1. get hit areas var node = $tree.tree('getNodeById', 123); var hit_areas = $tree.tree('testGenerateHitAreas', node); var strings = $.map(hit_areas, function(hit_area) { return hit_area.node.name + ' ' + Tree.Position.getName(hit_area.position); }); equal(strings.join(';'), 'node1 none;node2 inside;node2 after'); }); test('removeNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data, selectable: true }); // 1. Remove selected node; node is 'child1' var child1 = $tree.tree('getNodeByName', 'child1'); $tree.tree('selectNode', child1); equal($tree.tree('getSelectedNode').name, 'child1'); $tree.tree('removeNode', child1); equal( formatTitles($tree), 'node1 child2 node2 child3' ); // getSelectedNode must now return false equal($tree.tree('getSelectedNode'), false); // 2. No node is selected; remove child3 $tree.tree('loadData', example_data); var child3 = $tree.tree('getNodeByName', 'child3'); $tree.tree('removeNode', child3); equal( formatTitles($tree), 'node1 child1 child2 node2' ); equal($tree.tree('getSelectedNode'), false); // 3. Remove parent of selected node $tree.tree('loadData', example_data); child1 = $tree.tree('getNodeByName', 'child1'); var node1 = $tree.tree('getNodeByName', 'node1'); $tree.tree('selectNode', child1); $tree.tree('removeNode', node1); // node is unselected equal($tree.tree('getSelectedNode'), false); }); test('appendNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node1 = $tree.tree('getNodeByName', 'node1'); // 1. Add child3 to node1 $tree.tree('appendNode', 'child3', node1); equal( formatTitles($(node1.element)), 'node1 child1 child2 child3' ); // 2. Add child4 to child1 var child1 = $tree.tree('getNodeByName', 'child1'); // Node 'child1' does not have a toggler button equal( $(child1.element).find('> .jqtree-element > .jqtree-toggler').length, 0 ); $tree.tree('appendNode', 'child4', child1); equal(formatTitles($(child1.element)), 'child1 child4'); // Node 'child1' must get a toggler button equal( $(child1.element).find('> .jqtree-element > .jqtree-toggler').length, 1 ); }); test('prependNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node1 = $tree.tree('getNodeByName', 'node1'); // 1. Prepend child0 to node1 $tree.tree('prependNode', 'child0', node1); equal( formatTitles($(node1.element)), 'node1 child0 child1 child2' ); }); test('init event', function() { // setup var $tree = $('#tree1'); $tree.bind('tree.init', function() { start(); // Check that we can call functions in 'tree.init' event equal($tree.tree('getNodeByName', 'node2').name, 'node2'); }); stop(); $tree.tree({ data: example_data }); }); test('updateNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); equal(formatTitles($tree), 'node1 child1 child2 node2 child3'); // -- update label var node2 = $tree.tree('getNodeByName', 'node2'); $tree.tree('updateNode', node2, 'CHANGED'); equal(formatTitles($tree), 'node1 child1 child2 CHANGED child3'); equal(node2.name, 'CHANGED'); // -- update data $tree.tree( 'updateNode', node2, { name: 'xyz', tag1: 'abc' } ); equal(formatTitles($tree), 'node1 child1 child2 xyz child3'); equal(node2.name, 'xyz'); equal(node2.tag1, 'abc'); }); test('moveNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var child1 = $tree.tree('getNodeByName', 'child1'); var child2 = $tree.tree('getNodeByName', 'child2'); var node1 = $tree.tree('getNodeByName', 'node1'); var node2 = $tree.tree('getNodeByName', 'node2'); // -- Move child1 after node2 $tree.tree('moveNode', child1, node2, 'after'); equal(formatTitles($tree), 'node1 child2 node2 child3 child1'); // -- Check that illegal moves are skipped $tree.tree('moveNode', node1, child2, 'inside'); }); test('load on demand', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: [ { id: 1, label: 'node1', load_on_demand: true } ], dataUrl: '/tree/' }); $.mockjax({ url: '*', response: function(options) { equal(options.url, '/tree/'); deepEqual(options.data, { 'node' : 1 }) this.responseText = [ { id: 2, label: 'child1' } ]; } }); // -- open node $tree.bind('tree.refresh', function(e) { start(); equal(formatTitles($tree), 'node1 child1'); }); var node1 = $tree.tree('getNodeByName', 'node1'); equal(formatTitles($tree), 'node1'); $tree.tree('openNode', node1, true); stop(); }); test('addNodeAfter', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node1 = $tree.tree('getNodeByName', 'node1'); // -- add node after node1 $tree.tree('addNodeAfter', 'node3', node1); equal(formatTitles($tree), 'node1 child1 child2 node3 node2 child3'); }); test('addNodeBefore', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var node1 = $tree.tree('getNodeByName', 'node1'); // -- add node before node1 var new_node = $tree.tree('addNodeBefore', 'node3', node1); console.log(new_node.name, 'node3') equal(formatTitles($tree), 'node3 node1 child1 child2 node2 child3'); }); test('addParentNode', function() { // setup var $tree = $('#tree1'); $tree.tree({ data: example_data }); var child3 = $tree.tree('getNodeByName', 'child3'); // -- add parent to child3 $tree.tree('addParentNode', 'node3', child3); equal(formatTitles($tree), 'node1 child1 child2 node2 node3 child3'); }); module("Tree"); test('constructor', function() { // 1. Create node from string var node = new Tree.Node('n1'); equal(node.name, 'n1'); equal(node.children.length, 0); equal(node.parent, null); // 2. Create node from object node = new Tree.Node({ label: 'n2', id: 123, parent: 'abc', // parent must be ignored children: ['c'], // children must be ignored url: '/' }); equal(node.name, 'n2'); equal(node.id, 123); equal(node.url, '/'); equal(node.label, undefined); equal(node.children.length, 0); equal(node.parent, null); }); test("create tree from data", function() { function checkData(tree) { equal( formatNodes(tree.children), 'node1 node2', 'nodes on level 1' ); equal( formatNodes(tree.children[0].children), 'child1 child2', 'children of node1' ); equal( formatNodes(tree.children[1].children), 'child3', 'children of node2' ); equal( tree.children[0].id, 123, 'id' ); } // 1. create tree from example data var tree = new Tree.Tree(); tree.loadFromData(example_data); checkData(tree); // 2. create tree from new data format var data = [ { label: 'node1', id: 123, // extra data children: ['child1', 'child2'] }, { label: 'node2', id: 124, children: ['child3'] } ]; var tree = new Tree.Tree(); tree.loadFromData(data); checkData(tree); }); test("addChild", function() { var tree = new Tree.Tree('tree1'); tree.addChild( new Tree.Node('abc') ); tree.addChild( new Tree.Node('def') ); equal( formatNodes(tree.children), 'abc def', 'children' ); var node = tree.children[0]; equal( node.parent.name, 'tree1', 'parent of node' ); }); test('addChildAtPosition', function() { var tree = new Tree.Tree(); tree.addChildAtPosition(new Tree.Node('abc'), 0); // first tree.addChildAtPosition(new Tree.Node('ghi'), 2); // index 2 does not exist tree.addChildAtPosition(new Tree.Node('def'), 1); tree.addChildAtPosition(new Tree.Node('123'), 0); equal( formatNodes(tree.children), '123 abc def ghi', 'children' ); }); test('removeChild', function() { var tree = new Tree.Tree(); var abc = new Tree.Node({'label': 'abc', 'id': 1}); var def = new Tree.Node({'label': 'def', 'id': 2}); var ghi = new Tree.Node({'label': 'ghi', 'id': 3}); tree.addChild(abc); tree.addChild(def); tree.addChild(ghi); var jkl = new Tree.Node({'label': 'jkl', 'id': 4}); def.addChild(jkl); equal( formatNodes(tree.children), 'abc def ghi', 'children' ); equal(tree.id_mapping[2].name, 'def'); equal(tree.id_mapping[4].name, 'jkl'); // remove 'def' tree.removeChild(def); equal( formatNodes(tree.children), 'abc ghi', 'children' ); equal(tree.id_mapping[2], null); equal(tree.id_mapping[4], null); // remove 'ghi' tree.removeChild(ghi); equal( formatNodes(tree.children), 'abc', 'children' ); // remove 'abc' tree.removeChild(abc); equal( formatNodes(tree.children), '', 'children' ); }); test('getChildIndex', function() { // setup var tree = new Tree.Tree(); var abc = new Tree.Node('abc'); var def = new Tree.Node('def'); var ghi = new Tree.Node('ghi'); tree.addChild(abc); tree.addChild(def); tree.addChild(ghi); // 1. Get child index of 'def' equal(tree.getChildIndex(def), 1); // 2. Get child index of non-existing node equal(tree.getChildIndex(new Tree.Node('xyz')), -1); }); test('hasChildren', function() { var tree = new Tree.Tree(); equal( tree.hasChildren(), false, 'tree without children' ); tree.addChild(new Tree.Node('abc')); equal( tree.hasChildren(), true, 'tree has children' ); }); test('iterate', function() { var tree = new Tree.Tree(); tree.loadFromData(example_data); // iterate over all the nodes var nodes = []; tree.iterate( function(node, level) { nodes.push(node); return true; } ); equal( formatNodes(nodes), 'node1 child1 child2 node2 child3', 'all nodes' ); // iterate over nodes on first level nodes = []; tree.iterate( function(node, level) { nodes.push(node); return false; } ); equal( formatNodes(nodes), 'node1 node2', 'nodes on first level' ); // add child 4 var node3 = tree.getNodeById(124).children[0]; node3.addChild( new Tree.Node('child4') ); // test level parameter nodes = []; tree.iterate( function(node, level) { nodes.push(node.name + ' ' + level); return true; } ); equal( nodes.join(','), 'node1 0,child1 1,child2 1,node2 0,child3 1,child4 2' ); }); test('moveNode', function() { var tree = new Tree.Tree() tree.loadFromData(example_data); /* node1 ---child1 ---child2 node2 ---child3 */ var node1 = tree.children[0]; var node2 = tree.children[1]; var child1 = node1.children[0]; var child2 = node1.children[1]; equal(node2.name, 'node2', 'node2 name'); equal(child2.name, 'child2', 'child2 name'); // move child2 after node2 tree.moveNode(child2, node2, Tree.Position.AFTER); /* node1 ---child1 node2 ---child3 child2 */ equal( formatNodes(tree.children), 'node1 node2 child2', 'tree nodes at first level' ); equal( formatNodes(node1.children), 'child1', 'node1 children' ); // move child1 inside node2 // this means it's the first child tree.moveNode(child1, node2, Tree.Position.INSIDE); /* node1 node2 ---child1 ---child3 child2 */ equal( formatNodes(node2.children), 'child1 child3', 'node2 children' ); equal( formatNodes(node1.children), '', 'node1 has no children' ); // move child2 before child1 tree.moveNode(child2, child1, Tree.Position.BEFORE); /* node1 node2 ---child2 ---child1 ---child3 */ equal( formatNodes(node2.children), 'child2 child1 child3', 'node2 children' ); equal( formatNodes(tree.children), 'node1 node2', 'tree nodes at first level' ); }); test('initFromData', function() { var data = { label: 'main', children: [ 'c1', { label: 'c2', id: 201 } ] }; var node = new Tree.Tree(); node.initFromData(data); equal(node.name, 'main') equal( formatNodes(node.children), 'c1 c2', 'children' ); equal(node.children[1].id, 201); }); test('getData', function() { // 1. empty node var node = new Tree.Tree(); deepEqual(node.getData(), []); // 2.node with data node.loadFromData( [ { label: 'n1', children: [ { label: 'c1' } ] } ] ); deepEqual( node.getData(), [ { name: 'n1', children: [ { name: 'c1' } ] } ] ); }); test('addAfter', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); /* -node1 ---c1 ---c2 -node2 ---c3 */ equal(formatNodes(tree.children), 'node1 node2'); // 1. Add 'node_b' after node2 var node2 = tree.getNodeByName('node2'); node2.addAfter('node_b'); equal(formatNodes(tree.children), 'node1 node2 node_b'); var node_b = tree.getNodeByName('node_b'); equal(node_b.name, 'node_b'); // 2. Add 'node_a' after node1 var node1 = tree.getNodeByName('node1'); node1.addAfter('node_a'); equal(formatNodes(tree.children), 'node1 node_a node2 node_b'); // 3. Add 'node_c' after node_b; new node is an object node_b.addAfter({ label: 'node_c', id: 789 }); var node_c = tree.getNodeByName('node_c'); equal(node_c.id, 789); equal(formatNodes(tree.children), 'node1 node_a node2 node_b node_c'); }); test('addBefore', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); // 1. Add 'node_0' before node1 var node1 = tree.getNodeByName('node1'); node1.addBefore('node0'); equal(formatNodes(tree.children), 'node0 node1 node2'); }); test('addParent', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); // 1. Add node 'root' as parent of node1 // Note that node also becomes a child of 'root' var node1 = tree.getNodeByName('node1'); node1.addParent('root'); var root = tree.getNodeByName('root'); equal(formatNodes(root.children), 'node1 node2'); }); test('remove', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); var child1 = tree.getNodeByName('child1'); var node1 = tree.getNodeByName('node1'); equal(formatNodes(node1.children), 'child1 child2'); equal(child1.parent, node1); // 1. Remove child1 child1.remove(); equal(formatNodes(node1.children), 'child2'); equal(child1.parent, null); }); test('append', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); var node1 = tree.getNodeByName('node1'); // 1. Add child3 to node1 node1.append('child3'); equal(formatNodes(node1.children), 'child1 child2 child3'); }); test('prepend', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); var node1 = tree.getNodeByName('node1'); // 1. Prepend child0 to node1 node1.prepend('child0'); equal(formatNodes(node1.children), 'child0 child1 child2'); }); test('getNodeById', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); // 1. Get node with id 124 var node = tree.getNodeById(124); equal(node.name, 'node2'); // 2. Delete node with id 124 and search again node.remove(); equal(tree.getNodeById(124), null); // 3. Add node with id 456 and search for it var child3 = tree.getNodeByName('child2'); child3.append({ id: 456, label: 'new node' }); node = tree.getNodeById(456); equal(node.name, 'new node'); }); test('getLevel', function() { // setup var tree = new Tree.Tree() tree.loadFromData(example_data); // 1. get level for node1 and child1 equal(tree.getNodeByName('node1').getLevel(), 1); equal(tree.getNodeByName('child1').getLevel(), 2); }); module('util'); test('JSON.stringify', function() { equal(JSON.stringify('abc'), '"abc"'); equal(JSON.stringify(123), '123'); equal(JSON.stringify(true), 'true'); equal(JSON.stringify({abc: 'def'}), '{"abc":"def"}'); equal(JSON.stringify({}), '{}'); equal(JSON.stringify([1, 2, 3]), '[1,2,3]'); equal(JSON.stringify(null), 'null'); equal(JSON.stringify(Number.NEGATIVE_INFINITY), 'null'); // test escapable JSON.stringify("\u200c"); }); test('indexOf', function() { equal(Tree.indexOf([3, 2, 1], 1), 2); equal(Tree._indexOf([3, 2, 1], 1), 2); equal(Tree.indexOf([4, 5, 6], 1), -1); equal(Tree._indexOf([4, 5, 6], 1), -1); }); test('Position.getName', function() { equal(Tree.Position.getName(Tree.Position.BEFORE), 'before'); equal(Tree.Position.getName(Tree.Position.AFTER), 'after'); equal(Tree.Position.getName(Tree.Position.INSIDE), 'inside'); equal(Tree.Position.getName(Tree.Position.NONE), 'none'); }); test('Position.nameToIndex', function() { equal(Tree.Position.nameToIndex('before'), Tree.Position.BEFORE); equal(Tree.Position.nameToIndex('after'), Tree.Position.AFTER); equal(Tree.Position.nameToIndex(''), 0); }); });
Extended 'openNode and closeNode' test
test/test.js
Extended 'openNode and closeNode' test
<ide><path>est/test.js <ide> $tree.tree('closeNode', node2, false); <ide> equal(node2.is_open, false); <ide> equal(isNodeClosed($(node2.element)), true); <add> <add> // 3. open child1 <add> var node1 = $tree.tree('getNodeByName', 'node1'); <add> var child1 = $tree.tree('getNodeByName', 'child1'); <add> <add> // add a child to child1 so it is a folder <add> $tree.tree('appendNode', 'child1a', child1); <add> <add> // node1 is initialy closed <add> equal(node1.is_open, undefined); <add> <add> // open child1 <add> $tree.tree('openNode', child1, false); <add> <add> // node1 and child1 are now open1 <add> equal(node1.is_open, true); <add> equal(child1.is_open, true); <ide> }); <ide> <ide> test('selectNode', function() {
Java
agpl-3.0
1458162d266bee0b681faddfca7eb7a76bf35765
0
Marine-22/libre,PaulLuchyn/libreplan,dgray16/libreplan,LibrePlan/libreplan,poum/libreplan,skylow95/libreplan,dgray16/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,skylow95/libreplan,poum/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,poum/libreplan,poum/libreplan,dgray16/libreplan,skylow95/libreplan,dgray16/libreplan,dgray16/libreplan,poum/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,dgray16/libreplan,LibrePlan/libreplan,Marine-22/libre,poum/libreplan,LibrePlan/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,Marine-22/libre,Marine-22/libre,LibrePlan/libreplan,Marine-22/libre,Marine-22/libre,LibrePlan/libreplan
/* * This file is part of NavalPlan * * Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * * 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/>. */ package org.zkoss.ganttz.data; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; import java.util.Set; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgrapht.DirectedGraph; import org.jgrapht.graph.SimpleDirectedGraph; import org.zkoss.ganttz.data.constraint.Constraint; import org.zkoss.ganttz.data.criticalpath.ICriticalPathCalculable; import org.zkoss.ganttz.util.IAction; import org.zkoss.ganttz.util.PreAndPostNotReentrantActionsWrapper; /** * This class contains a graph with the {@link Task tasks} as vertexes and the * {@link Dependency dependency} as arcs. It enforces the rules embodied in the * dependencies and in the duration of the tasks using listeners. <br/> * @author Óscar González Fernández <[email protected]> */ public class GanttDiagramGraph<V, D> { private static final Log LOG = LogFactory.getLog(GanttDiagramGraph.class); public static IDependenciesEnforcerHook doNothingHook() { return new IDependenciesEnforcerHook() { @Override public void setLengthMilliseconds(long previousLengthMilliseconds, long lengthMilliseconds) { } @Override public void setStartDate(Date previousStart, long previousLength, Date newStart) { } }; } private static final GanttZKAdapter GANTTZK_ADAPTER = new GanttZKAdapter(); public static IAdapter<Task, Dependency> taskAdapter() { return GANTTZK_ADAPTER; } public interface IAdapter<V, D> { List<V> getChildren(V task); boolean isContainer(V task); void registerDependenciesEnforcerHookOn(V task, IDependenciesEnforcerHookFactory<V> hookFactory); Date getStartDate(V task); void setStartDateFor(V task, Date newStart); Date getEndDateFor(V task); void setEndDateFor(V task, Date newEnd); Date getSmallestBeginDateFromChildrenFor(V container); Constraint<Date> getCurrentLenghtConstraintFor(V task); Constraint<Date> getEndDateBiggerThanStartDateConstraintFor(V task); List<Constraint<Date>> getEndConstraintsGivenIncoming(Set<D> incoming); List<Constraint<Date>> getStartCosntraintsGiven(Set<D> withDependencies); List<Constraint<Date>> getStartConstraintsFor(V task); V getSource(D dependency); V getDestination(D dependency); Class<D> getDependencyType(); D createInvisibleDependency(V origin, V destination, DependencyType type); DependencyType getType(D dependency); TaskPoint<V, D> getDestinationPoint(D dependency); boolean isVisible(D dependency); boolean isFixed(V task); } static class GanttZKAdapter implements IAdapter<Task, Dependency> { @Override public List<Task> getChildren(Task task) { return task.getTasks(); } @Override public Task getDestination(Dependency dependency) { return dependency.getDestination(); } @Override public Task getSource(Dependency dependency) { return dependency.getSource(); } @Override public boolean isContainer(Task task) { return task.isContainer(); } @Override public void registerDependenciesEnforcerHookOn(Task task, IDependenciesEnforcerHookFactory<Task> hookFactory) { task.registerDependenciesEnforcerHook(hookFactory); } @Override public Dependency createInvisibleDependency(Task origin, Task destination, DependencyType type) { return new Dependency(origin, destination, type, false); } @Override public Class<Dependency> getDependencyType() { return Dependency.class; } @Override public DependencyType getType(Dependency dependency) { return dependency.getType(); } @Override public TaskPoint<Task, Dependency> getDestinationPoint( Dependency dependency) { return dependency.getDestinationPoint(); } @Override public boolean isVisible(Dependency dependency) { return dependency.isVisible(); } @Override public Date getEndDateFor(Task task) { return task.getEndDate(); } @Override public Constraint<Date> getCurrentLenghtConstraintFor(Task task) { return task.getCurrentLengthConstraint(); } @Override public Constraint<Date> getEndDateBiggerThanStartDateConstraintFor( Task task) { return task.getEndDateBiggerThanStartDate(); } @Override public List<Constraint<Date>> getEndConstraintsGivenIncoming( Set<Dependency> incoming) { return Dependency.getEndConstraints(incoming); } @Override public void setEndDateFor(Task task, Date newEnd) { task.setEndDate(newEnd); } @Override public Date getStartDate(Task task) { return task.getBeginDate(); } @Override public void setStartDateFor(Task task, Date newStart) { task.setBeginDate(newStart); } @Override public List<Constraint<Date>> getStartCosntraintsGiven( Set<Dependency> withDependencies) { return Dependency.getStartConstraints(withDependencies); } @Override public List<Constraint<Date>> getStartConstraintsFor(Task task) { return task.getStartConstraints(); } @Override public Date getSmallestBeginDateFromChildrenFor(Task container) { return ((TaskContainer) container).getSmallestBeginDateFromChildren(); } @Override public boolean isFixed(Task task) { return task.isFixed(); } } public static class GanttZKDiagramGraph extends GanttDiagramGraph<Task, Dependency> implements ICriticalPathCalculable<Task> { private GanttZKDiagramGraph( List<Constraint<Date>> globalStartConstraints, List<Constraint<Date>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { super(GANTTZK_ADAPTER, globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } } public interface IGraphChangeListener { public void execute(); } public static GanttZKDiagramGraph create( List<Constraint<Date>> globalStartConstraints, List<Constraint<Date>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { return new GanttZKDiagramGraph(globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } private final IAdapter<V, D> adapter; private final DirectedGraph<V, D> graph; private List<V> topLevelTasks = new ArrayList<V>(); private Map<V, V> fromChildToParent = new HashMap<V, V>(); private final List<Constraint<Date>> globalStartConstraints; private final List<Constraint<Date>> globalEndConstraints; private DependenciesEnforcer enforcer = new DependenciesEnforcer(); private final boolean dependenciesConstraintsHavePriority; private final ReentranceGuard positionsUpdatingGuard = new ReentranceGuard(); private final PreAndPostNotReentrantActionsWrapper preAndPostActions = new PreAndPostNotReentrantActionsWrapper() { @Override protected void postAction() { executeGraphChangeListeners(new ArrayList<IGraphChangeListener>( postGraphChangeListeners)); } @Override protected void preAction() { executeGraphChangeListeners(new ArrayList<IGraphChangeListener>( preGraphChangeListeners)); } private void executeGraphChangeListeners(List<IGraphChangeListener> graphChangeListeners) { for (IGraphChangeListener each : graphChangeListeners) { try { each.execute(); } catch (Exception e) { LOG.error("error executing execution listener", e); } } } }; private List<IGraphChangeListener> preGraphChangeListeners = new ArrayList<IGraphChangeListener>(); private List<IGraphChangeListener> postGraphChangeListeners = new ArrayList<IGraphChangeListener>(); public void addPreGraphChangeListener(IGraphChangeListener preGraphChangeListener) { preGraphChangeListeners.add(preGraphChangeListener); } public void removePreGraphChangeListener(IGraphChangeListener preGraphChangeListener) { preGraphChangeListeners.remove(preGraphChangeListener); } public void addPostGraphChangeListener(IGraphChangeListener postGraphChangeListener) { postGraphChangeListeners.add(postGraphChangeListener); } public void removePostGraphChangeListener(IGraphChangeListener postGraphChangeListener) { postGraphChangeListeners.remove(postGraphChangeListener); } public void addPreChangeListeners( Collection<? extends IGraphChangeListener> preChangeListeners) { for (IGraphChangeListener each : preChangeListeners) { addPreGraphChangeListener(each); } } public void addPostChangeListeners( Collection<? extends IGraphChangeListener> postChangeListeners) { for (IGraphChangeListener each : postChangeListeners) { addPostGraphChangeListener(each); } } public static <V, D> GanttDiagramGraph<V, D> create(IAdapter<V, D> adapter, List<Constraint<Date>> globalStartConstraints, List<Constraint<Date>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { return new GanttDiagramGraph<V, D>(adapter, globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } protected GanttDiagramGraph(IAdapter<V, D> adapter, List<Constraint<Date>> globalStartConstraints, List<Constraint<Date>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { this.adapter = adapter; this.globalStartConstraints = globalStartConstraints; this.globalEndConstraints = globalEndConstraints; this.dependenciesConstraintsHavePriority = dependenciesConstraintsHavePriority; this.graph = new SimpleDirectedGraph<V, D>(adapter.getDependencyType()); } public void enforceAllRestrictions() { enforcer.enforceRestrictionsOn(getTopLevelTasks()); } public void addTopLevel(V task) { topLevelTasks.add(task); addTask(task); } public void addTopLevel(Collection<? extends V> tasks) { for (V task : tasks) { addTopLevel(task); } } public void addTasks(Collection<? extends V> tasks) { for (V t : tasks) { addTask(t); } } public void addTask(V original) { List<V> stack = new LinkedList<V>(); stack.add(original); List<D> dependenciesToAdd = new ArrayList<D>(); while (!stack.isEmpty()){ V task = stack.remove(0); graph.addVertex(task); adapter.registerDependenciesEnforcerHookOn(task, enforcer); if (adapter.isContainer(task)) { for (V child : adapter.getChildren(task)) { fromChildToParent.put(child, task); stack.add(0, child); dependenciesToAdd.add(adapter.createInvisibleDependency( child, task, DependencyType.END_END)); dependenciesToAdd.add(adapter.createInvisibleDependency( task, child, DependencyType.START_START)); } } } for (D each : dependenciesToAdd) { add(each, false); } } public interface IDependenciesEnforcerHook { public void setStartDate(Date previousStart, long previousLength, Date newStart); public void setLengthMilliseconds(long previousLengthMilliseconds, long newLengthMilliseconds); } public interface IDependenciesEnforcerHookFactory<T> { public IDependenciesEnforcerHook create(T task, INotificationAfterDependenciesEnforcement notification); public IDependenciesEnforcerHook create(T task); } public interface INotificationAfterDependenciesEnforcement { public void onStartDateChange(Date previousStart, long previousLength, Date newStart); public void onLengthChange(long previousLength, long newLength); } private static final INotificationAfterDependenciesEnforcement EMPTY_NOTIFICATOR = new INotificationAfterDependenciesEnforcement() { @Override public void onStartDateChange(Date previousStart, long previousLength, Date newStart) { } @Override public void onLengthChange(long previousLength, long newLength) { } }; public class DeferedNotifier { private Map<V, NotificationPendingForTask> notificationsPending = new LinkedHashMap<V, NotificationPendingForTask>(); public void add(V task, StartDateNofitication notification) { retrieveOrCreateFor(task).setStartDateNofitication(notification); } private NotificationPendingForTask retrieveOrCreateFor(V task) { NotificationPendingForTask result = notificationsPending.get(task); if (result == null) { result = new NotificationPendingForTask(); notificationsPending.put(task, result); } return result; } void add(V task, LengthNotification notification) { retrieveOrCreateFor(task).setLengthNofitication(notification); } public void doNotifications() { for (NotificationPendingForTask each : notificationsPending .values()) { each.doNotification(); } notificationsPending.clear(); } } private class NotificationPendingForTask { private StartDateNofitication startDateNofitication; private LengthNotification lengthNofitication; void setStartDateNofitication( StartDateNofitication startDateNofitication) { this.startDateNofitication = this.startDateNofitication == null ? startDateNofitication : this.startDateNofitication .coalesce(startDateNofitication); } void setLengthNofitication(LengthNotification lengthNofitication) { this.lengthNofitication = this.lengthNofitication == null ? lengthNofitication : this.lengthNofitication.coalesce(lengthNofitication); } void doNotification() { if (startDateNofitication != null) { startDateNofitication.doNotification(); } if (lengthNofitication != null) { lengthNofitication.doNotification(); } } } private class StartDateNofitication { private final INotificationAfterDependenciesEnforcement notification; private final Date previousStart; private final long previousLength; private final Date newStart; public StartDateNofitication( INotificationAfterDependenciesEnforcement notification, Date previousStart, long previousLength, Date newStart) { this.notification = notification; this.previousStart = previousStart; this.previousLength = previousLength; this.newStart = newStart; } public StartDateNofitication coalesce( StartDateNofitication startDateNofitication) { return new StartDateNofitication(notification, previousStart, previousLength, startDateNofitication.newStart); } void doNotification() { notification.onStartDateChange(previousStart, previousLength, newStart); } } private class LengthNotification { private final INotificationAfterDependenciesEnforcement notification; private final long previousLengthMilliseconds; private final long newLengthMilliseconds; public LengthNotification( INotificationAfterDependenciesEnforcement notification, long previousLengthMilliseconds, long lengthMilliseconds) { this.notification = notification; this.previousLengthMilliseconds = previousLengthMilliseconds; this.newLengthMilliseconds = lengthMilliseconds; } public LengthNotification coalesce(LengthNotification lengthNofitication) { return new LengthNotification(notification, previousLengthMilliseconds, lengthNofitication.newLengthMilliseconds); } void doNotification() { notification.onLengthChange(previousLengthMilliseconds, newLengthMilliseconds); } } private class DependenciesEnforcer implements IDependenciesEnforcerHookFactory<V> { private ThreadLocal<DeferedNotifier> deferedNotifier = new ThreadLocal<DeferedNotifier>(); @Override public IDependenciesEnforcerHook create(V task, INotificationAfterDependenciesEnforcement notificator) { return onlyEnforceDependenciesOnEntrance(onEntrance(task), onNotification(task, notificator)); } @Override public IDependenciesEnforcerHook create(V task) { return create(task, EMPTY_NOTIFICATOR); } private IDependenciesEnforcerHook onEntrance(final V task) { return new IDependenciesEnforcerHook() { @Override public void setStartDate(Date previousStart, long previousLength, Date newStart) { taskPositionModified(task); } @Override public void setLengthMilliseconds( long previousLengthMilliseconds, long lengthMilliseconds) { taskPositionModified(task); } }; } private IDependenciesEnforcerHook onNotification(final V task, final INotificationAfterDependenciesEnforcement notification) { return new IDependenciesEnforcerHook() { @Override public void setStartDate(Date previousStart, long previousLength, Date newStart) { StartDateNofitication startDateNotification = new StartDateNofitication( notification, previousStart, previousLength, newStart); deferedNotifier.get().add(task, startDateNotification); } @Override public void setLengthMilliseconds( long previousLengthMilliseconds, long newLengthMilliseconds) { LengthNotification lengthNotification = new LengthNotification( notification, previousLengthMilliseconds, newLengthMilliseconds); deferedNotifier.get().add(task, lengthNotification); } }; } private IDependenciesEnforcerHook onlyEnforceDependenciesOnEntrance( final IDependenciesEnforcerHook onEntrance, final IDependenciesEnforcerHook notification) { return new IDependenciesEnforcerHook() { @Override public void setStartDate(final Date previousStart, final long previousLength, final Date newStart) { positionsUpdatingGuard .entranceRequested(new IReentranceCases() { @Override public void ifNewEntrance() { onNewEntrance(new IAction() { @Override public void doAction() { notification.setStartDate( previousStart, previousLength, newStart); onEntrance.setStartDate( previousStart, previousLength, newStart); } }); } @Override public void ifAlreadyInside() { notification.setStartDate(previousStart, previousLength, newStart); } }); } @Override public void setLengthMilliseconds( final long previousLengthMilliseconds, final long lengthMilliseconds) { positionsUpdatingGuard .entranceRequested(new IReentranceCases() { @Override public void ifNewEntrance() { onNewEntrance(new IAction() { @Override public void doAction() { notification.setLengthMilliseconds( previousLengthMilliseconds, lengthMilliseconds); onEntrance.setLengthMilliseconds( previousLengthMilliseconds, lengthMilliseconds); } }); } @Override public void ifAlreadyInside() { notification.setLengthMilliseconds( previousLengthMilliseconds, lengthMilliseconds); } }); } }; } void enforceRestrictionsOn(Collection<? extends V> tasks) { List<Recalculation> allRecalculations = new ArrayList<Recalculation>(); for (V each : tasks) { allRecalculations.addAll(getRecalculationsNeededFrom(each)); } enforceRestrictionsOn(allRecalculations); } void enforceRestrictionsOn(V task) { enforceRestrictionsOn(getRecalculationsNeededFrom(task)); } void enforceRestrictionsOn(final List<Recalculation> recalculations) { executeWithPreAndPostActionsOnlyIfNewEntrance(new IAction() { @Override public void doAction() { doRecalculations(recalculations); } }); } private void executeWithPreAndPostActionsOnlyIfNewEntrance( final IAction action) { positionsUpdatingGuard.entranceRequested(new IReentranceCases() { @Override public void ifAlreadyInside() { action.doAction(); } @Override public void ifNewEntrance() { onNewEntrance(action); } }); } private void onNewEntrance(final IAction action) { preAndPostActions.doAction(decorateWithNotifications(action)); } private IAction decorateWithNotifications(final IAction action) { return new IAction() { @Override public void doAction() { deferedNotifier.set(new DeferedNotifier()); try { action.doAction(); } finally { DeferedNotifier notifier = deferedNotifier.get(); notifier.doNotifications(); deferedNotifier.set(null); } } }; } DeferedNotifier manualNotification(final IAction action) { final DeferedNotifier result = new DeferedNotifier(); positionsUpdatingGuard.entranceRequested(new IReentranceCases() { @Override public void ifAlreadyInside() { throw new RuntimeException("it cannot do a manual notification if it's already inside"); } @Override public void ifNewEntrance() { preAndPostActions.doAction(new IAction() { @Override public void doAction() { deferedNotifier.set(result); try { action.doAction(); } finally { deferedNotifier.set(null); } } }); } }); return result; } private void taskPositionModified(final V task) { executeWithPreAndPostActionsOnlyIfNewEntrance(new IAction() { @Override public void doAction() { List<Recalculation> recalculationsNeededFrom = getRecalculationsNeededFrom(task); doRecalculations(recalculationsNeededFrom); } }); } private void doRecalculations(List<Recalculation> recalculationsNeeded) { Set<V> allModified = new HashSet<V>(); for (Recalculation each : recalculationsNeeded) { boolean modified = each.doRecalculation(); if (modified) { allModified.add(each.taskPoint.task); } } List<V> shrunkContainers = shrunkContainersOfModified(allModified); for (V each : getTaskAffectedByShrinking(shrunkContainers)) { doRecalculations(getRecalculationsNeededFrom(each)); } } private List<V> getTaskAffectedByShrinking(List<V> shrunkContainers) { List<V> tasksAffectedByShrinking = new ArrayList<V>(); for (V each : shrunkContainers) { for (D eachDependency : graph.outgoingEdgesOf(each)) { if (adapter.getType(eachDependency) == DependencyType.START_START && adapter.isVisible(eachDependency)) { tasksAffectedByShrinking.add(adapter .getDestination(eachDependency)); } } } return tasksAffectedByShrinking; } private List<V> shrunkContainersOfModified( Set<V> allModified) { Set<V> topmostToShrink = getTopMostThatCouldPotentiallyNeedShrinking(allModified); List<V> allToShrink = new ArrayList<V>(); for (V each : topmostToShrink) { allToShrink.addAll(getContainersBottomUp(each)); } List<V> result = new ArrayList<V>(); for (V each : allToShrink) { boolean modified = enforceParentShrinkage(each); if (modified) { result.add(each); } } return result; } private Set<V> getTopMostThatCouldPotentiallyNeedShrinking( Collection<V> modified) { Set<V> result = new HashSet<V>(); for (V each : modified) { V t = getTopmostFor(each); if (adapter.isContainer(t)) { result.add(t); } } return result; } private Collection<? extends V> getContainersBottomUp( V container) { List<V> result = new ArrayList<V>(); List<V> tasks = adapter.getChildren(container); for (V each : tasks) { if (adapter.isContainer(each)) { result.addAll(getContainersBottomUp(each)); result.add(each); } } result.add(container); return result; } boolean enforceParentShrinkage(V container) { Date oldBeginDate = adapter.getStartDate(container); Date firstStart = adapter .getSmallestBeginDateFromChildrenFor(container); Date previousEnd = adapter.getEndDateFor(container); if (firstStart.after(oldBeginDate)) { adapter.setStartDateFor(container, firstStart); adapter.setEndDateFor(container, previousEnd); return true; } return false; } } List<Recalculation> getRecalculationsNeededFrom(V task) { List<Recalculation> result = new LinkedList<Recalculation>(); Set<Recalculation> parentRecalculationsAlreadyDone = new HashSet<Recalculation>(); Recalculation first = recalculationFor(TaskPoint.both(adapter, task)); first.couldHaveBeenModifiedBeforehand(); Queue<Recalculation> pendingOfNavigate = new LinkedList<Recalculation>(); result.addAll(getParentsRecalculations(parentRecalculationsAlreadyDone, first.taskPoint)); result.add(first); pendingOfNavigate.offer(first); while (!pendingOfNavigate.isEmpty()) { Recalculation current = pendingOfNavigate.poll(); for (TaskPoint<V, D> each : getImmendiateReachableFrom(current.taskPoint)) { Recalculation recalculationToAdd = recalculationFor(each); ListIterator<Recalculation> listIterator = result .listIterator(); while (listIterator.hasNext()) { Recalculation previous = listIterator.next(); if (previous.equals(recalculationToAdd)) { listIterator.remove(); recalculationToAdd = previous; break; } } recalculationToAdd.fromParent(current); result.addAll(getParentsRecalculations( parentRecalculationsAlreadyDone, each)); result.add(recalculationToAdd); pendingOfNavigate.offer(recalculationToAdd); } } return result; } private List<Recalculation> getParentsRecalculations( Set<Recalculation> parentRecalculationsAlreadyDone, TaskPoint<V, D> taskPoint) { List<Recalculation> result = new ArrayList<Recalculation>(); for (TaskPoint<V, D> eachParent : parentsRecalculationsNeededFor(taskPoint)) { Recalculation parentRecalculation = parentRecalculation(eachParent.task); if (!parentRecalculationsAlreadyDone .contains(parentRecalculation)) { parentRecalculationsAlreadyDone.add(parentRecalculation); result.add(parentRecalculation); } } return result; } private Set<TaskPoint<V, D>> parentsRecalculationsNeededFor( TaskPoint<V, D> current) { Set<TaskPoint<V, D>> result = new LinkedHashSet<TaskPoint<V, D>>(); if (current.pointType == PointType.BOTH) { List<V> path = fromTaskToTop(current.task); if (path.size() > 1) { path = path.subList(1, path.size()); Collections.reverse(path); result.addAll(asBothPoints(path)); } } return result; } private Collection<? extends TaskPoint<V, D>> asBothPoints(List<V> parents) { List<TaskPoint<V, D>> result = new ArrayList<TaskPoint<V, D>>(); for (V each : parents) { result.add(TaskPoint.both(adapter, each)); } return result; } private List<V> fromTaskToTop(V task) { List<V> result = new ArrayList<V>(); V current = task; while (current != null) { result.add(current); current = fromChildToParent.get(current); } return result; } private Recalculation parentRecalculation(V task) { return new Recalculation(TaskPoint.both(adapter, task), true); } private Recalculation recalculationFor(TaskPoint<V, D> taskPoint) { return new Recalculation(taskPoint, false); } private class Recalculation { private final boolean parentRecalculation; private final TaskPoint<V, D> taskPoint; private Set<Recalculation> recalculationsCouldAffectThis = new HashSet<Recalculation>(); private boolean recalculationCalled = false; private boolean dataPointModified = false; private boolean couldHaveBeenModifiedBeforehand = false; Recalculation(TaskPoint<V, D> taskPoint, boolean isParentRecalculation) { Validate.notNull(taskPoint); this.taskPoint = taskPoint; this.parentRecalculation = isParentRecalculation; } public void couldHaveBeenModifiedBeforehand() { couldHaveBeenModifiedBeforehand = true; } public void fromParent(Recalculation parent) { recalculationsCouldAffectThis.add(parent); } boolean doRecalculation() { recalculationCalled = true; dataPointModified = haveToDoCalculation() && taskChangesPosition(); return dataPointModified; } private boolean haveToDoCalculation() { return (recalculationsCouldAffectThis.isEmpty() || parentsHaveBeenModified()); } private boolean taskChangesPosition() { PointType pointType = taskPoint.pointType; V task = taskPoint.task; switch (pointType) { case BOTH: return enforceStartAndEnd(task); case END: return enforceEnd(task); default: return false; } } private boolean parentsHaveBeenModified() { for (Recalculation each : recalculationsCouldAffectThis) { if (!each.recalculationCalled) { throw new RuntimeException( "the parent must be called first"); } if (each.dataPointModified || each.couldHaveBeenModifiedBeforehand) { return true; } } return false; } private boolean enforceStartAndEnd(V task) { Set<D> incoming = graph.incomingEdgesOf(task); Date previousEndDate = adapter.getEndDateFor(task); boolean startDateChanged = enforceStartDate(task, incoming); boolean endDateChanged = !parentRecalculation && enforceEndDate(task, previousEndDate, incoming); return startDateChanged || endDateChanged; } private boolean enforceEnd(V task) { Set<D> incoming = graph.incomingEdgesOf(task); Date previousEndDate = adapter.getEndDateFor(task); return enforceEndDate(task, previousEndDate, incoming); } @SuppressWarnings("unchecked") private boolean enforceEndDate(V task, Date previousEndDate, Set<D> incoming) { if (adapter.isFixed(task)) { return false; } Constraint<Date> currentLength = adapter .getCurrentLenghtConstraintFor(task); Constraint<Date> respectStartDate = adapter .getEndDateBiggerThanStartDateConstraintFor(task); Date newEnd = Constraint.<Date> initialValue(null) .withConstraints(currentLength) .withConstraints(adapter.getEndConstraintsGivenIncoming(incoming)) .withConstraints(respectStartDate) .apply(); if (!adapter.getEndDateFor(task).equals(newEnd)) { adapter.setEndDateFor(task, newEnd); } return !previousEndDate.equals(newEnd); } private boolean enforceStartDate(V task, Set<D> incoming) { if (adapter.isFixed(task)) { return false; } Date newStart = calculateStartDateFor(task, incoming); if (!adapter.getStartDate(task).equals(newStart)) { adapter.setStartDateFor(task, newStart); return true; } return false; } private Date calculateStartDateFor(V task, Set<D> withDependencies) { List<Constraint<Date>> dependencyConstraints = adapter .getStartCosntraintsGiven(withDependencies); Date newStart; if (dependenciesConstraintsHavePriority) { newStart = Constraint.<Date> initialValue(null) .withConstraints(adapter.getStartConstraintsFor(task)) .withConstraints(dependencyConstraints) .withConstraints(globalStartConstraints).apply(); } else { newStart = Constraint.<Date> initialValue(null) .withConstraints(dependencyConstraints) .withConstraints(adapter.getStartConstraintsFor(task)) .withConstraints(globalStartConstraints).apply(); } return newStart; } @Override public int hashCode() { return new HashCodeBuilder() .append(parentRecalculation) .append(taskPoint) .toHashCode(); } @Override public String toString() { return String.format("%s, parentRecalculation: %s, parents: %s", taskPoint, parentRecalculation, asSimpleString(recalculationsCouldAffectThis)); } private String asSimpleString( Collection<? extends Recalculation> recalculations) { StringBuilder result = new StringBuilder(); result.append("["); for (Recalculation each : recalculations) { result.append(each.taskPoint).append(", "); } result.append("]"); return result.toString(); } @Override public boolean equals(Object obj) { if (Recalculation.class.isInstance(obj)) { Recalculation other = (Recalculation) obj; return new EqualsBuilder().append(parentRecalculation, other.parentRecalculation) .append(taskPoint, other.taskPoint) .isEquals(); } return false; } } public void remove(final V task) { Set<V> needingEnforcing = getOutgoingTasksFor(task); graph.removeVertex(task); topLevelTasks.remove(task); fromChildToParent.remove(task); if (adapter.isContainer(task)) { for (V t : adapter.getChildren(task)) { remove(t); } } enforcer.enforceRestrictionsOn(needingEnforcing); } public void removeDependency(D dependency) { graph.removeEdge(dependency); V destination = adapter.getDestination(dependency); enforcer.enforceRestrictionsOn(destination); } public void add(D dependency) { add(dependency, true); } public void addWithoutEnforcingConstraints(D dependency) { add(dependency, false); } private void add(D dependency, boolean enforceRestrictions) { V source = adapter.getSource(dependency); V destination = adapter.getDestination(dependency); graph.addEdge(source, destination, dependency); if (enforceRestrictions) { enforceRestrictions(destination); } } public void enforceRestrictions(final V task) { enforcer.taskPositionModified(task); } public DeferedNotifier manualNotificationOn(IAction action) { return enforcer.manualNotification(action); } public boolean contains(D dependency) { return graph.containsEdge(dependency); } public List<V> getTasks() { return new ArrayList<V>(graph.vertexSet()); } public List<D> getVisibleDependencies() { ArrayList<D> result = new ArrayList<D>(); for (D dependency : graph.edgeSet()) { if (adapter.isVisible(dependency)) { result.add(dependency); } } return result; } public List<V> getTopLevelTasks() { return Collections.unmodifiableList(topLevelTasks); } public void childrenAddedTo(V task) { enforcer.enforceRestrictionsOn(task); } public List<V> getInitialTasks() { List<V> result = new ArrayList<V>(); for (V task : graph.vertexSet()) { int dependencies = graph.inDegreeOf(task); if ((dependencies == 0) || (dependencies == getNumberOfIncomingDependenciesByType( task, DependencyType.END_END))) { result.add(task); } } return result; } public D getDependencyFrom(V from, V to) { return graph.getEdge(from, to); } public Set<V> getOutgoingTasksFor(V task) { Set<V> result = new HashSet<V>(); for (D dependency : graph.outgoingEdgesOf(task)) { result.add(adapter.getDestination(dependency)); } return result; } public Set<V> getIncomingTasksFor(V task) { Set<V> result = new HashSet<V>(); for (D dependency : graph.incomingEdgesOf(task)) { result.add(adapter.getSource(dependency)); } return result; } public List<V> getLatestTasks() { List<V> tasks = new ArrayList<V>(); for (V task : graph.vertexSet()) { int dependencies = graph.outDegreeOf(task); if ((dependencies == 0) || (dependencies == getNumberOfOutgoingDependenciesByType( task, DependencyType.START_START))) { tasks.add(task); } } return tasks; } private int getNumberOfIncomingDependenciesByType(V task, DependencyType dependencyType) { int count = 0; for (D dependency : graph.incomingEdgesOf(task)) { if (adapter.getType(dependency).equals(dependencyType)) { count++; } } return count; } private int getNumberOfOutgoingDependenciesByType(V task, DependencyType dependencyType) { int count = 0; for (D dependency : graph.outgoingEdgesOf(task)) { if (adapter.getType(dependency).equals(dependencyType)) { count++; } } return count; } public boolean isContainer(V task) { if (task == null) { return false; } return adapter.isContainer(task); } public boolean contains(V container, V task) { if ((container == null) || (task == null)) { return false; } if (adapter.isContainer(container)) { return adapter.getChildren(container).contains(task); } return false; } public boolean doesNotProvokeLoop(D dependency) { Set<TaskPoint<V, D>> reachableFromDestination = getReachableFrom(adapter .getDestinationPoint(dependency)); for (TaskPoint<V, D> each : reachableFromDestination) { if (each.sendsModificationsThrough(dependency)) { return false; } } return true; } /** * It indicates if the task is modified both the start and end, only the end * property or none of the properties * @author Óscar González Fernández <[email protected]> */ public enum PointType { BOTH, END, NONE; public boolean sendsModificationsThrough(DependencyType type) { switch (this) { case NONE: return false; case BOTH: return true; case END: return type == DependencyType.END_END || type == DependencyType.END_START; default: throw new RuntimeException("unexpected value: " + this); } } } public static class TaskPoint<T, D> { public static <T, D> TaskPoint<T, D> both(IAdapter<T, D> adapter, T task) { return new TaskPoint<T, D>(adapter, task, PointType.BOTH); } public static <T, D> TaskPoint<T, D> endOf(IAdapter<T, D> adapter, T task) { return new TaskPoint<T, D>(adapter, task, PointType.END); } final T task; final PointType pointType; private final IAdapter<T, D> adapter; public TaskPoint(IAdapter<T, D> adapter, T task, PointType pointType) { this.adapter = adapter; this.task = task; this.pointType = pointType; } @Override public String toString() { return String.format("%s(%s)", task, pointType); } @Override public boolean equals(Object obj) { if (obj instanceof TaskPoint<?, ?>) { TaskPoint<?, ?> other = (TaskPoint<?, ?>) obj; return new EqualsBuilder().append(task, other.task).append( pointType, other.pointType).isEquals(); } return false; } @Override public int hashCode() { return new HashCodeBuilder().append(task).append(pointType).toHashCode(); } public boolean sendsModificationsThrough(D dependency) { DependencyType type = adapter.getType(dependency); return adapter.getSource(dependency).equals(task) && pointType.sendsModificationsThrough(type); } } private Set<TaskPoint<V, D>> getReachableFrom(TaskPoint<V, D> task) { Set<TaskPoint<V, D>> result = new HashSet<TaskPoint<V, D>>(); Queue<TaskPoint<V, D>> pending = new LinkedList<TaskPoint<V, D>>(); result.add(task); pending.offer(task); while (!pending.isEmpty()) { TaskPoint<V, D> current = pending.poll(); Set<TaskPoint<V, D>> immendiate = getImmendiateReachableFrom(current); for (TaskPoint<V, D> each : immendiate) { if (!result.contains(each)) { result.add(each); pending.offer(each); } } } return result; } private V getTopmostFor(V task) { V result = task; while (fromChildToParent.containsKey(result)) { result = fromChildToParent.get(result); } return result; } private Set<TaskPoint<V, D>> getImmendiateReachableFrom( TaskPoint<V, D> current) { Set<TaskPoint<V, D>> result = new HashSet<TaskPoint<V, D>>(); Set<D> outgoingEdgesOf = graph.outgoingEdgesOf(current.task); for (D each : outgoingEdgesOf) { if (current.sendsModificationsThrough(each)) { result.add(adapter.getDestinationPoint(each)); } } return result; } } interface IReentranceCases { public void ifNewEntrance(); public void ifAlreadyInside(); } class ReentranceGuard { private final ThreadLocal<Boolean> inside = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; }; }; public void entranceRequested(IReentranceCases reentranceCases) { if (inside.get()) { reentranceCases.ifAlreadyInside(); return; } inside.set(true); try { reentranceCases.ifNewEntrance(); } finally { inside.set(false); } } }
ganttzk/src/main/java/org/zkoss/ganttz/data/GanttDiagramGraph.java
/* * This file is part of NavalPlan * * Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * * 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/>. */ package org.zkoss.ganttz.data; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; import java.util.Set; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgrapht.DirectedGraph; import org.jgrapht.graph.SimpleDirectedGraph; import org.zkoss.ganttz.data.constraint.Constraint; import org.zkoss.ganttz.data.criticalpath.ICriticalPathCalculable; import org.zkoss.ganttz.util.IAction; import org.zkoss.ganttz.util.PreAndPostNotReentrantActionsWrapper; /** * This class contains a graph with the {@link Task tasks} as vertexes and the * {@link Dependency dependency} as arcs. It enforces the rules embodied in the * dependencies and in the duration of the tasks using listeners. <br/> * @author Óscar González Fernández <[email protected]> */ public class GanttDiagramGraph<V, D> { private static final Log LOG = LogFactory.getLog(GanttDiagramGraph.class); public static IDependenciesEnforcerHook doNothingHook() { return new IDependenciesEnforcerHook() { @Override public void setLengthMilliseconds(long previousLengthMilliseconds, long lengthMilliseconds) { } @Override public void setStartDate(Date previousStart, long previousLength, Date newStart) { } }; } private static final GanttZKAdapter GANTTZK_ADAPTER = new GanttZKAdapter(); public static IAdapter<Task, Dependency> taskAdapter() { return GANTTZK_ADAPTER; } public interface IAdapter<V, D> { List<V> getChildren(V task); boolean isContainer(V task); void registerDependenciesEnforcerHookOn(V task, IDependenciesEnforcerHookFactory<V> hookFactory); Date getStartDate(V task); void setStartDateFor(V task, Date newStart); Date getEndDateFor(V task); void setEndDateFor(V task, Date newEnd); Date getSmallestBeginDateFromChildrenFor(V container); Constraint<Date> getCurrentLenghtConstraintFor(V task); Constraint<Date> getEndDateBiggerThanStartDateConstraintFor(V task); List<Constraint<Date>> getEndConstraintsGivenIncoming(Set<D> incoming); List<Constraint<Date>> getStartCosntraintsGiven(Set<D> withDependencies); List<Constraint<Date>> getStartConstraintsFor(V task); V getSource(D dependency); V getDestination(D dependency); Class<D> getDependencyType(); D createInvisibleDependency(V origin, V destination, DependencyType type); DependencyType getType(D dependency); TaskPoint<V, D> getDestinationPoint(D dependency); boolean isVisible(D dependency); boolean isFixed(V task); } static class GanttZKAdapter implements IAdapter<Task, Dependency> { @Override public List<Task> getChildren(Task task) { return task.getTasks(); } @Override public Task getDestination(Dependency dependency) { return dependency.getDestination(); } @Override public Task getSource(Dependency dependency) { return dependency.getSource(); } @Override public boolean isContainer(Task task) { return task.isContainer(); } @Override public void registerDependenciesEnforcerHookOn(Task task, IDependenciesEnforcerHookFactory<Task> hookFactory) { task.registerDependenciesEnforcerHook(hookFactory); } @Override public Dependency createInvisibleDependency(Task origin, Task destination, DependencyType type) { return new Dependency(origin, destination, type, false); } @Override public Class<Dependency> getDependencyType() { return Dependency.class; } @Override public DependencyType getType(Dependency dependency) { return dependency.getType(); } @Override public TaskPoint<Task, Dependency> getDestinationPoint( Dependency dependency) { return dependency.getDestinationPoint(); } @Override public boolean isVisible(Dependency dependency) { return dependency.isVisible(); } @Override public Date getEndDateFor(Task task) { return task.getEndDate(); } @Override public Constraint<Date> getCurrentLenghtConstraintFor(Task task) { return task.getCurrentLengthConstraint(); } @Override public Constraint<Date> getEndDateBiggerThanStartDateConstraintFor( Task task) { return task.getEndDateBiggerThanStartDate(); } @Override public List<Constraint<Date>> getEndConstraintsGivenIncoming( Set<Dependency> incoming) { return Dependency.getEndConstraints(incoming); } @Override public void setEndDateFor(Task task, Date newEnd) { task.setEndDate(newEnd); } @Override public Date getStartDate(Task task) { return task.getBeginDate(); } @Override public void setStartDateFor(Task task, Date newStart) { task.setBeginDate(newStart); } @Override public List<Constraint<Date>> getStartCosntraintsGiven( Set<Dependency> withDependencies) { return Dependency.getStartConstraints(withDependencies); } @Override public List<Constraint<Date>> getStartConstraintsFor(Task task) { return task.getStartConstraints(); } @Override public Date getSmallestBeginDateFromChildrenFor(Task container) { return ((TaskContainer) container).getSmallestBeginDateFromChildren(); } @Override public boolean isFixed(Task task) { return task.isFixed(); } } public static class GanttZKDiagramGraph extends GanttDiagramGraph<Task, Dependency> implements ICriticalPathCalculable<Task> { private GanttZKDiagramGraph( List<Constraint<Date>> globalStartConstraints, List<Constraint<Date>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { super(GANTTZK_ADAPTER, globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } } public interface IGraphChangeListener { public void execute(); } public static GanttZKDiagramGraph create( List<Constraint<Date>> globalStartConstraints, List<Constraint<Date>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { return new GanttZKDiagramGraph(globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } private final IAdapter<V, D> adapter; private final DirectedGraph<V, D> graph; private List<V> topLevelTasks = new ArrayList<V>(); private Map<V, V> fromChildToParent = new HashMap<V, V>(); private final List<Constraint<Date>> globalStartConstraints; private final List<Constraint<Date>> globalEndConstraints; private DependenciesEnforcer enforcer = new DependenciesEnforcer(); private final boolean dependenciesConstraintsHavePriority; private final ReentranceGuard positionsUpdatingGuard = new ReentranceGuard(); private final PreAndPostNotReentrantActionsWrapper preAndPostActions = new PreAndPostNotReentrantActionsWrapper() { @Override protected void postAction() { executeGraphChangeListeners(new ArrayList<IGraphChangeListener>( postGraphChangeListeners)); } @Override protected void preAction() { executeGraphChangeListeners(new ArrayList<IGraphChangeListener>( preGraphChangeListeners)); } private void executeGraphChangeListeners(List<IGraphChangeListener> graphChangeListeners) { for (IGraphChangeListener each : graphChangeListeners) { try { each.execute(); } catch (Exception e) { LOG.error("error executing execution listener", e); } } } }; private List<IGraphChangeListener> preGraphChangeListeners = new ArrayList<IGraphChangeListener>(); private List<IGraphChangeListener> postGraphChangeListeners = new ArrayList<IGraphChangeListener>(); public void addPreGraphChangeListener(IGraphChangeListener preGraphChangeListener) { preGraphChangeListeners.add(preGraphChangeListener); } public void removePreGraphChangeListener(IGraphChangeListener preGraphChangeListener) { preGraphChangeListeners.remove(preGraphChangeListener); } public void addPostGraphChangeListener(IGraphChangeListener postGraphChangeListener) { postGraphChangeListeners.add(postGraphChangeListener); } public void removePostGraphChangeListener(IGraphChangeListener postGraphChangeListener) { postGraphChangeListeners.remove(postGraphChangeListener); } public void addPreChangeListeners( Collection<? extends IGraphChangeListener> preChangeListeners) { for (IGraphChangeListener each : preChangeListeners) { addPreGraphChangeListener(each); } } public void addPostChangeListeners( Collection<? extends IGraphChangeListener> postChangeListeners) { for (IGraphChangeListener each : postChangeListeners) { addPostGraphChangeListener(each); } } public static <V, D> GanttDiagramGraph<V, D> create(IAdapter<V, D> adapter, List<Constraint<Date>> globalStartConstraints, List<Constraint<Date>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { return new GanttDiagramGraph<V, D>(adapter, globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } protected GanttDiagramGraph(IAdapter<V, D> adapter, List<Constraint<Date>> globalStartConstraints, List<Constraint<Date>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { this.adapter = adapter; this.globalStartConstraints = globalStartConstraints; this.globalEndConstraints = globalEndConstraints; this.dependenciesConstraintsHavePriority = dependenciesConstraintsHavePriority; this.graph = new SimpleDirectedGraph<V, D>(adapter.getDependencyType()); } public void enforceAllRestrictions() { enforcer.enforceRestrictionsOn(getTopLevelTasks()); } public void addTopLevel(V task) { topLevelTasks.add(task); addTask(task); } public void addTopLevel(Collection<? extends V> tasks) { for (V task : tasks) { addTopLevel(task); } } public void addTasks(Collection<? extends V> tasks) { for (V t : tasks) { addTask(t); } } public void addTask(V original) { List<V> stack = new LinkedList<V>(); stack.add(original); List<D> dependenciesToAdd = new ArrayList<D>(); while (!stack.isEmpty()){ V task = stack.remove(0); graph.addVertex(task); adapter.registerDependenciesEnforcerHookOn(task, enforcer); if (adapter.isContainer(task)) { for (V child : adapter.getChildren(task)) { fromChildToParent.put(child, task); stack.add(0, child); dependenciesToAdd.add(adapter.createInvisibleDependency( child, task, DependencyType.END_END)); dependenciesToAdd.add(adapter.createInvisibleDependency( task, child, DependencyType.START_START)); } } } for (D each : dependenciesToAdd) { add(each, false); } } public interface IDependenciesEnforcerHook { public void setStartDate(Date previousStart, long previousLength, Date newStart); public void setLengthMilliseconds(long previousLengthMilliseconds, long newLengthMilliseconds); } public interface IDependenciesEnforcerHookFactory<T> { public IDependenciesEnforcerHook create(T task, INotificationAfterDependenciesEnforcement notification); public IDependenciesEnforcerHook create(T task); } public interface INotificationAfterDependenciesEnforcement { public void onStartDateChange(Date previousStart, long previousLength, Date newStart); public void onLengthChange(long previousLength, long newLength); } private static final INotificationAfterDependenciesEnforcement EMPTY_NOTIFICATOR = new INotificationAfterDependenciesEnforcement() { @Override public void onStartDateChange(Date previousStart, long previousLength, Date newStart) { } @Override public void onLengthChange(long previousLength, long newLength) { } }; public class DeferedNotifier { private Map<V, NotificationPendingForTask> notificationsPending = new LinkedHashMap<V, NotificationPendingForTask>(); public void add(V task, StartDateNofitication notification) { retrieveOrCreateFor(task).setStartDateNofitication(notification); } private NotificationPendingForTask retrieveOrCreateFor(V task) { NotificationPendingForTask result = notificationsPending.get(task); if (result == null) { result = new NotificationPendingForTask(); notificationsPending.put(task, result); } return result; } void add(V task, LengthNotification notification) { retrieveOrCreateFor(task).setLengthNofitication(notification); } public void doNotifications() { for (NotificationPendingForTask each : notificationsPending .values()) { each.doNotification(); } notificationsPending.clear(); } } private class NotificationPendingForTask { private StartDateNofitication startDateNofitication; private LengthNotification lengthNofitication; void setStartDateNofitication( StartDateNofitication startDateNofitication) { this.startDateNofitication = this.startDateNofitication == null ? startDateNofitication : this.startDateNofitication .coalesce(startDateNofitication); } void setLengthNofitication(LengthNotification lengthNofitication) { this.lengthNofitication = this.lengthNofitication == null ? lengthNofitication : this.lengthNofitication.coalesce(lengthNofitication); } void doNotification() { if (startDateNofitication != null) { startDateNofitication.doNotification(); } if (lengthNofitication != null) { lengthNofitication.doNotification(); } } } private class StartDateNofitication { private final INotificationAfterDependenciesEnforcement notification; private final Date previousStart; private final long previousLength; private final Date newStart; public StartDateNofitication( INotificationAfterDependenciesEnforcement notification, Date previousStart, long previousLength, Date newStart) { this.notification = notification; this.previousStart = previousStart; this.previousLength = previousLength; this.newStart = newStart; } public StartDateNofitication coalesce( StartDateNofitication startDateNofitication) { return new StartDateNofitication(notification, previousStart, previousLength, startDateNofitication.newStart); } void doNotification() { notification.onStartDateChange(previousStart, previousLength, newStart); } } private class LengthNotification { private final INotificationAfterDependenciesEnforcement notification; private final long previousLengthMilliseconds; private final long newLengthMilliseconds; public LengthNotification( INotificationAfterDependenciesEnforcement notification, long previousLengthMilliseconds, long lengthMilliseconds) { this.notification = notification; this.previousLengthMilliseconds = previousLengthMilliseconds; this.newLengthMilliseconds = lengthMilliseconds; } public LengthNotification coalesce(LengthNotification lengthNofitication) { return new LengthNotification(notification, previousLengthMilliseconds, lengthNofitication.newLengthMilliseconds); } void doNotification() { notification.onLengthChange(previousLengthMilliseconds, newLengthMilliseconds); } } private class DependenciesEnforcer implements IDependenciesEnforcerHookFactory<V> { private ThreadLocal<DeferedNotifier> deferedNotifier = new ThreadLocal<DeferedNotifier>(); @Override public IDependenciesEnforcerHook create(V task, INotificationAfterDependenciesEnforcement notificator) { return onlyEnforceDependenciesOnEntrance(onEntrance(task), onNotification(task, notificator)); } @Override public IDependenciesEnforcerHook create(V task) { return create(task, EMPTY_NOTIFICATOR); } private IDependenciesEnforcerHook onEntrance(final V task) { return new IDependenciesEnforcerHook() { @Override public void setStartDate(Date previousStart, long previousLength, Date newStart) { taskPositionModified(task); } @Override public void setLengthMilliseconds( long previousLengthMilliseconds, long lengthMilliseconds) { taskPositionModified(task); } }; } private IDependenciesEnforcerHook onNotification(final V task, final INotificationAfterDependenciesEnforcement notification) { return new IDependenciesEnforcerHook() { @Override public void setStartDate(Date previousStart, long previousLength, Date newStart) { StartDateNofitication startDateNotification = new StartDateNofitication( notification, previousStart, previousLength, newStart); deferedNotifier.get().add(task, startDateNotification); } @Override public void setLengthMilliseconds( long previousLengthMilliseconds, long newLengthMilliseconds) { LengthNotification lengthNotification = new LengthNotification( notification, previousLengthMilliseconds, newLengthMilliseconds); deferedNotifier.get().add(task, lengthNotification); } }; } private IDependenciesEnforcerHook onlyEnforceDependenciesOnEntrance( final IDependenciesEnforcerHook onEntrance, final IDependenciesEnforcerHook notification) { return new IDependenciesEnforcerHook() { @Override public void setStartDate(final Date previousStart, final long previousLength, final Date newStart) { positionsUpdatingGuard .entranceRequested(new IReentranceCases() { @Override public void ifNewEntrance() { onNewEntrance(new IAction() { @Override public void doAction() { notification.setStartDate( previousStart, previousLength, newStart); onEntrance.setStartDate( previousStart, previousLength, newStart); } }); } @Override public void ifAlreadyInside() { notification.setStartDate(previousStart, previousLength, newStart); } }); } @Override public void setLengthMilliseconds( final long previousLengthMilliseconds, final long lengthMilliseconds) { positionsUpdatingGuard .entranceRequested(new IReentranceCases() { @Override public void ifNewEntrance() { onNewEntrance(new IAction() { @Override public void doAction() { notification.setLengthMilliseconds( previousLengthMilliseconds, lengthMilliseconds); onEntrance.setLengthMilliseconds( previousLengthMilliseconds, lengthMilliseconds); } }); } @Override public void ifAlreadyInside() { notification.setLengthMilliseconds( previousLengthMilliseconds, lengthMilliseconds); } }); } }; } void enforceRestrictionsOn(Collection<? extends V> tasks) { List<Recalculation> allRecalculations = new ArrayList<Recalculation>(); for (V each : tasks) { allRecalculations.addAll(getRecalculationsNeededFrom(each)); } enforceRestrictionsOn(allRecalculations); } void enforceRestrictionsOn(V task) { enforceRestrictionsOn(getRecalculationsNeededFrom(task)); } void enforceRestrictionsOn(final List<Recalculation> recalculations) { executeWithPreAndPostActionsOnlyIfNewEntrance(new IAction() { @Override public void doAction() { doRecalculations(recalculations); } }); } private void executeWithPreAndPostActionsOnlyIfNewEntrance( final IAction action) { positionsUpdatingGuard.entranceRequested(new IReentranceCases() { @Override public void ifAlreadyInside() { action.doAction(); } @Override public void ifNewEntrance() { onNewEntrance(action); } }); } private void onNewEntrance(final IAction action) { preAndPostActions.doAction(decorateWithNotifications(action)); } private IAction decorateWithNotifications(final IAction action) { return new IAction() { @Override public void doAction() { deferedNotifier.set(new DeferedNotifier()); try { action.doAction(); } finally { DeferedNotifier notifier = deferedNotifier.get(); notifier.doNotifications(); deferedNotifier.set(null); } } }; } DeferedNotifier manualNotification(final IAction action) { final DeferedNotifier result = new DeferedNotifier(); positionsUpdatingGuard.entranceRequested(new IReentranceCases() { @Override public void ifAlreadyInside() { throw new RuntimeException("it cannot do a manual notification if it's already inside"); } @Override public void ifNewEntrance() { preAndPostActions.doAction(new IAction() { @Override public void doAction() { deferedNotifier.set(result); try { action.doAction(); } finally { deferedNotifier.set(null); } } }); } }); return result; } private void taskPositionModified(final V task) { executeWithPreAndPostActionsOnlyIfNewEntrance(new IAction() { @Override public void doAction() { List<Recalculation> recalculationsNeededFrom = getRecalculationsNeededFrom(task); doRecalculations(recalculationsNeededFrom); } }); } private void doRecalculations(List<Recalculation> recalculationsNeeded) { Set<V> allModified = new HashSet<V>(); for (Recalculation each : recalculationsNeeded) { boolean modified = each.doRecalculation(); if (modified) { allModified.add(each.taskPoint.task); } } List<V> shrunkContainers = shrunkContainersOfModified(allModified); for (V each : getTaskAffectedByShrinking(shrunkContainers)) { doRecalculations(getRecalculationsNeededFrom(each)); } } private List<V> getTaskAffectedByShrinking(List<V> shrunkContainers) { List<V> tasksAffectedByShrinking = new ArrayList<V>(); for (V each : shrunkContainers) { for (D eachDependency : graph.outgoingEdgesOf(each)) { if (adapter.getType(eachDependency) == DependencyType.START_START && adapter.isVisible(eachDependency)) { tasksAffectedByShrinking.add(adapter .getDestination(eachDependency)); } } } return tasksAffectedByShrinking; } private List<V> shrunkContainersOfModified( Set<V> allModified) { Set<V> topmostToShrink = getTopMostThatCouldPotentiallyNeedShrinking(allModified); List<V> allToShrink = new ArrayList<V>(); for (V each : topmostToShrink) { allToShrink.addAll(getContainersBottomUp(each)); } List<V> result = new ArrayList<V>(); for (V each : allToShrink) { boolean modified = enforceParentShrinkage(each); if (modified) { result.add(each); } } return result; } private Set<V> getTopMostThatCouldPotentiallyNeedShrinking( Collection<V> modified) { Set<V> result = new HashSet<V>(); for (V each : modified) { V t = getTopmostFor(each); if (adapter.isContainer(t)) { result.add(t); } } return result; } private Collection<? extends V> getContainersBottomUp( V container) { List<V> result = new ArrayList<V>(); List<V> tasks = adapter.getChildren(container); for (V each : tasks) { if (adapter.isContainer(each)) { result.addAll(getContainersBottomUp(each)); result.add(each); } } result.add(container); return result; } boolean enforceParentShrinkage(V container) { Date oldBeginDate = adapter.getStartDate(container); Date firstStart = adapter .getSmallestBeginDateFromChildrenFor(container); Date previousEnd = adapter.getEndDateFor(container); if (firstStart.after(oldBeginDate)) { adapter.setStartDateFor(container, firstStart); adapter.setEndDateFor(container, previousEnd); return true; } return false; } } List<Recalculation> getRecalculationsNeededFrom(V task) { List<Recalculation> result = new LinkedList<Recalculation>(); Set<Recalculation> parentRecalculationsAlreadyDone = new HashSet<Recalculation>(); Recalculation first = recalculationFor(TaskPoint.both(adapter, task)); first.couldHaveBeenModifiedBeforehand(); Queue<Recalculation> pendingOfNavigate = new LinkedList<Recalculation>(); result.addAll(getParentsRecalculations(parentRecalculationsAlreadyDone, first.taskPoint)); result.add(first); pendingOfNavigate.offer(first); while (!pendingOfNavigate.isEmpty()) { Recalculation current = pendingOfNavigate.poll(); for (TaskPoint<V, D> each : getImmendiateReachableFrom(current.taskPoint)) { Recalculation recalculationToAdd = recalculationFor(each); ListIterator<Recalculation> listIterator = result .listIterator(); while (listIterator.hasNext()) { Recalculation previous = listIterator.next(); if (previous.equals(recalculationToAdd)) { listIterator.remove(); recalculationToAdd = previous; break; } } recalculationToAdd.fromParent(current); result.addAll(getParentsRecalculations( parentRecalculationsAlreadyDone, each)); result.add(recalculationToAdd); pendingOfNavigate.offer(recalculationToAdd); } } return result; } private List<Recalculation> getParentsRecalculations( Set<Recalculation> parentRecalculationsAlreadyDone, TaskPoint<V, D> taskPoint) { List<Recalculation> result = new ArrayList<Recalculation>(); for (TaskPoint<V, D> eachParent : parentsRecalculationsNeededFor(taskPoint)) { Recalculation parentRecalculation = parentRecalculation(eachParent.task); if (!parentRecalculationsAlreadyDone .contains(parentRecalculation)) { parentRecalculationsAlreadyDone.add(parentRecalculation); result.add(parentRecalculation); } } return result; } private Set<TaskPoint<V, D>> parentsRecalculationsNeededFor( TaskPoint<V, D> current) { Set<TaskPoint<V, D>> result = new LinkedHashSet<TaskPoint<V, D>>(); if (current.pointType == PointType.BOTH) { List<V> path = fromTaskToTop(current.task); if (path.size() > 1) { path = path.subList(1, path.size()); Collections.reverse(path); result.addAll(asBothPoints(path)); } } return result; } private Collection<? extends TaskPoint<V, D>> asBothPoints(List<V> parents) { List<TaskPoint<V, D>> result = new ArrayList<TaskPoint<V, D>>(); for (V each : parents) { result.add(TaskPoint.both(adapter, each)); } return result; } private List<V> fromTaskToTop(V task) { List<V> result = new ArrayList<V>(); V current = task; while (current != null) { result.add(current); current = fromChildToParent.get(current); } return result; } private Recalculation parentRecalculation(V task) { return new Recalculation(TaskPoint.both(adapter, task), true); } private Recalculation recalculationFor(TaskPoint<V, D> taskPoint) { return new Recalculation(taskPoint, false); } private class Recalculation { private final boolean parentRecalculation; private final TaskPoint<V, D> taskPoint; private Set<Recalculation> recalculationsCouldAffectThis = new HashSet<Recalculation>(); private boolean recalculationCalled = false; private boolean dataPointModified = false; private boolean couldHaveBeenModifiedBeforehand = false; Recalculation(TaskPoint<V, D> taskPoint, boolean isParentRecalculation) { Validate.notNull(taskPoint); this.taskPoint = taskPoint; this.parentRecalculation = isParentRecalculation; } public void couldHaveBeenModifiedBeforehand() { couldHaveBeenModifiedBeforehand = true; } public void fromParent(Recalculation parent) { recalculationsCouldAffectThis.add(parent); } boolean doRecalculation() { recalculationCalled = true; dataPointModified = haveToDoCalculation() && taskChangesPosition(); return dataPointModified; } private boolean haveToDoCalculation() { return (recalculationsCouldAffectThis.isEmpty() || parentsHaveBeenModified()); } private boolean taskChangesPosition() { PointType pointType = taskPoint.pointType; V task = taskPoint.task; switch (pointType) { case BOTH: return enforceStartAndEnd(task); case END: return enforceEnd(task); default: return false; } } private boolean parentsHaveBeenModified() { for (Recalculation each : recalculationsCouldAffectThis) { if (!each.recalculationCalled) { throw new RuntimeException( "the parent must be called first"); } if (each.dataPointModified || each.couldHaveBeenModifiedBeforehand) { return true; } } return false; } private boolean enforceStartAndEnd(V task) { Set<D> incoming = graph.incomingEdgesOf(task); Date previousEndDate = adapter.getEndDateFor(task); boolean startDateChanged = enforceStartDate(task, incoming); boolean endDateChanged = enforceEndDate(task, previousEndDate, incoming); return startDateChanged || endDateChanged; } private boolean enforceEnd(V task) { Set<D> incoming = graph.incomingEdgesOf(task); Date previousEndDate = adapter.getEndDateFor(task); return enforceEndDate(task, previousEndDate, incoming); } @SuppressWarnings("unchecked") private boolean enforceEndDate(V task, Date previousEndDate, Set<D> incoming) { if (adapter.isFixed(task)) { return false; } Constraint<Date> currentLength = adapter .getCurrentLenghtConstraintFor(task); Constraint<Date> respectStartDate = adapter .getEndDateBiggerThanStartDateConstraintFor(task); Date newEnd = Constraint.<Date> initialValue(null) .withConstraints(currentLength) .withConstraints(adapter.getEndConstraintsGivenIncoming(incoming)) .withConstraints(respectStartDate) .apply(); if (!adapter.getEndDateFor(task).equals(newEnd)) { adapter.setEndDateFor(task, newEnd); } return !previousEndDate.equals(newEnd); } private boolean enforceStartDate(V task, Set<D> incoming) { if (adapter.isFixed(task)) { return false; } Date newStart = calculateStartDateFor(task, incoming); if (!adapter.getStartDate(task).equals(newStart)) { adapter.setStartDateFor(task, newStart); return true; } return false; } private Date calculateStartDateFor(V task, Set<D> withDependencies) { List<Constraint<Date>> dependencyConstraints = adapter .getStartCosntraintsGiven(withDependencies); Date newStart; if (dependenciesConstraintsHavePriority) { newStart = Constraint.<Date> initialValue(null) .withConstraints(adapter.getStartConstraintsFor(task)) .withConstraints(dependencyConstraints) .withConstraints(globalStartConstraints).apply(); } else { newStart = Constraint.<Date> initialValue(null) .withConstraints(dependencyConstraints) .withConstraints(adapter.getStartConstraintsFor(task)) .withConstraints(globalStartConstraints).apply(); } return newStart; } @Override public int hashCode() { return new HashCodeBuilder() .append(parentRecalculation) .append(taskPoint) .toHashCode(); } @Override public String toString() { return String.format("%s, parentRecalculation: %s, parents: %s", taskPoint, parentRecalculation, asSimpleString(recalculationsCouldAffectThis)); } private String asSimpleString( Collection<? extends Recalculation> recalculations) { StringBuilder result = new StringBuilder(); result.append("["); for (Recalculation each : recalculations) { result.append(each.taskPoint).append(", "); } result.append("]"); return result.toString(); } @Override public boolean equals(Object obj) { if (Recalculation.class.isInstance(obj)) { Recalculation other = (Recalculation) obj; return new EqualsBuilder().append(parentRecalculation, other.parentRecalculation) .append(taskPoint, other.taskPoint) .isEquals(); } return false; } } public void remove(final V task) { Set<V> needingEnforcing = getOutgoingTasksFor(task); graph.removeVertex(task); topLevelTasks.remove(task); fromChildToParent.remove(task); if (adapter.isContainer(task)) { for (V t : adapter.getChildren(task)) { remove(t); } } enforcer.enforceRestrictionsOn(needingEnforcing); } public void removeDependency(D dependency) { graph.removeEdge(dependency); V destination = adapter.getDestination(dependency); enforcer.enforceRestrictionsOn(destination); } public void add(D dependency) { add(dependency, true); } public void addWithoutEnforcingConstraints(D dependency) { add(dependency, false); } private void add(D dependency, boolean enforceRestrictions) { V source = adapter.getSource(dependency); V destination = adapter.getDestination(dependency); graph.addEdge(source, destination, dependency); if (enforceRestrictions) { enforceRestrictions(destination); } } public void enforceRestrictions(final V task) { enforcer.taskPositionModified(task); } public DeferedNotifier manualNotificationOn(IAction action) { return enforcer.manualNotification(action); } public boolean contains(D dependency) { return graph.containsEdge(dependency); } public List<V> getTasks() { return new ArrayList<V>(graph.vertexSet()); } public List<D> getVisibleDependencies() { ArrayList<D> result = new ArrayList<D>(); for (D dependency : graph.edgeSet()) { if (adapter.isVisible(dependency)) { result.add(dependency); } } return result; } public List<V> getTopLevelTasks() { return Collections.unmodifiableList(topLevelTasks); } public void childrenAddedTo(V task) { enforcer.enforceRestrictionsOn(task); } public List<V> getInitialTasks() { List<V> result = new ArrayList<V>(); for (V task : graph.vertexSet()) { int dependencies = graph.inDegreeOf(task); if ((dependencies == 0) || (dependencies == getNumberOfIncomingDependenciesByType( task, DependencyType.END_END))) { result.add(task); } } return result; } public D getDependencyFrom(V from, V to) { return graph.getEdge(from, to); } public Set<V> getOutgoingTasksFor(V task) { Set<V> result = new HashSet<V>(); for (D dependency : graph.outgoingEdgesOf(task)) { result.add(adapter.getDestination(dependency)); } return result; } public Set<V> getIncomingTasksFor(V task) { Set<V> result = new HashSet<V>(); for (D dependency : graph.incomingEdgesOf(task)) { result.add(adapter.getSource(dependency)); } return result; } public List<V> getLatestTasks() { List<V> tasks = new ArrayList<V>(); for (V task : graph.vertexSet()) { int dependencies = graph.outDegreeOf(task); if ((dependencies == 0) || (dependencies == getNumberOfOutgoingDependenciesByType( task, DependencyType.START_START))) { tasks.add(task); } } return tasks; } private int getNumberOfIncomingDependenciesByType(V task, DependencyType dependencyType) { int count = 0; for (D dependency : graph.incomingEdgesOf(task)) { if (adapter.getType(dependency).equals(dependencyType)) { count++; } } return count; } private int getNumberOfOutgoingDependenciesByType(V task, DependencyType dependencyType) { int count = 0; for (D dependency : graph.outgoingEdgesOf(task)) { if (adapter.getType(dependency).equals(dependencyType)) { count++; } } return count; } public boolean isContainer(V task) { if (task == null) { return false; } return adapter.isContainer(task); } public boolean contains(V container, V task) { if ((container == null) || (task == null)) { return false; } if (adapter.isContainer(container)) { return adapter.getChildren(container).contains(task); } return false; } public boolean doesNotProvokeLoop(D dependency) { Set<TaskPoint<V, D>> reachableFromDestination = getReachableFrom(adapter .getDestinationPoint(dependency)); for (TaskPoint<V, D> each : reachableFromDestination) { if (each.sendsModificationsThrough(dependency)) { return false; } } return true; } /** * It indicates if the task is modified both the start and end, only the end * property or none of the properties * @author Óscar González Fernández <[email protected]> */ public enum PointType { BOTH, END, NONE; public boolean sendsModificationsThrough(DependencyType type) { switch (this) { case NONE: return false; case BOTH: return true; case END: return type == DependencyType.END_END || type == DependencyType.END_START; default: throw new RuntimeException("unexpected value: " + this); } } } public static class TaskPoint<T, D> { public static <T, D> TaskPoint<T, D> both(IAdapter<T, D> adapter, T task) { return new TaskPoint<T, D>(adapter, task, PointType.BOTH); } public static <T, D> TaskPoint<T, D> endOf(IAdapter<T, D> adapter, T task) { return new TaskPoint<T, D>(adapter, task, PointType.END); } final T task; final PointType pointType; private final IAdapter<T, D> adapter; public TaskPoint(IAdapter<T, D> adapter, T task, PointType pointType) { this.adapter = adapter; this.task = task; this.pointType = pointType; } @Override public String toString() { return String.format("%s(%s)", task, pointType); } @Override public boolean equals(Object obj) { if (obj instanceof TaskPoint<?, ?>) { TaskPoint<?, ?> other = (TaskPoint<?, ?>) obj; return new EqualsBuilder().append(task, other.task).append( pointType, other.pointType).isEquals(); } return false; } @Override public int hashCode() { return new HashCodeBuilder().append(task).append(pointType).toHashCode(); } public boolean sendsModificationsThrough(D dependency) { DependencyType type = adapter.getType(dependency); return adapter.getSource(dependency).equals(task) && pointType.sendsModificationsThrough(type); } } private Set<TaskPoint<V, D>> getReachableFrom(TaskPoint<V, D> task) { Set<TaskPoint<V, D>> result = new HashSet<TaskPoint<V, D>>(); Queue<TaskPoint<V, D>> pending = new LinkedList<TaskPoint<V, D>>(); result.add(task); pending.offer(task); while (!pending.isEmpty()) { TaskPoint<V, D> current = pending.poll(); Set<TaskPoint<V, D>> immendiate = getImmendiateReachableFrom(current); for (TaskPoint<V, D> each : immendiate) { if (!result.contains(each)) { result.add(each); pending.offer(each); } } } return result; } private V getTopmostFor(V task) { V result = task; while (fromChildToParent.containsKey(result)) { result = fromChildToParent.get(result); } return result; } private Set<TaskPoint<V, D>> getImmendiateReachableFrom( TaskPoint<V, D> current) { Set<TaskPoint<V, D>> result = new HashSet<TaskPoint<V, D>>(); Set<D> outgoingEdgesOf = graph.outgoingEdgesOf(current.task); for (D each : outgoingEdgesOf) { if (current.sendsModificationsThrough(each)) { result.add(adapter.getDestinationPoint(each)); } } return result; } } interface IReentranceCases { public void ifNewEntrance(); public void ifAlreadyInside(); } class ReentranceGuard { private final ThreadLocal<Boolean> inside = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; }; }; public void entranceRequested(IReentranceCases reentranceCases) { if (inside.get()) { reentranceCases.ifAlreadyInside(); return; } inside.set(true); try { reentranceCases.ifNewEntrance(); } finally { inside.set(false); } } }
ItEr60S04ValidacionEProbasFuncionaisItEr59S04: [Bug #542] Fix bug. The parent recalculation was updating the end date. This caused that later thought that the end date was not modified and the grandparent tasks was not recalculated.
ganttzk/src/main/java/org/zkoss/ganttz/data/GanttDiagramGraph.java
ItEr60S04ValidacionEProbasFuncionaisItEr59S04: [Bug #542] Fix bug.
<ide><path>anttzk/src/main/java/org/zkoss/ganttz/data/GanttDiagramGraph.java <ide> Set<D> incoming = graph.incomingEdgesOf(task); <ide> Date previousEndDate = adapter.getEndDateFor(task); <ide> boolean startDateChanged = enforceStartDate(task, incoming); <del> boolean endDateChanged = enforceEndDate(task, previousEndDate, <del> incoming); <add> boolean endDateChanged = !parentRecalculation <add> && enforceEndDate(task, previousEndDate, incoming); <ide> return startDateChanged || endDateChanged; <ide> } <ide>
JavaScript
mit
88e813657c359e6f9713e1e7149d0a99693b1737
0
loggingroads/onboarding,loggingroads/onboarding,loggingroads/onboarding,loggingroads/onboarding
import staticReducer from './static'; import campaingsReducer from './campaingsReducer'; <<<<<<< HEAD import eventsReducer from './eventsReducer'; import tasksReducer from './tasksReducer'; export default { campaingsReducer, eventsReducer, tasksReducer, staticReducer };
app/assets/javascripts/reducers/index.js
import staticReducer from './static'; import campaingsReducer from './campaingsReducer'; import eventsReducer from './eventsReducer'; import tasksReducer from './tasksReducer'; export default { campaingsReducer, eventsReducer, tasksReducer, staticReducer };
fix conlfict with develop
app/assets/javascripts/reducers/index.js
fix conlfict with develop
<ide><path>pp/assets/javascripts/reducers/index.js <ide> import staticReducer from './static'; <ide> import campaingsReducer from './campaingsReducer'; <add><<<<<<< HEAD <ide> import eventsReducer from './eventsReducer'; <ide> import tasksReducer from './tasksReducer'; <ide>
Java
apache-2.0
92fe7d5b76bdb233e1ce1e6157de239d839a1541
0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.common.loader; import uk.ac.ebi.quickgo.common.validator.DbXRefEntity; import java.util.List; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; /** * @author Tony Wardell * Date: 19/04/2016 * Time: 09:27 * Created with IntelliJ IDEA. */ public class DbXRefLoaderTestIT { private static final String NOWHERE_CANTFIND = "OVER/RAINBOW"; private static final String FIND_IT_HERE = "src/test/resources/DB_XREFS_ENTITIES.dat.gz"; private static final boolean CASE_SENSITIVE_MATCHING = false; @Test public void loadFileUnsuccessfully(){ DbXRefLoader dbXRefLoader = new DbXRefLoader(NOWHERE_CANTFIND, CASE_SENSITIVE_MATCHING ); List<DbXRefEntity> list = dbXRefLoader.load(); assertThat(list, hasSize(0)); } @Test public void loadFileSuccessfully(){ DbXRefLoader dbXRefLoader = new DbXRefLoader(FIND_IT_HERE, CASE_SENSITIVE_MATCHING ); List<DbXRefEntity> list = dbXRefLoader.load(); assertThat(list, hasSize(142)); assertThat(list.get(0).toString(), is("GeneProductXrefEntity{database='AGI_LocusCode', " + "entityType='SO:0000704', entityTypeName='gene', idValidationPattern=A[Tt][MmCc0-5][Gg][0-9]{5}(\\\\" + ".[0-9]{1})?, databaseURL='http://arabidopsis.org/servlets/TairObject?type=locus&name=[example_id]'}")); } }
common/src/test/java/uk/ac/ebi/quickgo/common/loader/DbXRefLoaderTestIT.java
package uk.ac.ebi.quickgo.common.loader; import uk.ac.ebi.quickgo.common.validator.DbXRefEntity; import java.util.List; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; /** * @author Tony Wardell * Date: 19/04/2016 * Time: 09:27 * Created with IntelliJ IDEA. */ public class DbXRefLoaderTestIT { private static final String NOWHERE_CANTFIND = "OVER/RAINBOW"; private static final String FIND_IT_HERE = "src/test/resources/DB_XREFS_ENTITIES.dat.gz"; private static final boolean CASE_SENSITIVE_MATCHING = false; @Test public void loadFileUnsuccessfully(){ DbXRefLoader dbXRefLoader = new DbXRefLoader(NOWHERE_CANTFIND, CASE_SENSITIVE_MATCHING ); List<DbXRefEntity> list = dbXRefLoader.load(); assertThat(list, hasSize(0)); } @Test public void loadFileSuccessfully(){ DbXRefLoader dbXRefLoader = new DbXRefLoader(FIND_IT_HERE, CASE_SENSITIVE_MATCHING ); List<DbXRefEntity> list = dbXRefLoader.load(); assertThat(list, hasSize(119)); assertThat(list.get(0).toString(), is("GeneProductXrefEntity{database='AGI_LocusCode', " + "entityType='SO:0000704', entityTypeName='gene', idValidationPattern=A[Tt][MmCc0-5][Gg][0-9]{5}(\\\\" + ".[0-9]{1})?, databaseURL='http://arabidopsis.org/servlets/TairObject?type=locus&name=[example_id]'}")); } }
Update the expected NO_OF_DB_XREFS now that the file in resources has been updated (to now hold ComplexPortal regex).
common/src/test/java/uk/ac/ebi/quickgo/common/loader/DbXRefLoaderTestIT.java
Update the expected NO_OF_DB_XREFS now that the file in resources has been updated (to now hold ComplexPortal regex).
<ide><path>ommon/src/test/java/uk/ac/ebi/quickgo/common/loader/DbXRefLoaderTestIT.java <ide> public void loadFileSuccessfully(){ <ide> DbXRefLoader dbXRefLoader = new DbXRefLoader(FIND_IT_HERE, CASE_SENSITIVE_MATCHING ); <ide> List<DbXRefEntity> list = dbXRefLoader.load(); <del> assertThat(list, hasSize(119)); <add> assertThat(list, hasSize(142)); <ide> assertThat(list.get(0).toString(), is("GeneProductXrefEntity{database='AGI_LocusCode', " + <ide> "entityType='SO:0000704', entityTypeName='gene', idValidationPattern=A[Tt][MmCc0-5][Gg][0-9]{5}(\\\\" + <ide> ".[0-9]{1})?, databaseURL='http://arabidopsis.org/servlets/TairObject?type=locus&name=[example_id]'}"));
Java
mit
3748203b6d21090987b434803685ca9e27a3416c
0
jbosboom/bytecodelib
package edu.mit.streamjit.util.bytecode; import static com.google.common.base.Preconditions.*; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import edu.mit.streamjit.util.bytecode.insts.ArrayLengthInst; import edu.mit.streamjit.util.bytecode.insts.ArrayLoadInst; import edu.mit.streamjit.util.bytecode.insts.ArrayStoreInst; import edu.mit.streamjit.util.bytecode.insts.BinaryInst; import edu.mit.streamjit.util.bytecode.insts.BranchInst; import edu.mit.streamjit.util.bytecode.insts.CallInst; import edu.mit.streamjit.util.bytecode.insts.CastInst; import edu.mit.streamjit.util.bytecode.insts.InstanceofInst; import edu.mit.streamjit.util.bytecode.insts.Instruction; import edu.mit.streamjit.util.bytecode.insts.JumpInst; import edu.mit.streamjit.util.bytecode.insts.LoadInst; import edu.mit.streamjit.util.bytecode.insts.NewArrayInst; import edu.mit.streamjit.util.bytecode.insts.PhiInst; import edu.mit.streamjit.util.bytecode.insts.ReturnInst; import edu.mit.streamjit.util.bytecode.insts.StoreInst; import edu.mit.streamjit.util.bytecode.insts.SwitchInst; import edu.mit.streamjit.util.bytecode.insts.TerminatorInst; import edu.mit.streamjit.util.bytecode.insts.ThrowInst; import edu.mit.streamjit.util.bytecode.types.ArrayType; import edu.mit.streamjit.util.bytecode.types.MethodType; import edu.mit.streamjit.util.bytecode.types.NullType; import edu.mit.streamjit.util.bytecode.types.PrimitiveType; import edu.mit.streamjit.util.bytecode.types.ReferenceType; import edu.mit.streamjit.util.bytecode.types.RegularType; import edu.mit.streamjit.util.bytecode.types.ReturnType; import edu.mit.streamjit.util.bytecode.types.Type; import edu.mit.streamjit.util.bytecode.types.TypeFactory; import edu.mit.streamjit.util.bytecode.types.VoidType; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.LookupSwitchInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.MultiANewArrayInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; /** * Builds bytecode from methods. * @author Jeffrey Bosboom <[email protected]> * @since 4/17/2013 */ public final class MethodUnresolver { public static MethodNode unresolve(Method m) { checkNotNull(m); //Unresolving immutable methods (live Class methods) is only useful //during testing. //checkArgument(m.isMutable(), "unresolving immutable method %s", m); if (!m.modifiers().contains(Modifier.ABSTRACT)) checkArgument(m.isResolved(), "unresolving unresolved method %s", m); return new MethodUnresolver(m).unresolve(); } private final Method method; private final MethodNode methodNode; private final Value uninitializedThis; private final Map<Value, Integer> registers; private final Map<BasicBlock, LabelNode> labels; private final PrimitiveType booleanType, byteType, charType, shortType, intType, longType, floatType, doubleType; private MethodUnresolver(Method m) { this.method = m; this.methodNode = new MethodNode(Opcodes.ASM4); this.uninitializedThis = method.isConstructor() ? findUninitializedThis() : null; this.registers = new IdentityHashMap<>(); this.labels = new IdentityHashMap<>(); TypeFactory tf = m.getParent().getParent().types(); this.booleanType = tf.getPrimitiveType(boolean.class); this.byteType = tf.getPrimitiveType(byte.class); this.charType = tf.getPrimitiveType(char.class); this.shortType = tf.getPrimitiveType(short.class); this.intType = tf.getPrimitiveType(int.class); this.longType = tf.getPrimitiveType(long.class); this.floatType = tf.getPrimitiveType(float.class); this.doubleType = tf.getPrimitiveType(double.class); } public MethodNode unresolve() { this.methodNode.access = Modifier.toBits(method.modifiers()); this.methodNode.name = method.getName(); this.methodNode.desc = methodDescriptor(method); this.methodNode.exceptions = Collections.emptyList(); if (!method.modifiers().contains(Modifier.ABSTRACT)) { allocateRegisters(); createLabels(); for (BasicBlock b : method.basicBlocks()) methodNode.instructions.add(emit(b)); peepholeOptimizations(); int maxRegister = registers.values().isEmpty() ? 0 : Collections.max(registers.values()); this.methodNode.maxLocals = maxRegister+2; //We'd like to use ClassWriter's COMPUTE_MAXS option to compute this //for us, but we also want to use CheckClassAdapter before //ClassWriter to get useful errors. But CheckClassAdapter will //raise an error if we get this too low and run out of memory if we //just say Short.MAX_VALUE. I think any bytecode can push at most //+2 net, so conservatively try 2*instructions.size(). Note that //this counts labels and other pseudo-instructions, as well as //instructions that have obviously no stack increase or a decrease. this.methodNode.maxStack = Math.min(2*methodNode.instructions.size(), Short.MAX_VALUE); buildLocalVariableTable(); } return methodNode; } private void allocateRegisters() { //We allocate one or two registers (depending on type category) to each //instruction producing a non-void value, the method arguments, and the //local variables. int regNum = 0; if (method.isConstructor()) { registers.put(uninitializedThis, regNum); regNum += uninitializedThis.getType().getCategory(); } for (Argument a : method.arguments()) { registers.put(a, regNum); regNum += a.getType().getCategory(); } if (method.isMutable()) for (LocalVariable v : method.localVariables()) { registers.put(v, regNum); regNum += v.getType().getFieldType().getCategory(); } for (BasicBlock b : method.basicBlocks()) for (Instruction i : b.instructions()) if (!(i.getType() instanceof VoidType)) { registers.put(i, regNum); regNum += i.getType().getCategory(); } } private void createLabels() { for (BasicBlock b : method.basicBlocks()) labels.put(b, new LabelNode(new Label())); } private void buildLocalVariableTable() { LabelNode first = new LabelNode(), last = new LabelNode(); methodNode.instructions.insert(first); methodNode.instructions.add(last); methodNode.localVariables = new ArrayList<>(registers.size()); for (Map.Entry<Value, Integer> r : registers.entrySet()) { RegularType type = r.getKey() instanceof LocalVariable ? ((LocalVariable)r.getKey()).getType().getFieldType() : (RegularType)r.getKey().getType(); methodNode.localVariables.add(new LocalVariableNode( r.getKey().getName(), type.getDescriptor(), null, first, last, r.getValue())); } } private InsnList emit(BasicBlock block) { FluentIterable<TerminatorInst> terminators = FluentIterable.from(block.instructions()).filter(TerminatorInst.class); if (terminators.isEmpty()) throw new IllegalArgumentException("block "+block.getName()+" in method "+block.getParent().getName()+" lacks a terminator"); if (terminators.size() > 1) throw new IllegalArgumentException("block "+block.getName()+" in method "+block.getParent().getName()+" has multiple terminators: "+terminators); InsnList insns = new InsnList(); insns.add(labels.get(block)); for (Instruction i : block.instructions()) { if (i instanceof TerminatorInst) emitPhiMoves(block, insns); if (i instanceof ArrayLengthInst) emit((ArrayLengthInst)i, insns); else if (i instanceof ArrayLoadInst) emit((ArrayLoadInst)i, insns); else if (i instanceof ArrayStoreInst) emit((ArrayStoreInst)i, insns); else if (i instanceof BinaryInst) emit((BinaryInst)i, insns); else if (i instanceof BranchInst) emit((BranchInst)i, insns); else if (i instanceof CallInst) emit((CallInst)i, insns); else if (i instanceof CastInst) emit((CastInst)i, insns); else if (i instanceof InstanceofInst) emit((InstanceofInst)i, insns); else if (i instanceof JumpInst) emit((JumpInst)i, insns); else if (i instanceof LoadInst) emit((LoadInst)i, insns); else if (i instanceof NewArrayInst) emit((NewArrayInst)i, insns); else if (i instanceof PhiInst) //PhiInst deliberately omitted ; else if (i instanceof ReturnInst) emit((ReturnInst)i, insns); else if (i instanceof StoreInst) emit((StoreInst)i, insns); else if (i instanceof SwitchInst) emit((SwitchInst)i, insns); else if (i instanceof ThrowInst) emit((ThrowInst)i, insns); else throw new AssertionError("can't emit "+i); } return insns; } private void emit(ArrayLengthInst i, InsnList insns) { load(i.getOperand(0), insns); insns.add(new InsnNode(Opcodes.ARRAYLENGTH)); store(i, insns); } private void emit(ArrayLoadInst i, InsnList insns) { load(i.getArray(), insns); load(i.getIndex(), insns); if (i.getType() instanceof ReferenceType) insns.add(new InsnNode(Opcodes.AALOAD)); else if (i.getType().equals(booleanType) || i.getType().equals(byteType)) insns.add(new InsnNode(Opcodes.BALOAD)); else if (i.getType().equals(charType)) insns.add(new InsnNode(Opcodes.CALOAD)); else if (i.getType().equals(shortType)) insns.add(new InsnNode(Opcodes.SALOAD)); else if (i.getType().equals(intType)) insns.add(new InsnNode(Opcodes.IALOAD)); else if (i.getType().equals(longType)) insns.add(new InsnNode(Opcodes.LALOAD)); else if (i.getType().equals(floatType)) insns.add(new InsnNode(Opcodes.FALOAD)); else if (i.getType().equals(doubleType)) insns.add(new InsnNode(Opcodes.DALOAD)); else throw new AssertionError(i); store(i, insns); } private void emit(ArrayStoreInst i, InsnList insns) { load(i.getArray(), insns); load(i.getIndex(), insns); load(i.getData(), insns); //TODO: what if the array is a null constant? RegularType componentType = ((ArrayType)i.getArray().getType()).getComponentType(); if (componentType instanceof ReferenceType) insns.add(new InsnNode(Opcodes.AASTORE)); else if (componentType.equals(booleanType) || componentType.equals(byteType)) insns.add(new InsnNode(Opcodes.BASTORE)); else if (componentType.equals(charType)) insns.add(new InsnNode(Opcodes.CASTORE)); else if (componentType.equals(shortType)) insns.add(new InsnNode(Opcodes.SASTORE)); else if (componentType.equals(intType)) insns.add(new InsnNode(Opcodes.IASTORE)); else if (componentType.equals(longType)) insns.add(new InsnNode(Opcodes.LASTORE)); else if (componentType.equals(floatType)) insns.add(new InsnNode(Opcodes.FASTORE)); else if (componentType.equals(doubleType)) insns.add(new InsnNode(Opcodes.DASTORE)); else throw new AssertionError(i); } private void emit(BinaryInst i, InsnList insns) { load(i.getOperand(0), insns); load(i.getOperand(1), insns); int opcode = 0; if (i.getOperand(0).getType().isSubtypeOf(intType)) { switch (i.getOperation()) { case ADD: opcode = Opcodes.IADD; break; case SUB: opcode = Opcodes.ISUB; break; case MUL: opcode = Opcodes.IMUL; break; case DIV: opcode = Opcodes.IDIV; break; case REM: opcode = Opcodes.IREM; break; case SHL: opcode = Opcodes.ISHL; break; case SHR: opcode = Opcodes.ISHR; break; case USHR: opcode = Opcodes.ISHR; break; case AND: opcode = Opcodes.IAND; break; case OR: opcode = Opcodes.IOR; break; case XOR: opcode = Opcodes.IXOR; break; default: throw new AssertionError(i); } } else if (i.getOperand(0).getType().equals(longType)) { switch (i.getOperation()) { case ADD: opcode = Opcodes.LADD; break; case SUB: opcode = Opcodes.LSUB; break; case MUL: opcode = Opcodes.LMUL; break; case DIV: opcode = Opcodes.LDIV; break; case REM: opcode = Opcodes.LREM; break; case SHL: opcode = Opcodes.LSHL; break; case SHR: opcode = Opcodes.LSHR; break; case USHR: opcode = Opcodes.LSHR; break; case AND: opcode = Opcodes.LAND; break; case OR: opcode = Opcodes.LOR; break; case XOR: opcode = Opcodes.LXOR; break; case CMP: opcode = Opcodes.LCMP; break; default: throw new AssertionError(i); } } else if (i.getOperand(0).getType().equals(floatType)) { switch (i.getOperation()) { case ADD: opcode = Opcodes.FADD; break; case SUB: opcode = Opcodes.FSUB; break; case MUL: opcode = Opcodes.FMUL; break; case DIV: opcode = Opcodes.FDIV; break; case REM: opcode = Opcodes.FREM; break; case CMP: opcode = Opcodes.FCMPL; break; case CMPG: opcode = Opcodes.FCMPG; break; default: throw new AssertionError(i); } } else if (i.getOperand(0).getType().equals(doubleType)) { switch (i.getOperation()) { case ADD: opcode = Opcodes.DADD; break; case SUB: opcode = Opcodes.DSUB; break; case MUL: opcode = Opcodes.DMUL; break; case DIV: opcode = Opcodes.DDIV; break; case REM: opcode = Opcodes.DREM; break; case CMP: opcode = Opcodes.DCMPL; break; case CMPG: opcode = Opcodes.DCMPG; break; default: throw new AssertionError(i); } } else throw new AssertionError(i); insns.add(new InsnNode(opcode)); store(i, insns); } private void emit(BranchInst i, InsnList insns) { //TODO: accessor methods on BranchInst Value left = i.getOperand(0), right = i.getOperand(1); BasicBlock target = (BasicBlock)i.getOperand(2), fallthrough = (BasicBlock)i.getOperand(3); if (!method.basicBlocks().contains(target)) throw new IllegalArgumentException("Branch targets block not in method: "+i); if (!method.basicBlocks().contains(fallthrough)) throw new IllegalArgumentException("Branch falls through to block not in method: "+i); load(i.getOperand(0), insns); load(i.getOperand(1), insns); //TODO: long, float, doubles need to go through CMP inst first int opcode; if (left.getType() instanceof ReferenceType || left.getType() instanceof VoidType) { switch (i.getSense()) { case EQ: opcode = Opcodes.IF_ACMPEQ; break; case NE: opcode = Opcodes.IF_ACMPNE; break; default: throw new AssertionError(i); } } else if (left.getType().isSubtypeOf(intType)) { switch (i.getSense()) { case EQ: opcode = Opcodes.IF_ICMPEQ; break; case NE: opcode = Opcodes.IF_ICMPNE; break; case LT: opcode = Opcodes.IF_ICMPLT; break; case GT: opcode = Opcodes.IF_ICMPGT; break; case LE: opcode = Opcodes.IF_ICMPLE; break; case GE: opcode = Opcodes.IF_ICMPGE; break; default: throw new AssertionError(i); } } else throw new AssertionError(i); insns.add(new JumpInsnNode(opcode, labels.get(target))); insns.add(new JumpInsnNode(Opcodes.GOTO, labels.get(fallthrough))); } private void emit(CallInst i, InsnList insns) { Method m = i.getMethod(); if (m.isConstructor()) { //If we're calling super(), load uninitializedThis. //TODO: this will get confused if we call a superclass constructor //for any reason other than our own initialization! if (method.isConstructor() && method.getParent().getSuperclass().equals(m.getParent())) load(uninitializedThis, insns); else insns.add(new TypeInsnNode(Opcodes.NEW, internalName(m.getType().getReturnType().getKlass()))); insns.add(new InsnNode(Opcodes.DUP)); } int opcode; if (m.modifiers().contains(Modifier.STATIC)) opcode = Opcodes.INVOKESTATIC; else if (m.isConstructor() || m.getAccess().equals(Access.PRIVATE) || Iterables.contains(method.getParent().superclasses(), m.getParent())) opcode = Opcodes.INVOKESPECIAL; else if (m.getParent().modifiers().contains(Modifier.INTERFACE)) //TODO: may not be correct? opcode = Opcodes.INVOKEINTERFACE; else opcode = Opcodes.INVOKEVIRTUAL; String owner = internalName(m.getParent()); //hack to make cloning arrays work if (opcode == Opcodes.INVOKESPECIAL && m.getName().equals("clone") && i.getArgument(0).getType() instanceof ArrayType) { opcode = Opcodes.INVOKEVIRTUAL; owner = internalName(((ArrayType)i.getArgument(0).getType()).getKlass()); } for (Value v : i.arguments()) load(v, insns); insns.add(new MethodInsnNode(opcode, owner, m.getName(), i.callDescriptor())); if (!(i.getType() instanceof VoidType)) store(i, insns); } private void emit(CastInst i, InsnList insns) { load(i.getOperand(0), insns); if (i.getType() instanceof ReferenceType) { insns.add(new TypeInsnNode(Opcodes.CHECKCAST, internalName(((ReferenceType)i.getType()).getKlass()))); } else { PrimitiveType from = (PrimitiveType)i.getOperand(0).getType(); PrimitiveType to = (PrimitiveType)i.getType(); for (int op : from.getCastOpcode(to)) insns.add(new InsnNode(op)); } store(i, insns); } private void emit(InstanceofInst i, InsnList insns) { load(i.getOperand(0), insns); insns.add(new TypeInsnNode(Opcodes.INSTANCEOF, internalName(i.getTestType().getKlass()))); store(i, insns); } private void emit(JumpInst i, InsnList insns) { BasicBlock target = (BasicBlock)i.getOperand(0); if (!method.basicBlocks().contains(target)) throw new IllegalArgumentException("Jump to block not in method: "+i); insns.add(new JumpInsnNode(Opcodes.GOTO, labels.get(target))); } private void emit(LoadInst i, InsnList insns) { Value location = i.getLocation(); if (location instanceof LocalVariable) { load(location, insns); store(i, insns); } else { Field f = (Field)location; if (!f.isStatic()) load(i.getInstance(), insns); insns.add(new FieldInsnNode( f.isStatic() ? Opcodes.GETSTATIC : Opcodes.GETFIELD, internalName(f.getParent()), f.getName(), f.getType().getFieldType().getDescriptor())); store(i, insns); } } private void emit(NewArrayInst i, InsnList insns) { ArrayType t = i.getType(); if (t.getDimensions() == 1) { load(i.getOperand(0), insns); RegularType ct = t.getComponentType(); if (ct instanceof PrimitiveType) { if (ct.equals(booleanType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_BOOLEAN)); else if (ct.equals(byteType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_BYTE)); else if (ct.equals(charType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_CHAR)); else if (ct.equals(shortType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_SHORT)); else if (ct.equals(intType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_INT)); else if (ct.equals(longType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_LONG)); else if (ct.equals(floatType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_FLOAT)); else if (ct.equals(doubleType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_DOUBLE)); } else { insns.add(new TypeInsnNode(Opcodes.ANEWARRAY, internalName(ct.getKlass()))); } } else { for (Value v : i.operands()) load(v, insns); insns.add(new MultiANewArrayInsnNode(t.getDescriptor(), i.getNumOperands())); } store(i, insns); } private void emit(ReturnInst i, InsnList insns) { ReturnType rt = i.getReturnType(); if (rt instanceof VoidType) insns.add(new InsnNode(Opcodes.RETURN)); else { load(i.getOperand(0), insns); if (rt instanceof ReferenceType) insns.add(new InsnNode(Opcodes.ARETURN)); else if (rt.isSubtypeOf(intType)) insns.add(new InsnNode(Opcodes.IRETURN)); else if (rt.equals(longType)) insns.add(new InsnNode(Opcodes.LRETURN)); else if (rt.equals(floatType)) insns.add(new InsnNode(Opcodes.FRETURN)); else if (rt.equals(doubleType)) insns.add(new InsnNode(Opcodes.DRETURN)); else throw new AssertionError(i); } } private void emit(StoreInst i, InsnList insns) { Value location = i.getLocation(); if (location instanceof LocalVariable) { load(i.getData(), insns); store(location, insns); } else { Field f = (Field)location; if (!f.isStatic()) load(i.getInstance(), insns); load(i.getData(), insns); insns.add(new FieldInsnNode( f.isStatic() ? Opcodes.PUTSTATIC : Opcodes.PUTFIELD, internalName(f.getParent()), f.getName(), f.getType().getFieldType().getDescriptor())); } } private void emit(SwitchInst i, InsnList insns) { load(i.getValue(), insns); LookupSwitchInsnNode insn = new LookupSwitchInsnNode(null, null, null); insn.dflt = labels.get(i.getDefault()); Iterator<Constant<Integer>> cases = i.cases().iterator(); Iterator<BasicBlock> targets = i.successors().iterator(); while (cases.hasNext()) { insn.keys.add(cases.next().getConstant()); insn.labels.add(labels.get(targets.next())); } insns.add(insn); } private void emit(ThrowInst i, InsnList insns) { load(i.getOperand(0), insns); insns.add(new InsnNode(Opcodes.ATHROW)); } private void emitPhiMoves(BasicBlock block, InsnList insns) { //In case phi instructions refer to one another, load all values onto //the operand stack, then store all at once. Deque<Value> pendingStores = new ArrayDeque<>(); for (BasicBlock b : block.successors()) for (Instruction i : b.instructions()) if (i instanceof PhiInst) { PhiInst p = (PhiInst)i; Value ourDef = p.get(block); if (ourDef != null) { load(ourDef, insns); pendingStores.push(p); } } while (!pendingStores.isEmpty()) store(pendingStores.pop(), insns); } private void load(Value v, InsnList insns) { if (v instanceof Constant) { Object c = ((Constant<?>)v).getConstant(); if (c == null) insns.add(new InsnNode(Opcodes.ACONST_NULL)); else if (c instanceof Class) insns.add(new LdcInsnNode(org.objectweb.asm.Type.getType((Class)c))); else if (c instanceof Boolean) insns.add(loadIntegerConstant(((Boolean)c) ? 1 : 0)); else if (c instanceof Character) insns.add(loadIntegerConstant((int)((Character)c).charValue())); else if (c instanceof Byte || c instanceof Short || c instanceof Integer) insns.add(loadIntegerConstant(((Number)c).intValue())); else if (c instanceof Long) insns.add(loadLongConstant((Long)c)); else if (c instanceof Float) insns.add(loadFloatConstant((Float)c)); else if (c instanceof Double) insns.add(loadDoubleConstant((Double)c)); else insns.add(new LdcInsnNode(c)); return; } assert registers.containsKey(v) : v; int reg = registers.get(v); Type t = v instanceof LocalVariable ? ((LocalVariable)v).getType().getFieldType() : v.getType(); if (t instanceof ReferenceType || t instanceof NullType) insns.add(new VarInsnNode(Opcodes.ALOAD, reg)); else if (t.equals(longType)) insns.add(new VarInsnNode(Opcodes.LLOAD, reg)); else if (t.equals(floatType)) insns.add(new VarInsnNode(Opcodes.FLOAD, reg)); else if (t.equals(doubleType)) insns.add(new VarInsnNode(Opcodes.DLOAD, reg)); else if (t.isSubtypeOf(intType)) insns.add(new VarInsnNode(Opcodes.ILOAD, reg)); else throw new AssertionError("unloadable value: "+v); } private AbstractInsnNode loadIntegerConstant(int c) { if (c == -1) return new InsnNode(Opcodes.ICONST_M1); if (c == 0) return new InsnNode(Opcodes.ICONST_0); if (c == 1) return new InsnNode(Opcodes.ICONST_1); if (c == 2) return new InsnNode(Opcodes.ICONST_2); if (c == 3) return new InsnNode(Opcodes.ICONST_3); if (c == 4) return new InsnNode(Opcodes.ICONST_4); if (c == 5) return new InsnNode(Opcodes.ICONST_5); if (Byte.MIN_VALUE <= c && c <= Byte.MAX_VALUE) return new IntInsnNode(Opcodes.BIPUSH, c); if (Short.MIN_VALUE <= c && c <= Short.MAX_VALUE) return new IntInsnNode(Opcodes.SIPUSH, c); return new LdcInsnNode(c); } private AbstractInsnNode loadLongConstant(long c) { if (c == 0) return new InsnNode(Opcodes.LCONST_0); if (c == 1) return new InsnNode(Opcodes.LCONST_1); return new LdcInsnNode(c); } private AbstractInsnNode loadFloatConstant(float c) { if (c == 0.0f) return new InsnNode(Opcodes.FCONST_0); if (c == 1.0f) return new InsnNode(Opcodes.FCONST_1); if (c == 2.0f) return new InsnNode(Opcodes.FCONST_2); return new LdcInsnNode(c); } private AbstractInsnNode loadDoubleConstant(double c) { if (c == 0.0) return new InsnNode(Opcodes.DCONST_0); if (c == 1.0) return new InsnNode(Opcodes.DCONST_1); return new LdcInsnNode(c); } private void store(Value v, InsnList insns) { assert registers.containsKey(v) : v; int reg = registers.get(v); Type t = v instanceof LocalVariable ? ((LocalVariable)v).getType().getFieldType() : v.getType(); if (t instanceof ReferenceType || t instanceof NullType) insns.add(new VarInsnNode(Opcodes.ASTORE, reg)); else if (t.equals(longType)) insns.add(new VarInsnNode(Opcodes.LSTORE, reg)); else if (t.equals(floatType)) insns.add(new VarInsnNode(Opcodes.FSTORE, reg)); else if (t.equals(doubleType)) insns.add(new VarInsnNode(Opcodes.DSTORE, reg)); else if (t.isSubtypeOf(intType)) insns.add(new VarInsnNode(Opcodes.ISTORE, reg)); else throw new AssertionError("unstorable value: "+v); } private UninitializedValue findUninitializedThis() { for (BasicBlock b : method.basicBlocks()) for (Instruction i : b.instructions()) for (Value v : i.operands()) if (v instanceof UninitializedValue && v.getName().equals("uninitializedThis")) return (UninitializedValue)v; //We didn't use it for anything, so we didn't save it, but we need one. ReturnType type = method.getParent().getParent().types().getType(method.getParent()); return new UninitializedValue(type, "uninitializedThis"); } private static String methodDescriptor(Method m) { //TODO: maybe put this on Method? I vaguely recall using it somewhere else... MethodType type = m.getType(); if (m.isConstructor()) type = type.withReturnType(type.getTypeFactory().getVoidType()); if (m.hasReceiver()) type = type.dropFirstArgument(); return type.getDescriptor(); } private String internalName(Klass k) { return k.getName().replace('.', '/'); } /** * Performs peephole optimizations at the bytecode level, primarily to * reduce bytecode size for better inlining. (HotSpot makes inlining * decisions based partially on the number of bytes in a method.) */ private void peepholeOptimizations() { boolean progress; do { progress = false; progress |= removeLoadStore(); progress |= removeUnnecessaryGotos(); } while (progress); } private static final ImmutableList<Integer> LOADS = ImmutableList.of( Opcodes.ALOAD, Opcodes.DLOAD, Opcodes.FLOAD, Opcodes.ILOAD, Opcodes.LLOAD ); private static final ImmutableList<Integer> STORES = ImmutableList.of( Opcodes.ASTORE, Opcodes.DSTORE, Opcodes.FSTORE, Opcodes.ISTORE, Opcodes.LSTORE ); /** * Removes "xLOAD N xSTORE N". * @return true iff changes were made */ private boolean removeLoadStore() { InsnList insns = methodNode.instructions; for (int i = 0; i < insns.size()-1; ++i) { AbstractInsnNode first = insns.get(i); int index = LOADS.indexOf(first.getOpcode()); if (index == -1) continue; AbstractInsnNode second = insns.get(i+1); if (second.getOpcode() != STORES.get(index)) continue; if (((VarInsnNode)first).var != ((VarInsnNode)second).var) continue; insns.remove(first); insns.remove(second); return true; } return false; } /** * Removes goto instructions that go to the label immediately following * them. * @return true iff changes were made */ private boolean removeUnnecessaryGotos() { InsnList insns = methodNode.instructions; for (int i = 0; i < insns.size()-1; ++i) { AbstractInsnNode first = insns.get(i); if (first.getOpcode() != Opcodes.GOTO) continue; AbstractInsnNode second = insns.get(i+1); if (!(second instanceof LabelNode)) continue; if (((JumpInsnNode)first).label != second) continue; insns.remove(first); return true; } return false; } public static void main(String[] args) { Module m = new Module(); Klass k = m.getKlass(Module.class); Method ar = k.getMethods("getArrayKlass").iterator().next(); ar.resolve(); MethodNode mn = unresolve(ar); for (int i = 0; i < mn.instructions.size(); ++i) { AbstractInsnNode insn = mn.instructions.get(i); System.out.format("%d: %d %s%n", i, insn.getOpcode(), insn); } } }
MethodUnresolver.java
package edu.mit.streamjit.util.bytecode; import static com.google.common.base.Preconditions.*; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import edu.mit.streamjit.util.bytecode.insts.ArrayLengthInst; import edu.mit.streamjit.util.bytecode.insts.ArrayLoadInst; import edu.mit.streamjit.util.bytecode.insts.ArrayStoreInst; import edu.mit.streamjit.util.bytecode.insts.BinaryInst; import edu.mit.streamjit.util.bytecode.insts.BranchInst; import edu.mit.streamjit.util.bytecode.insts.CallInst; import edu.mit.streamjit.util.bytecode.insts.CastInst; import edu.mit.streamjit.util.bytecode.insts.InstanceofInst; import edu.mit.streamjit.util.bytecode.insts.Instruction; import edu.mit.streamjit.util.bytecode.insts.JumpInst; import edu.mit.streamjit.util.bytecode.insts.LoadInst; import edu.mit.streamjit.util.bytecode.insts.NewArrayInst; import edu.mit.streamjit.util.bytecode.insts.PhiInst; import edu.mit.streamjit.util.bytecode.insts.ReturnInst; import edu.mit.streamjit.util.bytecode.insts.StoreInst; import edu.mit.streamjit.util.bytecode.insts.SwitchInst; import edu.mit.streamjit.util.bytecode.insts.TerminatorInst; import edu.mit.streamjit.util.bytecode.insts.ThrowInst; import edu.mit.streamjit.util.bytecode.types.ArrayType; import edu.mit.streamjit.util.bytecode.types.MethodType; import edu.mit.streamjit.util.bytecode.types.NullType; import edu.mit.streamjit.util.bytecode.types.PrimitiveType; import edu.mit.streamjit.util.bytecode.types.ReferenceType; import edu.mit.streamjit.util.bytecode.types.RegularType; import edu.mit.streamjit.util.bytecode.types.ReturnType; import edu.mit.streamjit.util.bytecode.types.Type; import edu.mit.streamjit.util.bytecode.types.TypeFactory; import edu.mit.streamjit.util.bytecode.types.VoidType; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.LookupSwitchInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.MultiANewArrayInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; /** * Builds bytecode from methods. * @author Jeffrey Bosboom <[email protected]> * @since 4/17/2013 */ public final class MethodUnresolver { public static MethodNode unresolve(Method m) { checkNotNull(m); //Unresolving immutable methods (live Class methods) is only useful //during testing. //checkArgument(m.isMutable(), "unresolving immutable method %s", m); if (!m.modifiers().contains(Modifier.ABSTRACT)) checkArgument(m.isResolved(), "unresolving unresolved method %s", m); return new MethodUnresolver(m).unresolve(); } private final Method method; private final MethodNode methodNode; private final Value uninitializedThis; private final Map<Value, Integer> registers; private final Map<BasicBlock, LabelNode> labels; private final PrimitiveType booleanType, byteType, charType, shortType, intType, longType, floatType, doubleType; private MethodUnresolver(Method m) { this.method = m; this.methodNode = new MethodNode(Opcodes.ASM4); this.uninitializedThis = method.isConstructor() ? findUninitializedThis() : null; this.registers = new IdentityHashMap<>(); this.labels = new IdentityHashMap<>(); TypeFactory tf = m.getParent().getParent().types(); this.booleanType = tf.getPrimitiveType(boolean.class); this.byteType = tf.getPrimitiveType(byte.class); this.charType = tf.getPrimitiveType(char.class); this.shortType = tf.getPrimitiveType(short.class); this.intType = tf.getPrimitiveType(int.class); this.longType = tf.getPrimitiveType(long.class); this.floatType = tf.getPrimitiveType(float.class); this.doubleType = tf.getPrimitiveType(double.class); } public MethodNode unresolve() { this.methodNode.access = Modifier.toBits(method.modifiers()); this.methodNode.name = method.getName(); this.methodNode.desc = methodDescriptor(method); this.methodNode.exceptions = Collections.emptyList(); if (!method.modifiers().contains(Modifier.ABSTRACT)) { allocateRegisters(); createLabels(); for (BasicBlock b : method.basicBlocks()) methodNode.instructions.add(emit(b)); peepholeOptimizations(); int maxRegister = registers.values().isEmpty() ? 0 : Collections.max(registers.values()); this.methodNode.maxLocals = maxRegister+2; //We'd like to use ClassWriter's COMPUTE_MAXS option to compute this //for us, but we also want to use CheckClassAdapter before //ClassWriter to get useful errors. But CheckClassAdapter will //raise an error if we get this too low and run out of memory if we //just say Short.MAX_VALUE. I think any bytecode can push at most //+2 net, so conservatively try 2*instructions.size(). Note that //this counts labels and other pseudo-instructions, as well as //instructions that have obviously no stack increase or a decrease. this.methodNode.maxStack = Math.min(2*methodNode.instructions.size(), Short.MAX_VALUE); buildLocalVariableTable(); } return methodNode; } private void allocateRegisters() { //We allocate one or two registers (depending on type category) to each //instruction producing a non-void value, the method arguments, and the //local variables. int regNum = 0; if (method.isConstructor()) { registers.put(uninitializedThis, regNum); regNum += uninitializedThis.getType().getCategory(); } for (Argument a : method.arguments()) { registers.put(a, regNum); regNum += a.getType().getCategory(); } if (method.isMutable()) for (LocalVariable v : method.localVariables()) { registers.put(v, regNum); regNum += v.getType().getFieldType().getCategory(); } for (BasicBlock b : method.basicBlocks()) for (Instruction i : b.instructions()) if (!(i.getType() instanceof VoidType)) { registers.put(i, regNum); regNum += i.getType().getCategory(); } } private void createLabels() { for (BasicBlock b : method.basicBlocks()) labels.put(b, new LabelNode(new Label())); } private void buildLocalVariableTable() { LabelNode first = new LabelNode(), last = new LabelNode(); methodNode.instructions.insert(first); methodNode.instructions.add(last); methodNode.localVariables = new ArrayList<>(registers.size()); for (Map.Entry<Value, Integer> r : registers.entrySet()) { RegularType type = r.getKey() instanceof LocalVariable ? ((LocalVariable)r.getKey()).getType().getFieldType() : (RegularType)r.getKey().getType(); methodNode.localVariables.add(new LocalVariableNode( r.getKey().getName(), type.getDescriptor(), null, first, last, r.getValue())); } } private InsnList emit(BasicBlock block) { FluentIterable<TerminatorInst> terminators = FluentIterable.from(block.instructions()).filter(TerminatorInst.class); if (terminators.isEmpty()) throw new IllegalArgumentException("block "+block.getName()+" in method "+block.getParent().getName()+" lacks a terminator"); if (terminators.size() > 1) throw new IllegalArgumentException("block "+block.getName()+" in method "+block.getParent().getName()+" has multiple terminators: "+terminators); InsnList insns = new InsnList(); insns.add(labels.get(block)); for (Instruction i : block.instructions()) { if (i instanceof TerminatorInst) emitPhiMoves(block, insns); if (i instanceof ArrayLengthInst) emit((ArrayLengthInst)i, insns); else if (i instanceof ArrayLoadInst) emit((ArrayLoadInst)i, insns); else if (i instanceof ArrayStoreInst) emit((ArrayStoreInst)i, insns); else if (i instanceof BinaryInst) emit((BinaryInst)i, insns); else if (i instanceof BranchInst) emit((BranchInst)i, insns); else if (i instanceof CallInst) emit((CallInst)i, insns); else if (i instanceof CastInst) emit((CastInst)i, insns); else if (i instanceof InstanceofInst) emit((InstanceofInst)i, insns); else if (i instanceof JumpInst) emit((JumpInst)i, insns); else if (i instanceof LoadInst) emit((LoadInst)i, insns); else if (i instanceof NewArrayInst) emit((NewArrayInst)i, insns); else if (i instanceof PhiInst) //PhiInst deliberately omitted ; else if (i instanceof ReturnInst) emit((ReturnInst)i, insns); else if (i instanceof StoreInst) emit((StoreInst)i, insns); else if (i instanceof SwitchInst) emit((SwitchInst)i, insns); else if (i instanceof ThrowInst) emit((ThrowInst)i, insns); else throw new AssertionError("can't emit "+i); } return insns; } private void emit(ArrayLengthInst i, InsnList insns) { load(i.getOperand(0), insns); insns.add(new InsnNode(Opcodes.ARRAYLENGTH)); store(i, insns); } private void emit(ArrayLoadInst i, InsnList insns) { load(i.getArray(), insns); load(i.getIndex(), insns); if (i.getType() instanceof ReferenceType) insns.add(new InsnNode(Opcodes.AALOAD)); else if (i.getType().equals(booleanType) || i.getType().equals(byteType)) insns.add(new InsnNode(Opcodes.BALOAD)); else if (i.getType().equals(charType)) insns.add(new InsnNode(Opcodes.CALOAD)); else if (i.getType().equals(shortType)) insns.add(new InsnNode(Opcodes.SALOAD)); else if (i.getType().equals(intType)) insns.add(new InsnNode(Opcodes.IALOAD)); else if (i.getType().equals(longType)) insns.add(new InsnNode(Opcodes.LALOAD)); else if (i.getType().equals(floatType)) insns.add(new InsnNode(Opcodes.FALOAD)); else if (i.getType().equals(doubleType)) insns.add(new InsnNode(Opcodes.DALOAD)); else throw new AssertionError(i); store(i, insns); } private void emit(ArrayStoreInst i, InsnList insns) { load(i.getArray(), insns); load(i.getIndex(), insns); load(i.getData(), insns); //TODO: what if the array is a null constant? RegularType componentType = ((ArrayType)i.getArray().getType()).getComponentType(); if (componentType instanceof ReferenceType) insns.add(new InsnNode(Opcodes.AASTORE)); else if (componentType.equals(booleanType) || componentType.equals(byteType)) insns.add(new InsnNode(Opcodes.BASTORE)); else if (componentType.equals(charType)) insns.add(new InsnNode(Opcodes.CASTORE)); else if (componentType.equals(shortType)) insns.add(new InsnNode(Opcodes.SASTORE)); else if (componentType.equals(intType)) insns.add(new InsnNode(Opcodes.IASTORE)); else if (componentType.equals(longType)) insns.add(new InsnNode(Opcodes.LASTORE)); else if (componentType.equals(floatType)) insns.add(new InsnNode(Opcodes.FASTORE)); else if (componentType.equals(doubleType)) insns.add(new InsnNode(Opcodes.DASTORE)); else throw new AssertionError(i); } private void emit(BinaryInst i, InsnList insns) { load(i.getOperand(0), insns); load(i.getOperand(1), insns); int opcode = 0; if (i.getOperand(0).getType().isSubtypeOf(intType)) { switch (i.getOperation()) { case ADD: opcode = Opcodes.IADD; break; case SUB: opcode = Opcodes.ISUB; break; case MUL: opcode = Opcodes.IMUL; break; case DIV: opcode = Opcodes.IDIV; break; case REM: opcode = Opcodes.IREM; break; case SHL: opcode = Opcodes.ISHL; break; case SHR: opcode = Opcodes.ISHR; break; case USHR: opcode = Opcodes.ISHR; break; case AND: opcode = Opcodes.IAND; break; case OR: opcode = Opcodes.IOR; break; case XOR: opcode = Opcodes.IXOR; break; default: throw new AssertionError(i); } } else if (i.getOperand(0).getType().equals(longType)) { switch (i.getOperation()) { case ADD: opcode = Opcodes.LADD; break; case SUB: opcode = Opcodes.LSUB; break; case MUL: opcode = Opcodes.LMUL; break; case DIV: opcode = Opcodes.LDIV; break; case REM: opcode = Opcodes.LREM; break; case SHL: opcode = Opcodes.LSHL; break; case SHR: opcode = Opcodes.LSHR; break; case USHR: opcode = Opcodes.LSHR; break; case AND: opcode = Opcodes.LAND; break; case OR: opcode = Opcodes.LOR; break; case XOR: opcode = Opcodes.LXOR; break; case CMP: opcode = Opcodes.LCMP; break; default: throw new AssertionError(i); } } else if (i.getOperand(0).getType().equals(floatType)) { switch (i.getOperation()) { case ADD: opcode = Opcodes.FADD; break; case SUB: opcode = Opcodes.FSUB; break; case MUL: opcode = Opcodes.FMUL; break; case DIV: opcode = Opcodes.FDIV; break; case REM: opcode = Opcodes.FREM; break; case CMP: opcode = Opcodes.FCMPL; break; case CMPG: opcode = Opcodes.FCMPG; break; default: throw new AssertionError(i); } } else if (i.getOperand(0).getType().equals(doubleType)) { switch (i.getOperation()) { case ADD: opcode = Opcodes.DADD; break; case SUB: opcode = Opcodes.DSUB; break; case MUL: opcode = Opcodes.DMUL; break; case DIV: opcode = Opcodes.DDIV; break; case REM: opcode = Opcodes.DREM; break; case CMP: opcode = Opcodes.DCMPL; break; case CMPG: opcode = Opcodes.DCMPG; break; default: throw new AssertionError(i); } } else throw new AssertionError(i); insns.add(new InsnNode(opcode)); store(i, insns); } private void emit(BranchInst i, InsnList insns) { //TODO: accessor methods on BranchInst Value left = i.getOperand(0), right = i.getOperand(1); BasicBlock target = (BasicBlock)i.getOperand(2), fallthrough = (BasicBlock)i.getOperand(3); if (!method.basicBlocks().contains(target)) throw new IllegalArgumentException("Branch targets block not in method: "+i); if (!method.basicBlocks().contains(fallthrough)) throw new IllegalArgumentException("Branch falls through to block not in method: "+i); load(i.getOperand(0), insns); load(i.getOperand(1), insns); //TODO: long, float, doubles need to go through CMP inst first int opcode; if (left.getType() instanceof ReferenceType || left.getType() instanceof VoidType) { switch (i.getSense()) { case EQ: opcode = Opcodes.IF_ACMPEQ; break; case NE: opcode = Opcodes.IF_ACMPNE; break; default: throw new AssertionError(i); } } else if (left.getType().isSubtypeOf(intType)) { switch (i.getSense()) { case EQ: opcode = Opcodes.IF_ICMPEQ; break; case NE: opcode = Opcodes.IF_ICMPNE; break; case LT: opcode = Opcodes.IF_ICMPLT; break; case GT: opcode = Opcodes.IF_ICMPGT; break; case LE: opcode = Opcodes.IF_ICMPLE; break; case GE: opcode = Opcodes.IF_ICMPGE; break; default: throw new AssertionError(i); } } else throw new AssertionError(i); insns.add(new JumpInsnNode(opcode, labels.get(target))); insns.add(new JumpInsnNode(Opcodes.GOTO, labels.get(fallthrough))); } private void emit(CallInst i, InsnList insns) { Method m = i.getMethod(); if (m.isConstructor()) { //If we're calling super(), load uninitializedThis. //TODO: this will get confused if we call a superclass constructor //for any reason other than our own initialization! if (method.isConstructor() && method.getParent().getSuperclass().equals(m.getParent())) load(uninitializedThis, insns); else insns.add(new TypeInsnNode(Opcodes.NEW, internalName(m.getType().getReturnType().getKlass()))); insns.add(new InsnNode(Opcodes.DUP)); } int opcode; if (m.modifiers().contains(Modifier.STATIC)) opcode = Opcodes.INVOKESTATIC; else if (m.isConstructor() || m.getAccess().equals(Access.PRIVATE) || Iterables.contains(method.getParent().superclasses(), m.getParent())) opcode = Opcodes.INVOKESPECIAL; else if (m.getParent().modifiers().contains(Modifier.INTERFACE)) //TODO: may not be correct? opcode = Opcodes.INVOKEINTERFACE; else opcode = Opcodes.INVOKEVIRTUAL; String owner = internalName(m.getParent()); //hack to make cloning arrays work if (opcode == Opcodes.INVOKESPECIAL && m.getName().equals("clone") && i.getArgument(0).getType() instanceof ArrayType) { opcode = Opcodes.INVOKEVIRTUAL; owner = internalName(((ArrayType)i.getArgument(0).getType()).getKlass()); } for (Value v : i.arguments()) load(v, insns); insns.add(new MethodInsnNode(opcode, owner, m.getName(), i.callDescriptor())); if (!(i.getType() instanceof VoidType)) store(i, insns); } private void emit(CastInst i, InsnList insns) { load(i.getOperand(0), insns); if (i.getType() instanceof ReferenceType) { insns.add(new TypeInsnNode(Opcodes.CHECKCAST, internalName(((ReferenceType)i.getType()).getKlass()))); } else { PrimitiveType from = (PrimitiveType)i.getOperand(0).getType(); PrimitiveType to = (PrimitiveType)i.getType(); for (int op : from.getCastOpcode(to)) insns.add(new InsnNode(op)); } store(i, insns); } private void emit(InstanceofInst i, InsnList insns) { load(i.getOperand(0), insns); insns.add(new TypeInsnNode(Opcodes.INSTANCEOF, internalName(i.getTestType().getKlass()))); store(i, insns); } private void emit(JumpInst i, InsnList insns) { BasicBlock target = (BasicBlock)i.getOperand(0); if (!method.basicBlocks().contains(target)) throw new IllegalArgumentException("Jump to block not in method: "+i); insns.add(new JumpInsnNode(Opcodes.GOTO, labels.get(target))); } private void emit(LoadInst i, InsnList insns) { Value location = i.getLocation(); if (location instanceof LocalVariable) { load(location, insns); store(i, insns); } else { Field f = (Field)location; if (!f.isStatic()) load(i.getInstance(), insns); insns.add(new FieldInsnNode( f.isStatic() ? Opcodes.GETSTATIC : Opcodes.GETFIELD, internalName(f.getParent()), f.getName(), f.getType().getFieldType().getDescriptor())); store(i, insns); } } private void emit(NewArrayInst i, InsnList insns) { ArrayType t = i.getType(); if (t.getDimensions() == 1) { load(i.getOperand(0), insns); RegularType ct = t.getComponentType(); if (ct instanceof PrimitiveType) { if (ct.equals(booleanType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_BOOLEAN)); else if (ct.equals(byteType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_BYTE)); else if (ct.equals(charType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_CHAR)); else if (ct.equals(shortType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_SHORT)); else if (ct.equals(intType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_INT)); else if (ct.equals(longType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_LONG)); else if (ct.equals(floatType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_FLOAT)); else if (ct.equals(doubleType)) insns.add(new IntInsnNode(Opcodes.NEWARRAY, Opcodes.T_DOUBLE)); } else { insns.add(new TypeInsnNode(Opcodes.ANEWARRAY, internalName(ct.getKlass()))); } } else { for (Value v : i.operands()) load(v, insns); insns.add(new MultiANewArrayInsnNode(t.getDescriptor(), i.getNumOperands())); } store(i, insns); } private void emit(ReturnInst i, InsnList insns) { ReturnType rt = i.getReturnType(); if (rt instanceof VoidType) insns.add(new InsnNode(Opcodes.RETURN)); else { load(i.getOperand(0), insns); if (rt instanceof ReferenceType) insns.add(new InsnNode(Opcodes.ARETURN)); else if (rt.isSubtypeOf(intType)) insns.add(new InsnNode(Opcodes.IRETURN)); else if (rt.equals(longType)) insns.add(new InsnNode(Opcodes.LRETURN)); else if (rt.equals(floatType)) insns.add(new InsnNode(Opcodes.FRETURN)); else if (rt.equals(doubleType)) insns.add(new InsnNode(Opcodes.DRETURN)); else throw new AssertionError(i); } } private void emit(StoreInst i, InsnList insns) { Value location = i.getLocation(); if (location instanceof LocalVariable) { load(i.getData(), insns); store(location, insns); } else { Field f = (Field)location; if (!f.isStatic()) load(i.getInstance(), insns); load(i.getData(), insns); insns.add(new FieldInsnNode( f.isStatic() ? Opcodes.PUTSTATIC : Opcodes.PUTFIELD, internalName(f.getParent()), f.getName(), f.getType().getFieldType().getDescriptor())); } } private void emit(SwitchInst i, InsnList insns) { load(i.getValue(), insns); LookupSwitchInsnNode insn = new LookupSwitchInsnNode(null, null, null); insn.dflt = labels.get(i.getDefault()); Iterator<Constant<Integer>> cases = i.cases().iterator(); Iterator<BasicBlock> targets = i.successors().iterator(); while (cases.hasNext()) { insn.keys.add(cases.next().getConstant()); insn.labels.add(labels.get(targets.next())); } insns.add(insn); } private void emit(ThrowInst i, InsnList insns) { load(i.getOperand(0), insns); insns.add(new InsnNode(Opcodes.ATHROW)); } private void emitPhiMoves(BasicBlock block, InsnList insns) { //In case phi instructions refer to one another, load all values onto //the operand stack, then store all at once. Deque<Value> pendingStores = new ArrayDeque<>(); for (BasicBlock b : block.successors()) for (Instruction i : b.instructions()) if (i instanceof PhiInst) { PhiInst p = (PhiInst)i; Value ourDef = p.get(block); if (ourDef != null) { load(ourDef, insns); pendingStores.push(p); } } while (!pendingStores.isEmpty()) store(pendingStores.pop(), insns); } private void load(Value v, InsnList insns) { if (v instanceof Constant) { Object c = ((Constant<?>)v).getConstant(); if (c == null) insns.add(new InsnNode(Opcodes.ACONST_NULL)); else if (c instanceof Boolean) if ((Boolean)c) insns.add(new LdcInsnNode(1)); else insns.add(new LdcInsnNode(0)); else if (c instanceof Character) insns.add(new LdcInsnNode((int)((Character)c).charValue())); else if (c instanceof Byte || c instanceof Short) insns.add(new LdcInsnNode(((Number)c).intValue())); else if (c instanceof Class) insns.add(new LdcInsnNode(org.objectweb.asm.Type.getType((Class)c))); else insns.add(new LdcInsnNode(c)); return; } assert registers.containsKey(v) : v; int reg = registers.get(v); Type t = v instanceof LocalVariable ? ((LocalVariable)v).getType().getFieldType() : v.getType(); if (t instanceof ReferenceType || t instanceof NullType) insns.add(new VarInsnNode(Opcodes.ALOAD, reg)); else if (t.equals(longType)) insns.add(new VarInsnNode(Opcodes.LLOAD, reg)); else if (t.equals(floatType)) insns.add(new VarInsnNode(Opcodes.FLOAD, reg)); else if (t.equals(doubleType)) insns.add(new VarInsnNode(Opcodes.DLOAD, reg)); else if (t.isSubtypeOf(intType)) insns.add(new VarInsnNode(Opcodes.ILOAD, reg)); else throw new AssertionError("unloadable value: "+v); } private void store(Value v, InsnList insns) { assert registers.containsKey(v) : v; int reg = registers.get(v); Type t = v instanceof LocalVariable ? ((LocalVariable)v).getType().getFieldType() : v.getType(); if (t instanceof ReferenceType || t instanceof NullType) insns.add(new VarInsnNode(Opcodes.ASTORE, reg)); else if (t.equals(longType)) insns.add(new VarInsnNode(Opcodes.LSTORE, reg)); else if (t.equals(floatType)) insns.add(new VarInsnNode(Opcodes.FSTORE, reg)); else if (t.equals(doubleType)) insns.add(new VarInsnNode(Opcodes.DSTORE, reg)); else if (t.isSubtypeOf(intType)) insns.add(new VarInsnNode(Opcodes.ISTORE, reg)); else throw new AssertionError("unstorable value: "+v); } private UninitializedValue findUninitializedThis() { for (BasicBlock b : method.basicBlocks()) for (Instruction i : b.instructions()) for (Value v : i.operands()) if (v instanceof UninitializedValue && v.getName().equals("uninitializedThis")) return (UninitializedValue)v; //We didn't use it for anything, so we didn't save it, but we need one. ReturnType type = method.getParent().getParent().types().getType(method.getParent()); return new UninitializedValue(type, "uninitializedThis"); } private static String methodDescriptor(Method m) { //TODO: maybe put this on Method? I vaguely recall using it somewhere else... MethodType type = m.getType(); if (m.isConstructor()) type = type.withReturnType(type.getTypeFactory().getVoidType()); if (m.hasReceiver()) type = type.dropFirstArgument(); return type.getDescriptor(); } private String internalName(Klass k) { return k.getName().replace('.', '/'); } /** * Performs peephole optimizations at the bytecode level, primarily to * reduce bytecode size for better inlining. (HotSpot makes inlining * decisions based partially on the number of bytes in a method.) */ private void peepholeOptimizations() { boolean progress; do { progress = false; progress |= removeLoadStore(); progress |= removeUnnecessaryGotos(); } while (progress); } private static final ImmutableList<Integer> LOADS = ImmutableList.of( Opcodes.ALOAD, Opcodes.DLOAD, Opcodes.FLOAD, Opcodes.ILOAD, Opcodes.LLOAD ); private static final ImmutableList<Integer> STORES = ImmutableList.of( Opcodes.ASTORE, Opcodes.DSTORE, Opcodes.FSTORE, Opcodes.ISTORE, Opcodes.LSTORE ); /** * Removes "xLOAD N xSTORE N". * @return true iff changes were made */ private boolean removeLoadStore() { InsnList insns = methodNode.instructions; for (int i = 0; i < insns.size()-1; ++i) { AbstractInsnNode first = insns.get(i); int index = LOADS.indexOf(first.getOpcode()); if (index == -1) continue; AbstractInsnNode second = insns.get(i+1); if (second.getOpcode() != STORES.get(index)) continue; if (((VarInsnNode)first).var != ((VarInsnNode)second).var) continue; insns.remove(first); insns.remove(second); return true; } return false; } /** * Removes goto instructions that go to the label immediately following * them. * @return true iff changes were made */ private boolean removeUnnecessaryGotos() { InsnList insns = methodNode.instructions; for (int i = 0; i < insns.size()-1; ++i) { AbstractInsnNode first = insns.get(i); if (first.getOpcode() != Opcodes.GOTO) continue; AbstractInsnNode second = insns.get(i+1); if (!(second instanceof LabelNode)) continue; if (((JumpInsnNode)first).label != second) continue; insns.remove(first); return true; } return false; } public static void main(String[] args) { Module m = new Module(); Klass k = m.getKlass(Module.class); Method ar = k.getMethods("getArrayKlass").iterator().next(); ar.resolve(); MethodNode mn = unresolve(ar); for (int i = 0; i < mn.instructions.size(); ++i) { AbstractInsnNode insn = mn.instructions.get(i); System.out.format("%d: %d %s%n", i, insn.getOpcode(), insn); } } }
MethodUnresolver: use the immediate constant opcodes
MethodUnresolver.java
MethodUnresolver: use the immediate constant opcodes
<ide><path>ethodUnresolver.java <ide> Object c = ((Constant<?>)v).getConstant(); <ide> if (c == null) <ide> insns.add(new InsnNode(Opcodes.ACONST_NULL)); <del> else if (c instanceof Boolean) <del> if ((Boolean)c) <del> insns.add(new LdcInsnNode(1)); <del> else <del> insns.add(new LdcInsnNode(0)); <del> else if (c instanceof Character) <del> insns.add(new LdcInsnNode((int)((Character)c).charValue())); <del> else if (c instanceof Byte || c instanceof Short) <del> insns.add(new LdcInsnNode(((Number)c).intValue())); <ide> else if (c instanceof Class) <ide> insns.add(new LdcInsnNode(org.objectweb.asm.Type.getType((Class)c))); <add> else if (c instanceof Boolean) <add> insns.add(loadIntegerConstant(((Boolean)c) ? 1 : 0)); <add> else if (c instanceof Character) <add> insns.add(loadIntegerConstant((int)((Character)c).charValue())); <add> else if (c instanceof Byte || c instanceof Short || c instanceof Integer) <add> insns.add(loadIntegerConstant(((Number)c).intValue())); <add> else if (c instanceof Long) <add> insns.add(loadLongConstant((Long)c)); <add> else if (c instanceof Float) <add> insns.add(loadFloatConstant((Float)c)); <add> else if (c instanceof Double) <add> insns.add(loadDoubleConstant((Double)c)); <ide> else <ide> insns.add(new LdcInsnNode(c)); <ide> return; <ide> insns.add(new VarInsnNode(Opcodes.ILOAD, reg)); <ide> else <ide> throw new AssertionError("unloadable value: "+v); <add> } <add> <add> private AbstractInsnNode loadIntegerConstant(int c) { <add> if (c == -1) <add> return new InsnNode(Opcodes.ICONST_M1); <add> if (c == 0) <add> return new InsnNode(Opcodes.ICONST_0); <add> if (c == 1) <add> return new InsnNode(Opcodes.ICONST_1); <add> if (c == 2) <add> return new InsnNode(Opcodes.ICONST_2); <add> if (c == 3) <add> return new InsnNode(Opcodes.ICONST_3); <add> if (c == 4) <add> return new InsnNode(Opcodes.ICONST_4); <add> if (c == 5) <add> return new InsnNode(Opcodes.ICONST_5); <add> if (Byte.MIN_VALUE <= c && c <= Byte.MAX_VALUE) <add> return new IntInsnNode(Opcodes.BIPUSH, c); <add> if (Short.MIN_VALUE <= c && c <= Short.MAX_VALUE) <add> return new IntInsnNode(Opcodes.SIPUSH, c); <add> return new LdcInsnNode(c); <add> } <add> <add> private AbstractInsnNode loadLongConstant(long c) { <add> if (c == 0) <add> return new InsnNode(Opcodes.LCONST_0); <add> if (c == 1) <add> return new InsnNode(Opcodes.LCONST_1); <add> return new LdcInsnNode(c); <add> } <add> <add> private AbstractInsnNode loadFloatConstant(float c) { <add> if (c == 0.0f) <add> return new InsnNode(Opcodes.FCONST_0); <add> if (c == 1.0f) <add> return new InsnNode(Opcodes.FCONST_1); <add> if (c == 2.0f) <add> return new InsnNode(Opcodes.FCONST_2); <add> return new LdcInsnNode(c); <add> } <add> <add> private AbstractInsnNode loadDoubleConstant(double c) { <add> if (c == 0.0) <add> return new InsnNode(Opcodes.DCONST_0); <add> if (c == 1.0) <add> return new InsnNode(Opcodes.DCONST_1); <add> return new LdcInsnNode(c); <ide> } <ide> <ide> private void store(Value v, InsnList insns) {
JavaScript
apache-2.0
f41b6ab002121983118de8a5b8d8256ed4b6a746
0
einhverfr/binary-static,brodiecapel16/binary-static,animeshsaxena/binary-static,borisyankov/binary-static,animeshsaxena/binary-static,borisyankov/binary-static,junbon/binary-static-www2,borisyankov/binary-static,einhverfr/binary-static,einhverfr/binary-static,brodiecapel16/binary-static,einhverfr/binary-static,brodiecapel16/binary-static,animeshsaxena/binary-static,massihx/binary-static,brodiecapel16/binary-static,junbon/binary-static-www2,tfoertsch/binary-static,tfoertsch/binary-static,massihx/binary-static,borisyankov/binary-static,massihx/binary-static,massihx/binary-static,animeshsaxena/binary-static
var TickDisplay = function() { return { reset: function() { var $self = this; $self.contract_barrier = null; $self.applicable_ticks = []; $self.chart.destroy(); }, initialize: function(data) { var $self = this; // setting up globals $self.number_of_ticks = parseInt(data.number_of_ticks); $self.symbol = data.symbol; $self.display_symbol = data.display_symbol; $self.contract_start_ms = parseInt(data.contract_start * 1000); $self.contract_type = data.contract_type; $self.set_barrier = ($self.contract_type.match('DIGIT')) ? false : true; $self.display_decimal = 0; if (typeof data.decimal !== 'undefined') { $self.number_of_decimal = parseInt(data.decimal) + 1; //calculated barrier is rounded to one more decimal place } if (data.show_contract_result) { $self.show_contract_result = true; $self.contract_sentiment = data.contract_sentiment; $self.price = parseFloat(data.price); $self.payout = parseFloat(data.payout); } var minimize = data.show_contract_result; $self.set_x_indicators(); $self.initialize_chart({ plot_from: data.previous_tick_epoch * 1000, plot_to: new Date((parseInt(data.contract_start) + parseInt(($self.number_of_ticks+2)*2)) * 1000).getTime(), minimize: minimize, }); }, set_x_indicators: function() { var $self = this; var exit_tick_index = $self.number_of_ticks - 1; if ($self.contract_type.match('ASIAN')) { $self.ticks_needed = $self.number_of_ticks; $self.x_indicators = { '_0': { label: 'Tick 1', id: 'start_tick'}, }; $self.x_indicators['_' + exit_tick_index] = { label: 'Exit Spot', id: 'exit_tick', }; } else if ($self.contract_type.match('FLASH')) { $self.ticks_needed = $self.number_of_ticks + 1; $self.x_indicators = { '_1': { label: 'Tick 1', id: 'start_tick'}, }; $self.x_indicators['_' + $self.number_of_ticks] = { label: 'Exit Spot', id: 'exit_tick', }; } else if ($self.contract_type.match('DIGIT')) { $self.ticks_needed = $self.number_of_ticks; $self.x_indicators = { '_0': { label: 'Tick 1', id: 'start_tick'}, }; $self.x_indicators['_' + exit_tick_index] = { label: 'Tick ' + $self.number_of_ticks, id: 'last_tick', }; } else { $self.x_indicators = {}; } }, initialize_chart: function(config) { var $self = this; $self.chart = new Highcharts.Chart({ chart: { type: 'line', renderTo: 'tick_chart', width: config.minimize ? 394 : null, height: config.minimize ? 125 : null, backgroundColor: null, events: { load: $self.plot(config.plot_from, config.plot_to) }, }, credits: {enabled: false}, tooltip: { formatter: function () { var that = this; var new_decimal = that.y.toString().split('.')[1].length; var decimal_places = Math.max( $self.display_decimal, new_decimal); $self.display_decimal = decimal_places; var new_y = that.y.toFixed(decimal_places); var mom = moment.utc(that.x*1000).format("dddd, MMM D, HH:mm:ss"); return mom + "<br/>" + $self.display_symbol + " " + new_y; }, }, xAxis: { type: 'datetime', min: parseInt(config['plot_from']), max: parseInt(config['plot_to']), labels: { enabled: false, } }, yAxis: { title: '', }, series: [{ data: [], }], title: '', exporting: {enabled: false, enableImages: false}, legend: {enabled: false}, }); }, plot: function(plot_from, plot_to) { var $self = this; var plot_from_moment = moment(plot_from).utc(); var plot_to_moment = moment(plot_to).utc(); var contract_start_moment = moment($self.contract_start_ms).utc(); $self.applicable_ticks = []; var symbol = $self.symbol; var stream_url = window.location.protocol + '//' + page.settings.get('streaming_server'); stream_url += "/stream/ticks/" + symbol + "/" + plot_from_moment.unix() + "/" + plot_to_moment.unix(); $self.ev = new EventSource(stream_url, { withCredentials: true }); $self.ev.onmessage = function(msg) { if ($self.applicable_ticks.length >= $self.ticks_needed) { $self.ev.close(); $self.evaluate_contract_outcome(); return; } var data = JSON.parse(msg.data); if (!(data[0] instanceof Array)) { data = [ data ]; } for (var i = 0; i < data.length; i++) { if (data[i][0] === 'tick') { var tick = { epoch: parseInt(data[i][1]), quote: parseFloat(data[i][2]) }; if ($self.applicable_ticks.length < $self.ticks_needed) { $self.chart.series[0].addPoint([tick.epoch*1000, tick.quote], true, false); } if (tick.epoch > contract_start_moment.unix()) { if ($self.applicable_ticks.length >= $self.ticks_needed) { $self.ev.close(); $self.evaluate_contract_outcome(); return; } else { $self.applicable_ticks.push(tick); var tick_index = $self.applicable_ticks.length - 1; var indicator_key = '_' + tick_index; if (typeof $self.x_indicators[indicator_key] !== 'undefined') { $self.x_indicators[indicator_key]['index'] = tick_index; $self.add($self.x_indicators[indicator_key]); } $self.add_barrier(); } } } } }; $self.ev.onerror = function(e) {$self.ev.close(); }; }, add_barrier: function() { var $self = this; if (!$self.set_barrier) { return; } var barrier_type = $self.contract_type.match('ASIAN') ? 'asian' : 'static'; if (barrier_type === 'static') { var barrier_tick = $self.applicable_ticks[0]; $self.chart.yAxis[0].addPlotLine({ id: 'tick-barrier', value: barrier_tick.quote, label: {text: 'Barrier ('+barrier_tick.quote+')', align: 'center'}, color: 'green', width: 2, }); $self.contract_barrier = barrier_tick.quote; $self.set_barrier = false; } if (barrier_type === 'asian') { var total = 0; for (var i=0; i < $self.applicable_ticks.length; i++) { total += parseFloat($self.applicable_ticks[i].quote); } var calc_barrier = total/$self.applicable_ticks.length; calc_barrier = calc_barrier.toFixed($self.number_of_decimal); // round calculated barrier $self.chart.yAxis[0].removePlotLine('tick-barrier'); $self.chart.yAxis[0].addPlotLine({ id: 'tick-barrier', value: calc_barrier, color: 'green', label: { text: 'Average ('+calc_barrier+')', align: 'center' }, width: 2, }); $self.contract_barrier = calc_barrier; } }, add: function(indicator) { var $self = this; $self.chart.xAxis[0].addPlotLine({ value: $self.applicable_ticks[indicator.index].epoch * 1000, id: indicator.id, label: {text: indicator.label}, color: '#e98024', width: 2, }); }, evaluate_contract_outcome: function() { var $self = this; if (!$self.contract_barrier) { return; // can't do anything without barrier } var exit_tick_index = $self.applicable_ticks.length - 1; var exit_spot = $self.applicable_ticks[exit_tick_index].quote; if ($self.contract_sentiment === 'up') { if (exit_spot > $self.contract_barrier) { $self.win(); } else { $self.lose(); } } else if ($self.contract_sentiment === 'down') { if (exit_spot < $self.contract_barrier) { $self.win(); } else { $self.lose(); } } }, win: function() { var $self = this; var profit = $self.payout - $self.price; $self.update_ui($self.payout, profit, 'This contract won'); }, lose: function() { var $self = this; $self.update_ui(0, -$self.price, 'This contract lost'); }, update_ui: function(final_price, pnl, contract_status) { var $self = this; $('#bet-confirm-header').text(text.localize(contract_status)); $('#contract-outcome-buyprice').text($self.to_monetary_format($self.price)); $('#contract-outcome-payout').text($self.to_monetary_format(final_price)); if (pnl > 0) { $('#contract-outcome-label').text(text.localize('Profit')); $('#contract-outcome-profit').addClass('profit').text($self.to_monetary_format(pnl)); } else { $('#contract-outcome-label').removeClass('standout').text(text.localize('Loss')); $('#contract-outcome-profit').addClass('loss').text($self.to_monetary_format(pnl)); } $('#contract-confirmation-details').hide(); $('#contract-outcome-details').show(); }, to_monetary_format: function(number) { return number.toFixed(2); } }; }();
src/javascript/pages/bet/tick_trade.js
var TickDisplay = function() { return { reset: function() { var $self = this; $self.contract_barrier = null; $self.applicable_ticks = []; $self.chart.destroy(); }, initialize: function(data) { var $self = this; // setting up globals $self.number_of_ticks = parseInt(data.number_of_ticks); $self.symbol = data.symbol; $self.display_symbol = data.display_symbol; $self.contract_start_ms = parseInt(data.contract_start * 1000); $self.contract_type = data.contract_type; $self.set_barrier = ($self.contract_type.match('DIGIT')) ? false : true; $self.display_decimal = 0; if (typeof data.decimal !== 'undefined') { $self.number_of_decimal = parseInt(data.decimal) + 1; //calculated barrier is rounded to one more decimal place } if (data.show_contract_result) { $self.show_contract_result = true; $self.contract_sentiment = data.contract_sentiment; $self.price = parseFloat(data.price); $self.payout = parseFloat(data.payout); } var minimize = data.show_contract_result; $self.set_x_indicators(); $self.initialize_chart({ plot_from: data.previous_tick_epoch * 1000, plot_to: new Date((parseInt(data.contract_start) + parseInt(($self.number_of_ticks+2)*2)) * 1000).getTime(), minimize: minimize, }); }, set_x_indicators: function() { var $self = this; if ($self.contract_type.match('ASIAN')) { $self.ticks_needed = $self.number_of_ticks; var exit_tick_index = $self.number_of_ticks - 1; $self.x_indicators = { '_0': { label: 'Tick 1', id: 'start_tick'}, }; $self.x_indicators['_' + exit_tick_index] = { label: 'Exit Spot', id: 'exit_tick', }; } else if ($self.contract_type.match('FLASH')) { $self.ticks_needed = $self.number_of_ticks + 1; $self.x_indicators = { '_1': { label: 'Tick 1', id: 'start_tick'}, }; $self.x_indicators['_' + $self.number_of_ticks] = { label: 'Exit Spot', id: 'exit_tick', }; } else if ($self.contract_type.match('DIGIT')) { $self.ticks_needed = $self.number_of_ticks; var exit_tick_index = $self.number_of_ticks - 1; $self.x_indicators = { '_0': { label: 'Tick 1', id: 'start_tick'}, }; $self.x_indicators['_' + exit_tick_index] = { label: 'Tick ' + $self.number_of_ticks, id: 'last_tick', }; } else { $self.x_indicators = {}; } }, initialize_chart: function(config) { var $self = this; $self.chart = new Highcharts.Chart({ chart: { type: 'line', renderTo: 'tick_chart', width: config.minimize ? 394 : null, height: config.minimize ? 125 : null, backgroundColor: null, events: { load: $self.plot(config.plot_from, config.plot_to) }, }, credits: {enabled: false}, tooltip: { formatter: function () { var that = this; var new_decimal = that.y.toString().split('.')[1].length; var decimal_places = Math.max( $self.display_decimal, new_decimal); $self.display_decimal = decimal_places; var new_y = that.y.toFixed(decimal_places); var mom = moment.utc(that.x*1000).format("dddd, MMM D, HH:mm:ss"); return mom + "<br/>" + $self.display_symbol + " " + new_y; }, }, xAxis: { type: 'datetime', min: parseInt(config['plot_from']), max: parseInt(config['plot_to']), labels: { enabled: false, } }, yAxis: { title: '', }, series: [{ data: [], }], title: '', exporting: {enabled: false, enableImages: false}, legend: {enabled: false}, }); }, plot: function(plot_from, plot_to) { var $self = this; var plot_from_moment = moment(plot_from).utc(); var plot_to_moment = moment(plot_to).utc(); var contract_start_moment = moment($self.contract_start_ms).utc(); $self.applicable_ticks = []; var symbol = $self.symbol; var stream_url = window.location.protocol + '//' + page.settings.get('streaming_server'); stream_url += "/stream/ticks/" + symbol + "/" + plot_from_moment.unix() + "/" + plot_to_moment.unix(); $self.ev = new EventSource(stream_url, { withCredentials: true }); $self.ev.onmessage = function(msg) { if ($self.applicable_ticks.length >= $self.ticks_needed) { $self.ev.close(); $self.evaluate_contract_outcome(); return; } var data = JSON.parse(msg.data); if (!(data[0] instanceof Array)) { data = [ data ]; } for (var i = 0; i < data.length; i++) { if (data[i][0] === 'tick') { var tick = { epoch: parseInt(data[i][1]), quote: parseFloat(data[i][2]) }; if ($self.applicable_ticks.length < $self.ticks_needed) { $self.chart.series[0].addPoint([tick.epoch*1000, tick.quote], true, false); } if (tick.epoch > contract_start_moment.unix()) { if ($self.applicable_ticks.length >= $self.ticks_needed) { $self.ev.close(); $self.evaluate_contract_outcome(); return; } else { $self.applicable_ticks.push(tick); var tick_index = $self.applicable_ticks.length - 1; var indicator_key = '_' + tick_index; if (typeof $self.x_indicators[indicator_key] !== 'undefined') { $self.x_indicators[indicator_key]['index'] = tick_index; $self.add($self.x_indicators[indicator_key]); } $self.add_barrier(); } } } } }; $self.ev.onerror = function(e) {$self.ev.close(); }; }, add_barrier: function() { var $self = this; if (!$self.set_barrier) { return; } var barrier_type = $self.contract_type.match('ASIAN') ? 'asian' : 'static'; if (barrier_type === 'static') { var barrier_tick = $self.applicable_ticks[0]; $self.chart.yAxis[0].addPlotLine({ id: 'tick-barrier', value: barrier_tick.quote, label: {text: 'Barrier ('+barrier_tick.quote+')', align: 'center'}, color: 'green', width: 2, }); $self.contract_barrier = barrier_tick.quote; $self.set_barrier = false; } if (barrier_type === 'asian') { var total = 0; for (var i=0; i < $self.applicable_ticks.length; i++) { total += parseFloat($self.applicable_ticks[i].quote); } var calc_barrier = total/$self.applicable_ticks.length; calc_barrier = calc_barrier.toFixed($self.number_of_decimal); // round calculated barrier $self.chart.yAxis[0].removePlotLine('tick-barrier'); $self.chart.yAxis[0].addPlotLine({ id: 'tick-barrier', value: calc_barrier, color: 'green', label: { text: 'Average ('+calc_barrier+')', align: 'center' }, width: 2, }); $self.contract_barrier = calc_barrier; } }, add: function(indicator) { var $self = this; $self.chart.xAxis[0].addPlotLine({ value: $self.applicable_ticks[indicator.index].epoch * 1000, id: indicator.id, label: {text: indicator.label}, color: '#e98024', width: 2, }); }, evaluate_contract_outcome: function() { var $self = this; if (!$self.contract_barrier) { return; // can't do anything without barrier } var exit_tick_index = $self.applicable_ticks.length - 1; var exit_spot = $self.applicable_ticks[exit_tick_index].quote; if ($self.contract_sentiment === 'up') { if (exit_spot > $self.contract_barrier) { $self.win(); } else { $self.lose(); } } else if ($self.contract_sentiment === 'down') { if (exit_spot < $self.contract_barrier) { $self.win(); } else { $self.lose(); } } }, win: function() { var $self = this; var profit = $self.payout - $self.price; $self.update_ui($self.payout, profit, 'This contract won'); }, lose: function() { var $self = this; $self.update_ui(0, -$self.price, 'This contract lost'); }, update_ui: function(final_price, pnl, contract_status) { var $self = this; $('#bet-confirm-header').text(text.localize(contract_status)); $('#contract-outcome-buyprice').text($self.to_monetary_format($self.price)); $('#contract-outcome-payout').text($self.to_monetary_format(final_price)); if (pnl > 0) { $('#contract-outcome-label').text(text.localize('Profit')); $('#contract-outcome-profit').addClass('profit').text($self.to_monetary_format(pnl)); } else { $('#contract-outcome-label').removeClass('standout').text(text.localize('Loss')); $('#contract-outcome-profit').addClass('loss').text($self.to_monetary_format(pnl)); } $('#contract-confirmation-details').hide(); $('#contract-outcome-details').show(); }, to_monetary_format: function(number) { return number.toFixed(2); } }; }();
exit_tick_index redefined?
src/javascript/pages/bet/tick_trade.js
exit_tick_index redefined?
<ide><path>rc/javascript/pages/bet/tick_trade.js <ide> set_x_indicators: function() { <ide> var $self = this; <ide> <add> var exit_tick_index = $self.number_of_ticks - 1; <ide> if ($self.contract_type.match('ASIAN')) { <ide> $self.ticks_needed = $self.number_of_ticks; <del> var exit_tick_index = $self.number_of_ticks - 1; <ide> $self.x_indicators = { <ide> '_0': { label: 'Tick 1', id: 'start_tick'}, <ide> }; <ide> }; <ide> } else if ($self.contract_type.match('DIGIT')) { <ide> $self.ticks_needed = $self.number_of_ticks; <del> var exit_tick_index = $self.number_of_ticks - 1; <ide> $self.x_indicators = { <ide> '_0': { label: 'Tick 1', id: 'start_tick'}, <ide> };
Java
apache-2.0
3545df15f7ea5973911a2b413964e3e6c8c5c607
0
aika-algorithm/aika,aika-algorithm/aika
/* * 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.aika.lattice; import org.aika.*; import org.aika.corpus.Document; import org.aika.corpus.Document.DiscoveryConfig; import org.aika.corpus.InterprNode; import org.aika.corpus.Range; import org.aika.corpus.Range.Operator; import org.aika.corpus.Range.Mapping; import org.aika.lattice.AndNode.Refinement; import org.aika.neuron.Activation; import org.aika.neuron.INeuron; import org.aika.neuron.Synapse; import org.aika.neuron.Synapse.Key; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.*; import java.util.stream.Stream; import static org.aika.corpus.Range.Operator.*; /** * The {@code InputNode} class is the input layer for the boolean logic. The input-node has two sources of * activations. First, it might be underlying logic node of an {@code InputNeuron} in which case the input * activations come from the outside. The second option is that the activation come from the output of another neuron. * * @author Lukas Molzberger */ public class InputNode extends Node<InputNode, NodeActivation<InputNode>> { public Key key; public Neuron inputNeuron; // Key: Output Neuron public Map<SynapseKey, Synapse> synapses; public ReadWriteLock synapseLock = new ReadWriteLock(); private long visitedDiscover; public InputNode() { } public InputNode(Model m, Key key) { super(m, 1); this.key = Synapse.lookupKey(key); } public static InputNode add(Model m, Key key, INeuron input) { Provider<InputNode> pin = (input != null ? input.outputNodes.get(key) : null); if (pin != null) { return pin.get(); } InputNode in = new InputNode(m, key); if (input != null && in.inputNeuron == null) { in.inputNeuron = input.provider; input.outputNodes.put(key, in.provider); input.setModified(); } return in; } @Override protected NodeActivation<InputNode> createActivation(Document doc, NodeActivation.Key ak) { return new NodeActivation<>(doc.activationIdCounter++, doc, ak); } private NodeActivation.Key computeActivationKey(NodeActivation iAct) { NodeActivation.Key ak = iAct.key; if ((key.absoluteRid != null && key.absoluteRid != ak.rid) || ak.interpretation.isConflicting(ak.interpretation.doc.visitedCounter++)) return null; return new NodeActivation.Key( this, key.rangeOutput.map(ak.range), key.relativeRid != null ? ak.rid : null, ak.interpretation ); } public void addActivation(Document doc, NodeActivation inputAct) { NodeActivation.Key ak = computeActivationKey(inputAct); if (ak != null) { addActivationAndPropagate(doc, ak, Collections.singleton(inputAct)); } } public void propagateAddedActivation(Document doc, NodeActivation act) { if (!key.isRecurrent) { apply(doc, act); } } @Override public boolean isAllowedOption(int threadId, InterprNode n, NodeActivation act, long v) { return false; } @Override Collection<Refinement> collectNodeAndRefinements(Refinement newRef) { List<Refinement> result = new ArrayList<>(2); result.add(new Refinement(key.relativeRid, newRef.rid, provider)); result.add(newRef); return result; } /** * @param doc * @param act */ @Override void apply(Document doc, NodeActivation act) { lock.acquireReadLock(); if (andChildren != null) { andChildren.forEach((ref, cn) -> { InputNode in = ref.input.getIfNotSuspended(); if (in != null) { addNextLevelActivations(doc, in, ref, cn, act); } }); } lock.releaseReadLock(); OrNode.processCandidate(doc, this, act, false); } private static void addNextLevelActivations(Document doc, InputNode secondNode, Refinement ref, Provider<AndNode> pnlp, NodeActivation act) { INeuron.ThreadState th = secondNode.inputNeuron.get().getThreadState(doc.threadId, false); if (th == null || th.activations.isEmpty()) return; Activation iAct = (Activation) act.inputs.firstEntry().getValue(); AndNode nlp = pnlp.get(doc); if(nlp.combinatorialExpensive) return; Activation.Key ak = act.key; Activation.Key iak = iAct.key; InputNode firstNode = ((InputNode) ak.node); Integer secondRid = Utils.nullSafeAdd(ak.rid, false, ref.rid, false); Stream<Activation> s = Activation.select( th, secondNode.inputNeuron.get(), secondRid, iak.range, Range.Relation.createQuery(firstNode.key.rangeMatch, secondNode.key.rangeOutput, firstNode.key.rangeOutput, secondNode.key.rangeMatch), null, null ); s.filter(secondAct -> !secondAct.outputs.isEmpty()) .forEach(secondAct -> { InterprNode o = InterprNode.add(doc, true, ak.interpretation, secondAct.key.interpretation); if (o != null) { Node.addActivationAndPropagate(doc, new NodeActivation.Key( nlp, Range.mergeRange( firstNode.key.rangeOutput.map(iak.range), secondNode.key.rangeOutput.map(secondAct.key.range) ), Utils.nullSafeMin(ak.rid, secondAct.key.rid), o ), AndNode.prepareInputActs(act, secondNode.getInputNodeActivation(secondAct)) ); } } ); } private NodeActivation getInputNodeActivation(Activation act) { for(NodeActivation inAct: act.outputs.values()) { if(inAct.key.node == this) return inAct; } return null; } @Override public void discover(Document doc, NodeActivation<InputNode> act, DiscoveryConfig discoveryConfig) { long v = provider.model.visitedCounter.addAndGet(1); for (INeuron n : doc.finallyActivatedNeurons) { for (Activation secondNAct : n.getFinalActivations(doc)) { for (NodeActivation secondAct : secondNAct.outputs.values()) { Refinement ref = new Refinement(secondAct.key.rid, act.key.rid, (Provider<InputNode>) secondAct.key.node.provider); InputNode in = ref.input.get(doc); Range.Relation rm = Range.Relation.createQuery(key.rangeMatch, in.key.rangeOutput, key.rangeOutput, in.key.rangeMatch); if (act != secondAct && this != in && in.visitedDiscover != v && !in.key.isRecurrent && rm.compare(secondAct.key.range, act.key.range) ) { in.visitedDiscover = v; AndNode nln = AndNode.createNextLevelNode(doc.model, doc.threadId, this, ref, discoveryConfig); if(nln != null) { nln.isDiscovered = true; doc.addedNodes.add(nln); } } } } } } @Override boolean contains(Refinement ref) { return this == ref.input.get() && Utils.compareInteger(key.relativeRid, ref.rid) == 0; } @Override public double computeSynapseWeightSum(Integer offset, INeuron n) { return n.biasSum + Math.abs(getSynapse(key.relativeRid == null ? null : offset, n.provider).weight); } public Synapse getSynapse(Integer rid, Neuron outputNeuron) { synapseLock.acquireReadLock(); Synapse s = synapses != null ? synapses.get(new SynapseKey(rid, outputNeuron)) : null; synapseLock.releaseReadLock(); return s; } public void setSynapse(Synapse s) { synapseLock.acquireWriteLock(); if (synapses == null) { synapses = new TreeMap<>(); } synapses.put(new SynapseKey(s.key.relativeRid, s.output), s); synapseLock.releaseWriteLock(); } public void removeSynapse(Synapse s) { if(synapses != null) { synapseLock.acquireWriteLock(); synapses.remove(new SynapseKey(s.key.relativeRid, s.output)); synapseLock.releaseWriteLock(); } } @Override public void cleanup() { } @Override public void remove() { inputNeuron.get().outputNodes.remove(key); super.remove(); } public String logicToString() { StringBuilder sb = new StringBuilder(); sb.append("I"); sb.append(key.isRecurrent ? "R" : ""); sb.append(getRangeBrackets(key.rangeOutput.begin)); if (inputNeuron != null) { sb.append(inputNeuron.id); if (inputNeuron.get().label != null) { sb.append(","); sb.append(inputNeuron.get().label); } } sb.append(getRangeBrackets(key.rangeOutput.end)); return sb.toString(); } private String getRangeBrackets(Mapping rs) { if (rs == Mapping.NONE) return "|"; return rs == Mapping.BEGIN ? "[" : "]"; } @Override public void write(DataOutput out) throws IOException { out.writeBoolean(false); out.writeChar('I'); super.write(out); key.write(out); out.writeBoolean(inputNeuron != null); if (inputNeuron != null) { out.writeInt(inputNeuron.id); } } @Override public void readFields(DataInput in, Model m) throws IOException { super.readFields(in, m); key = Synapse.lookupKey(Key.read(in, m)); if (in.readBoolean()) { inputNeuron = m.lookupNeuron(in.readInt()); } } private static class SynapseKey implements Writable, Comparable<SynapseKey> { Integer rid; Neuron neuron; private SynapseKey() { } public SynapseKey(Integer rid, Neuron neuron) { this.rid = rid; this.neuron = neuron; } @Override public int compareTo(SynapseKey sk) { int r = Utils.compareInteger(rid, sk.rid); if (r != 0) return r; return neuron.compareTo(sk.neuron); } public static SynapseKey read(DataInput in, Model m) throws IOException { SynapseKey sk = new SynapseKey(); sk.readFields(in, m); return sk; } @Override public void write(DataOutput out) throws IOException { out.writeBoolean(rid != null); if (rid != null) { out.writeInt(rid); } out.writeInt(neuron.id); } @Override public void readFields(DataInput in, Model m) throws IOException { if (in.readBoolean()) { rid = in.readInt(); } neuron = m.lookupNeuron(in.readInt()); } } }
src/main/java/org/aika/lattice/InputNode.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.aika.lattice; import org.aika.*; import org.aika.corpus.Document; import org.aika.corpus.Document.DiscoveryConfig; import org.aika.corpus.InterprNode; import org.aika.corpus.Range; import org.aika.corpus.Range.Operator; import org.aika.corpus.Range.Mapping; import org.aika.lattice.AndNode.Refinement; import org.aika.neuron.Activation; import org.aika.neuron.INeuron; import org.aika.neuron.Synapse; import org.aika.neuron.Synapse.Key; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.*; import java.util.stream.Stream; import static org.aika.corpus.Range.Operator.*; /** * The {@code InputNode} class is the input layer for the boolean logic. The input-node has two sources of * activations. First, it might be underlying logic node of an {@code InputNeuron} in which case the input * activations come from the outside. The second option is that the activation come from the output of another neuron. * * @author Lukas Molzberger */ public class InputNode extends Node<InputNode, NodeActivation<InputNode>> { public Key key; public Neuron inputNeuron; // Key: Output Neuron public Map<SynapseKey, Synapse> synapses; public ReadWriteLock synapseLock = new ReadWriteLock(); private long visitedDiscover; public InputNode() { } public InputNode(Model m, Key key) { super(m, 1); this.key = Synapse.lookupKey(key); } public static InputNode add(Model m, Key key, INeuron input) { Provider<InputNode> pin = (input != null ? input.outputNodes.get(key) : null); if (pin != null) { return pin.get(); } InputNode in = new InputNode(m, key); if (input != null && in.inputNeuron == null) { in.inputNeuron = input.provider; input.outputNodes.put(key, in.provider); input.setModified(); } return in; } @Override protected NodeActivation<InputNode> createActivation(Document doc, NodeActivation.Key ak) { return new NodeActivation<>(doc.activationIdCounter++, doc, ak); } private NodeActivation.Key computeActivationKey(NodeActivation iAct) { NodeActivation.Key ak = iAct.key; if ((key.absoluteRid != null && key.absoluteRid != ak.rid) || ak.interpretation.isConflicting(ak.interpretation.doc.visitedCounter++)) return null; return new NodeActivation.Key( this, key.rangeOutput.map(ak.range), key.relativeRid != null ? ak.rid : null, ak.interpretation ); } public void addActivation(Document doc, NodeActivation inputAct) { NodeActivation.Key ak = computeActivationKey(inputAct); if (ak != null) { addActivationAndPropagate(doc, ak, Collections.singleton(inputAct)); } } public void propagateAddedActivation(Document doc, NodeActivation act) { if (!key.isRecurrent) { apply(doc, act); } } @Override public boolean isAllowedOption(int threadId, InterprNode n, NodeActivation act, long v) { return false; } @Override Collection<Refinement> collectNodeAndRefinements(Refinement newRef) { List<Refinement> result = new ArrayList<>(2); result.add(new Refinement(key.relativeRid, newRef.rid, provider)); result.add(newRef); return result; } /** * @param doc * @param act */ @Override void apply(Document doc, NodeActivation act) { lock.acquireReadLock(); if (andChildren != null) { andChildren.forEach((ref, cn) -> { InputNode in = ref.input.getIfNotSuspended(); if (in != null) { addNextLevelActivations(doc, in, ref, cn, act); } }); } lock.releaseReadLock(); OrNode.processCandidate(doc, this, act, false); } private static void addNextLevelActivations(Document doc, InputNode secondNode, Refinement ref, Provider<AndNode> pnlp, NodeActivation act) { INeuron.ThreadState th = secondNode.inputNeuron.get().getThreadState(doc.threadId, false); if (th == null || th.activations.isEmpty()) return; Activation iAct = (Activation) act.inputs.firstEntry().getValue(); AndNode nlp = pnlp.get(doc); if(nlp.combinatorialExpensive) return; Activation.Key ak = act.key; Activation.Key iak = iAct.key; InputNode firstNode = ((InputNode) ak.node); Integer secondRid = Utils.nullSafeAdd(ak.rid, false, ref.rid, false); Stream<Activation> s = Activation.select( th, secondNode.inputNeuron.get(), secondRid, iak.range, Range.Relation.createQuery(firstNode.key.rangeMatch, secondNode.key.rangeOutput, firstNode.key.rangeOutput, secondNode.key.rangeMatch), null, null ); s.forEach(secondAct -> { InterprNode o = InterprNode.add(doc, true, ak.interpretation, secondAct.key.interpretation); if (o != null) { Node.addActivationAndPropagate(doc, new NodeActivation.Key( nlp, Range.mergeRange( firstNode.key.rangeOutput.map(iak.range), secondNode.key.rangeOutput.map(secondAct.key.range) ), Utils.nullSafeMin(ak.rid, secondAct.key.rid), o ), AndNode.prepareInputActs(act, secondNode.getInputNodeActivation(secondAct)) ); } } ); } private NodeActivation getInputNodeActivation(Activation act) { for(NodeActivation inAct: act.outputs.values()) { if(inAct.key.node == this) return inAct; } return null; } @Override public void discover(Document doc, NodeActivation<InputNode> act, DiscoveryConfig discoveryConfig) { long v = provider.model.visitedCounter.addAndGet(1); for (INeuron n : doc.finallyActivatedNeurons) { for (Activation secondNAct : n.getFinalActivations(doc)) { for (NodeActivation secondAct : secondNAct.outputs.values()) { Refinement ref = new Refinement(secondAct.key.rid, act.key.rid, (Provider<InputNode>) secondAct.key.node.provider); InputNode in = ref.input.get(doc); Range.Relation rm = Range.Relation.createQuery(key.rangeMatch, in.key.rangeOutput, key.rangeOutput, in.key.rangeMatch); if (act != secondAct && this != in && in.visitedDiscover != v && !in.key.isRecurrent && rm.compare(secondAct.key.range, act.key.range) ) { in.visitedDiscover = v; AndNode nln = AndNode.createNextLevelNode(doc.model, doc.threadId, this, ref, discoveryConfig); if(nln != null) { nln.isDiscovered = true; doc.addedNodes.add(nln); } } } } } } @Override boolean contains(Refinement ref) { return this == ref.input.get() && Utils.compareInteger(key.relativeRid, ref.rid) == 0; } @Override public double computeSynapseWeightSum(Integer offset, INeuron n) { return n.biasSum + Math.abs(getSynapse(key.relativeRid == null ? null : offset, n.provider).weight); } public Synapse getSynapse(Integer rid, Neuron outputNeuron) { synapseLock.acquireReadLock(); Synapse s = synapses != null ? synapses.get(new SynapseKey(rid, outputNeuron)) : null; synapseLock.releaseReadLock(); return s; } public void setSynapse(Synapse s) { synapseLock.acquireWriteLock(); if (synapses == null) { synapses = new TreeMap<>(); } synapses.put(new SynapseKey(s.key.relativeRid, s.output), s); synapseLock.releaseWriteLock(); } public void removeSynapse(Synapse s) { if(synapses != null) { synapseLock.acquireWriteLock(); synapses.remove(new SynapseKey(s.key.relativeRid, s.output)); synapseLock.releaseWriteLock(); } } @Override public void cleanup() { } @Override public void remove() { inputNeuron.get().outputNodes.remove(key); super.remove(); } public String logicToString() { StringBuilder sb = new StringBuilder(); sb.append("I"); sb.append(key.isRecurrent ? "R" : ""); sb.append(getRangeBrackets(key.rangeOutput.begin)); if (inputNeuron != null) { sb.append(inputNeuron.id); if (inputNeuron.get().label != null) { sb.append(","); sb.append(inputNeuron.get().label); } } sb.append(getRangeBrackets(key.rangeOutput.end)); return sb.toString(); } private String getRangeBrackets(Mapping rs) { if (rs == Mapping.NONE) return "|"; return rs == Mapping.BEGIN ? "[" : "]"; } @Override public void write(DataOutput out) throws IOException { out.writeBoolean(false); out.writeChar('I'); super.write(out); key.write(out); out.writeBoolean(inputNeuron != null); if (inputNeuron != null) { out.writeInt(inputNeuron.id); } } @Override public void readFields(DataInput in, Model m) throws IOException { super.readFields(in, m); key = Synapse.lookupKey(Key.read(in, m)); if (in.readBoolean()) { inputNeuron = m.lookupNeuron(in.readInt()); } } private static class SynapseKey implements Writable, Comparable<SynapseKey> { Integer rid; Neuron neuron; private SynapseKey() { } public SynapseKey(Integer rid, Neuron neuron) { this.rid = rid; this.neuron = neuron; } @Override public int compareTo(SynapseKey sk) { int r = Utils.compareInteger(rid, sk.rid); if (r != 0) return r; return neuron.compareTo(sk.neuron); } public static SynapseKey read(DataInput in, Model m) throws IOException { SynapseKey sk = new SynapseKey(); sk.readFields(in, m); return sk; } @Override public void write(DataOutput out) throws IOException { out.writeBoolean(rid != null); if (rid != null) { out.writeInt(rid); } out.writeInt(neuron.id); } @Override public void readFields(DataInput in, Model m) throws IOException { if (in.readBoolean()) { rid = in.readInt(); } neuron = m.lookupNeuron(in.readInt()); } } }
fixed test case
src/main/java/org/aika/lattice/InputNode.java
fixed test case
<ide><path>rc/main/java/org/aika/lattice/InputNode.java <ide> null <ide> ); <ide> <del> s.forEach(secondAct -> { <add> s.filter(secondAct -> !secondAct.outputs.isEmpty()) <add> .forEach(secondAct -> { <ide> InterprNode o = InterprNode.add(doc, true, ak.interpretation, secondAct.key.interpretation); <ide> if (o != null) { <ide> Node.addActivationAndPropagate(doc,
Java
apache-2.0
a1a6e0afee36152152b2c2e0d47afd823124a13e
0
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
package io.quarkus.rest.runtime.handlers; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import io.netty.handler.codec.http.HttpHeaderNames; import io.quarkus.rest.runtime.core.QuarkusRestRequestContext; import io.quarkus.rest.runtime.mapping.RuntimeResource; import io.quarkus.rest.runtime.util.MediaTypeHelper; import io.quarkus.rest.runtime.util.ServerMediaType; import io.vertx.core.http.HttpServerRequest; /** * Handler that deals with the case when two methods have the same path, * and it needs to select based on content type. * <p> * This is not super optimised, as it is not a common case. Most apps * won't every use this handler. */ public class MediaTypeMapper implements RestHandler { final Map<MediaType, Holder> resourcesByConsumes; final List<MediaType> consumesTypes; public MediaTypeMapper(List<RuntimeResource> runtimeResources) { resourcesByConsumes = new HashMap<>(); consumesTypes = new ArrayList<>(); for (RuntimeResource runtimeResource : runtimeResources) { MediaType consumesMT = runtimeResource.getConsumes().isEmpty() ? MediaType.WILDCARD_TYPE : runtimeResource.getConsumes().get(0); if (!resourcesByConsumes.containsKey(consumesMT)) { consumesTypes.add(consumesMT); resourcesByConsumes.put(consumesMT, new Holder()); } MediaType[] produces = runtimeResource.getProduces() != null ? runtimeResource.getProduces().getSortedOriginalMediaTypes() : null; if (produces == null) { produces = new MediaType[] { MediaType.WILDCARD_TYPE }; } for (MediaType producesMT : produces) { resourcesByConsumes.get(consumesMT).setResource(runtimeResource, producesMT); } } for (Holder holder : resourcesByConsumes.values()) { holder.setupServerMediaType(); } } @Override public void handle(QuarkusRestRequestContext requestContext) throws Exception { String contentType = requestContext.getContext().request().headers().get(HttpHeaders.CONTENT_TYPE); // if there's no Content-Type it's */* MediaType contentMediaType = contentType != null ? MediaType.valueOf(contentType) : MediaType.WILDCARD_TYPE; // find the best matching consumes type. Note that the arguments are reversed from their definition // of desired/provided, but we do want the result to be a media type we consume, since that's how we key // our methods, rather than the single media type we get from the client. This way we ensure we get the // best match. MediaType consumes = MediaTypeHelper.getBestMatch(Collections.singletonList(contentMediaType), consumesTypes); Holder selectedHolder = resourcesByConsumes.get(consumes); // if we haven't found anything, try selecting the wildcard type, if any if (selectedHolder == null) { selectedHolder = resourcesByConsumes.get(MediaType.WILDCARD_TYPE); } if (selectedHolder == null) { throw new WebApplicationException(Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).build()); } RuntimeResource selectedResource; if (selectedHolder.mtWithoutParamsToResource.size() == 1) { selectedResource = selectedHolder.mtWithoutParamsToResource.values().iterator().next(); } else { MediaType produces = selectMediaType(requestContext, selectedHolder); requestContext.setProducesMediaType(produces); MediaType key = produces; if (!key.getParameters().isEmpty()) { key = new MediaType(key.getType(), key.getSubtype()); } selectedResource = selectedHolder.mtWithoutParamsToResource.get(key); if (selectedResource == null) { selectedResource = selectedHolder.mtWithoutParamsToResource.get(MediaType.WILDCARD_TYPE); } } if (selectedResource == null) { throw new WebApplicationException(Response.status(416).build()); } requestContext.restart(selectedResource); } public MediaType selectMediaType(QuarkusRestRequestContext requestContext, Holder holder) { MediaType selected = null; HttpServerRequest httpServerRequest = requestContext.getContext().request(); if (httpServerRequest.headers().contains(HttpHeaderNames.ACCEPT)) { Map.Entry<MediaType, MediaType> entry = holder.serverMediaType .negotiateProduces(requestContext.getContext().request(), null); if (entry.getValue() != null) { selected = entry.getValue(); } } if (selected == null) { selected = holder.mtsWithParams.get(0); } if (selected.equals(MediaType.WILDCARD_TYPE)) { return MediaType.APPLICATION_OCTET_STREAM_TYPE; } return selected; } private static final class Holder { private final Map<MediaType, RuntimeResource> mtWithoutParamsToResource = new HashMap<>(); private final List<MediaType> mtsWithParams = new ArrayList<>(); private ServerMediaType serverMediaType; public void setResource(RuntimeResource runtimeResource, MediaType mediaType) { MediaType withoutParams = mediaType; MediaType withParas = mediaType; if (!mediaType.getParameters().isEmpty()) { withoutParams = new MediaType(mediaType.getType(), mediaType.getSubtype()); } mtWithoutParamsToResource.put(withoutParams, runtimeResource); mtsWithParams.add(withParas); } public void setupServerMediaType() { serverMediaType = new ServerMediaType(mtsWithParams, StandardCharsets.UTF_8.name(), true); } } }
extensions/quarkus-rest/runtime/src/main/java/io/quarkus/rest/runtime/handlers/MediaTypeMapper.java
package io.quarkus.rest.runtime.handlers; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import io.netty.handler.codec.http.HttpHeaderNames; import io.quarkus.rest.runtime.core.QuarkusRestRequestContext; import io.quarkus.rest.runtime.mapping.RuntimeResource; import io.quarkus.rest.runtime.util.MediaTypeHelper; import io.vertx.core.http.HttpServerRequest; /** * Handler that deals with the case when two methods have the same path, * and it needs to select based on content type. * <p> * This is not super optimised, as it is not a common case. Most apps * won't every use this handler. */ public class MediaTypeMapper implements RestHandler { final Map<MediaType, Holder> resourcesByConsumes; final List<MediaType> consumesTypes; public MediaTypeMapper(List<RuntimeResource> runtimeResources) { resourcesByConsumes = new HashMap<>(); consumesTypes = new ArrayList<>(); for (RuntimeResource runtimeResource : runtimeResources) { MediaType consumesMT = runtimeResource.getConsumes().isEmpty() ? MediaType.WILDCARD_TYPE : runtimeResource.getConsumes().get(0); if (!resourcesByConsumes.containsKey(consumesMT)) { consumesTypes.add(consumesMT); resourcesByConsumes.put(consumesMT, new Holder()); } MediaType[] produces = runtimeResource.getProduces() != null ? runtimeResource.getProduces().getSortedOriginalMediaTypes() : null; if (produces == null) { produces = new MediaType[] { MediaType.WILDCARD_TYPE }; } for (MediaType producesMT : produces) { resourcesByConsumes.get(consumesMT).setResource(runtimeResource, producesMT); } } } @Override public void handle(QuarkusRestRequestContext requestContext) throws Exception { String contentType = requestContext.getContext().request().headers().get(HttpHeaders.CONTENT_TYPE); // if there's no Content-Type it's */* MediaType contentMediaType = contentType != null ? MediaType.valueOf(contentType) : MediaType.WILDCARD_TYPE; // find the best matching consumes type. Note that the arguments are reversed from their definition // of desired/provided, but we do want the result to be a media type we consume, since that's how we key // our methods, rather than the single media type we get from the client. This way we ensure we get the // best match. MediaType consumes = MediaTypeHelper.getBestMatch(Collections.singletonList(contentMediaType), consumesTypes); Holder selectedHolder = resourcesByConsumes.get(consumes); // if we haven't found anything, try selecting the wildcard type, if any if (selectedHolder == null) { selectedHolder = resourcesByConsumes.get(MediaType.WILDCARD_TYPE); } if (selectedHolder == null) { throw new WebApplicationException(Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).build()); } RuntimeResource selectedResource; if (selectedHolder.mtWithoutParamsToResource.size() == 1) { selectedResource = selectedHolder.mtWithoutParamsToResource.values().iterator().next(); } else { MediaType produces = selectMediaType(requestContext, selectedHolder); requestContext.setProducesMediaType(produces); MediaType key = produces; if (!key.getParameters().isEmpty()) { key = new MediaType(key.getType(), key.getSubtype()); } selectedResource = selectedHolder.mtWithoutParamsToResource.get(key); if (selectedResource == null) { selectedResource = selectedHolder.mtWithoutParamsToResource.get(MediaType.WILDCARD_TYPE); } } if (selectedResource == null) { throw new WebApplicationException(Response.status(416).build()); } requestContext.restart(selectedResource); } public MediaType selectMediaType(QuarkusRestRequestContext requestContext, Holder holder) { MediaType selected = null; HttpServerRequest httpServerRequest = requestContext.getContext().request(); if (httpServerRequest.headers().contains(HttpHeaderNames.ACCEPT)) { List<MediaType> acceptedMediaTypes = requestContext.getHttpHeaders().getModifiableAcceptableMediaTypes(); if (!acceptedMediaTypes.isEmpty()) { MediaTypeHelper.sortByWeight(acceptedMediaTypes); List<MediaType> methodMediaTypes = holder.mtsWithParams; methodMediaTypes.sort(MethodMediaTypeComparator.INSTANCE); selected = doSelectMediaType(methodMediaTypes, acceptedMediaTypes); } } if (selected == null) { selected = holder.mtsWithParams.get(0); } if (selected.equals(MediaType.WILDCARD_TYPE)) { return MediaType.APPLICATION_OCTET_STREAM_TYPE; } return selected; } // similar to what ServerMediaType#negotiate does but adapted for this use case private MediaType doSelectMediaType(List<MediaType> methodMediaTypes, List<MediaType> acceptedMediaTypes) { MediaType selected = null; String currentClientQ = null; int currentServerIndex = Integer.MAX_VALUE; for (MediaType desired : acceptedMediaTypes) { if (selected != null) { //this is to enable server side q values to take effect //the client side is sorted by q, if we have already picked one and the q is //different then we can return the current one if (!Objects.equals(desired.getParameters().get("q"), currentClientQ)) { if (selected.equals(MediaType.WILDCARD_TYPE)) { return MediaType.APPLICATION_OCTET_STREAM_TYPE; } return selected; } } for (int j = 0; j < methodMediaTypes.size(); j++) { MediaType provided = methodMediaTypes.get(j); if (provided.isCompatible(desired)) { if (selected == null || j < currentServerIndex) { if (provided.isWildcardType()) { selected = MediaType.APPLICATION_OCTET_STREAM_TYPE; } else { selected = provided; } currentServerIndex = j; currentClientQ = desired.getParameters().get("q"); } } } } return selected; } private static final class Holder { private final Map<MediaType, RuntimeResource> mtWithoutParamsToResource = new HashMap<>(); private final List<MediaType> mtsWithParams = new ArrayList<>(); public void setResource(RuntimeResource runtimeResource, MediaType mediaType) { MediaType withoutParams = mediaType; MediaType withParas = mediaType; if (!mediaType.getParameters().isEmpty()) { withoutParams = new MediaType(mediaType.getType(), mediaType.getSubtype()); } mtWithoutParamsToResource.put(withoutParams, runtimeResource); mtsWithParams.add(withParas); } } private static class MethodMediaTypeComparator implements Comparator<MediaType> { private final static MethodMediaTypeComparator INSTANCE = new MethodMediaTypeComparator(); /** * The idea here is to de-prioritize wildcards as the spec mentions that they should be picked with lower priority * Then we utilize the qs property just like ServerMediaType does */ @Override public int compare(MediaType m1, MediaType m2) { if (m1.isWildcardType() && !m2.isWildcardType()) { return 1; } if (!m1.isWildcardType() && m2.isWildcardType()) { return -1; } if (!m1.isWildcardType() && !m2.isWildcardType()) { if (m1.isWildcardSubtype() && !m2.isWildcardSubtype()) { return 1; } if (!m1.isWildcardSubtype() && m2.isWildcardSubtype()) { return -1; } } String qs1s = m1.getParameters().get("qs"); String qs2s = m2.getParameters().get("qs"); if (qs1s == null && qs2s == null) { return 0; } if (qs1s != null) { if (qs2s == null) { return 1; } else { float q1 = Float.parseFloat(qs1s); float q2 = Float.parseFloat(qs2s); return Float.compare(q2, q1); } } else { return -1; } } } }
Get of a lot of ugly MediaTypeMapper code Utilize the recently enhanced ServerMediaType#negotiate which provides the same functionality
extensions/quarkus-rest/runtime/src/main/java/io/quarkus/rest/runtime/handlers/MediaTypeMapper.java
Get of a lot of ugly MediaTypeMapper code
<ide><path>xtensions/quarkus-rest/runtime/src/main/java/io/quarkus/rest/runtime/handlers/MediaTypeMapper.java <ide> package io.quarkus.rest.runtime.handlers; <ide> <add>import java.nio.charset.StandardCharsets; <ide> import java.util.ArrayList; <ide> import java.util.Collections; <del>import java.util.Comparator; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <del>import java.util.Objects; <ide> <ide> import javax.ws.rs.WebApplicationException; <ide> import javax.ws.rs.core.HttpHeaders; <ide> import io.quarkus.rest.runtime.core.QuarkusRestRequestContext; <ide> import io.quarkus.rest.runtime.mapping.RuntimeResource; <ide> import io.quarkus.rest.runtime.util.MediaTypeHelper; <add>import io.quarkus.rest.runtime.util.ServerMediaType; <ide> import io.vertx.core.http.HttpServerRequest; <ide> <ide> /** <ide> resourcesByConsumes.get(consumesMT).setResource(runtimeResource, producesMT); <ide> } <ide> } <del> <add> for (Holder holder : resourcesByConsumes.values()) { <add> holder.setupServerMediaType(); <add> } <ide> } <ide> <ide> @Override <ide> MediaType selected = null; <ide> HttpServerRequest httpServerRequest = requestContext.getContext().request(); <ide> if (httpServerRequest.headers().contains(HttpHeaderNames.ACCEPT)) { <del> List<MediaType> acceptedMediaTypes = requestContext.getHttpHeaders().getModifiableAcceptableMediaTypes(); <del> if (!acceptedMediaTypes.isEmpty()) { <del> MediaTypeHelper.sortByWeight(acceptedMediaTypes); <del> <del> List<MediaType> methodMediaTypes = holder.mtsWithParams; <del> methodMediaTypes.sort(MethodMediaTypeComparator.INSTANCE); <del> <del> selected = doSelectMediaType(methodMediaTypes, acceptedMediaTypes); <add> Map.Entry<MediaType, MediaType> entry = holder.serverMediaType <add> .negotiateProduces(requestContext.getContext().request(), null); <add> if (entry.getValue() != null) { <add> selected = entry.getValue(); <ide> } <ide> } <ide> if (selected == null) { <ide> return selected; <ide> } <ide> <del> // similar to what ServerMediaType#negotiate does but adapted for this use case <del> private MediaType doSelectMediaType(List<MediaType> methodMediaTypes, List<MediaType> acceptedMediaTypes) { <del> MediaType selected = null; <del> String currentClientQ = null; <del> int currentServerIndex = Integer.MAX_VALUE; <del> for (MediaType desired : acceptedMediaTypes) { <del> if (selected != null) { <del> //this is to enable server side q values to take effect <del> //the client side is sorted by q, if we have already picked one and the q is <del> //different then we can return the current one <del> if (!Objects.equals(desired.getParameters().get("q"), currentClientQ)) { <del> if (selected.equals(MediaType.WILDCARD_TYPE)) { <del> return MediaType.APPLICATION_OCTET_STREAM_TYPE; <del> } <del> return selected; <del> } <del> } <del> for (int j = 0; j < methodMediaTypes.size(); j++) { <del> MediaType provided = methodMediaTypes.get(j); <del> if (provided.isCompatible(desired)) { <del> if (selected == null || j < currentServerIndex) { <del> if (provided.isWildcardType()) { <del> selected = MediaType.APPLICATION_OCTET_STREAM_TYPE; <del> } else { <del> selected = provided; <del> } <del> currentServerIndex = j; <del> currentClientQ = desired.getParameters().get("q"); <del> } <del> } <del> } <del> } <del> return selected; <del> } <del> <ide> private static final class Holder { <ide> <ide> private final Map<MediaType, RuntimeResource> mtWithoutParamsToResource = new HashMap<>(); <ide> private final List<MediaType> mtsWithParams = new ArrayList<>(); <add> private ServerMediaType serverMediaType; <ide> <ide> public void setResource(RuntimeResource runtimeResource, MediaType mediaType) { <ide> MediaType withoutParams = mediaType; <ide> mtWithoutParamsToResource.put(withoutParams, runtimeResource); <ide> mtsWithParams.add(withParas); <ide> } <del> } <ide> <del> private static class MethodMediaTypeComparator implements Comparator<MediaType> { <del> <del> private final static MethodMediaTypeComparator INSTANCE = new MethodMediaTypeComparator(); <del> <del> /** <del> * The idea here is to de-prioritize wildcards as the spec mentions that they should be picked with lower priority <del> * Then we utilize the qs property just like ServerMediaType does <del> */ <del> @Override <del> public int compare(MediaType m1, MediaType m2) { <del> if (m1.isWildcardType() && !m2.isWildcardType()) { <del> return 1; <del> } <del> if (!m1.isWildcardType() && m2.isWildcardType()) { <del> return -1; <del> } <del> if (!m1.isWildcardType() && !m2.isWildcardType()) { <del> if (m1.isWildcardSubtype() && !m2.isWildcardSubtype()) { <del> return 1; <del> } <del> if (!m1.isWildcardSubtype() && m2.isWildcardSubtype()) { <del> return -1; <del> } <del> } <del> <del> String qs1s = m1.getParameters().get("qs"); <del> String qs2s = m2.getParameters().get("qs"); <del> if (qs1s == null && qs2s == null) { <del> return 0; <del> } <del> if (qs1s != null) { <del> if (qs2s == null) { <del> return 1; <del> } else { <del> float q1 = Float.parseFloat(qs1s); <del> float q2 = Float.parseFloat(qs2s); <del> return Float.compare(q2, q1); <del> } <del> } else { <del> return -1; <del> } <add> public void setupServerMediaType() { <add> serverMediaType = new ServerMediaType(mtsWithParams, StandardCharsets.UTF_8.name(), true); <ide> } <ide> } <ide> }
Java
apache-2.0
b26b6502296b43e5760d3f9be0012ed9b265f089
0
galan/packtag,galan/packtag,galan/packtag
/** * Project pack:tag >> http://packtag.sf.net * * This software is published under the terms of the LGPL * License version 2.1, a copy of which has been included with this * distribution in the 'lgpl.txt' file. * * Creation date: 13.11.2008 - 23:49:49 * Last author: $Author: danielgalan $ * Last modified: $Date:$ * Revision: $Revision:$ * * $Log:$ */ package net.sf.packtag.cache.provider; import javax.servlet.ServletContext; import net.sf.packtag.cache.CacheProvider; import net.sf.packtag.cache.Resource; /** * Basic CacheProvider functions * * @author Daniel Galán y Martins * @version $Revision:$ */ public abstract class AbstractCacheProvider implements CacheProvider { public void init(final ServletContext context) { } protected synchronized void clearDependingCombinedResources(final Resource resource) { String absolutePath = resource.getAbsolutePath(); Object[] keys = getAbsolutePathKeys().toArray(); for (int i = 0; i < keys.length; i++) { Resource currentResource = getResourceByAbsolutePath((String)keys[i]); // Difference between combined and wildcard resources String paths = currentResource.isWildcard() ? currentResource.getWildcardAbsolutePaths() : currentResource.getAbsolutePath(); int idx = paths.indexOf(absolutePath); // "> 0" because the normal resource doesn't starts with "[" if (idx > 0) { removeAbsolutePath((String)keys[i]); } } } }
packtag-core/src/main/java/net/sf/packtag/cache/provider/AbstractCacheProvider.java
/** * Project pack:tag >> http://packtag.sf.net * * This software is published under the terms of the LGPL * License version 2.1, a copy of which has been included with this * distribution in the 'lgpl.txt' file. * * Creation date: 13.11.2008 - 23:49:49 * Last author: $Author: danielgalan $ * Last modified: $Date:$ * Revision: $Revision:$ * * $Log:$ */ package net.sf.packtag.cache.provider; import javax.servlet.ServletContext; import net.sf.packtag.cache.CacheProvider; import net.sf.packtag.cache.Resource; /** * Basic CacheProvider functions * * @author Daniel Galán y Martins * @version $Revision:$ */ public abstract class AbstractCacheProvider implements CacheProvider { public void init(final ServletContext context) { } protected void clearDependingCombinedResources(final Resource resource) { String absolutePath = resource.getAbsolutePath(); Object[] keys = getAbsolutePathKeys().toArray(); for (int i = 0; i < keys.length; i++) { Resource currentResource = getResourceByAbsolutePath((String)keys[i]); // Difference between combined and wildcard resources String paths = currentResource.isWildcard() ? currentResource.getWildcardAbsolutePaths() : currentResource.getAbsolutePath(); int idx = paths.indexOf(absolutePath); // "> 0" because the normal resource doesn't starts with "[" if (idx > 0) { removeAbsolutePath((String)keys[i]); } } } }
making clearDependingCombinedResources synchronized to line up with historical Rally changes
packtag-core/src/main/java/net/sf/packtag/cache/provider/AbstractCacheProvider.java
making clearDependingCombinedResources synchronized to line up with historical Rally changes
<ide><path>acktag-core/src/main/java/net/sf/packtag/cache/provider/AbstractCacheProvider.java <ide> } <ide> <ide> <del> protected void clearDependingCombinedResources(final Resource resource) { <add> protected synchronized void clearDependingCombinedResources(final Resource resource) { <ide> String absolutePath = resource.getAbsolutePath(); <ide> Object[] keys = getAbsolutePathKeys().toArray(); <ide> for (int i = 0; i < keys.length; i++) {
Java
apache-2.0
cde2d1659416736ee291f71ed26712528219bc7a
0
renekrie/querqy,shopping24/querqy
/** * */ package querqy.rewrite; import java.util.Collections; import java.util.Set; import querqy.model.ExpandedQuery; import querqy.model.Term; /** * @author René Kriegler, @renekrie * */ public abstract class RewriterFactory { private final String rewriterId; protected RewriterFactory(final String rewriterId) { this.rewriterId = rewriterId; } public abstract QueryRewriter createRewriter(ExpandedQuery input, SearchEngineRequestAdapter searchEngineRequestAdapter); /** * For clarity, implement {@link #getCacheableGenerableTerms()} instead of this * method. To ensure backwards compatibility, said method delegates to this one. * * @return The set of {@link Term}s to be generated, defaults to an empty set. */ @Deprecated public Set<Term> getGenerableTerms() { return Collections.emptySet(); } /** * <p>Get all {@link querqy.model.Term}s that will be generated by Rewriters that will be created by this class.</p> * <p>This only includes terms that are known when the factory is created. The terms returned from this method might * be used to optimise caching.</p> * <p>This method must return an empty set if no such term exists.</p> * * @return The set of {@link Term}s to be generated, defaults to an empty set. */ public Set<Term> getCacheableGenerableTerms() { return getGenerableTerms(); } public String getRewriterId() { return rewriterId; } }
querqy-core/src/main/java/querqy/rewrite/RewriterFactory.java
/** * */ package querqy.rewrite; import java.util.Set; import querqy.model.ExpandedQuery; import querqy.model.Term; /** * @author René Kriegler, @renekrie * */ public abstract class RewriterFactory { private final String rewriterId; protected RewriterFactory(final String rewriterId) { this.rewriterId = rewriterId; } public abstract QueryRewriter createRewriter(ExpandedQuery input, SearchEngineRequestAdapter searchEngineRequestAdapter); /** * <p>Get all {@link querqy.model.Term}s that will be generated by Rewriters that will be created by this class.</p> * <p>This only includes terms that are known when the factory is created. The terms returned from this method might * be used to optimise caching.</p> * <p>This method must return an empty set if no such term exists.</p> * * @return The set of {@link Term}s to be generated. */ public abstract Set<Term> getCacheableGenerableTerms(); public String getRewriterId() { return rewriterId; } }
[#129] make method signature backwards compatible
querqy-core/src/main/java/querqy/rewrite/RewriterFactory.java
[#129] make method signature backwards compatible
<ide><path>uerqy-core/src/main/java/querqy/rewrite/RewriterFactory.java <ide> */ <ide> package querqy.rewrite; <ide> <add>import java.util.Collections; <ide> import java.util.Set; <ide> <ide> import querqy.model.ExpandedQuery; <ide> SearchEngineRequestAdapter searchEngineRequestAdapter); <ide> <ide> /** <add> * For clarity, implement {@link #getCacheableGenerableTerms()} instead of this <add> * method. To ensure backwards compatibility, said method delegates to this one. <add> * <add> * @return The set of {@link Term}s to be generated, defaults to an empty set. <add> */ <add> @Deprecated <add> public Set<Term> getGenerableTerms() { <add> return Collections.emptySet(); <add> } <add> <add> /** <ide> * <p>Get all {@link querqy.model.Term}s that will be generated by Rewriters that will be created by this class.</p> <del> * <p>This only includes terms that are known when the factory is created. The terms returned from this method might <del> * be used to optimise caching.</p> <del> * <p>This method must return an empty set if no such term exists.</p> <del> * <del> * @return The set of {@link Term}s to be generated. <del> */ <del> public abstract Set<Term> getCacheableGenerableTerms(); <add> * <p>This only includes terms that are known when the factory is created. The terms returned from this method might <add> * be used to optimise caching.</p> <add> * <p>This method must return an empty set if no such term exists.</p> <add> * <add> * @return The set of {@link Term}s to be generated, defaults to an empty set. <add> */ <add> public Set<Term> getCacheableGenerableTerms() { <add> return getGenerableTerms(); <add> } <ide> <ide> public String getRewriterId() { <ide> return rewriterId;
Java
apache-2.0
e8b6f48a44f06060869bae6906cf2fd99b0b7522
0
OmniKryptec/OmniKryptec-Engine
package omnikryptec.gameobject.terrain; import omnikryptec.shader.base.Shader; import omnikryptec.shader.base.UniformMatrix; import omnikryptec.shader.base.UniformSampler; /** * * @author Panzer1119 */ public class TerrainShader extends Shader { private static final String SHADER_FOLDER = "/omnikryptec/gameobject/terrain/"; /* VertexShader Uniforms */ public static final UniformMatrix transformationMatrix = new UniformMatrix("transformationMatrix"); public static final UniformMatrix projectionMatrix = new UniformMatrix("projectionMatrix"); public static final UniformMatrix viewMatrix = new UniformMatrix("viewMatrix"); /* FragmentShader Uniforms */ public static final UniformSampler backgroundTexture = new UniformSampler("backgroundTexture"); public static final UniformSampler rTexture = new UniformSampler("rTexture"); public static final UniformSampler gTexture = new UniformSampler("gTexture"); public static final UniformSampler bTexture = new UniformSampler("bTexture"); public static final UniformSampler blendMap = new UniformSampler("blendMap"); public TerrainShader() { super(TerrainShader.class.getResourceAsStream(SHADER_FOLDER + "terrainVertexShader.txt"), TerrainShader.class.getResourceAsStream(SHADER_FOLDER + "terrainFragmentShader.txt"), "position", "textureCoordinates", "normal", "tangents", transformationMatrix, projectionMatrix, viewMatrix, backgroundTexture, rTexture, gTexture, bTexture, blendMap); start(); backgroundTexture.loadTexUnit(0); rTexture.loadTexUnit(1); gTexture.loadTexUnit(2); bTexture.loadTexUnit(3); blendMap.loadTexUnit(4); } }
src/omnikryptec/gameobject/terrain/TerrainShader.java
package omnikryptec.gameobject.terrain; import omnikryptec.shader.base.Shader; import omnikryptec.shader.base.UniformMatrix; import omnikryptec.shader.base.UniformSampler; /** * * @author Panzer1119 */ public class TerrainShader extends Shader { private static final String SHADER_FOLDER = "/omnikryptec/terrain/"; /* VertexShader Uniforms */ public static final UniformMatrix transformationMatrix = new UniformMatrix("transformationMatrix"); public static final UniformMatrix projectionMatrix = new UniformMatrix("projectionMatrix"); public static final UniformMatrix viewMatrix = new UniformMatrix("viewMatrix"); /* FragmentShader Uniforms */ public static final UniformSampler backgroundTexture = new UniformSampler("backgroundTexture"); public static final UniformSampler rTexture = new UniformSampler("rTexture"); public static final UniformSampler gTexture = new UniformSampler("gTexture"); public static final UniformSampler bTexture = new UniformSampler("bTexture"); public static final UniformSampler blendMap = new UniformSampler("blendMap"); public TerrainShader() { super(TerrainShader.class.getResourceAsStream(SHADER_FOLDER + "terrainVertexShader.txt"), TerrainShader.class.getResourceAsStream(SHADER_FOLDER + "terrainFragmentShader.txt"), "position", "textureCoordinates", "normal", "tangents", transformationMatrix, projectionMatrix, viewMatrix, backgroundTexture, rTexture, gTexture, bTexture, blendMap); start(); backgroundTexture.loadTexUnit(0); rTexture.loadTexUnit(1); gTexture.loadTexUnit(2); bTexture.loadTexUnit(3); blendMap.loadTexUnit(4); } }
hotfix
src/omnikryptec/gameobject/terrain/TerrainShader.java
hotfix
<ide><path>rc/omnikryptec/gameobject/terrain/TerrainShader.java <ide> */ <ide> public class TerrainShader extends Shader { <ide> <del> private static final String SHADER_FOLDER = "/omnikryptec/terrain/"; <add> private static final String SHADER_FOLDER = "/omnikryptec/gameobject/terrain/"; <ide> <ide> /* VertexShader Uniforms */ <ide> public static final UniformMatrix transformationMatrix = new UniformMatrix("transformationMatrix");
JavaScript
mit
d5e8cc6a3e6ec1859b884e64386136e363d444b6
0
georgecheteles/jQuery.isAlive
/* _ __ __ _ | | / /__ _________ ____/ /__ ____ ___ ____ _____ _(_)____ | | /| / / _ \______/ ___/ __ \/ __ / _ \______/ __ `__ \/ __ `/ __ `/ / ___/ | |/ |/ / __/_____/ /__/ /_/ / /_/ / __/_____/ / / / / / /_/ / /_/ / / /__ |__/|__/\___/ \___/\____/\__,_/\___/ /_/ /_/ /_/\__,_/\__, /_/\___/ /____/ jQuery.isAlive(1.10.0) Written by George Cheteles ([email protected]). Licensed under the MIT (https://github.com/georgecheteles/jQuery.isAlive/blob/master/MIT-LICENSE.txt) license. Please attribute the author if you use it. Find me at: [email protected] https://github.com/georgecheteles Last modification on this file: 03 June 2014 */ (function(jQuery) { /*THIS IS THE MAIN ARRAY THAT KEEPS ALL THE OBJECTS*/ var isAliveObjects = []; var incIndex = 0; var browserObj = null; var indexOf = null; var vPArray = {opacity:"opacity",left:"left",right:"right",top:"top",bottom:"bottom",width:"width",height:"height"}; var _fix = {}; var canRGBA = false; var MSPointerEnabled,MSPointerDown,MSPointerMove,MSPointerUp,MSMaxTouchPoints,WheelEvent; var resizeOn = false; var resizeTimer; var windowWidth; var windowHeight; /*CHECK IF BROWSER SUPPORTS RGBA*/ function supportsRGBA(){ var el = document.createElement('foo'); var prevColor = el.style.color; try { el.style.color = 'rgba(0,0,0,0)'; } catch(e) {} return el.style.color != prevColor; } /*COMPARES VERSIONS*/ function ifVersion(value1,cond,value2){ value1 = value1.toString().split('.'); value2 = value2.toString().split('.'); var maxLength = Math.max(value1.length,value2.length); for(var i=0;i<=maxLength-1;i++){ var v1 = (typeof(value1[i])!="undefined") ? parseInt(value1[i]) : 0; var v2 = (typeof(value2[i])!="undefined") ? parseInt(value2[i]) : 0; if(cond=="<" || cond=="<="){ if(v1<v2) return true; if(v1>v2) return false; } else if(cond==">" || cond==">="){ if(v1>v2) return true; if(v1<v2) return false; } else if(cond=="==" && v1!=v2) return false; } if(cond=="==" || cond=="<=" || cond==">=") return true; return false; } /*RETURN THE FIRST FLOAT VALUE*/ function getFloat(value){ return value.match(/[-]?[0-9]*\.?[0-9]+/)[0]; } /*FIXES CSS3 TRANSITION DURATION BUG*/ function breakCSS3(property,value){ var success = false; var fix = function(value,format){ if(success) return value; if(value.indexOf(' ')!=-1){ value = value.split(' '); for(var key in value) value[key] = fix(value[key],format); return value.join(' '); } if(value.indexOf('(')!=-1){ format = value.substr(0,value.indexOf('(')); if(format=='url') return value; value = value.substr(value.indexOf('(')+1,value.indexOf(')')-value.indexOf('(')-1); return format + '(' + fix(value,format) + ')'; } if(value.indexOf(',')!=-1){ value = value.split(','); for(var key in value) value[key] = fix(value[key],format); return value.join(','); } var unitType = value.match('px|%|deg|em'); if(unitType!=null){ unitType = unitType[0]; var fNumber = getFloat(value); if(fNumber!=null){ success = true; return value.replace(fNumber,parseFloat(fNumber) + _fix[unitType]); } } if(format!=null){ if(format=='rgb' || format=='rgba'){ success = true; if(value<255) return parseInt(value) + 1; else return parseInt(value) - 1; } if(property==vP('transform')){ if(format.indexOf('matrix')==0 || format.indexOf('scale')==0){ success = true; return parseFloat(value) + 0.001; } } if(property=='-webkit-filter'){ if(format=='grayscale' || format=='sepia' || format=='invert' || format=='opacity'){ if(value<=0.5) value = parseFloat(value) + 0.001; else value = parseFloat(value) - 0.001; success = true; return value; } if(format=='brightness' || format=='contrast' || format=='saturate'){ success = true; return parseFloat(value) + 0.001; } } } return value; } if(property=='opacity'){ if(value<=0.5) value = parseFloat(value) + _fix['opacity']; else value = parseFloat(value) - _fix['opacity']; } else if(isNumber(value)) value = parseFloat(value) + _fix['px']; else value = fix(value,null); return value; } /*EASING TO BEZIER*/ function convertEasing(value){ var easings = {'swing':'0.02,0.01,0.47,1','easeInSine':'0.47,0,0.745,0.715','easeOutSine':'0.39,0.575,0.565,1','easeInOutSine':'0.445,0.05,0.55,0.95','easeInQuad':'0.55,0.085,0.68,0.53','easeOutQuad':'0.25,0.46,0.45,0.94','easeInOutQuad':'0.455,0.03,0.515,0.955','easeInCubic':'0.55,0.055,0.675,0.19','easeOutCubic':'0.215,0.61,0.355,1','easeInOutCubic':'0.645,0.045,0.355,1','easeInQuart':'0.895,0.03,0.685,0.22','easeOutQuart':'0.165,0.84,0.44,1','easeInOutQuart':'0.77,0,0.175,1','easeInQuint':'0.755,0.05,0.855,0.06','easeOutQuint':'0.23,1,0.32,1','easeInOutQuint':'0.86,0,0.07,1','easeInExpo':'0.95,0.05,0.795,0.035','easeOutExpo':'0.19,1,0.22,1','easeInOutExpo':'1,0,0,1','easeInCirc':'0.6,0.04,0.98,0.335','easeOutCirc':'0.075,0.82,0.165,1','easeInOutCirc':'0.785,0.135,0.15,0.86','easeInBack':'0.6,-0.28,0.735,0.045','easeOutBack':'0.175,0.885,0.32,1.275','easeInOutBack':'0.68,-0.55,0.265,1.55'}; if(typeof(easings[value])!='undefined') return 'cubic-bezier('+easings[value]+')'; return value; } /*FIX SPACES FOR CSS VALUES*/ function fixSpaces(params){ if(params.indexOf(' ')==-1) return params; params = jQuery.trim(params).split(' '); var ret = []; for(var key in params) if(params[key]!="") ret.push(params[key]); params = ret.join(' '); if(params.indexOf('(')!=-1){ var bracketCount = 0; ret = ""; for(var c=0;c<params.length;c++){ if(params.charAt(c)=='(') bracketCount++; else if(params.charAt(c)==')') bracketCount--; if(params.charAt(c)!=' ' || (params.charAt(c)==' ' && bracketCount==0)) ret = ret + params.charAt(c); } params = ret; } return params; } /*CONVERT IN PROPERTY LIKE STYLE OBJ*/ function propertyToStyle(property,firstUp){ if(property.indexOf('-')!=-1){ if(property.charAt(0)=='-') property = property.substr(1); property = property.split('-'); for(var key in property) if(key>0 || firstUp) property[key] = property[key].charAt(0).toUpperCase()+property[key].substr(1); property = property.join(''); } return property; } /*GET TEXT BETWEEN BRACKETS*/ function getBetweenBrackets(text,doEval){ var lastBracket; for(lastBracket=text.length;lastBracket>=0;lastBracket--) if(text.charAt(lastBracket)==')') break; if(typeof(doEval)=='undefined') return text.substr(text.indexOf('(')+1,lastBracket-text.indexOf('(')-1); var evalExp = text.substr(text.indexOf('(')+1,lastBracket-text.indexOf('(')-1); try{ eval("evalExp = "+evalExp+';'); }catch(err){} return evalExp + text.substr(lastBracket+1,text.length-lastBracket-1); } /*CONVERT COLORS TO CODE*/ function nameToRgb(name){ var colors={"aliceblue":"240,248,255","antiquewhite":"250,235,215","aqua":"0,255,255","aquamarine":"127,255,212","azure":"240,255,255","beige":"245,245,220","bisque":"255,228,196","black":"0,0,0","blanchedalmond":"255,235,205","blue":"0,0,255","blueviolet":"138,43,226","brown":"165,42,42","burlywood":"222,184,135","cadetblue":"95,158,160","chartreuse":"127,255,0","chocolate":"210,105,30","coral":"255,127,80","cornflowerblue":"100,149,237","cornsilk":"255,248,220","crimson":"220,20,60","cyan":"0,255,255","darkblue":"0,0,139","darkcyan":"0,139,139","darkgoldenrod":"184,134,11","darkgray":"169,169,169","darkgreen":"0,100,0","darkkhaki":"189,183,107","darkmagenta":"139,0,139","darkolivegreen":"85,107,47","darkorange":"255,140,0","darkorchid":"153,50,204","darkred":"139,0,0","darksalmon":"233,150,122","darkseagreen":"143,188,143","darkslateblue":"72,61,139","darkslategray":"47,79,79","darkturquoise":"0,206,209","darkviolet":"148,0,211","deeppink":"255,20,147","deepskyblue":"0,191,255","dimgray":"105,105,105","dodgerblue":"30,144,255","firebrick":"178,34,34","floralwhite":"255,250,240","forestgreen":"34,139,34","fuchsia":"255,0,255","gainsboro":"220,220,220","ghostwhite":"248,248,255","gold":"255,215,0","goldenrod":"218,165,32","gray":"128,128,128","green":"0,128,0","greenyellow":"173,255,47","honeydew":"240,255,240","hotpink":"255,105,180","indianred ":"205,92,92","indigo ":"75,0,130","ivory":"255,255,240","khaki":"240,230,140","lavender":"230,230,250","lavenderblush":"255,240,245","lawngreen":"124,252,0","lemonchiffon":"255,250,205","lightblue":"173,216,230","lightcoral":"240,128,128","lightcyan":"224,255,255","lightgoldenrodyellow":"250,250,210","lightgrey":"211,211,211","lightgreen":"144,238,144","lightpink":"255,182,193","lightsalmon":"255,160,122","lightseagreen":"32,178,170","lightskyblue":"135,206,250","lightslategray":"119,136,153","lightsteelblue":"176,196,222","lightyellow":"255,255,224","lime":"0,255,0","limegreen":"50,205,50","linen":"250,240,230","magenta":"255,0,255","maroon":"128,0,0","mediumaquamarine":"102,205,170","mediumblue":"0,0,205","mediumorchid":"186,85,211","mediumpurple":"147,112,216","mediumseagreen":"60,179,113","mediumslateblue":"123,104,238","mediumspringgreen":"0,250,154","mediumturquoise":"72,209,204","mediumvioletred":"199,21,133","midnightblue":"25,25,112","mintcream":"245,255,250","mistyrose":"255,228,225","moccasin":"255,228,181","navajowhite":"255,222,173","navy":"0,0,128","oldlace":"253,245,230","olive":"128,128,0","olivedrab":"107,142,35","orange":"255,165,0","orangered":"255,69,0","orchid":"218,112,214","palegoldenrod":"238,232,170","palegreen":"152,251,152","paleturquoise":"175,238,238","palevioletred":"216,112,147","papayawhip":"255,239,213","peachpuff":"255,218,185","peru":"205,133,63","pink":"255,192,203","plum":"221,160,221","powderblue":"176,224,230","purple":"128,0,128","red":"255,0,0","rosybrown":"188,143,143","royalblue":"65,105,225","saddlebrown":"139,69,19","salmon":"250,128,114","sandybrown":"244,164,96","seagreen":"46,139,87","seashell":"255,245,238","sienna":"160,82,45","silver":"192,192,192","skyblue":"135,206,235","slateblue":"106,90,205","slategray":"112,128,144","snow":"255,250,250","springgreen":"0,255,127","steelblue":"70,130,180","tan":"210,180,140","teal":"0,128,128","thistle":"216,191,216","tomato":"255,99,71","turquoise":"64,224,208","violet":"238,130,238","wheat":"245,222,179","white":"255,255,255","whitesmoke":"245,245,245","yellow":"255,255,0","yellowgreen":"154,205,50"}; if(typeof(colors[name.toLowerCase()])!="undefined"){ if(canRGBA) return "rgba("+colors[name.toLowerCase()]+",1)"; else return "rgb("+colors[name.toLowerCase()]+")"; } return false; } /*CONVERTING HEX TO RGB*/ function hexToRgb(hex) { var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if(result){ if(canRGBA) return "rgba("+parseInt(result[1],16)+","+parseInt(result[2],16)+","+parseInt(result[3], 16)+",1)"; else return "rgb("+parseInt(result[1],16)+","+parseInt(result[2],16)+","+parseInt(result[3], 16)+")"; } return false; } /*ACTION ON RESIZE*/ function onResizeAction(e){ var key; clearTimeout(resizeTimer); resizeTimer = setTimeout(function(){ if(windowWidth!=jQuery(window).width() || windowHeight!=jQuery(window).height()){ windowWidth = jQuery(window).width(); windowHeight = jQuery(window).height(); for(key in isAliveObjects) if(isAliveObjects[key].settings.rebuildOnResize) isAliveObjects[key].rebuildLayout(); } },250); } /*VALIDATES BROWSERS*/ function validateBrowsers(exp){ var isValid = function(browser){ var validBrowser = false; if(browserObj[browser]) validBrowser = true; if(browser=="msie7-" && browserObj.msie && parseInt(browserObj.version)<7) validBrowser = true; if(browser=="msie7" && browserObj.msie && parseInt(browserObj.version)==7) validBrowser = true; if(browser=="msie8" && browserObj.msie && parseInt(browserObj.version)==8) validBrowser = true; if(browser=="msie9" && browserObj.msie && parseInt(browserObj.version)==9) validBrowser = true; if(browser=="msie10" && browserObj.msie && parseInt(browserObj.version)==10) validBrowser = true; if(browser=="msie11" && browserObj.msie && parseInt(browserObj.version)==11) validBrowser = true; if(browser=="msie11+" && browserObj.msie && parseInt(browserObj.version)>11) validBrowser = true; if(browser=="unknown" && typeof(browserObj.webkit)=="undefined" && typeof(browserObj.mozilla)=="undefined" && typeof(browserObj.opera)=="undefined" && typeof(browserObj.msie)=="undefined") validBrowser = true; return validBrowser; } var valid = false; exp = exp.split("|"); for(var key in exp){ if(exp[key].indexOf("&")!=-1){ var temp = exp[key].split("&"); if(temp.length==2 && isValid(temp[0]) && isValid(temp[1])) valid = true; } else if(exp[key].indexOf("!")!=-1){ var temp = exp[key].split("!"); if(temp.length==2 && isValid(temp[0]) && !isValid(temp[2])) valid = true; } else if(isValid(exp[key])) valid = true; } return valid; } /*CONVERT TO STRING*/ function toString(value){ if(typeof(value)=='function') return sdbmCode(value.toString()).toString(); return value.toString(); } /*MAKES UNIQUE HASH FOR A STRING*/ function sdbmCode(str){ var hash = 0; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); hash = c + (hash << 6) + (hash << 16) - hash; } return hash; } /*CHECKS IF NUMBER*/ function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } /* DETECTS BROWSER / ENGINE / VERSION (THANKS TO KENNEBEC)*/ function getBrowser(){ var browser = {}, temp; var ua = (navigator.userAgent||navigator.vendor||window.opera); var M = ua.match(/(konqueror|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || []; M = M[2] ? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?']; temp = ua.match(/version\/([\.\d]+)/i); if(temp!=null) M[1] = temp[1]; browser[M[0].toLowerCase()] = true; if(browser.trident){ browser['msie'] = true; temp = /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || []; browser['version'] = (temp[1] || ''); delete browser.trident; } else{ if(browser.chrome || browser.safari) browser['webkit'] = true; if(browser.firefox) browser['mozilla'] = true; browser['version'] = M[1]; } var mobile = (/(android|bb\d+|meego).+mobile|webos|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(ua)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(ua.substr(0,4))); if(mobile) browser.mobile = true; browser.isTouch = ('ontouchstart' in document.documentElement || window.navigator.maxTouchPoints || window.navigator.msMaxTouchPoints) ? true : false; return browser; } /* CHECKS IF PARAMS ARE DETECTED */ function isDinamic(params){ if(typeof(params) == "function") return true; if(params.toString().indexOf('eval(')!==-1) return true; return false; } /*MAKES THE CSS CHANGES FOR EACH BROWSER*/ function vP(property){ if(typeof(vPArray[property])=="undefined"){ vPArray[property] = false; var el = document.createElement('foo'); var pLower = propertyToStyle(property); var pUpper = propertyToStyle(property,true); if(typeof(el.style[pLower])!="undefined" || typeof(el.style[pUpper])!="undefined") vPArray[property] = property; else if(property.indexOf('-webkit-')!=0 && property.indexOf('-moz-')!=0 && property.indexOf('-ms-')!=0 && property.indexOf('-o-')!=0 && property.indexOf('-khtml-')!=0){ if(browserObj.webkit){ var v = propertyToStyle("-webkit-"+property); if(typeof(el.style[v])!="undefined") vPArray[property] = "-webkit-"+property; } else if(browserObj.mozilla){ var v = propertyToStyle("-moz-"+property,true); if(typeof(el.style[v])!="undefined") vPArray[property] = "-moz-"+property; } else if(browserObj.msie){ var v = propertyToStyle("-ms-"+property); if(typeof(el.style[v])!="undefined") vPArray[property] = "-ms-"+property; } else if(browserObj.opera){ var v = propertyToStyle("-o-"+property,true); if(typeof(el.style[v])!="undefined") vPArray[property] = "-o-"+property; } else if(browserObj.konqueror){ var v = propertyToStyle("-khtml-"+property,true); if(typeof(el.style[v])!="undefined") vPArray[property] = "-khtml-"+property; } } } return vPArray[property]; } /*CALCULATE THE CSS PROPERTY AT A POSITION*/ function getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd){ valStart = valStart.toString(); valEnd = valEnd.toString(); var doRecursive = function(valStart,valEnd,colorFound){ if(valStart==valEnd) return valStart; if(valStart.indexOf(' ')!=-1){ var value = []; valStart = valStart.split(' '); valEnd = valEnd.split(' '); for(var key in valStart) value.push(doRecursive(valStart[key],valEnd[key])); return value.join(' '); } if(valStart.indexOf('(')!=-1){ var format = valStart.substr(0,valStart.indexOf('(')); valStart = valStart.substr(valStart.indexOf('(')+1,valStart.indexOf(')')-valStart.indexOf('(')-1); valEnd = valEnd.substr(valEnd.indexOf('(')+1,valEnd.indexOf(')')-valEnd.indexOf('(')-1); return format + '(' + doRecursive(valStart,valEnd,(format=='rgb' || format=='rgba')) + ')'; } if(valStart.indexOf(',')!=-1){ var value = []; valStart = valStart.split(','); valEnd = valEnd.split(','); for(var key in valStart) value.push(doRecursive(valStart[key],valEnd[key],(colorFound && key<3))); return value.join(','); } if(isNumber(valStart)) var format = false; else{ var format = valStart.replace(getFloat(valStart),'$'); valStart = getFloat(valStart); valEnd = getFloat(valEnd); } valStart = parseFloat(valStart); valEnd = parseFloat(valEnd); var value = Math.floor((valStart+((valEnd-valStart)*((pos-stepStart)/(stepEnd-stepStart))))*1000)/1000; if(colorFound) return Math.round(Math.min(255,Math.max(0,value))); if(format!==false) return format.replace('$',value); return value; } return doRecursive(valStart,valEnd); } /*ISALIVE MAIN OBJECT:BEGIN*/ function isAlive(selector,options){ this.mySelector = selector; this.TimeLine; this.step=0; this.lastStep=0; this.animating = false; this.forceAnimation = false; this.wheelTimer; this.animPositions = []; this.animateDuration; this.wipePosition; this.jumpPosition; this.animationType='none'; this.allowWheel = true; this.allowTouch = true; this.scrollbarActive = null; this.waitWheellEnd = false; this.cssDinamicElements = []; this.params = {}; this.onComplete = null; this.uniqId = incIndex; this.functionsArray = {}; this.haveNavPoints; this.rebuildOnStop = false; this.scrollBarPosition = 0; this.toggleState = 0; this.CSS3DefaultTransitionArray = {}; this.CSS3TransitionArray = {}; this.CSS3ValuesArray = {}; this.JSValuesArray = {}; this.DOMElement = false; /* MY CLASS/SET ARRAYS */ this.setArray = {}; this.onOffClassArray = {}; this.settings = jQuery.extend(true,{},{ elements:{}, elementsType:"linear", /*linear|tree*/ duration: 1000, durationTweaks:{}, /*obj: {wheel|touch|scrollBar:duration|durationType|minStepDuration}*/ enableWheel:true, wheelType:"scroll", /*scroll|jump*/ wheelActions:{}, jumpPoints:[], max:null, min:0, maxScroll:1000000, maxDrag:1000000, debug:false, easing:'linear', JSEasing:null, CSS3Easing:null, start:0, loop:false, preventWheel:true, navPoints:[], navPointsSelector:null, navPointsActiveClass:null, navPointsClickEvent:false, enableTouch:false, touchType:'drag',/*drag|wipe*/ touchActions:{}, touchXFrom:null, touchYFrom:null, wipePoints:[], preventTouch:true, animateClass:'isalive-'+incIndex, rebuildOnResize:true, playPoints:[], stepsOnScroll:1, stepsOnDrag:1, stepsOnScrollbar:1, minStepDuration:0, initCSS:false, useCSS3:false, scrollbarType:'scroll',/*scroll|jump*/ scrollbarPoints:[], scrollbarActiveClass:null, enableScrollbarTouch:false, wheelDelay:250, /*number or false*/ enableGPU:false, /*false|true|webkit|chrome|safari|mobile*/ useIdAttribute:false, elementTweaks:{'left':0,'top':0,'width':0,'height':0}, onStep:null, onLoadingComplete:null, onRebuild:null },options); /*MAKES THE PLUGIN INITIOALIZATION*/ this.initAnimations(); /*CALL ONLOADINGCOMPLETE FUNCTION*/ if(this.settings.onLoadingComplete!=null) this.settings.onLoadingComplete(selector); } /* LOGS IN DEBUGER */ isAlive.prototype.log = function(value){ if(this.settings.debug) jQuery('#isalive-'+this.uniqId+'-debuger').append('<br/>'+value); } /*GET LOOP VALUE*/ isAlive.prototype.getLoop = function(value){ return Math.floor(value/this.settings.max); } /* CONVERTS REAL POSITION TO RANGE POSITION */ isAlive.prototype.getPos = function(value){ if(value%this.settings.max<0) return this.settings.max+(value%this.settings.max); else return value%this.settings.max; } /*ANIMATE FUNCTION*/ isAlive.prototype.animate = function(animType,selector,property,value,duration,easing,step){ var thisObj = this; switch(animType){ case 1: /*DELETE CSS3 VALUES*/ if(typeof(thisObj.CSS3TransitionArray[selector])!="undefined" && typeof(thisObj.CSS3TransitionArray[selector][property])!="undefined"){ delete thisObj.CSS3TransitionArray[selector][property]; delete thisObj.CSS3ValuesArray[selector][property]; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); } /*DO ANIMATION*/ var animateObj = {}; animateObj[property] = value; jQuery(selector).animate(animateObj,{duration:duration,easing:easing,queue:false}); break; case 2: /*DELETE JS VALUES IF EXIST*/ if(typeof(thisObj.JSValuesArray[selector][property])=="undefined") thisObj.JSValuesArray[selector][property] = thisObj.animPositions[Math.round(thisObj.getPos(step))][selector][property].toString(); /*DO ANIMATION*/ var start = thisObj.JSValuesArray[selector][property]; var end = value.toString(); var tempObj = {}; tempObj[property+'Timer']="+=100"; jQuery(selector).animate(tempObj,{duration:duration,easing:easing,queue:false, step: function(step,fx){ thisObj.setCSS(selector,property,getAtPosValue(step-fx.start,start,end,0,100)); } }); break; case 3: /*DELETE VALUE IF ELEMENT IS ANIMATED ALSO BY JS*/ if(typeof(thisObj.JSValuesArray[selector])!="undefined" && typeof(thisObj.JSValuesArray[selector][property])!="undefined") delete thisObj.JSValuesArray[selector][property]; /*SET TRANSITION AND BREAK CSS3 BUG IF NEEDED*/ thisObj.CSS3TransitionArray[selector][property] = property+' '+duration+'ms '+easing+' 0s'; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); if(typeof(thisObj.CSS3ValuesArray[selector][property])!="undefined" && thisObj.CSS3ValuesArray[selector][property]==value) value = breakCSS3(property,value); thisObj.CSS3ValuesArray[selector][property] = value; /*DO ANIMATION*/ jQuery(selector).css(property,value); break; } } /*SET CSS VALUES*/ isAlive.prototype.setCSS = function(selector,property,value){ var thisObj = this; if(property.indexOf('F:')==0){ thisObj.JSValuesArray[selector][property] = value; thisObj.functionsArray[property](selector,value); return; } if(property=="scrollTop"){ jQuery(selector).scrollTop(value); return; } if(property=="scrollLeft"){ jQuery(selector).scrollLeft(value); return; } if(property==vP('transition')){ jQuery(selector).css(property,thisObj.getTransitionArray(selector,value)); return; } if(typeof(thisObj.CSS3TransitionArray[selector])!="undefined" && typeof(thisObj.CSS3TransitionArray[selector][property])!="undefined"){ delete thisObj.CSS3TransitionArray[selector][property]; delete thisObj.CSS3ValuesArray[selector][property]; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); } if(typeof(thisObj.JSValuesArray[selector])!="undefined" && typeof(thisObj.JSValuesArray[selector][property])!="undefined") thisObj.JSValuesArray[selector][property] = value; jQuery(selector).css(property,value); } /* REPLACES PARAMS */ isAlive.prototype.convertParams = function(params,format){ var thisObj = this; var stringPositions = {top:"0%",center:"50%",bottom:"100%",left:"0%",right:"100%"}; if(typeof(params)!="function"){ params = params.toString(); params = params.replace(/elementLeft/g,thisObj.params.elementLeft.toString()); params = params.replace(/elementTop/g,thisObj.params.elementTop.toString()); params = params.replace(/elementWidth/g,thisObj.params.elementWidth.toString()); params = params.replace(/elementHeight/g,thisObj.params.elementHeight.toString()); params = params.replace(/documentWidth/g,thisObj.params.documentWidth.toString()); params = params.replace(/documentHeight/g,thisObj.params.documentHeight.toString()); params = params.replace(/windowWidth/g,thisObj.params.windowWidth.toString()); params = params.replace(/windowHeight/g,thisObj.params.windowHeight.toString()); } else params = params(thisObj.mySelector,thisObj.params).toString(); var doRecursive = function(params){ if(params.indexOf(' ')!=-1){ params = params.split(' '); for(var key in params) params[key] = doRecursive(params[key]); return params.join(' '); } if(params.indexOf('(')!=-1 && params.substr(0,params.indexOf('('))!='eval'){ var format = params.substr(0,params.indexOf('(')); if(format=="url") return params; if(format=='rgb' && canRGBA) return 'rgba(' + doRecursive(getBetweenBrackets(params)) + ',1)'; return format + '(' + doRecursive(getBetweenBrackets(params)) + ')'; } if(params.indexOf(',')!=-1){ params = params.split(','); for(var key in params) params[key] = doRecursive(params[key]); return params.join(','); } if(params.indexOf('(')!=-1 && params.substr(0,params.indexOf('('))=='eval') return getBetweenBrackets(params,true); if(typeof(stringPositions[params])!="undefined") return stringPositions[params]; if(params.charAt(0)=="#"){ var convertValue = hexToRgb(params); if(convertValue!=false) return convertValue; } var convertValue = nameToRgb(params); if(convertValue!=false) return convertValue; return params; } params = doRecursive(fixSpaces(params)); if(typeof(format)!='undefined') params = format.replace('(X)','('+params+')').replace('Xpx',params+'px').replace('X%',params+'%').replace('Xdeg',params+'deg').replace('Xem',params+'em'); if(isNumber(params)) return parseFloat(params); return params; } /* CREATES AND GETS CSS3 ARRAY */ isAlive.prototype.getTransitionArray = function(selector,value){ var thisObj = this; if(typeof(value)!="undefined"){ thisObj.CSS3DefaultTransitionArray[selector] = {}; if(value.indexOf('cubic-bezier')==-1) var tempArray = value.split(','); else{ var tempArray = value.split('('); for (var key in tempArray){ if(tempArray[key].indexOf(')')!=-1){ tempArray[key] = tempArray[key].split(')'); tempArray[key][0] = tempArray[key][0].replace(/,/g,'*CHAR*'); tempArray[key] = tempArray[key].join(')'); } } tempArray = tempArray.join('(').split(','); } for(key in tempArray){ var temp = tempArray[key].split(' '); var property = vP(temp[0]); if(property) thisObj.CSS3DefaultTransitionArray[selector][property] = tempArray[key].replace(temp[0],property).replace(/\*CHAR\*/g,","); } } var tempObj = {}; if(typeof(thisObj.CSS3DefaultTransitionArray[selector])!="undefined") tempObj = jQuery.extend({},tempObj,thisObj.CSS3DefaultTransitionArray[selector]); if(typeof(thisObj.CSS3TransitionArray[selector])!="undefined") tempObj = jQuery.extend({},tempObj,thisObj.CSS3TransitionArray[selector]); var rt = ""; for(var key in tempObj){ if(rt=="") rt = tempObj[key]; else rt = rt + "," + tempObj[key]; } if(rt=="") rt = "all 0s"; return rt; } /*REMAKES PAGE LAYOUT*/ isAlive.prototype.rebuildLayout = function(){ var thisObj = this; var key,selector,property,valStart,valEnd,stepStart,stepEnd,value,pos,valUnder,valAbove,stepFrom,oldValue; var changedElements = []; if(!thisObj.animating){ thisObj.params.windowWidth = jQuery(window).width(); thisObj.params.windowHeight = jQuery(window).height(); thisObj.params.documentWidth = jQuery(document).width(); thisObj.params.documentHeight = jQuery(document).height(); if(thisObj.DOMElement){ thisObj.params.elementLeft = jQuery(thisObj.mySelector).offset().left; thisObj.params.elementTop = jQuery(thisObj.mySelector).offset().top; thisObj.params.elementWidth = jQuery(thisObj.mySelector).width(); thisObj.params.elementHeight = jQuery(thisObj.mySelector).height(); } /* RESET ALL DINAMIC ELEMENTS*/ for(key in thisObj.cssDinamicElements){ if(thisObj.cssDinamicElements[key]['method']=="static"){ /*REPOSITION STATIC ELEMNTS*/ selector = thisObj.cssDinamicElements[key]['selector']; property = thisObj.cssDinamicElements[key]['property']; value = thisObj.convertParams(thisObj.cssDinamicElements[key]['value'],thisObj.cssDinamicElements[key]['format']); thisObj.setCSS(selector,property,value); } else if(thisObj.cssDinamicElements[key]['method']=="animate"){ /*REPOSITION ANIMATE*/ selector = thisObj.cssDinamicElements[key]['selector']; property = thisObj.cssDinamicElements[key]['property']; valStart = thisObj.convertParams(thisObj.cssDinamicElements[key]['value-start'],thisObj.cssDinamicElements[key]['format']); valEnd = thisObj.convertParams(thisObj.cssDinamicElements[key]['value-end'],thisObj.cssDinamicElements[key]['format']); if(thisObj.cssDinamicElements[key]['scrollbar']==true){ thisObj.settings.elements[thisObj.cssDinamicElements[key]['key']]['value-start']=valStart; thisObj.settings.elements[thisObj.cssDinamicElements[key]['key']]['value-end']=valEnd; } stepStart = thisObj.cssDinamicElements[key]['step-start'] stepEnd = thisObj.cssDinamicElements[key]['step-end'] for(pos=stepStart;pos<=stepEnd;pos++){ value = getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd); thisObj.animPositions[pos][selector][property]=value; } if(typeof(changedElements[selector])=="undefined") changedElements[selector] = []; if(indexOf(changedElements[selector],property)==-1) changedElements[selector].push(property); } else if(thisObj.cssDinamicElements[key]['method']=="set"){ /*REPOSITION SET*/ selector = thisObj.cssDinamicElements[key]['selector']; property = thisObj.cssDinamicElements[key]['property']; stepFrom = thisObj.cssDinamicElements[key]['step-from']; valAbove = thisObj.cssDinamicElements[key]['value-above']; if(isDinamic(valAbove)){ valAbove = thisObj.convertParams(valAbove,thisObj.cssDinamicElements[key]['format']); thisObj.setArray['forward'][stepFrom][selector][property] = valAbove; } valUnder = thisObj.cssDinamicElements[key]['value-under']; if(isDinamic(valUnder)){ valUnder = thisObj.convertParams(valUnder,thisObj.cssDinamicElements[key]['format']); thisObj.setArray['backward'][stepFrom][selector][property] = valUnder; } if(typeof(changedElements[selector])=="undefined") changedElements[selector] = []; if(indexOf(changedElements[selector],property)==-1) changedElements[selector].push(property); } else if(thisObj.cssDinamicElements[key]['method']=="animate-set"){ /*REPOSITION ANIMATE-SET*/ selector = thisObj.cssDinamicElements[key]['selector']; property = thisObj.cssDinamicElements[key]['property']; valStart = thisObj.convertParams(thisObj.cssDinamicElements[key]['value-start'],thisObj.cssDinamicElements[key]['format']); valEnd = thisObj.convertParams(thisObj.cssDinamicElements[key]['value-end'],thisObj.cssDinamicElements[key]['format']); stepStart = thisObj.cssDinamicElements[key]['step-start']; stepEnd = thisObj.cssDinamicElements[key]['step-end']; moveOn = thisObj.cssDinamicElements[key]['move-on']; for(pos=stepStart;pos<=stepEnd;pos++){ if((pos-stepStart)%moveOn==0){ value = getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd); if(pos>stepStart){ thisObj.setArray['forward'][pos][selector][property] = value; thisObj.setArray['backward'][pos][selector][property] = oldValue; } oldValue = value; } } if(typeof(changedElements[selector])=="undefined") changedElements[selector] = []; if(indexOf(changedElements[selector],property)==-1) changedElements[selector].push(property); } } /* REMAKE THE PAGE LAYOUT */ for(selector in changedElements){ for(key in changedElements[selector]){ property = changedElements[selector][key]; value = null; for(pos=thisObj.getPos(Math.round(thisObj.lastStep));pos>=0;pos--){ if(typeof(thisObj.setArray['forward'][pos])!="undefined" && typeof(thisObj.setArray['forward'][pos][selector])!="undefined" && typeof(thisObj.setArray['forward'][pos][selector][property])!="undefined") value = thisObj.setArray['forward'][pos][selector][property]; else if(typeof(thisObj.animPositions[pos])!="undefined" && typeof(thisObj.animPositions[pos][selector])!="undefined" && typeof(thisObj.animPositions[pos][selector][changedElements[selector][key]])!="undefined") value = thisObj.animPositions[pos][selector][changedElements[selector][key]]; if(value!=null){ thisObj.setCSS(selector,changedElements[selector][key],value); delete changedElements[selector][key]; break; } } } } for(selector in changedElements){ for(key in changedElements[selector]){ property = changedElements[selector][key]; value = null; for(pos=thisObj.getPos(Math.round(thisObj.lastStep))+1;pos<=thisObj.getPos(thisObj.settings.max-1);pos++){ if(typeof(thisObj.setArray['backward'][pos])!="undefined" && typeof(thisObj.setArray['backward'][pos][selector])!="undefined" && typeof(thisObj.setArray['backward'][pos][selector][property])!="undefined") value = thisObj.setArray['backward'][pos][selector][property]; else if(typeof(thisObj.animPositions[pos])!="undefined" && typeof(thisObj.animPositions[pos][selector])!="undefined" && typeof(thisObj.animPositions[pos][selector][changedElements[selector][key]])!="undefined") value = thisObj.animPositions[pos][selector][changedElements[selector][key]]; if(value!=null){ thisObj.setCSS(selector,changedElements[selector][key],value); break; } } } } /*CALLS THE ONREBUILD EVENT*/ if(thisObj.settings.onRebuild!=null) thisObj.settings.onRebuild(thisObj.params,thisObj.getPos(thisObj.step),Math.floor(thisObj.step/(thisObj.settings.max+1))); } else thisObj.rebuildOnStop = true; } /*GETS START VALUES*/ isAlive.prototype.getStartCssValue = function(index){ var key,pos,posFrom; var thisObj = this; if(thisObj.settings.elements[index]['method']=='animate' || thisObj.settings.elements[index]['method']=='animate-set') posFrom = parseInt(thisObj.settings.elements[index]['step-start']); else if(thisObj.settings.elements[index]['method']=='set') posFrom = parseInt(thisObj.settings.elements[index]['step-from']); for(pos=posFrom;pos>=0;pos--){ for(key in thisObj.settings.elements){ if(key!=index && thisObj.settings.elements[key]['selector']==thisObj.settings.elements[index]['selector'] && thisObj.settings.elements[key]['property']==thisObj.settings.elements[index]['property'] && thisObj.settings.elements[key]['method']=="set" && thisObj.settings.elements[key]['step-from']==pos) return thisObj.settings.elements[key]['value-above']; else if(key!=index && thisObj.settings.elements[key]['selector']==thisObj.settings.elements[index]['selector'] && thisObj.settings.elements[key]['property']==thisObj.settings.elements[index]['property'] && (thisObj.settings.elements[key]['method']=="animate" || thisObj.settings.elements[key]['method']=="animate-set") && thisObj.settings.elements[key]['step-end']==pos) return thisObj.settings.elements[key]['value-end']; else if(key!=index && thisObj.settings.elements[key]['selector']==thisObj.settings.elements[index]['selector'] && thisObj.settings.elements[key]['property']==thisObj.settings.elements[index]['property'] && thisObj.settings.elements[key]['method']=="set@start" && pos==thisObj.settings.start) return thisObj.settings.elements[key]['value']; } } if(thisObj.settings.elements[index]['property']=="scrollTop") return jQuery(thisObj.settings.elements[index]['selector']).scrollTop(); if(thisObj.settings.elements[index]['property']=="scrollLeft") return jQuery(thisObj.settings.elements[index]['selector']).scrollLeft(); if(thisObj.settings.elements[index]['property'].indexOf('F:')==0) return 0; return jQuery(thisObj.settings.elements[index]['selector']).css(thisObj.settings.elements[index]['property']); } /*FUNCTION FOR BIND MOUSE AND SCROLL EVENTS*/ isAlive.prototype.bindScrollTouchEvents = function(){ var thisObj = this; /* BIND SCROLL EVENTS */ if(thisObj.settings.enableWheel){ jQuery(thisObj.mySelector).bind(WheelEvent+'.isAlive',function(e){ var wheelValue; (e.type=='wheel') ? wheelValue = (e.originalEvent.deltaY > 0) : ((e.type=='mousewheel') ? wheelValue = (e.originalEvent.wheelDelta < 0) : wheelValue = (e.originalEvent.detail > 0)); (thisObj.settings.wheelType=="scroll") ? ((wheelValue) ? thisObj.doScroll(thisObj.settings.wheelActions.down) : thisObj.doScroll(thisObj.settings.wheelActions.up)) : ((wheelValue) ? thisObj.doJump(thisObj.settings.wheelActions.down) : thisObj.doJump(thisObj.settings.wheelActions.up)); if(thisObj.settings.preventWheel) return false; }); } /* BIND TOUCH EVENTS */ if(thisObj.settings.enableTouch){ var startX; var startY; var isMoving = false; var dragHorizontal = null; var pointerType = null; function onTouchStart(e){ if(!MSPointerEnabled){ if(e.originalEvent.touches.length != 1) return; startX = e.originalEvent.touches[0].clientX; startY = e.originalEvent.touches[0].clientY; isMoving = true; this.addEventListener('touchmove', onTouchMove, false); this.addEventListener('touchend', cancelTouch, false); } else{ if(e.originalEvent.pointerType != (e.originalEvent.MSPOINTER_TYPE_TOUCH || 'touch')) return; pointerType = e.originalEvent.pointerType; startX = e.originalEvent.clientX; startY = e.originalEvent.clientY; isMoving = true; document.addEventListener(MSPointerMove, onTouchMove, false); document.addEventListener(MSPointerUp, cancelTouch, false); } } function cancelTouch(e){ if(!MSPointerEnabled){ this.removeEventListener('touchmove', onTouchMove); this.removeEventListener('touchend', cancelTouch); } else{ if(typeof(e)!="undefined" && e.pointerType != pointerType) return; pointerType = null; document.removeEventListener(MSPointerMove, onTouchMove); document.removeEventListener(MSPointerUp, cancelTouch); } isMoving = false; dragHorizontal = null; } if(thisObj.settings.touchType=='wipe'){ var onTouchMove = function(e){ if(MSPointerEnabled && e.pointerType != pointerType) return; if(!MSPointerEnabled && thisObj.settings.preventTouch) e.preventDefault(); if(isMoving){ if(!MSPointerEnabled){ var x = e.touches[0].clientX; var y = e.touches[0].clientY; } else{ var x = e.clientX; var y = e.clientY; } var dx = startX - x; var dy = startY - y; if(Math.abs(dx)>=thisObj.settings.touchXFrom){ if(thisObj.settings.touchActions.left!=0 && dx>0){ cancelTouch(); thisObj.doWipe(thisObj.settings.touchActions.left); return; } else if(thisObj.settings.touchActions.right!=0 && dx<0){ cancelTouch(); thisObj.doWipe(thisObj.settings.touchActions.right); return; } } if(Math.abs(dy)>=thisObj.settings.touchYFrom){ if(thisObj.settings.touchActions.up!=0 && dy>0){ cancelTouch(); thisObj.doWipe(thisObj.settings.touchActions.up); return; } else if(thisObj.settings.touchActions.down!=0 && dy<0 ){ cancelTouch(); thisObj.doWipe(thisObj.settings.touchActions.down); return; } } } } } else{ var onTouchMove = function (e){ if(MSPointerEnabled && e.pointerType != pointerType) return; if(!MSPointerEnabled && thisObj.settings.preventTouch) e.preventDefault(); if(isMoving){ if(!MSPointerEnabled){ var x = e.touches[0].clientX; var y = e.touches[0].clientY; } else{ var x = e.clientX; var y = e.clientY; } var dx = startX - x; var dy = startY - y; if(Math.abs(dx)>=thisObj.settings.touchXFrom){ if(thisObj.settings.touchActions.left!=0 && dx>0 && (dragHorizontal==null || dragHorizontal==true)){ dragHorizontal = true; thisObj.doDrag(thisObj.settings.touchActions.left); startX = x; } else if(thisObj.settings.touchActions.right!=0 && dx<0 && (dragHorizontal==null || dragHorizontal==true)){ dragHorizontal = true; thisObj.doDrag(thisObj.settings.touchActions.right); startX = x; } } if(Math.abs(dy)>=thisObj.settings.touchYFrom){ if(thisObj.settings.touchActions.up!=0 && dy>0 && (dragHorizontal==null || dragHorizontal==false)){ dragHorizontal = false; thisObj.doDrag(thisObj.settings.touchActions.up); startY = y; } else if(thisObj.settings.touchActions.down!=0 && dy<0 && (dragHorizontal==null || dragHorizontal==false)){ dragHorizontal = false; thisObj.doDrag(thisObj.settings.touchActions.down); startY = y; } } } } } if(MSPointerEnabled && MSMaxTouchPoints){ jQuery(thisObj.mySelector).bind(MSPointerDown+'.isAlive',onTouchStart); /*PREVENT TOUCH EVENTS*/ if(thisObj.settings.preventTouch) jQuery(thisObj.mySelector).addClass('isalive-notouchaction'); } if('ontouchstart' in document.documentElement) jQuery(thisObj.mySelector).bind('touchstart.isAlive',onTouchStart); } } /*THIS FUNCTION CREATES ANIMATION, SET AND CLASS ARRAYS*/ isAlive.prototype.createElementsArray = function(){ var thisObj = this; var pos,key,selector,property,className,valStart,valEnd,stepStart,stepEnd,value; var oldValue = {}; thisObj.setArray['forward'] = {}; thisObj.setArray['backward'] = {}; thisObj.onOffClassArray['forward'] = {}; thisObj.onOffClassArray['backward'] = {}; /*CREATES ARRAYS FOR ADDCLASS, REMOVECLASS, SET, ANIMATION PROPERTY*/ for(pos=0;pos<=thisObj.settings.max;pos++){ for(key in thisObj.settings.elements){ if(thisObj.settings.elements[key]['method']=='animate'){ if(pos>=thisObj.settings.elements[key]['step-start'] && pos<=thisObj.settings.elements[key]['step-end']){ selector = thisObj.settings.elements[key]['selector']; property = thisObj.settings.elements[key]['property']; valStart = thisObj.settings.elements[key]['value-start']; valEnd = thisObj.settings.elements[key]['value-end']; stepStart = thisObj.settings.elements[key]['step-start']; stepEnd = thisObj.settings.elements[key]['step-end']; value = getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd); if(typeof(thisObj.animPositions[pos])=="undefined") thisObj.animPositions[pos]=[]; if(typeof(thisObj.animPositions[pos][selector])=="undefined") thisObj.animPositions[pos][selector]=[]; thisObj.animPositions[pos][selector][property]=value; } } else if(thisObj.settings.elements[key]['method']=="animate-set"){ if(pos>=thisObj.settings.elements[key]['step-start'] && pos<=thisObj.settings.elements[key]['step-end'] && (pos-thisObj.settings.elements[key]['step-start'])%thisObj.settings.elements[key]['move-on']==0){ selector = thisObj.settings.elements[key]['selector']; property = thisObj.settings.elements[key]['property']; valStart = thisObj.settings.elements[key]['value-start']; valEnd = thisObj.settings.elements[key]['value-end']; stepStart = thisObj.settings.elements[key]['step-start']; stepEnd = thisObj.settings.elements[key]['step-end']; value = getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd); if(pos>stepStart){ if(typeof(thisObj.setArray['forward'][pos])=="undefined") thisObj.setArray['forward'][pos] = {}; if(typeof(thisObj.setArray['forward'][pos][selector])=="undefined") thisObj.setArray['forward'][pos][selector] = {}; thisObj.setArray['forward'][pos][selector][property] = value; if(typeof(thisObj.setArray['backward'][pos])=="undefined") thisObj.setArray['backward'][pos] = {}; if(typeof(thisObj.setArray['backward'][pos][selector])=="undefined") thisObj.setArray['backward'][pos][selector] = {}; thisObj.setArray['backward'][pos][selector][property] = oldValue[selector+'-'+property]; } oldValue[selector+'-'+property] = value; } } else if(thisObj.settings.elements[key]['method']=="set"){ if(pos==thisObj.settings.elements[key]['step-from']){ selector = thisObj.settings.elements[key]['selector']; property = thisObj.settings.elements[key]['property']; if(typeof(thisObj.setArray['forward'][pos])=="undefined") thisObj.setArray['forward'][pos] = {}; if(typeof(thisObj.setArray['forward'][pos][selector])=="undefined") thisObj.setArray['forward'][pos][selector] = {}; thisObj.setArray['forward'][pos][selector][property] = thisObj.settings.elements[key]['value-above']; if(typeof(thisObj.setArray['backward'][pos])=="undefined") thisObj.setArray['backward'][pos] = {}; if(typeof(thisObj.setArray['backward'][pos][selector])=="undefined") thisObj.setArray['backward'][pos][selector] = {}; thisObj.setArray['backward'][pos][selector][property] = thisObj.settings.elements[key]['value-under']; } }else if(thisObj.settings.elements[key]['method']=="add-class"){ if(pos==thisObj.settings.elements[key]['step-from']){ selector = thisObj.settings.elements[key]['selector']; className = thisObj.settings.elements[key]['class-name']; if(typeof(thisObj.onOffClassArray['forward'][pos])=="undefined") thisObj.onOffClassArray['forward'][pos] = {}; if(typeof(thisObj.onOffClassArray['forward'][pos][selector])=="undefined") thisObj.onOffClassArray['forward'][pos][selector] = {}; thisObj.onOffClassArray['forward'][pos][selector][className] = true; if(typeof(thisObj.onOffClassArray['backward'][pos])=="undefined") thisObj.onOffClassArray['backward'][pos] = {}; if(typeof(thisObj.onOffClassArray['backward'][pos][selector])=="undefined") thisObj.onOffClassArray['backward'][pos][selector] = {}; thisObj.onOffClassArray['backward'][pos][selector][className] = false; } }else if(thisObj.settings.elements[key]['method']=="remove-class"){ if(pos==thisObj.settings.elements[key]['step-from']){ selector = thisObj.settings.elements[key]['selector']; className = thisObj.settings.elements[key]['class-name']; if(typeof(thisObj.onOffClassArray['forward'][pos])=="undefined") thisObj.onOffClassArray['forward'][pos] = {}; if(typeof(thisObj.onOffClassArray['forward'][pos][selector])=="undefined") thisObj.onOffClassArray['forward'][pos][selector] = {}; thisObj.onOffClassArray['forward'][pos][selector][className] = false; if(typeof(thisObj.onOffClassArray['backward'][pos])=="undefined") thisObj.onOffClassArray['backward'][pos] = {}; if(typeof(thisObj.onOffClassArray['backward'][pos][selector])=="undefined") thisObj.onOffClassArray['backward'][pos][selector] = {}; thisObj.onOffClassArray['backward'][pos][selector][className] = true; } } } } } /*INITS THE STARTING POINTS*/ isAlive.prototype.initCSS = function(){ var thisObj = this; var CSSArray = {}; var classesArray = {}; var pos,selector,property,className; var pointFoundSelector = -1; for(pos=thisObj.settings.start;pos>=0;pos--){ if(thisObj.haveNavPoints && pointFoundSelector==-1) pointFoundSelector=indexOf(thisObj.settings.navPoints,pos); if(typeof(thisObj.setArray['forward'][pos])!="undefined"){ for(selector in thisObj.setArray['forward'][pos]){ if(typeof(CSSArray[selector])=="undefined") CSSArray[selector] = {}; for(property in thisObj.setArray['forward'][pos][selector]){ if(typeof(CSSArray[selector][property])=="undefined") CSSArray[selector][property] = thisObj.setArray['forward'][pos][selector][property]; } } } if(typeof(thisObj.onOffClassArray['forward'][pos])!="undefined"){ for(selector in thisObj.onOffClassArray['forward'][pos]){ if(typeof(classesArray[selector])=="undefined") classesArray[selector] = {}; for(className in thisObj.onOffClassArray['forward'][pos][selector]){ if(typeof(classesArray[selector][className])=="undefined") classesArray[selector][className] = thisObj.onOffClassArray['forward'][pos][selector][className]; } } } if(typeof(thisObj.animPositions[pos])!="undefined"){ for(selector in thisObj.animPositions[pos]){ if(typeof(CSSArray[selector])=="undefined") CSSArray[selector] = {}; for(property in thisObj.animPositions[pos][selector]) if(typeof(CSSArray[selector][property]) == "undefined") CSSArray[selector][property] = thisObj.animPositions[pos][selector][property]; } } } for(pos=thisObj.settings.start+1;pos<=thisObj.settings.max-1;pos++){ if(typeof(thisObj.setArray['backward'][pos])!="undefined"){ for(selector in thisObj.setArray['backward'][pos]){ if(typeof(CSSArray[selector])=="undefined") CSSArray[selector] = {}; for(property in thisObj.setArray['backward'][pos][selector]){ if(typeof(CSSArray[selector][property])=="undefined") CSSArray[selector][property] = thisObj.setArray['backward'][pos][selector][property]; } } } if(typeof(thisObj.onOffClassArray['backward'][pos])!="undefined"){ for(selector in thisObj.onOffClassArray['backward'][pos]){ if(typeof(classesArray[selector])=="undefined") classesArray[selector] = {}; for(className in thisObj.onOffClassArray['backward'][pos][selector]){ if(typeof(classesArray[selector][className])=="undefined") classesArray[selector][className] = thisObj.onOffClassArray['backward'][pos][selector][className]; } } } if(typeof(thisObj.animPositions[pos])!="undefined"){ for(selector in thisObj.animPositions[pos]){ if(typeof(CSSArray[selector])=="undefined") CSSArray[selector] = {}; for(property in thisObj.animPositions[pos][selector]) if(typeof(CSSArray[selector][property]) == "undefined") CSSArray[selector][property] = thisObj.animPositions[pos][selector][property]; } } } for(selector in CSSArray) for(property in CSSArray[selector]) thisObj.setCSS(selector,property,CSSArray[selector][property]); for(selector in classesArray){ for(className in classesArray[selector]){ if(classesArray[selector][className]==true) jQuery(selector).addClass(className); else jQuery(selector).removeClass(className); } } if(pointFoundSelector!=-1){ jQuery(thisObj.settings.navPointsSelector).removeClass(thisObj.settings.navPointsActiveClass); jQuery(thisObj.settings.navPointsSelector).eq(pointFoundSelector).addClass(thisObj.settings.navPointsActiveClass); } for(pos=0;pos<=thisObj.settings.start;pos++) if(thisObj.settings.onStep!=null) thisObj.settings.onStep(pos,0,'init'); }; /*THIS FUNCTION MAKES ALL THE INITIALIZATIONS FOR ANIMATIONS*/ isAlive.prototype.initAnimations = function(){ var thisObj = this; var pos,key,key2; /*GET IE VERSION AND BROWSER VARS*/ if(!incIndex){ browserObj = getBrowser(); /* ARRAY SEARCH FOR IE7&IE8 FIX*/ if(!Array.prototype.indexOf){ indexOf = function (myArray,myValue){ for(var key in myArray) if(myArray[key]==myValue) return parseInt(key); return -1; } }else{ indexOf = function (myArray,myValue){ return myArray.indexOf(myValue); } } /*ADDED VALUE FOR CSS BUG FIXED*/ _fix['opacity'] = (browserObj.opera) ? 0.004 : 0.001; _fix['px'] = (browserObj.opera || (browserObj.safari && !browserObj.mobile && ifVersion(browserObj.version,'<','6.0.0'))) ? 1 : 0.01; _fix['%'] = 0.01; _fix['deg'] = 0.01; _fix['em'] = (browserObj.opera || (browserObj.safari && !browserObj.mobile && ifVersion(browserObj.version,'<','6.0.0'))) ? 0.1 : 0.01; /*CHECK IF RGBA IS SUPPORTED*/ canRGBA = supportsRGBA(); /*GET MS POINTER EVENTS*/ MSPointerEnabled = Boolean(window.navigator.msPointerEnabled || window.navigator.pointerEnabled); MSPointerDown = (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) ? ((window.navigator.pointerEnabled) ? "pointerdown" : "MSPointerDown") : false; MSPointerMove = (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) ? ((window.navigator.pointerEnabled) ? "pointermove" : "MSPointerMove") : false; MSPointerUp = (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) ? ((window.navigator.pointerEnabled) ? "pointerup" : "MSPointerUp") : false; MSMaxTouchPoints = (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) ? (window.navigator.maxTouchPoints || window.navigator.msMaxTouchPoints) : false; /*GET WHEEL EVENT*/ WheelEvent = "onwheel" in document.createElement("div") ? "wheel" : ((typeof(document.onmousewheel) !== "undefined") ? "mousewheel" : ((browserObj.mozilla) ? "MozMousePixelScroll" : "DOMMouseScroll")); } /*BINDS RESIZE EVENT*/ if(!resizeOn){ resizeOn = true; windowWidth = jQuery(window).width(); windowHeight = jQuery(window).height(); jQuery(window).bind('resize.general',onResizeAction); /*CREATE STYLES*/ if(vP('user-select')) jQuery('head').append('<style class="isalive-style"> .isalive-nouserselect{'+vP('user-select')+':none;} </style>'); if(vP('touch-action')) jQuery('head').append('<style class="isalive-style"> .isalive-notouchaction{'+vP('touch-action')+':none;} </style>'); if (vP('backface-visibility') && vP('perspective')) jQuery('head').append('<style class="isalive-style"> .isalive-enablegpu{'+vP('backface-visibility')+':hidden;'+vP('perspective')+':1000px;} </style>'); } /*INCREMENT INDEX*/ incIndex++; /*CHECK IF ELEMENT IS FROM DOM*/ thisObj.DOMElement = (jQuery(thisObj.mySelector).length!=0); /*TIMELINE WRAPPER*/ thisObj.TimeLine = document.createElement('foo'); /*SHOW SCROLL POSITION*/ if(thisObj.settings.debug) thisObj.DOMElement ? jQuery(thisObj.mySelector).append('<div style="position:absolute;padding:5px;border:1px solid gray; color: red; top:10px;left:10px;display:inline-block;background:white;z-index:9999;" id="isalive-'+thisObj.uniqId+'-debuger" class="isalive-debuger"><span>'+thisObj.settings.start+'</span></div>') : jQuery('body').append('<div style="position:absolute;padding:5px;border:1px solid gray; color: red; top:10px;left:10px;display:inline-block;background:white;z-index:9999;" id="isalive-'+thisObj.uniqId+'-debuger" class="isalive-debuger"><span>'+thisObj.settings.start+'</span></div>'); /*GET WIDTH AND HEIGHT OF THE PARENT ELEMENT*/ thisObj.params.windowWidth = jQuery(window).width(); thisObj.params.windowHeight = jQuery(window).height(); thisObj.params.documentWidth = jQuery(document).width(); thisObj.params.documentHeight = jQuery(document).height(); if(thisObj.DOMElement){ thisObj.params.elementLeft = jQuery(thisObj.mySelector).offset().left; thisObj.params.elementTop = jQuery(thisObj.mySelector).offset().top; thisObj.params.elementWidth = jQuery(thisObj.mySelector).width(); thisObj.params.elementHeight = jQuery(thisObj.mySelector).height(); } else{ thisObj.params.elementLeft = thisObj.settings.elementTweaks['left']; thisObj.params.elementTop = thisObj.settings.elementTweaks['top']; thisObj.params.elementWidth = thisObj.settings.elementTweaks['width']; thisObj.params.elementHeight = thisObj.settings.elementTweaks['height']; } /*FIX JQUERY/CSS3 EASING*/ if(thisObj.settings.JSEasing==null) thisObj.settings.JSEasing = thisObj.settings.easing; if(thisObj.settings.CSS3Easing==null) thisObj.settings.CSS3Easing = thisObj.settings.easing; /*MAKE SURE THAT MAXSCROLL AND MAXTOUCH IS NO BIGGER THEN SCROLLJUMP AND TOUCHJUMP*/ if(thisObj.settings.maxScroll<thisObj.settings.stepsOnScroll) thisObj.settings.maxScroll = thisObj.settings.stepsOnScroll; if(thisObj.settings.maxDrag<thisObj.settings.stepsOnDrag) thisObj.settings.maxDrag = thisObj.settings.stepsOnDrag; /*CHECK FOR TOUCH*/ if(!thisObj.DOMElement || (thisObj.settings.enableTouch && thisObj.settings.touchType=="wipe" && thisObj.settings.wipePoints.length<=1)) thisObj.settings.enableTouch = false; /*CHECK FOR SCROLL*/ if(!thisObj.DOMElement || (thisObj.settings.enableWheel && thisObj.settings.wheelType=="jump" && thisObj.settings.jumpPoints.length<=1)) thisObj.settings.enableWheel = false; /*CHECK IF SCROLLBARPOINTS EXIST*/ if(thisObj.settings.scrollbarType=="jump" && thisObj.settings.scrollbarPoints.length<=1) thisObj.settings.scrollbarType = "scroll"; /*SORT AND INIT STEP POINTS*/ thisObj.haveNavPoints = (thisObj.settings.navPointsSelector!=null && thisObj.settings.navPointsActiveClass!=null && thisObj.settings.navPoints.length>0); /*SORT POINTS ARRAYS*/ thisObj.settings.wipePoints.sort(function(a,b){return a-b}); thisObj.settings.jumpPoints.sort(function(a,b){return a-b}); thisObj.settings.playPoints.sort(function(a,b){return a-b}); thisObj.settings.scrollbarPoints.sort(function(a,b){return a-b}); thisObj.settings.navPoints.sort(function(a,b){return a-b}); /*SETS THE DURATION TWEAKS*/ if(typeof(thisObj.settings.durationTweaks['wheel'])=="undefined") thisObj.settings.durationTweaks['wheel'] = {}; if(typeof(thisObj.settings.durationTweaks['touch'])=="undefined") thisObj.settings.durationTweaks['touch'] = {}; if(typeof(thisObj.settings.durationTweaks['scrollbar'])=="undefined") thisObj.settings.durationTweaks['scrollbar'] = {}; if(typeof(thisObj.settings.durationTweaks['nav'])=="undefined") thisObj.settings.durationTweaks['nav'] = {}; thisObj.settings.durationTweaks['wheel'] = jQuery.extend({duration:thisObj.settings.duration,durationType:"default",minStepDuration:thisObj.settings.minStepDuration},thisObj.settings.durationTweaks['wheel']); thisObj.settings.durationTweaks['touch'] = jQuery.extend({duration:thisObj.settings.duration,durationType:"default",minStepDuration:thisObj.settings.minStepDuration},thisObj.settings.durationTweaks['touch']); thisObj.settings.durationTweaks['scrollbar'] = jQuery.extend({duration:thisObj.settings.duration,durationType:"default",minStepDuration:thisObj.settings.minStepDuration},thisObj.settings.durationTweaks['scrollbar']); thisObj.settings.durationTweaks['nav'] = jQuery.extend({duration:thisObj.settings.duration,durationType:"default",minStepDuration:thisObj.settings.minStepDuration},thisObj.settings.durationTweaks['nav']); /*SET SCROLL & TOUCH ACTIONS*/ thisObj.settings.wheelActions = jQuery.extend({up:-1,down:1},thisObj.settings.wheelActions); if(thisObj.settings.touchXFrom==null) (thisObj.settings.touchType=="drag") ? thisObj.settings.touchXFrom = 10 : thisObj.settings.touchXFrom = 20; if(thisObj.settings.touchYFrom==null) (thisObj.settings.touchType=="drag") ? thisObj.settings.touchYFrom = 10 : thisObj.settings.touchYFrom = 20; thisObj.settings.touchActions = jQuery.extend({up:1,down:-1,right:0,left:0},thisObj.settings.touchActions); /* CONVERT FROM TREE TO LINEAR STRUCTURE */ if(thisObj.settings.elementsType=="tree"){ var tempObj = {}; var i = 0; for(key in thisObj.settings.elements){ for(key2 in thisObj.settings.elements[key]){ tempObj[i] = {}; tempObj[i] = jQuery.extend({"selector":key},thisObj.settings.elements[key][key2]); i++; } delete thisObj.settings.elements[key]; } thisObj.settings.elements = jQuery.extend({},tempObj); } var new_elements = []; var idIndex = 0; var keyIndex = 0; var tempArray = []; for(key in thisObj.settings.elements){ /*IF NO SELECTOR IS FOUND*/ if(typeof(thisObj.settings.elements[key]['selector'])=="undefined"){ delete thisObj.settings.elements[key]; continue; } /*DELETE ELEMENTS FOR OTHER BROWSERS THEN MINE*/ if(typeof(thisObj.settings.elements[key]['+browsers'])!="undefined"){ if(!validateBrowsers(thisObj.settings.elements[key]['+browsers'])){ delete thisObj.settings.elements[key]; continue; } } if(typeof(thisObj.settings.elements[key]['-browsers'])!="undefined"){ if(validateBrowsers(thisObj.settings.elements[key]['-browsers'])){ delete thisObj.settings.elements[key]; continue; } } /*DELETE NON EXISTING DOM ELEMENTS*/ if(indexOf(tempArray,thisObj.settings.elements[key]['selector'])==-1){ if(jQuery(thisObj.settings.elements[key]['selector']).length==0){ delete thisObj.settings.elements[key]; continue; } tempArray.push(thisObj.settings.elements[key]['selector']); } /*UNPACK SHORT ELEMENTS*/ if(typeof(thisObj.settings.elements[key]['do'])!="undefined"){ if(thisObj.settings.elements[key]['do'].indexOf('(')!=-1){ thisObj.settings.elements[key]['property'] = thisObj.settings.elements[key]['do'].substr(0,thisObj.settings.elements[key]['do'].indexOf('(')); var temp = getBetweenBrackets(thisObj.settings.elements[key]['do']); var values = []; var s = 0; var k = 0; for(var i=0;i<=temp.length-1;i++){ if(temp.charAt(i) == '(') s++; else if(temp.charAt(i) == ')') s--; if(temp.charAt(i)==',' && s==0) k++; else{ if(typeof(values[k])=="undefined") values[k] = ""; values[k] = values[k] + temp.charAt(i); } } if(values.length==1) thisObj.settings.elements[key]['value-end'] = values[0]; else if(values.length==2){ thisObj.settings.elements[key]['value-start'] = values[0]; thisObj.settings.elements[key]['value-end'] = values[1]; } else{ delete thisObj.settings.elements[key]; continue; } } else if(thisObj.settings.elements[key]['do']=="fadeOut"){ thisObj.settings.elements[key]['property'] = "opacity"; thisObj.settings.elements[key]['value-end'] = 0; } else if(thisObj.settings.elements[key]['do']=="fadeIn"){ thisObj.settings.elements[key]['property'] = "opacity"; thisObj.settings.elements[key]['value-end'] = 1; } else{ delete thisObj.settings.elements[key]; continue; } thisObj.settings.elements[key]['method'] = "animate"; delete thisObj.settings.elements[key]['do']; } /*ADD IF USEIDATTRIBUTE IS SET TO TRUE*/ if((thisObj.settings.useIdAttribute && (typeof(thisObj.settings.elements[key]['use-id-attribute'])=="undefined" || thisObj.settings.elements[key]['use-id-attribute']==true)) || (!thisObj.settings.useIdAttribute && thisObj.settings.elements[key]['use-id-attribute']==true)){ if(typeof(thisObj.settings.elements[key]['use-id-attribute'])!="undefined") delete thisObj.settings.elements[key]['use-id-attribute']; if(jQuery(thisObj.settings.elements[key]['selector']).length==1){ var id = jQuery(thisObj.settings.elements[key]['selector']).attr('id'); if(typeof(id)=='undefined'){ id = 'isalive-'+thisObj.uniqId+'-element-' + idIndex; idIndex++; jQuery(thisObj.settings.elements[key]['selector']).attr('id', id); thisObj.settings.elements[key]['selector'] = '#'+id; } else thisObj.settings.elements[key]['selector'] = '#'+id; } else{ jQuery(thisObj.settings.elements[key]['selector']).each(function(k, child){ if(typeof(jQuery(child).attr('id')) == "undefined"){ var id = 'isalive-'+thisObj.uniqId+'-element-' + idIndex; jQuery(child).attr('id', id); idIndex++; } else var id = jQuery(child).attr('id'); var newElement = jQuery.extend({},thisObj.settings.elements[key]); newElement['selector'] = "#"+id; new_elements.push(newElement); }); delete thisObj.settings.elements[key]; } } } for(key in new_elements){ thisObj.settings.elements["ISALIVE_OBJECT_"+keyIndex] = jQuery.extend({},new_elements[key]); keyIndex++; } /*DELETES UNVALID ELEMENTS AND ADDS ISALIVE CLASS / PREPARES CSS3*/ var tempArray = []; var jQueryCanAnimate = ('borderWidth,borderBottomWidth,borderLeftWidth,borderRightWidth,borderTopWidth,borderSpacing,margin,marginBottom,marginLeft,marginRight,marginTop,outlineWidth,padding,paddingBottom,paddingLeft,paddingRight,paddingTop,height,width,maxHeight,maxWidth,minHeight,minWidth,fontSize,bottom,left,right,top,letterSpacing,wordSpacing,lineHeight,textIndent,opacity,scrollLeft,scrollTop').split(','); for(key in thisObj.settings.elements){ if(typeof(thisObj.settings.elements[key]['property'])!="undefined"){ /*BUILD FUNCTIONS ARRAY && TRIMS PROPERTY*/ if(typeof(thisObj.settings.elements[key]['property'])=='function'){ var fTemp = 'F:'+toString(thisObj.settings.elements[key]['property']); if(typeof(thisObj.functionsArray[fTemp])=="undefined") thisObj.functionsArray[fTemp] = thisObj.settings.elements[key]['property']; thisObj.settings.elements[key]['property'] = fTemp; } else if(thisObj.settings.elements[key]['property']!='scrollTop' && thisObj.settings.elements[key]['property']!='scrollLeft'){ /*PUTS PREFIX FOR CSS3*/ thisObj.settings.elements[key]['property'] = vP(thisObj.settings.elements[key]['property']); if(!thisObj.settings.elements[key]['property']){ delete thisObj.settings.elements[key]; continue; } } /* SET@START IS NOT USED WHEN INITCSS IS TRUE*/ if(thisObj.settings.elements[key]["method"]=="set@start" && thisObj.settings.initCSS){ delete thisObj.settings.elements[key]; continue; } /*PUTS MOVE-ON VALUE TO THE ANIMATE-SET ELEMENTS*/ if(thisObj.settings.elements[key]["method"]=="animate-set" && typeof(thisObj.settings.elements[key]['move-on'])=='undefined') thisObj.settings.elements[key]['move-on'] = 1; /*SET CSS3 VARS*/ if(thisObj.settings.elements[key]["method"]=="animate"){ if(!vP('transition') || thisObj.settings.elements[key]['property']=='scrollTop' || thisObj.settings.elements[key]['property']=='scrollLeft' || thisObj.settings.elements[key]["property"].indexOf('F:')==0 || (!thisObj.settings.useCSS3 && typeof(thisObj.settings.elements[key]['useCSS3'])=="undefined") || thisObj.settings.elements[key]['useCSS3']==false){ /*BUILD JS ARRAY*/ if(indexOf(jQueryCanAnimate,propertyToStyle(thisObj.settings.elements[key]["property"]))!=-1) thisObj.settings.elements[key]['animType'] = 1; else{ thisObj.settings.elements[key]['animType'] = 2; if(typeof(thisObj.JSValuesArray[thisObj.settings.elements[key]["selector"]])=="undefined") thisObj.JSValuesArray[thisObj.settings.elements[key]["selector"]] = {}; } /*SET EASING*/ if(typeof(thisObj.settings.elements[key]["easing"])=="undefined"){ if(typeof(thisObj.settings.elements[key]["JSEasing"])=="undefined") thisObj.settings.elements[key]["easing"] = thisObj.settings.JSEasing; else thisObj.settings.elements[key]["easing"] = thisObj.settings.elements[key]["JSEasing"]; } if(typeof(jQuery.easing[thisObj.settings.elements[key]["easing"]])=='undefined') thisObj.settings.elements[key]["easing"] = "linear"; if(typeof(thisObj.settings.elements[key]["JSEasing"])!="undefined") delete thisObj.settings.elements[key]['JSEasing']; if(typeof(thisObj.settings.elements[key]["CSS3Easing"])!="undefined") delete thisObj.settings.elements[key]['CSS3Easing']; } else { /*BUILD CSS3 ARRAYS*/ thisObj.settings.elements[key]['animType'] = 3; if(typeof(thisObj.CSS3TransitionArray[thisObj.settings.elements[key]["selector"]])=="undefined"){ thisObj.CSS3TransitionArray[thisObj.settings.elements[key]["selector"]] = {}; thisObj.CSS3ValuesArray[thisObj.settings.elements[key]["selector"]] = {}; } /*SET EASING*/ if(typeof(thisObj.settings.elements[key]["easing"])=="undefined"){ if(typeof(thisObj.settings.elements[key]["CSS3Easing"])=="undefined") thisObj.settings.elements[key]["easing"] = thisObj.settings.CSS3Easing; else thisObj.settings.elements[key]["easing"] = thisObj.settings.elements[key]["CSS3Easing"]; } thisObj.settings.elements[key]["easing"] = convertEasing(thisObj.settings.elements[key]["easing"]); if(indexOf(['linear','ease','ease-in','ease-out','ease-in-out'],thisObj.settings.elements[key]["easing"])==-1 && thisObj.settings.elements[key]["easing"].indexOf('cubic-bezier')==-1) thisObj.settings.elements[key]["easing"] = "linear"; if(typeof(thisObj.settings.elements[key]["JSEasing"])!="undefined") delete thisObj.settings.elements[key]['JSEasing']; if(typeof(thisObj.settings.elements[key]["CSS3Easing"])!="undefined") delete thisObj.settings.elements[key]['CSS3Easing']; } if(typeof(thisObj.settings.elements[key]['useCSS3'])!="undefined") delete thisObj.settings.elements[key]['useCSS3']; } /*PUT ANIMATE CLASS FOR ANIMATIONS*/ if(thisObj.settings.elements[key]['method']=="animate" && indexOf(tempArray,thisObj.settings.elements[key]['selector'])==-1){ jQuery(thisObj.settings.elements[key]['selector']).addClass(thisObj.settings.animateClass); tempArray.push(thisObj.settings.elements[key]['selector']); } } } /*CHECKS IF ENABLE GPU IS VALID AND ADD SPECIAL CSS*/ if(thisObj.settings.enableGPU==true || (thisObj.settings.enableGPU!=false && validateBrowsers(thisObj.settings.enableGPU))) if(vP('backface-visibility') && vP('perspective')) jQuery('.'+thisObj.settings.animateClass).addClass('isalive-enablegpu'); var tempArray = []; for(key in thisObj.settings.elements){ /* CREATES ARRAY WITH TRANSITIONS CSS VALUES*/ if(thisObj.settings.elements[key]['animType']==3 && vP('transition')) if(typeof(thisObj.CSS3DefaultTransitionArray[thisObj.settings.elements[key]['selector']])=="undefined"){ var propTempArray = []; var pTemp1 = jQuery(thisObj.settings.elements[key]['selector']).css(vP('transition-property')); var pTemp2 = jQuery(thisObj.settings.elements[key]['selector']).css(vP('transition-duration')); if(typeof(pTemp1)!="undefined" && typeof(pTemp2)!="undefined" && (pTemp1!="all" || pTemp2!="0s")){ propTempArray.push(pTemp1); propTempArray.push(pTemp2); propTempArray.push(jQuery(thisObj.settings.elements[key]['selector']).css(vP('transition-timing-function'))); propTempArray.push(jQuery(thisObj.settings.elements[key]['selector']).css(vP('transition-delay'))); thisObj.CSS3DefaultTransitionArray[thisObj.settings.elements[key]['selector']] = propTempArray; } else thisObj.CSS3DefaultTransitionArray[thisObj.settings.elements[key]['selector']] = null; } /*FIXES IE OPACITY BUG*/ if(browserObj.msie && parseInt(browserObj.version)<9 && thisObj.settings.elements[key]['property']=='opacity' && indexOf(tempArray,thisObj.settings.elements[key]['selector'])==-1){ var cssValue=parseFloat(jQuery(thisObj.settings.elements[key]['selector']).css('opacity')); jQuery(thisObj.settings.elements[key]['selector']).css('opacity',cssValue); tempArray.push(thisObj.settings.elements[key]['selector']); } } /* DELETES UNWANTED ELEMENTS FROM TRANSITION ARRAY AND MAKES DEFAULT TRANSITION ARRAY*/ for(key in thisObj.CSS3DefaultTransitionArray){ if(thisObj.CSS3DefaultTransitionArray[key]==null){ delete thisObj.CSS3DefaultTransitionArray[key]; continue; } var tempArray = []; for(key2 in thisObj.CSS3DefaultTransitionArray[key]){ if(thisObj.CSS3DefaultTransitionArray[key][key2].indexOf('cubic-bezier')==-1) tempArray.push(thisObj.CSS3DefaultTransitionArray[key][key2].split(',')); else{ var aTemp = thisObj.CSS3DefaultTransitionArray[key][key2].split('('); for (var keyA in aTemp){ if(aTemp[keyA].indexOf(')')!=-1){ aTemp[keyA] = aTemp[keyA].split(')'); aTemp[keyA][0] = aTemp[keyA][0].replace(/,/g,'*CHAR*'); aTemp[keyA] = aTemp[keyA].join(')'); } } tempArray.push(aTemp.join('(').split(',')); } delete(thisObj.CSS3DefaultTransitionArray[key][key2]); } for(key2 in tempArray[0]){ var transVal = []; transVal.push(jQuery.trim(tempArray[0][key2])); transVal.push(jQuery.trim(tempArray[1][key2])); transVal.push(jQuery.trim(tempArray[2][key2])); transVal.push(jQuery.trim(tempArray[3][key2])); thisObj.CSS3DefaultTransitionArray[key][jQuery.trim(tempArray[0][key2])] = transVal.join(" ").replace(/\*CHAR\*/g,','); } } /*GETS MAX*/ if(thisObj.settings.max==null){ thisObj.settings.max = 0; for(key in thisObj.settings.elements){ if(thisObj.settings.elements[key]['method']=='animate' || thisObj.settings.elements[key]['method']=='animate-set'){ if(typeof(thisObj.settings.elements[key]['step-end'])!='undefined') thisObj.settings.max = Math.max(thisObj.settings.max,thisObj.settings.elements[key]['step-end']); } else if(thisObj.settings.elements[key]['method']=='set' || thisObj.settings.elements[key]['method']=='add-class' || thisObj.settings.elements[key]['method']=='remove-class'){ if(typeof(thisObj.settings.elements[key]['step-from'])!='undefined') thisObj.settings.max = Math.max(thisObj.settings.max,thisObj.settings.elements[key]['step-from']); } } } /*INCREMENT MAX*/ thisObj.settings.max++; /*INIT STARTING POINT*/ thisObj.step=thisObj.settings.start; thisObj.lastStep=thisObj.settings.start; /*GETS STARING VALUES*/ for(key in thisObj.settings.elements){ if(thisObj.settings.elements[key]['scrollbar'] && thisObj.settings.elements[key]['method']=="animate" && (thisObj.settings.elements[key]['property']=="top" || thisObj.settings.elements[key]['property']=="left")){ if(typeof(thisObj.settings.elements[key]['step-start'])=="undefined") thisObj.settings.elements[key]['step-start'] = thisObj.settings.min; if(typeof(thisObj.settings.elements[key]['step-end'])=="undefined") thisObj.settings.elements[key]['step-end'] = thisObj.settings.max-1; } if((thisObj.settings.elements[key]['method']=='animate' || thisObj.settings.elements[key]['method']=='animate-set') && typeof(thisObj.settings.elements[key]['value-start'])=="undefined") thisObj.settings.elements[key]['value-start'] = thisObj.getStartCssValue(key); else if(thisObj.settings.elements[key]['method']=='set' && typeof(thisObj.settings.elements[key]['value-under'])=="undefined") thisObj.settings.elements[key]['value-under'] = thisObj.getStartCssValue(key); } /* GET VALUES FOR CUSTOM PARAMS */ for(key in thisObj.settings.elements){ if(thisObj.settings.elements[key]["method"]=="animate" || thisObj.settings.elements[key]["method"]=="animate-set"){ if(isDinamic(thisObj.settings.elements[key]['value-start']) || isDinamic(thisObj.settings.elements[key]['value-end'])){ var tempObj = (thisObj.settings.elements[key]['scrollbar']) ? jQuery.extend({key:parseInt(key)},thisObj.settings.elements[key]) : jQuery.extend({},thisObj.settings.elements[key]); thisObj.cssDinamicElements.push(tempObj); } thisObj.settings.elements[key]['value-start'] = thisObj.convertParams(thisObj.settings.elements[key]['value-start'],thisObj.settings.elements[key]['format']); thisObj.settings.elements[key]['value-end'] = thisObj.convertParams(thisObj.settings.elements[key]['value-end'],thisObj.settings.elements[key]['format']); } else if(thisObj.settings.elements[key]["method"]=="set"){ if(isDinamic(thisObj.settings.elements[key]['value-under']) || isDinamic(thisObj.settings.elements[key]['value-above'])){ var tempObj = jQuery.extend({},thisObj.settings.elements[key]); thisObj.cssDinamicElements.push(tempObj); } thisObj.settings.elements[key]['value-under'] = thisObj.convertParams(thisObj.settings.elements[key]['value-under'],thisObj.settings.elements[key]['format']); thisObj.settings.elements[key]['value-above'] = thisObj.convertParams(thisObj.settings.elements[key]['value-above'],thisObj.settings.elements[key]['format']); } else if(thisObj.settings.elements[key]["method"]=="static"){ if(isDinamic(thisObj.settings.elements[key]['value'])){ var tempObj = jQuery.extend({},thisObj.settings.elements[key]); thisObj.cssDinamicElements.push(tempObj); } convertValue = thisObj.convertParams(thisObj.settings.elements[key]['value'],thisObj.settings.elements[key]['format']); thisObj.setCSS(thisObj.settings.elements[key]['selector'],thisObj.settings.elements[key]['property'],convertValue); delete thisObj.settings.elements[key]; } else if(thisObj.settings.elements[key]["method"]=="set@start"){ var convertValue = thisObj.convertParams(thisObj.settings.elements[key]["value"],thisObj.settings.elements[key]['format']); thisObj.setCSS(thisObj.settings.elements[key]["selector"],thisObj.settings.elements[key]["property"],convertValue); delete thisObj.settings.elements[key]; } } /*THIS FUNCTION CREATES ANIMATION, SET AND CLASS ARRAYS*/ thisObj.createElementsArray(); /*SCROLLBAR EVENTS*/ var addScrollbarEvents = function(selector,scrollbarKey){ var mousedownFunction = function(e){ var myObj = this; var eType = e.originalEvent.type; var pointerType = null; if(thisObj.animating && thisObj.animationType!="scrollbar") return; if(eType==MSPointerDown){ if(e.originalEvent.pointerType==(e.originalEvent.MSPOINTER_TYPE_PEN || 'pen') || (e.originalEvent.pointerType==(e.originalEvent.MSPOINTER_TYPE_TOUCH || 'touch') && !thisObj.settings.enableScrollbarTouch)) return; pointerType = e.originalEvent.pointerType; } else if(eType=='touchstart') if(e.originalEvent.touches.length!=1) return; var parentTopLeft,clickPos,position,positionTo,positionValid; var valStart = parseFloat(getFloat(thisObj.settings.elements[scrollbarKey]['value-start'].toString())); var valEnd = parseFloat(getFloat(thisObj.settings.elements[scrollbarKey]['value-end'].toString())); thisObj.scrollbarActive = scrollbarKey; if('onselectstart' in document.documentElement){ jQuery('body').bind("selectstart.myEventSelectStart",function(e){ e.preventDefault(); }); } if(thisObj.settings.scrollbarActiveClass!=null) jQuery(myObj).addClass(thisObj.settings.scrollbarActiveClass); if(eType=="mousedown"){ if(thisObj.settings.elements[scrollbarKey]['property']=="top"){ parentTopLeft = jQuery(myObj).parent().offset().top; clickPos = e.pageY - jQuery(myObj).offset().top; }else{ parentTopLeft = jQuery(myObj).parent().offset().left; clickPos = e.pageX - jQuery(myObj).offset().left; } } else if(eType==MSPointerDown){ if(thisObj.settings.elements[scrollbarKey]['property']=="top"){ parentTopLeft = jQuery(myObj).parent().offset().top; clickPos = e.originalEvent.pageY - jQuery(myObj).offset().top; }else{ parentTopLeft = jQuery(myObj).parent().offset().left; clickPos = e.originalEvent.pageX - jQuery(myObj).offset().left; } } else{ if(thisObj.settings.elements[scrollbarKey]['property']=="top"){ parentTopLeft = jQuery(myObj).parent().offset().top; clickPos = e.originalEvent.touches[0].pageY - jQuery(myObj).offset().top; }else{ parentTopLeft = jQuery(myObj).parent().offset().left; clickPos = e.originalEvent.touches[0].pageX - jQuery(myObj).offset().left; } } if(!thisObj.animating) thisObj.scrollBarPosition = thisObj.getPos(thisObj.step); var mousemoveFunction = function(e){ var eType = e.originalEvent.type; if(eType=="mousemove"){ if(thisObj.settings.elements[scrollbarKey]['property']=="top") var mouseNow = (e.pageY - parentTopLeft)-clickPos; else var mouseNow = (e.pageX - parentTopLeft)-clickPos; } else if(eType==MSPointerMove){ if(e.originalEvent.pointerType!=pointerType) return; if(thisObj.settings.elements[scrollbarKey]['property']=="top") var mouseNow = (e.originalEvent.pageY - parentTopLeft)-clickPos; else var mouseNow = (e.originalEvent.pageX - parentTopLeft)-clickPos; } else{ if(thisObj.settings.elements[scrollbarKey]['property']=="top") var mouseNow = (e.originalEvent.touches[0].pageY - parentTopLeft)-clickPos; else var mouseNow = (e.originalEvent.touches[0].pageX - parentTopLeft)-clickPos; } if(mouseNow>=valStart && mouseNow<=valEnd) jQuery(myObj).css(thisObj.settings.elements[scrollbarKey]['property'],mouseNow); else if(mouseNow<valStart){ jQuery(myObj).css(thisObj.settings.elements[scrollbarKey]['property'],valStart); mouseNow = valStart; } else if(mouseNow>valEnd){ jQuery(myObj).css(thisObj.settings.elements[scrollbarKey]['property'],valEnd); mouseNow = valEnd; } positionValid = false; position = thisObj.settings.elements[scrollbarKey]['step-start']+Math.round(Math.abs(thisObj.settings.elements[scrollbarKey]['step-end']-thisObj.settings.elements[scrollbarKey]['step-start'])*((mouseNow-valStart)/Math.abs(valEnd-valStart))); if(thisObj.settings.scrollbarType=="scroll"){ positionTo = thisObj.settings.elements[scrollbarKey]['step-start']+(Math.round((position-thisObj.settings.elements[scrollbarKey]['step-start'])/thisObj.settings.stepsOnScrollbar)*thisObj.settings.stepsOnScrollbar); if(positionTo!=thisObj.scrollBarPosition) if(positionTo>=thisObj.settings.elements[scrollbarKey]['step-start'] && positionTo<=thisObj.settings.elements[scrollbarKey]['step-end']) positionValid = true; }else{ if(thisObj.scrollBarPosition<position){ for(var i=position;i>=thisObj.scrollBarPosition+1;i--){ if(indexOf(thisObj.settings.scrollbarPoints,i)!=-1){ positionValid = true; positionTo = i; break; } } }else if(thisObj.scrollBarPosition>position){ for(var i=position;i<=thisObj.scrollBarPosition-1;i++){ if(indexOf(thisObj.settings.scrollbarPoints,i)!=-1){ positionValid = true; positionTo = i; break; } } } } if(positionValid){ thisObj.scrollBarPosition=positionTo; thisObj.goTo({to:positionTo,animationType:'scrollbar',duration:thisObj.settings.durationTweaks['scrollbar']['duration'],durationType:thisObj.settings.durationTweaks['scrollbar']['durationType'],minStepDuration:thisObj.settings.durationTweaks['scrollbar']['minStepDuration']}); } e.preventDefault(); e.stopPropagation(); } if(eType=="mousedown"){ jQuery(document).bind('mousemove.myEventMouseMove',mousemoveFunction); jQuery(document).bind('mouseup.myEventMouseUp',function(e){ jQuery(document).unbind('mousemove.myEventMouseMove'); jQuery(document).unbind('mouseup.myEventMouseUp'); jQuery('body').unbind("selectstart.myEventSelectStart"); if(thisObj.settings.scrollbarActiveClass!=null) jQuery(myObj).removeClass(thisObj.settings.scrollbarActiveClass); }); } else if(eType==MSPointerDown){ jQuery(document).bind(MSPointerMove+'.myEventPointerMove',mousemoveFunction); jQuery(document).bind(MSPointerUp+'.myEventPointerUp',function(e){ if(e.originalEvent.pointerType!=pointerType) return; jQuery(document).unbind(MSPointerMove+'.myEventPointerMove'); jQuery(document).unbind(MSPointerUp+'.myEventPointerUp'); jQuery('body').unbind("selectstart.myEventSelectStart"); if(thisObj.settings.scrollbarActiveClass!=null) jQuery(myObj).removeClass(thisObj.settings.scrollbarActiveClass); }); } else{ jQuery(myObj).bind('touchmove.myEventTouchMove',mousemoveFunction); jQuery(myObj).bind('touchend.myEventTouchEnd',function(e){ jQuery(myObj).unbind('touchmove.myEventTouchMove'); jQuery(myObj).unbind('touchend.myEventTouchEnd'); jQuery('body').unbind("selectstart.myEventSelectStart"); if(thisObj.settings.scrollbarActiveClass!=null) jQuery(myObj).removeClass(thisObj.settings.scrollbarActiveClass); }); } e.preventDefault(); e.stopPropagation(); } jQuery(selector).addClass('isalive-nouserselect'); jQuery(selector).attr('unselectable', 'on'); if(MSPointerEnabled){ jQuery(selector).bind(MSPointerDown+'.scrollbar',mousedownFunction); /*PREVENT TOUCH EVENTS*/ if(thisObj.settings.enableScrollbarTouch) jQuery(selector).addClass('isalive-notouchaction'); } else if('onmousedown' in document.documentElement) jQuery(selector).bind('mousedown.scrollbar',mousedownFunction); if(('ontouchstart' in document.documentElement) && thisObj.settings.enableScrollbarTouch) jQuery(selector).bind('touchstart.scrollbar',mousedownFunction); } for(key in thisObj.settings.elements){ /*DELETES ALL NON ANIMATED ELEMENTS*/ if(thisObj.settings.elements[key]['method']!='animate'){ delete thisObj.settings.elements[key]; continue; } /*DELETES THE METHOD*/ delete thisObj.settings.elements[key]['method']; /*DELETES UNUSED ELEMENTS AND FINDS SCROLLBAR*/ if(thisObj.settings.elements[key]['scrollbar']){ if(thisObj.settings.elements[key]['property']=="top" || thisObj.settings.elements[key]['property']=="left"){ /*BINDS MOUSEEVENTS TO SCROLLBAR*/ jQuery(thisObj.settings.elements[key]['selector']).each(function(){ addScrollbarEvents(thisObj.settings.elements[key]['selector'],key); }); } else{ delete thisObj.settings.elements[key]['scrollbar']; delete thisObj.settings.elements[key]['value-start']; delete thisObj.settings.elements[key]['value-end']; } } else { delete thisObj.settings.elements[key]['value-start']; delete thisObj.settings.elements[key]['value-end']; } } /*BIND CLICK ON STEP POINTS*/ if(thisObj.settings.navPointsSelector!=null && thisObj.settings.navPoints.length>0 && thisObj.settings.navPointsClickEvent) jQuery(thisObj.settings.navPointsSelector).each(function(index){ jQuery(this).bind('click',function(){ thisObj.goTo({to:thisObj.settings.navPoints[index],animationType:'nav',duration:thisObj.settings.durationTweaks['nav']['duration'],durationType:thisObj.settings.durationTweaks['nav']['durationType'],minStepDuration:thisObj.settings.durationTweaks['nav']['minStepDuration']}); }) }); /*CALLS FUNCTION TO BIND MOUSE AND SCROLL EVENTS*/ thisObj.bindScrollTouchEvents(); /*THIS WILL SET THE CSS VALUES ON LOAD*/ if(thisObj.settings.initCSS) thisObj.initCSS(); } /*ANIMATING MAIN FUNCTION!!!*/ isAlive.prototype.animateSite = function(){ var thisObj = this; //console.log('lastScroll:'+thisObj.lastStep+'|Scroll:'+thisObj.step+'|Duration:'+thisObj.animateDuration); if(thisObj.animating){ jQuery(thisObj.TimeLine).stop(); jQuery('.'+thisObj.settings.animateClass).stop(); } thisObj.animating=true; var key; var animations = {}; var start; var end; var timing; var loopFix; var directionForward; var loop,loopStart,loopEnd; loopStart = thisObj.getLoop(thisObj.lastStep); loopEnd = thisObj.getLoop(thisObj.step); if(thisObj.step>thisObj.lastStep){ /*SCROLL DOWN*/ directionForward = true; for(loop=loopStart;loop<=loopEnd;loop++){ loopFix = loop * thisObj.settings.max; for(key in thisObj.settings.elements){ if(thisObj.animationType=='scrollbar' && key==thisObj.scrollbarActive) continue; if(thisObj.settings.elements[key]['step-start']+loopFix<thisObj.step && thisObj.settings.elements[key]['step-end']+loopFix>thisObj.lastStep){ start = Math.max((thisObj.settings.elements[key]['step-start']+loopFix),thisObj.lastStep); (thisObj.settings.elements[key]['step-end']+loopFix>=thisObj.step) ? end = thisObj.getPos(thisObj.step) : end = thisObj.settings.elements[key]['step-end']; timing = Math.floor((thisObj.animateDuration/(thisObj.step-thisObj.lastStep))*((end+loopFix)-start)); if(typeof(animations[start])=="undefined") animations[start] = {}; if(typeof(animations[start][thisObj.settings.elements[key]['selector']])=="undefined") animations[start][thisObj.settings.elements[key]['selector']] = {}; animations[start][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']] = { 'animType':thisObj.settings.elements[key]['animType'], 'duration':timing, 'end':end, 'to':thisObj.animPositions[end][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']], 'easing':thisObj.settings.elements[key]['easing'] }; //console.log('Id:'+thisObj.settings.elements[key]['selector']+'|Lastscroll:'+thisObj.lastStep+'|Scroll:'+thisObj.step+'|Css:'+thisObj.settings.elements[key]['property']+'|Start:'+start+'|End:'+end+'|Duration:'+timing+'|Css Value:'+thisObj.animPositions[end][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']]+'|Css Real:'+jQuery(thisObj.settings.elements[key]['selector']).css(thisObj.settings.elements[key]['property'])); } } } }else{ /*SCROLL UP*/ directionForward = false; for(loop=loopStart;loop>=loopEnd;loop--){ loopFix = loop * thisObj.settings.max; for(key in thisObj.settings.elements){ if(thisObj.animationType=='scrollbar' && key==thisObj.scrollbarActive) continue; if(thisObj.settings.elements[key]['step-start']+loopFix<thisObj.lastStep && thisObj.settings.elements[key]['step-end']+loopFix>thisObj.step){ start = Math.min((thisObj.settings.elements[key]['step-end']+loopFix),thisObj.lastStep); (thisObj.settings.elements[key]['step-start']+loopFix<=thisObj.step) ? end = thisObj.getPos(thisObj.step) : end = thisObj.settings.elements[key]['step-start']; timing = Math.floor((thisObj.animateDuration/(thisObj.lastStep-thisObj.step))*(start-(end+loopFix))); if(typeof(animations[start])=="undefined") animations[start] = {}; if(typeof(animations[start][thisObj.settings.elements[key]['selector']])=="undefined") animations[start][thisObj.settings.elements[key]['selector']] = {}; animations[start][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']] = { 'animType':thisObj.settings.elements[key]['animType'], 'duration':timing, 'end':end, 'to':thisObj.animPositions[end][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']], 'easing':thisObj.settings.elements[key]['easing'] }; //console.log('Id:'+thisObj.settings.elements[key]['selector']+'|Lastscroll:'+thisObj.lastStep+'|Scroll:'+thisObj.step+'|Css:'+thisObj.settings.elements[key]['property']+'|Start:'+start+'|End:'+end+'|Duration:'+timing+'|Css Value:'+thisObj.animPositions[end][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']]+'|Css Real:'+jQuery(thisObj.settings.elements[key]['selector']).css(thisObj.settings.elements[key]['property'])); } } } } var stepStart = thisObj.lastStep; var stepEnd = thisObj.step; var firstTime = true; var lastStep = thisObj.lastStep; /* STARTS ANIMATION */ jQuery(thisObj.TimeLine).animate({"timer":"+=100"},{duration:thisObj.animateDuration,easing:'linear',queue:false, complete : function(){ var selector,property; thisObj.animating = false; thisObj.animationType = 'none'; thisObj.forceAnimation = false; for(selector in thisObj.CSS3TransitionArray){ thisObj.CSS3TransitionArray[selector] = {}; thisObj.CSS3ValuesArray[selector] = {}; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); } if(thisObj.rebuildOnStop){ thisObj.rebuildLayout(); thisObj.rebuildOnStop = false; if(thisObj.onComplete!==null){ setTimeout(function(){ var onComplete = thisObj.onComplete; thisObj.onComplete = null; onComplete(); },25); } } else{ if(thisObj.onComplete!==null){ var onComplete = thisObj.onComplete; thisObj.onComplete = null; onComplete(); } } }, step: function(now, fx) { var pos,step,selector,property,className,direction,duration; var value = Math.round((stepStart+(((stepEnd-stepStart)/100)*(now-fx.start)))*100)/100; thisObj.lastStep = value; var valid = false; if(firstTime){ valid = true; pos = value; } else if(directionForward && Math.floor(value)>lastStep){ valid = true; pos = Math.floor(value); } else if(!directionForward && Math.ceil(value)<lastStep){ valid = true; pos = Math.ceil(value); } if(valid){ if(firstTime){ step = lastStep; firstTime = false; } else { if(directionForward) step = lastStep+1; else step = lastStep-1; } while((directionForward && step<=pos) || (!directionForward && step>=pos)){ /*ANIMATE-SET && SET && ADD && REMOVE CLASS*/ if(step==parseInt(step)){ (directionForward)?((step!=stepStart)?direction = 'forward':direction = null):((step!=stepEnd)?direction = 'backward':direction = null); if(direction!=null){ if(typeof(thisObj.setArray[direction][thisObj.getPos(step)])!="undefined"){ for(selector in thisObj.setArray[direction][thisObj.getPos(step)]){ for(property in thisObj.setArray[direction][thisObj.getPos(step)][selector]) thisObj.setCSS(selector,property,thisObj.setArray[direction][thisObj.getPos(step)][selector][property]); } } if(typeof(thisObj.onOffClassArray[direction][thisObj.getPos(step)])!="undefined"){ for(selector in thisObj.onOffClassArray[direction][thisObj.getPos(step)]){ for(className in thisObj.onOffClassArray[direction][thisObj.getPos(step)][selector]){ if(thisObj.onOffClassArray[direction][thisObj.getPos(step)][selector][className]==true) jQuery(selector).addClass(className); else jQuery(selector).removeClass(className); } } } } } /*ANIMATE*/ if(step!=stepEnd && typeof(animations[step])!="undefined"){ for(selector in animations[step]){ for(property in animations[step][selector]){ duration = 0; if ((directionForward && (animations[step][selector][property]['end']-thisObj.getPos(value))>0) || (!directionForward && (thisObj.getPos(value)-animations[step][selector][property]['end'])>0)) duration = Math.floor(animations[step][selector][property]['duration']*(Math.abs(animations[step][selector][property]['end']-thisObj.getPos(value))/Math.abs(animations[step][selector][property]['end']-thisObj.getPos(step)))); thisObj.animate(animations[step][selector][property]['animType'],selector,property,animations[step][selector][property]['to'],duration,animations[step][selector][property]['easing'],step); } } } /*STEP-POINTS AND ON-STEP EVENT*/ if(step!=stepStart){ if(thisObj.haveNavPoints){ var pointFound=indexOf(thisObj.settings.navPoints,thisObj.getPos(step)); if(pointFound!=-1){ jQuery(thisObj.settings.navPointsSelector).removeClass(thisObj.settings.navPointsActiveClass); jQuery(thisObj.settings.navPointsSelector).eq(pointFound).addClass(thisObj.settings.navPointsActiveClass); } } if(thisObj.settings.onStep!=null) thisObj.settings.onStep(thisObj.getPos(step),thisObj.getLoop(step),thisObj.animationType); } if(directionForward){ lastStep = Math.floor(step); step = Math.floor(step)+1; } else { lastStep = Math.ceil(step); step = Math.ceil(step)-1; } } } } }); } /* FUNCTION FOR JUMP */ isAlive.prototype.doJump = function(value){ var thisObj = this; var directionForward,stepPos,currentPosition,nextPosition,notAllowed; if(!value || !thisObj.allowWheel || thisObj.forceAnimation) return false; if(thisObj.settings.wheelDelay!==false){ clearTimeout(thisObj.wheelTimer); thisObj.wheelTimer = setTimeout(function(){ thisObj.waitWheellEnd = false; },thisObj.settings.wheelDelay); } (thisObj.animating)?((thisObj.lastStep<thisObj.step)?directionForward=true:directionForward=false):directionForward=null; if(thisObj.settings.wheelDelay===false && thisObj.animating && thisObj.animationType=='jump' && ((directionForward && value==1)||(!directionForward && value==-1))) return false; if(thisObj.settings.wheelDelay!==false && thisObj.waitWheellEnd && thisObj.animating && thisObj.animationType=='jump' && ((directionForward && value==1)||(!directionForward && value==-1))) return false; if(thisObj.settings.wheelDelay!==false) thisObj.waitWheellEnd = true; stepPos = thisObj.getPos(thisObj.lastStep); currentPosition = indexOf(thisObj.settings.jumpPoints,stepPos); if(currentPosition==-1){ currentPosition = null; if(stepPos<=thisObj.settings.jumpPoints[0]) currentPosition=-0.5; else{ for(var i=0;i<=thisObj.settings.jumpPoints.length-2;i++){ if(stepPos>thisObj.settings.jumpPoints[i] && stepPos<thisObj.settings.jumpPoints[i+1]){ currentPosition = i + 0.5; break; } } if(currentPosition==null) currentPosition=(thisObj.settings.jumpPoints.length-1)+0.5; } } if(!thisObj.animating || (thisObj.animating && thisObj.animationType!='jump') || (thisObj.animating && thisObj.animationType=='jump' && ((directionForward && value==-1)||(!directionForward && value==1)))){ notAllowed = null; nextPosition = currentPosition; }else{ if(value==1){ if(currentPosition<thisObj.settings.jumpPoints.length-1) notAllowed = Math.ceil(currentPosition); else notAllowed = 0; } else{ if(currentPosition>0) notAllowed = Math.floor(currentPosition); else notAllowed = thisObj.settings.jumpPoints.length-1; } nextPosition = thisObj.jumpPosition; } if(value==1){ if(nextPosition<(thisObj.settings.jumpPoints.length-1)) nextPosition = Math.floor(nextPosition+1); else if(thisObj.settings.loop) nextPosition=0; else return; } else{ if(nextPosition>0) nextPosition = Math.ceil(nextPosition-1); else if(thisObj.settings.loop) nextPosition=thisObj.settings.jumpPoints.length-1 else return; } if(value==1){ if(nextPosition === notAllowed) return false; thisObj.jumpPosition = nextPosition; thisObj.goTo({to:thisObj.settings.jumpPoints[thisObj.jumpPosition],orientation:'next',animationType:'jump',duration:thisObj.settings.durationTweaks['wheel']['duration'],durationType:thisObj.settings.durationTweaks['wheel']['durationType'],minStepDuration:thisObj.settings.durationTweaks['wheel']['minStepDuration']}); }else{ if(nextPosition === notAllowed) return false; thisObj.jumpPosition = nextPosition; thisObj.goTo({to:thisObj.settings.jumpPoints[thisObj.jumpPosition],orientation:'prev',animationType:'jump',duration:thisObj.settings.durationTweaks['wheel']['duration'],durationType:thisObj.settings.durationTweaks['wheel']['durationType'],minStepDuration:thisObj.settings.durationTweaks['wheel']['minStepDuration']}); } } /* FUNCTION FOR SCROLL */ isAlive.prototype.doScroll = function(value){ var thisObj = this; if(!value || !thisObj.allowWheel || thisObj.forceAnimation) return false; if(thisObj.animating && thisObj.animationType!='scroll'){ thisObj.step=Math.round(thisObj.lastStep); thisObj.onComplete=null; } else if(thisObj.animating && thisObj.animationType=='scroll' && ((thisObj.lastStep<thisObj.step && value==-1)||(thisObj.lastStep>thisObj.step && value==1))) thisObj.step=Math.round(thisObj.lastStep); if(value==1){ if((thisObj.step+thisObj.settings.stepsOnScroll<=thisObj.settings.max-1 || thisObj.settings.loop) && (thisObj.step+thisObj.settings.stepsOnScroll)-thisObj.lastStep<=thisObj.settings.maxScroll) thisObj.step = thisObj.step+thisObj.settings.stepsOnScroll; else if(thisObj.step<thisObj.settings.max-1 && thisObj.step+thisObj.settings.stepsOnScroll>thisObj.settings.max-1 && !thisObj.settings.loop && (thisObj.settings.max-1)-thisObj.lastStep<=thisObj.settings.maxScroll){ thisObj.step = thisObj.settings.max-1; }else return; }else{ if((thisObj.step-thisObj.settings.stepsOnScroll>=thisObj.settings.min || thisObj.settings.loop) && thisObj.lastStep-(thisObj.step-thisObj.settings.stepsOnScroll)<=thisObj.settings.maxScroll) thisObj.step = thisObj.step-thisObj.settings.stepsOnScroll; else if(thisObj.step>thisObj.settings.min && thisObj.step-thisObj.settings.stepsOnScroll<thisObj.settings.min && !thisObj.settings.loop && thisObj.lastStep-thisObj.settings.min<=thisObj.settings.maxScroll) thisObj.step = thisObj.settings.min; else return; } if(thisObj.settings.debug) jQuery('#isalive-'+thisObj.uniqId+'-debuger span:first').html(thisObj.step); clearTimeout(thisObj.wheelTimer); if(!thisObj.animating || (thisObj.animating && thisObj.animationType!='scroll')){ thisObj.animationType='scroll'; thisObj.animateDuration = thisObj.settings.durationTweaks.wheel.duration; thisObj.animateSite(); } else{ thisObj.wheelTimer = setTimeout(function(){ thisObj.animationType='scroll'; thisObj.animateDuration = thisObj.settings.durationTweaks.wheel.duration; thisObj.animateSite(); },20); } } /*DO TOUCH WIPE*/ isAlive.prototype.doWipe = function(value){ var thisObj = this; var directionForward,stepPos,currentPosition,nextPosition,notAllowed; if(!thisObj.allowTouch || thisObj.forceAnimation) return false; (thisObj.animating)?((thisObj.lastStep<thisObj.step)?directionForward=true:directionForward=false):directionForward=null; stepPos = thisObj.getPos(thisObj.lastStep); currentPosition = indexOf(thisObj.settings.wipePoints,stepPos); if(currentPosition==-1){ currentPosition = null; if(stepPos<=thisObj.settings.wipePoints[0]) currentPosition=-0.5; else{ for(var i=0;i<=thisObj.settings.wipePoints.length-2;i++){ if(stepPos>thisObj.settings.wipePoints[i] && stepPos<thisObj.settings.wipePoints[i+1]){ currentPosition = i + 0.5; break; } } if(currentPosition==null) currentPosition=(thisObj.settings.wipePoints.length-1)+0.5; } } if(!thisObj.animating || (thisObj.animating && thisObj.animationType!='wipe') || (thisObj.animating && thisObj.animationType=='wipe' && ((directionForward && value==-1)||(!directionForward && value==1)))){ notAllowed = null; nextPosition = currentPosition; }else{ if(value==1){ if(currentPosition<thisObj.settings.wipePoints.length-1) notAllowed = Math.ceil(currentPosition); else notAllowed = 0; } else{ if(currentPosition>0) notAllowed = Math.floor(currentPosition); else notAllowed = thisObj.settings.wipePoints.length-1; } nextPosition = thisObj.wipePosition; } if(value==1){ if(nextPosition<(thisObj.settings.wipePoints.length-1)) nextPosition = Math.floor(nextPosition+1); else if(thisObj.settings.loop) nextPosition=0; else return; } else{ if(nextPosition>0) nextPosition = Math.ceil(nextPosition-1); else if(thisObj.settings.loop) nextPosition=thisObj.settings.wipePoints.length-1 else return; } if(value==1){ if(nextPosition===notAllowed) return false; thisObj.wipePosition = nextPosition; thisObj.goTo({to:thisObj.settings.wipePoints[thisObj.wipePosition],orientation:'next',animationType:'wipe',duration:thisObj.settings.durationTweaks['touch']['duration'],durationType:thisObj.settings.durationTweaks['touch']['durationType'],minStepDuration:thisObj.settings.durationTweaks['touch']['minStepDuration']}); }else{ if(nextPosition===notAllowed) return false; thisObj.wipePosition = nextPosition; thisObj.goTo({to:thisObj.settings.wipePoints[thisObj.wipePosition],orientation:'prev',animationType:'wipe',duration:thisObj.settings.durationTweaks['touch']['duration'],durationType:thisObj.settings.durationTweaks['touch']['durationType'],minStepDuration:thisObj.settings.durationTweaks['touch']['minStepDuration']}); } } /*DO TOUCH DRAG*/ isAlive.prototype.doDrag = function(value){ var thisObj = this; if(!thisObj.allowTouch || thisObj.forceAnimation) return false; if(thisObj.animating && thisObj.animationType!='drag'){ thisObj.step=Math.round(thisObj.lastStep); thisObj.onComplete=null; } else if(thisObj.animating && thisObj.animationType=='drag' && ((thisObj.lastStep<thisObj.step && value==-1)||(thisObj.lastStep>thisObj.step && value==1))) thisObj.step=Math.round(thisObj.lastStep); if(value==1){ if((thisObj.step+thisObj.settings.stepsOnDrag<=thisObj.settings.max-1 || thisObj.settings.loop) && (thisObj.step+thisObj.settings.stepsOnDrag)-thisObj.lastStep<=thisObj.settings.maxDrag) thisObj.step = thisObj.step+thisObj.settings.stepsOnDrag; else if(thisObj.step<thisObj.settings.max-1 && thisObj.step+thisObj.settings.stepsOnDrag>thisObj.settings.max-1 && !thisObj.settings.loop && (thisObj.settings.max-1)-thisObj.lastStep<=thisObj.settings.maxDrag) thisObj.step = thisObj.settings.max-1; else return; }else{ if((thisObj.step-thisObj.settings.stepsOnDrag>=thisObj.settings.min || thisObj.settings.loop) && thisObj.lastStep-(thisObj.step-thisObj.settings.stepsOnDrag)<=thisObj.settings.maxDrag) thisObj.step = thisObj.step-thisObj.settings.stepsOnDrag; else if(thisObj.step>thisObj.settings.min && thisObj.step-thisObj.settings.stepsOnDrag<thisObj.settings.min && !thisObj.settings.loop && thisObj.lastStep-thisObj.settings.min<=thisObj.settings.maxDrag) thisObj.step = thisObj.settings.min; else return; } if(thisObj.settings.debug) jQuery('#isalive-'+thisObj.uniqId+'-debuger span:first').html(thisObj.step); thisObj.animationType='drag'; thisObj.animateDuration = thisObj.settings.durationTweaks.touch.duration; thisObj.animateSite(); } /*GO TO FUNCTION*/ isAlive.prototype.goTo = function(options){ settings = jQuery.extend({ to:null, duration: null, durationType: 'default', /*default|step*/ orientation:'default', /*default|loop|next|prev*/ animationType:'goTo', onComplete:null, minStepDuration:null, force:false },options); var thisObj = this; var pos,posNext,posPrev; if(thisObj.forceAnimation) return false; pos = settings.to + (thisObj.getLoop(thisObj.lastStep)*thisObj.settings.max); if(thisObj.settings.loop){ if(settings.orientation=='loop'){ if(thisObj.lastStep<=pos) posNext = pos; else posNext = settings.to + ((thisObj.getLoop(thisObj.lastStep)+1)*thisObj.settings.max); if(thisObj.lastStep>=pos) posPrev = pos; else posPrev = settings.to + ((thisObj.getLoop(thisObj.lastStep)-1)*thisObj.settings.max); if(Math.abs(thisObj.lastStep-posNext)>Math.abs(thisObj.lastStep-posPrev)) pos = posPrev; else pos = posNext; } else if(settings.orientation == 'next'){ if(thisObj.lastStep>=pos) pos = settings.to + ((thisObj.getLoop(thisObj.lastStep)+1)*thisObj.settings.max); } else if(settings.orientation == 'prev'){ if(thisObj.lastStep<=pos) pos = settings.to + ((thisObj.getLoop(thisObj.lastStep)-1)*thisObj.settings.max); } } if(!thisObj.animating && pos==thisObj.lastStep) return; thisObj.step = pos; thisObj.animationType = settings.animationType; thisObj.forceAnimation = settings.force; (settings.onComplete!==null)?thisObj.onComplete=settings.onComplete:thisObj.onComplete=null; /*MIN VALUE FOR DURATION*/ if(settings.minStepDuration==null) var minStep = thisObj.settings.minStepDuration; else var minStep = settings.minStepDuration; if(settings.durationType=='step' && settings.duration!=null){ if(settings.duration<minStep) thisObj.animateDuration=Math.abs(thisObj.lastStep-thisObj.step)*minStep; else thisObj.animateDuration=Math.abs(thisObj.lastStep-thisObj.step)*settings.duration; } else{ if(settings.duration==null){ if(thisObj.settings.duration/Math.abs(thisObj.lastStep-thisObj.step)<minStep) thisObj.animateDuration = Math.abs(thisObj.lastStep-thisObj.step)*minStep; else thisObj.animateDuration = thisObj.settings.duration; }else{ if(settings.duration/Math.abs(thisObj.lastStep-thisObj.step)<minStep) thisObj.animateDuration = Math.abs(thisObj.lastStep-thisObj.step)*minStep; else thisObj.animateDuration = settings.duration; } } thisObj.animateSite(); } /*SKIPS TO A POSITION*/ isAlive.prototype.skip = function(step){ var thisObj = this; if(thisObj.forceAnimation) return false; var doSkip = function(step){ var pos,pointFound,pointFoundSelector,direction; var valuesCSS = {}; var valuesClasses = {}; var selector,property,className; pos = thisObj.getPos(thisObj.step); pointFoundSelector = -1; pointFound = -1; while((pos<=step && thisObj.getPos(thisObj.step)<step) || (pos>=step && thisObj.getPos(thisObj.step)>step) || (pos==step && thisObj.getPos(thisObj.step)==step)){ (step>thisObj.step)?direction = 'forward':((pos!=step)?direction = 'backward':direction = 'forward'); if(typeof(thisObj.setArray[direction][pos])!="undefined"){ for(selector in thisObj.setArray[direction][pos]){ if(typeof(valuesCSS[selector]) == "undefined") valuesCSS[selector] = {}; for(property in thisObj.setArray[direction][pos][selector]) valuesCSS[selector][property] = thisObj.setArray[direction][pos][selector][property]; } } if(typeof(thisObj.onOffClassArray[direction][pos])!="undefined"){ for(selector in thisObj.onOffClassArray[direction][pos]){ if(typeof(valuesClasses[selector]) == "undefined") valuesClasses[selector] = {} for(className in thisObj.onOffClassArray[direction][pos][selector]) valuesClasses[selector][className] = thisObj.onOffClassArray[direction][pos][selector][className]; } } if(typeof(thisObj.animPositions[pos])!="undefined"){ for(selector in thisObj.animPositions[pos]){ if(typeof(valuesCSS[selector]) == "undefined") valuesCSS[selector] = {}; for(property in thisObj.animPositions[pos][selector]) valuesCSS[selector][property] = thisObj.animPositions[pos][selector][property]; } } if(thisObj.haveNavPoints){ pointFound=indexOf(thisObj.settings.navPoints,pos); if(pointFound!=-1) pointFoundSelector = pointFound; } if(thisObj.settings.onStep!=null) thisObj.settings.onStep(pos,thisObj.getLoop(thisObj.step),'skip'); (thisObj.getPos(thisObj.step)<step)?pos = pos + 1:pos = pos - 1; } for(selector in valuesCSS) for(property in valuesCSS[selector]) thisObj.setCSS(selector,property,valuesCSS[selector][property]); for(selector in valuesClasses){ for(className in valuesClasses[selector]){ if(valuesClasses[selector][className]==true) jQuery(selector).addClass(className); else jQuery(selector).removeClass(className); } } if(pointFoundSelector!=-1 ){ jQuery(thisObj.settings.navPointsSelector).removeClass(thisObj.settings.navPointsActiveClass); jQuery(thisObj.settings.navPointsSelector).eq(pointFoundSelector).addClass(thisObj.settings.navPointsActiveClass); } step = step + (thisObj.getLoop(thisObj.step)*thisObj.settings.max); thisObj.step = step; thisObj.lastStep = step; } if(thisObj.animating){ thisObj.stop(); setTimeout(function(){ doSkip(step); },25); } else doSkip(step); } /*STOPS ANIMATIONS*/ isAlive.prototype.stopTransitions = function(){ var thisObj = this; for(var selector in thisObj.CSS3TransitionArray){ var CSSValues = {}; for(var property in thisObj.CSS3TransitionArray[selector]) CSSValues[property] = jQuery(selector).css(property); thisObj.CSS3TransitionArray[selector] = {}; thisObj.CSS3ValuesArray[selector] = {}; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); jQuery(selector).css(CSSValues); } } /*STOPS ANIMATIONS*/ isAlive.prototype.stop = function(){ var thisObj = this; if(!thisObj.animating) return true; jQuery(thisObj.TimeLine).stop(); jQuery('.'+thisObj.settings.animateClass).stop(); thisObj.stopTransitions(); thisObj.animating = false; thisObj.animationType='none'; thisObj.forceAnimation = false; thisObj.onComplete = null; thisObj.step = Math.round(thisObj.lastStep); if(thisObj.rebuildOnStop){ thisObj.rebuildLayout(); thisObj.rebuildOnStop = false; } } /*PLAYS ANIMATIONS TO THE NEXT PLAY POINT*/ isAlive.prototype.play = function(options){ var thisObj = this; if(thisObj.forceAnimation || thisObj.settings.playPoints.length<=1) return false; options = jQuery.extend({},options); var pos = Math.floor(thisObj.getPos(thisObj.lastStep)); var max = thisObj.settings.max-1; var found = null; for(var i=pos+1;i<=max;i++) if(indexOf(thisObj.settings.playPoints,i)!=-1){ found = i; break } if(found==null && thisObj.settings.loop) found = thisObj.settings.playPoints[0]; if(found==null) return false; options['to'] = found; options['orientation'] = 'next'; options['animationType'] = 'play'; thisObj.goTo(options); } /*PLAYS BACK ANIMATIONS TO THE PREV PLAY POINT*/ isAlive.prototype.rewind = function(options){ var thisObj = this; if(thisObj.forceAnimation || thisObj.settings.playPoints.length<=1) return false; options = jQuery.extend({},options); var pos = Math.ceil(thisObj.getPos(thisObj.lastStep)); var found = null; for(var i=pos-1;i>=0;i--) if(indexOf(thisObj.settings.playPoints,i)!=-1){ found = i; break } if(found==null && thisObj.settings.loop) found = thisObj.settings.playPoints[thisObj.settings.playPoints.length-1]; if(found==null) return false; options['to'] = found; options['orientation'] = 'prev'; options['animationType'] = 'rewind'; thisObj.goTo(options); } /*AUTOPLAY ANIMATION IN LOOPS*/ isAlive.prototype.autoplay = function(options){ var thisObj = this; if(thisObj.forceAnimation || !thisObj.settings.loop) return false; options = jQuery.extend({},options); var count = false; var loop = 0; if(typeof(options['count'])!="undefined"){ count = options['count']; delete options['count']; } var onLoop = null; if(typeof(options['onLoop'])!="undefined"){ onLoop = options['onLoop']; delete options['onLoop']; } options['animationType'] = 'autoplay'; options['to'] = 0; if(typeof(options['orientation'])=="undefined" || (options['orientation']!="next" && options['orientation']!="prev")) options['orientation'] = "next"; options['onComplete'] = function(){ doAutoplay(); }; var doAutoplay = function(){ if(count===false || count>0){ if(onLoop!=null){ loop++; onLoop(loop); } thisObj.goTo(options); if(count!==false) count--; } }; doAutoplay(); } /*TOGGLE ANIMATION*/ isAlive.prototype.toggle = function(options){ var thisObj = this; if(thisObj.forceAnimation) return false; options = jQuery.extend({},options); options['animationType'] = 'toggle'; if((!thisObj.animating || (thisObj.animating && thisObj.animationType!='toggle') || (thisObj.animating && thisObj.animationType=='toggle' && thisObj.toggleState==-1)) && (thisObj.getPos(thisObj.lastStep)<thisObj.settings.max-1)){ thisObj.toggleState = 1; options['to'] = thisObj.settings.max-1; } else{ thisObj.toggleState = -1; options['to'] = thisObj.settings.min; } thisObj.goTo(options); } /*UNBIND EVENTS*/ isAlive.prototype.destroy = function(){ var thisObj = this; /*UNBIND EVENTS*/ if(thisObj.DOMElement) jQuery(thisObj.mySelector).unbind('.isAlive'); for(var key in thisObj.settings.elements){ if(thisObj.settings.elements[key]['scrollbar']){ jQuery(thisObj.settings.elements[key]['selector']).unbind('.scrollbar'); jQuery(thisObj.settings.elements[key]['selector']).removeAttr('unselectable'); jQuery(thisObj.settings.elements[key]['selector']).removeClass('isalive-nouserselect'); jQuery(thisObj.settings.elements[key]['selector']).removeClass('isalive-notouchaction'); } } /*REMOVE DEBUGER*/ jQuery('#isalive-'+this.uniqId+'-debuger').remove(); /*REMOVE ADDED ID ATTRIBUTES*/ jQuery('[id^="isalive-'+this.uniqId+'-element"]').removeAttr('id'); /*REMOVE ENABLE GPU CLASS*/ jQuery('.'+thisObj.settings.animateClass).removeClass('isalive-enablegpu'); /*REMOVE ADDED CLASSES*/ jQuery('.'+thisObj.settings.animateClass).removeClass(thisObj.settings.animateClass); } /*ISALIVE MAIN OBJECT:END*/ /*JQUERY PLUGIN PART:BEGIN*/ var methods = { create : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])!="undefined") return false; if(typeof(options) == "undefined") options = {}; isAliveObjects[selector] = new isAlive(selector,options); return thisObj; }, destroy : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].destroy(); delete isAliveObjects[selector]; return thisObj; }, goTo : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; if(typeof(options) == "undefined" || typeof(options['to']) == "undefined" || options['to']<0 || options['to']>isAliveObjects[selector].settings.max-1) return false; options['to'] = Math.round(options['to']); isAliveObjects[selector].goTo(options); return thisObj; }, skip : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; if(typeof(options) == "undefined" || typeof(options['to']) == "undefined" || options['to']<0 || options['to']>isAliveObjects[selector].settings.max-1) return false; options['to'] = Math.round(options['to']); isAliveObjects[selector].skip(options['to']); return thisObj; }, play : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].play(options); return thisObj; }, rewind : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].rewind(options); return thisObj; }, autoplay : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].autoplay(options); return thisObj; }, toggle : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].toggle(options); return thisObj; }, stop : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].stop(); return thisObj; }, rebuild : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].rebuildLayout(); return thisObj; }, enableWheel : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].allowWheel = options; return thisObj; }, enableTouch : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].allowTouch = options; return thisObj; }, addOnComplete : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined" || !isAliveObjects[selector].animating) return false; isAliveObjects[selector].onComplete = options; return thisObj; }, getCurrentPosition : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; return isAliveObjects[selector].getPos(isAliveObjects[selector].lastStep); }, getStepPosition : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; return isAliveObjects[selector].getPos(isAliveObjects[selector].step); }, getMaxStep : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; return (isAliveObjects[selector].settings.max-1); }, getAnimationState : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; return (isAliveObjects[selector].animating); }, destroyAll : function(){ for(var selector in isAliveObjects){ isAliveObjects[selector].destroy(); delete isAliveObjects[selector]; } jQuery('style.isalive-style').remove() jQuery(window).unbind('resize.general'); resizeOn = false; return true; }, getBrowser : function(){ return getBrowser(); }, getVersion : function(){ return "1.10.0"; } }; jQuery.fn.isAlive = function(method,options) { if(methods[method]){ var mFunc = methods[method]; return mFunc(this,options); } else return (typeof(method)=='undefined') ? (typeof(isAliveObjects[this.selector])!='undefined') : false; }; /*JQUERY PLUGIN PART:END*/ })(jQuery);
src/jquery.isAlive.js
/* _ __ __ _ | | / /__ _________ ____/ /__ ____ ___ ____ _____ _(_)____ | | /| / / _ \______/ ___/ __ \/ __ / _ \______/ __ `__ \/ __ `/ __ `/ / ___/ | |/ |/ / __/_____/ /__/ /_/ / /_/ / __/_____/ / / / / / /_/ / /_/ / / /__ |__/|__/\___/ \___/\____/\__,_/\___/ /_/ /_/ /_/\__,_/\__, /_/\___/ /____/ jQuery.isAlive(1.10.0) Written by George Cheteles ([email protected]). Licensed under the MIT (https://github.com/georgecheteles/jQuery.isAlive/blob/master/MIT-LICENSE.txt) license. Please attribute the author if you use it. Find me at: [email protected] https://github.com/georgecheteles Last modification on this file: 03 June 2014 */ (function(jQuery) { /*THIS IS THE MAIN ARRAY THAT KEEPS ALL THE OBJECTS*/ var isAliveObjects = []; var incIndex = 0; var browserObj = null; var indexOf = null; var vPArray = {opacity:"opacity",left:"left",right:"right",top:"top",bottom:"bottom",width:"width",height:"height"}; var _fix = {}; var canRGBA = false; var MSPointerEnabled,MSPointerDown,MSPointerMove,MSPointerUp,MSMaxTouchPoints,WheelEvent; var resizeOn = false; var resizeTimer; var windowWidth; var windowHeight; /*CHECK IF BROWSER SUPPORTS RGBA*/ function supportsRGBA(){ var el = document.createElement('foo'); var prevColor = el.style.color; try { el.style.color = 'rgba(0,0,0,0)'; } catch(e) {} return el.style.color != prevColor; } /*COMPARES VERSIONS*/ function ifVersion(value1,cond,value2){ value1 = value1.toString().split('.'); value2 = value2.toString().split('.'); var maxLength = Math.max(value1.length,value2.length); for(var i=0;i<=maxLength-1;i++){ var v1 = (typeof(value1[i])!="undefined") ? parseInt(value1[i]) : 0; var v2 = (typeof(value2[i])!="undefined") ? parseInt(value2[i]) : 0; if(cond=="<" || cond=="<="){ if(v1<v2) return true; if(v1>v2) return false; } else if(cond==">" || cond==">="){ if(v1>v2) return true; if(v1<v2) return false; } else if(cond=="==" && v1!=v2) return false; } if(cond=="==" || cond=="<=" || cond==">=") return true; return false; } /*RETURN THE FIRST FLOAT VALUE*/ function getFloat(value){ return value.match(/[-]?[0-9]*\.?[0-9]+/)[0]; } /*FIXES CSS3 TRANSITION DURATION BUG*/ function breakCSS3(property,value){ var success = false; var fix = function(value,format){ if(success) return value; if(value.indexOf(' ')!=-1){ value = value.split(' '); for(var key in value) value[key] = fix(value[key],format); return value.join(' '); } if(value.indexOf('(')!=-1){ format = value.substr(0,value.indexOf('(')); if(format=='url') return value; value = value.substr(value.indexOf('(')+1,value.indexOf(')')-value.indexOf('(')-1); return format + '(' + fix(value,format) + ')'; } if(value.indexOf(',')!=-1){ value = value.split(','); for(var key in value) value[key] = fix(value[key],format); return value.join(','); } var unitType = value.match('px|%|deg|em'); if(unitType!=null){ unitType = unitType[0]; var fNumber = getFloat(value); if(fNumber!=null){ success = true; return value.replace(fNumber,parseFloat(fNumber) + _fix[unitType]); } } if(format!=null){ if(format=='rgb' || format=='rgba'){ success = true; if(value<255) return parseInt(value) + 1; else return parseInt(value) - 1; } if(property==vP('transform')){ if(format.indexOf('matrix')==0 || format.indexOf('scale')==0){ success = true; return parseFloat(value) + 0.001; } } if(property=='-webkit-filter'){ if(format=='grayscale' || format=='sepia' || format=='invert' || format=='opacity'){ if(value<=0.5) value = parseFloat(value) + 0.001; else value = parseFloat(value) - 0.001; success = true; return value; } if(format=='brightness' || format=='contrast' || format=='saturate'){ success = true; return parseFloat(value) + 0.001; } } } return value; } if(property=='opacity'){ if(value<=0.5) value = parseFloat(value) + _fix['opacity']; else value = parseFloat(value) - _fix['opacity']; } else if(isNumber(value)) value = parseFloat(value) + _fix['px']; else value = fix(value,null); return value; } /*EASING TO BEZIER*/ function convertEasing(value){ var easings = {'swing':'0.02,0.01,0.47,1','easeInSine':'0.47,0,0.745,0.715','easeOutSine':'0.39,0.575,0.565,1','easeInOutSine':'0.445,0.05,0.55,0.95','easeInQuad':'0.55,0.085,0.68,0.53','easeOutQuad':'0.25,0.46,0.45,0.94','easeInOutQuad':'0.455,0.03,0.515,0.955','easeInCubic':'0.55,0.055,0.675,0.19','easeOutCubic':'0.215,0.61,0.355,1','easeInOutCubic':'0.645,0.045,0.355,1','easeInQuart':'0.895,0.03,0.685,0.22','easeOutQuart':'0.165,0.84,0.44,1','easeInOutQuart':'0.77,0,0.175,1','easeInQuint':'0.755,0.05,0.855,0.06','easeOutQuint':'0.23,1,0.32,1','easeInOutQuint':'0.86,0,0.07,1','easeInExpo':'0.95,0.05,0.795,0.035','easeOutExpo':'0.19,1,0.22,1','easeInOutExpo':'1,0,0,1','easeInCirc':'0.6,0.04,0.98,0.335','easeOutCirc':'0.075,0.82,0.165,1','easeInOutCirc':'0.785,0.135,0.15,0.86','easeInBack':'0.6,-0.28,0.735,0.045','easeOutBack':'0.175,0.885,0.32,1.275','easeInOutBack':'0.68,-0.55,0.265,1.55'}; if(typeof(easings[value])!='undefined') return 'cubic-bezier('+easings[value]+')'; return value; } /*FIX SPACES FOR CSS VALUES*/ function fixSpaces(params){ if(params.indexOf(' ')==-1) return params; params = jQuery.trim(params).split(' '); var ret = []; for(var key in params) if(params[key]!="") ret.push(params[key]); params = ret.join(' '); if(params.indexOf('(')!=-1){ var bracketCount = 0; ret = ""; for(var c=0;c<params.length;c++){ if(params.charAt(c)=='(') bracketCount++; else if(params.charAt(c)==')') bracketCount--; if(params.charAt(c)!=' ' || (params.charAt(c)==' ' && bracketCount==0)) ret = ret + params.charAt(c); } params = ret; } return params; } /*CONVERT IN PROPERTY LIKE STYLE OBJ*/ function propertyToStyle(property,firstUp){ if(property.indexOf('-')!=-1){ if(property.charAt(0)=='-') property = property.substr(1); property = property.split('-'); for(var key in property) if(key>0 || firstUp) property[key] = property[key].charAt(0).toUpperCase()+property[key].substr(1); property = property.join(''); } return property; } /*GET TEXT BETWEEN BRACKETS*/ function getBetweenBrackets(text,doEval){ var lastBracket; for(lastBracket=text.length;lastBracket>=0;lastBracket--) if(text.charAt(lastBracket)==')') break; if(typeof(doEval)=='undefined') return text.substr(text.indexOf('(')+1,lastBracket-text.indexOf('(')-1); var evalExp = text.substr(text.indexOf('(')+1,lastBracket-text.indexOf('(')-1); try{ eval("evalExp = "+evalExp+';'); }catch(err){} return evalExp + text.substr(lastBracket+1,text.length-lastBracket-1); } /*CONVERT COLORS TO CODE*/ function nameToRgb(name){ var colors={"aliceblue":"240,248,255","antiquewhite":"250,235,215","aqua":"0,255,255","aquamarine":"127,255,212","azure":"240,255,255","beige":"245,245,220","bisque":"255,228,196","black":"0,0,0","blanchedalmond":"255,235,205","blue":"0,0,255","blueviolet":"138,43,226","brown":"165,42,42","burlywood":"222,184,135","cadetblue":"95,158,160","chartreuse":"127,255,0","chocolate":"210,105,30","coral":"255,127,80","cornflowerblue":"100,149,237","cornsilk":"255,248,220","crimson":"220,20,60","cyan":"0,255,255","darkblue":"0,0,139","darkcyan":"0,139,139","darkgoldenrod":"184,134,11","darkgray":"169,169,169","darkgreen":"0,100,0","darkkhaki":"189,183,107","darkmagenta":"139,0,139","darkolivegreen":"85,107,47","darkorange":"255,140,0","darkorchid":"153,50,204","darkred":"139,0,0","darksalmon":"233,150,122","darkseagreen":"143,188,143","darkslateblue":"72,61,139","darkslategray":"47,79,79","darkturquoise":"0,206,209","darkviolet":"148,0,211","deeppink":"255,20,147","deepskyblue":"0,191,255","dimgray":"105,105,105","dodgerblue":"30,144,255","firebrick":"178,34,34","floralwhite":"255,250,240","forestgreen":"34,139,34","fuchsia":"255,0,255","gainsboro":"220,220,220","ghostwhite":"248,248,255","gold":"255,215,0","goldenrod":"218,165,32","gray":"128,128,128","green":"0,128,0","greenyellow":"173,255,47","honeydew":"240,255,240","hotpink":"255,105,180","indianred ":"205,92,92","indigo ":"75,0,130","ivory":"255,255,240","khaki":"240,230,140","lavender":"230,230,250","lavenderblush":"255,240,245","lawngreen":"124,252,0","lemonchiffon":"255,250,205","lightblue":"173,216,230","lightcoral":"240,128,128","lightcyan":"224,255,255","lightgoldenrodyellow":"250,250,210","lightgrey":"211,211,211","lightgreen":"144,238,144","lightpink":"255,182,193","lightsalmon":"255,160,122","lightseagreen":"32,178,170","lightskyblue":"135,206,250","lightslategray":"119,136,153","lightsteelblue":"176,196,222","lightyellow":"255,255,224","lime":"0,255,0","limegreen":"50,205,50","linen":"250,240,230","magenta":"255,0,255","maroon":"128,0,0","mediumaquamarine":"102,205,170","mediumblue":"0,0,205","mediumorchid":"186,85,211","mediumpurple":"147,112,216","mediumseagreen":"60,179,113","mediumslateblue":"123,104,238","mediumspringgreen":"0,250,154","mediumturquoise":"72,209,204","mediumvioletred":"199,21,133","midnightblue":"25,25,112","mintcream":"245,255,250","mistyrose":"255,228,225","moccasin":"255,228,181","navajowhite":"255,222,173","navy":"0,0,128","oldlace":"253,245,230","olive":"128,128,0","olivedrab":"107,142,35","orange":"255,165,0","orangered":"255,69,0","orchid":"218,112,214","palegoldenrod":"238,232,170","palegreen":"152,251,152","paleturquoise":"175,238,238","palevioletred":"216,112,147","papayawhip":"255,239,213","peachpuff":"255,218,185","peru":"205,133,63","pink":"255,192,203","plum":"221,160,221","powderblue":"176,224,230","purple":"128,0,128","red":"255,0,0","rosybrown":"188,143,143","royalblue":"65,105,225","saddlebrown":"139,69,19","salmon":"250,128,114","sandybrown":"244,164,96","seagreen":"46,139,87","seashell":"255,245,238","sienna":"160,82,45","silver":"192,192,192","skyblue":"135,206,235","slateblue":"106,90,205","slategray":"112,128,144","snow":"255,250,250","springgreen":"0,255,127","steelblue":"70,130,180","tan":"210,180,140","teal":"0,128,128","thistle":"216,191,216","tomato":"255,99,71","turquoise":"64,224,208","violet":"238,130,238","wheat":"245,222,179","white":"255,255,255","whitesmoke":"245,245,245","yellow":"255,255,0","yellowgreen":"154,205,50"}; if(typeof(colors[name.toLowerCase()])!="undefined"){ if(canRGBA) return "rgba("+colors[name.toLowerCase()]+",1)"; else return "rgb("+colors[name.toLowerCase()]+")"; } return false; } /*CONVERTING HEX TO RGB*/ function hexToRgb(hex) { var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if(result){ if(canRGBA) return "rgba("+parseInt(result[1],16)+","+parseInt(result[2],16)+","+parseInt(result[3], 16)+",1)"; else return "rgb("+parseInt(result[1],16)+","+parseInt(result[2],16)+","+parseInt(result[3], 16)+")"; } return false; } /*ACTION ON RESIZE*/ function onResizeAction(e){ var key; clearTimeout(resizeTimer); resizeTimer = setTimeout(function(){ if(windowWidth!=jQuery(window).width() || windowHeight!=jQuery(window).height()){ windowWidth = jQuery(window).width(); windowHeight = jQuery(window).height(); for(key in isAliveObjects) if(isAliveObjects[key].settings.rebuildOnResize) isAliveObjects[key].rebuildLayout(); } },250); } /*VALIDATES BROWSERS*/ function validateBrowsers(exp){ var isValid = function(browser){ var validBrowser = false; if(browserObj[browser]) validBrowser = true; if(browser=="msie7-" && browserObj.msie && parseInt(browserObj.version)<7) validBrowser = true; if(browser=="msie7" && browserObj.msie && parseInt(browserObj.version)==7) validBrowser = true; if(browser=="msie8" && browserObj.msie && parseInt(browserObj.version)==8) validBrowser = true; if(browser=="msie9" && browserObj.msie && parseInt(browserObj.version)==9) validBrowser = true; if(browser=="msie10" && browserObj.msie && parseInt(browserObj.version)==10) validBrowser = true; if(browser=="msie11" && browserObj.msie && parseInt(browserObj.version)==11) validBrowser = true; if(browser=="msie11+" && browserObj.msie && parseInt(browserObj.version)>11) validBrowser = true; if(browser=="unknown" && typeof(browserObj.webkit)=="undefined" && typeof(browserObj.mozilla)=="undefined" && typeof(browserObj.opera)=="undefined" && typeof(browserObj.msie)=="undefined") validBrowser = true; return validBrowser; } var valid = false; exp = exp.split("|"); for(var key in exp){ if(exp[key].indexOf("&")!=-1){ var temp = exp[key].split("&"); if(temp.length==2 && isValid(temp[0]) && isValid(temp[1])) valid = true; } else if(exp[key].indexOf("!")!=-1){ var temp = exp[key].split("!"); if(temp.length==2 && isValid(temp[0]) && !isValid(temp[2])) valid = true; } else if(isValid(exp[key])) valid = true; } return valid; } /*CONVERT TO STRING*/ function toString(value){ if(typeof(value)=='function') return sdbmCode(value.toString()).toString(); return value.toString(); } /*MAKES UNIQUE HASH FOR A STRING*/ function sdbmCode(str){ var hash = 0; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); hash = c + (hash << 6) + (hash << 16) - hash; } return hash; } /*CHECKS IF NUMBER*/ function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } /* DETECTS BROWSER / ENGINE / VERSION (THANKS TO KENNEBEC)*/ function getBrowser(){ var browser = {}, temp; var ua = (navigator.userAgent||navigator.vendor||window.opera); var M = ua.match(/(konqueror|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || []; M = M[2] ? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?']; temp = ua.match(/version\/([\.\d]+)/i); if(temp!=null) M[1] = temp[1]; browser[M[0].toLowerCase()] = true; if(browser.trident){ browser['msie'] = true; temp = /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || []; browser['version'] = (temp[1] || ''); delete browser.trident; } else{ if(browser.chrome || browser.safari) browser['webkit'] = true; if(browser.firefox) browser['mozilla'] = true; browser['version'] = M[1]; } var mobile = (/(android|bb\d+|meego).+mobile|webos|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(ua)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(ua.substr(0,4))); if(mobile) browser.mobile = true; browser.isTouch = ('ontouchstart' in document.documentElement || window.navigator.maxTouchPoints || window.navigator.msMaxTouchPoints) ? true : false; return browser; } /* CHECKS IF PARAMS ARE DETECTED */ function isDinamic(params){ if(typeof(params) == "function") return true; if(params.toString().indexOf('eval(')!==-1) return true; return false; } /*MAKES THE CSS CHANGES FOR EACH BROWSER*/ function vP(property){ if(typeof(vPArray[property])=="undefined"){ vPArray[property] = false; var el = document.createElement('foo'); var pLower = propertyToStyle(property); var pUpper = propertyToStyle(property,true); if(typeof(el.style[pLower])!="undefined" || typeof(el.style[pUpper])!="undefined") vPArray[property] = property; else if(property.indexOf('-webkit-')!=0 && property.indexOf('-moz-')!=0 && property.indexOf('-ms-')!=0 && property.indexOf('-o-')!=0 && property.indexOf('-khtml-')!=0){ if(browserObj.webkit){ var v = propertyToStyle("-webkit-"+property); if(typeof(el.style[v])!="undefined") vPArray[property] = "-webkit-"+property; } else if(browserObj.mozilla){ var v = propertyToStyle("-moz-"+property,true); if(typeof(el.style[v])!="undefined") vPArray[property] = "-moz-"+property; } else if(browserObj.msie){ var v = propertyToStyle("-ms-"+property); if(typeof(el.style[v])!="undefined") vPArray[property] = "-ms-"+property; } else if(browserObj.opera){ var v = propertyToStyle("-o-"+property,true); if(typeof(el.style[v])!="undefined") vPArray[property] = "-o-"+property; } else if(browserObj.konqueror){ var v = propertyToStyle("-khtml-"+property,true); if(typeof(el.style[v])!="undefined") vPArray[property] = "-khtml-"+property; } } } return vPArray[property]; } /*CALCULATE THE CSS PROPERTY AT A POSITION*/ function getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd){ valStart = valStart.toString(); valEnd = valEnd.toString(); var doRecursive = function(valStart,valEnd,colorFound){ if(valStart==valEnd) return valStart; if(valStart.indexOf(' ')!=-1){ var value = []; valStart = valStart.split(' '); valEnd = valEnd.split(' '); for(var key in valStart) value.push(doRecursive(valStart[key],valEnd[key])); return value.join(' '); } if(valStart.indexOf('(')!=-1){ var format = valStart.substr(0,valStart.indexOf('(')); valStart = valStart.substr(valStart.indexOf('(')+1,valStart.indexOf(')')-valStart.indexOf('(')-1); valEnd = valEnd.substr(valEnd.indexOf('(')+1,valEnd.indexOf(')')-valEnd.indexOf('(')-1); return format + '(' + doRecursive(valStart,valEnd,(format=='rgb' || format=='rgba')) + ')'; } if(valStart.indexOf(',')!=-1){ var value = []; valStart = valStart.split(','); valEnd = valEnd.split(','); for(var key in valStart) value.push(doRecursive(valStart[key],valEnd[key],(colorFound && key<3))); return value.join(','); } if(isNumber(valStart)) var format = false; else{ var format = valStart.replace(getFloat(valStart),'$'); valStart = getFloat(valStart); valEnd = getFloat(valEnd); } valStart = parseFloat(valStart); valEnd = parseFloat(valEnd); var value = Math.floor((valStart+((valEnd-valStart)*((pos-stepStart)/(stepEnd-stepStart))))*1000)/1000; if(colorFound) return Math.round(Math.min(255,Math.max(0,value))); if(format!==false) return format.replace('$',value); return value; } return doRecursive(valStart,valEnd); } /*ISALIVE MAIN OBJECT:BEGIN*/ function isAlive(selector,options){ this.mySelector = selector; this.TimeLine; this.step=0; this.lastStep=0; this.animating = false; this.forceAnimation = false; this.wheelTimer; this.animPositions = []; this.animateDuration; this.wipePosition; this.jumpPosition; this.animationType='none'; this.allowWheel = true; this.allowTouch = true; this.scrollbarActive = null; this.waitWheellEnd = false; this.cssDinamicElements = []; this.params = {}; this.onComplete = null; this.uniqId = incIndex; this.functionsArray = {}; this.haveNavPoints; this.rebuildOnStop = false; this.scrollBarPosition = 0; this.toggleState = 0; this.CSS3DefaultTransitionArray = {}; this.CSS3TransitionArray = {}; this.CSS3ValuesArray = {}; this.JSValuesArray = {}; this.DOMElement = false; /* MY CLASS/SET ARRAYS */ this.setArray = {}; this.onOffClassArray = {}; this.settings = jQuery.extend(true,{},{ elements:{}, elementsType:"linear", /*linear|tree*/ duration: 1000, durationTweaks:{}, /*obj: {wheel|touch|scrollBar:duration|durationType|minStepDuration}*/ enableWheel:true, wheelType:"scroll", /*scroll|jump*/ wheelActions:{}, jumpPoints:[], max:null, min:0, maxScroll:1000000, maxDrag:1000000, debug:false, easing:'linear', JSEasing:null, CSS3Easing:null, start:0, loop:false, preventWheel:true, navPoints:[], navPointsSelector:null, navPointsActiveClass:null, navPointsClickEvent:false, enableTouch:false, touchType:'drag',/*drag|wipe*/ touchActions:{}, touchXFrom:null, touchYFrom:null, wipePoints:[], preventTouch:true, animateClass:'isalive-'+incIndex, rebuildOnResize:true, playPoints:[], stepsOnScroll:1, stepsOnDrag:1, stepsOnScrollbar:1, minStepDuration:0, initCSS:false, useCSS3:false, scrollbarType:'scroll',/*scroll|jump*/ scrollbarPoints:[], scrollbarActiveClass:null, enableScrollbarTouch:false, wheelDelay:250, /*number or false*/ enableGPU:false, /*false|true|webkit|chrome|safari|mobile*/ useIdAttribute:false, elementTweaks:{'left':0,'top':0,'width':0,'height':0}, onStep:null, onLoadingComplete:null, onRebuild:null },options); /*MAKES THE PLUGIN INITIOALIZATION*/ this.initAnimations(); /*CALL ONLOADINGCOMPLETE FUNCTION*/ if(this.settings.onLoadingComplete!=null) this.settings.onLoadingComplete(selector); } /* LOGS IN DEBUGER */ isAlive.prototype.log = function(value){ if(this.settings.debug) jQuery('#isalive-'+this.uniqId+'-debuger').append('<br/>'+value); } /*GET LOOP VALUE*/ isAlive.prototype.getLoop = function(value){ return Math.floor(value/this.settings.max); } /* CONVERTS REAL POSITION TO RANGE POSITION */ isAlive.prototype.getPos = function(value){ if(value%this.settings.max<0) return this.settings.max+(value%this.settings.max); else return value%this.settings.max; } /*ANIMATE FUNCTION*/ isAlive.prototype.animate = function(animType,selector,property,value,duration,easing,step){ var thisObj = this; switch(animType){ case 1: /*DELETE CSS3 VALUES*/ if(typeof(thisObj.CSS3TransitionArray[selector])!="undefined" && typeof(thisObj.CSS3TransitionArray[selector][property])!="undefined"){ delete thisObj.CSS3TransitionArray[selector][property]; delete thisObj.CSS3ValuesArray[selector][property]; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); } /*DO ANIMATION*/ var animateObj = {}; animateObj[property] = value; jQuery(selector).animate(animateObj,{duration:duration,easing:easing,queue:false}); break; case 2: /*DELETE JS VALUES IF EXIST*/ if(typeof(thisObj.JSValuesArray[selector][property])=="undefined") thisObj.JSValuesArray[selector][property] = thisObj.animPositions[Math.round(thisObj.getPos(step))][selector][property].toString(); /*DO ANIMATION*/ var start = thisObj.JSValuesArray[selector][property]; var end = value.toString(); var tempObj = {}; tempObj[property+'Timer']="+=100"; jQuery(selector).animate(tempObj,{duration:duration,easing:easing,queue:false, step: function(step,fx){ thisObj.setCSS(selector,property,getAtPosValue(step-fx.start,start,end,0,100)); } }); break; case 3: /*DELETE VALUE IF ELEMENT IS ANIMATED ALSO BY JS*/ if(typeof(thisObj.JSValuesArray[selector])!="undefined" && typeof(thisObj.JSValuesArray[selector][property])!="undefined") delete thisObj.JSValuesArray[selector][property]; /*SET TRANSITION AND BREAK CSS3 BUG IF NEEDED*/ thisObj.CSS3TransitionArray[selector][property] = property+' '+duration+'ms '+easing+' 0s'; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); if(typeof(thisObj.CSS3ValuesArray[selector][property])!="undefined" && thisObj.CSS3ValuesArray[selector][property]==value) value = breakCSS3(property,value); thisObj.CSS3ValuesArray[selector][property] = value; /*DO ANIMATION*/ jQuery(selector).css(property,value); break; } } /*SET CSS VALUES*/ isAlive.prototype.setCSS = function(selector,property,value){ var thisObj = this; if(property.indexOf('F:')==0){ thisObj.JSValuesArray[selector][property] = value; thisObj.functionsArray[property](selector,value); return; } if(property=="scrollTop"){ jQuery(selector).scrollTop(value); return; } if(property=="scrollLeft"){ jQuery(selector).scrollLeft(value); return; } if(property==vP('transition')){ jQuery(selector).css(property,thisObj.getTransitionArray(selector,value)); return; } if(typeof(thisObj.CSS3TransitionArray[selector])!="undefined" && typeof(thisObj.CSS3TransitionArray[selector][property])!="undefined"){ delete thisObj.CSS3TransitionArray[selector][property]; delete thisObj.CSS3ValuesArray[selector][property]; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); } if(typeof(thisObj.JSValuesArray[selector])!="undefined" && typeof(thisObj.JSValuesArray[selector][property])!="undefined") thisObj.JSValuesArray[selector][property] = value; jQuery(selector).css(property,value); } /* REPLACES PARAMS */ isAlive.prototype.convertParams = function(params,format){ var thisObj = this; var stringPositions = {top:"0%",center:"50%",bottom:"100%",left:"0%",right:"100%"}; if(typeof(params)!="function"){ params = params.toString(); params = params.replace(/elementLeft/g,thisObj.params.elementLeft.toString()); params = params.replace(/elementTop/g,thisObj.params.elementTop.toString()); params = params.replace(/elementWidth/g,thisObj.params.elementWidth.toString()); params = params.replace(/elementHeight/g,thisObj.params.elementHeight.toString()); params = params.replace(/documentWidth/g,thisObj.params.documentWidth.toString()); params = params.replace(/documentHeight/g,thisObj.params.documentHeight.toString()); params = params.replace(/windowWidth/g,thisObj.params.windowWidth.toString()); params = params.replace(/windowHeight/g,thisObj.params.windowHeight.toString()); } else params = params(thisObj.mySelector,thisObj.params).toString(); var doRecursive = function(params){ if(params.indexOf(' ')!=-1){ params = params.split(' '); for(var key in params) params[key] = doRecursive(params[key]); return params.join(' '); } if(params.indexOf('(')!=-1 && params.substr(0,params.indexOf('('))!='eval'){ var format = params.substr(0,params.indexOf('(')); if(format=="url") return params; if(format=='rgb' && canRGBA) return 'rgba(' + doRecursive(getBetweenBrackets(params)) + ',1)'; return format + '(' + doRecursive(getBetweenBrackets(params)) + ')'; } if(params.indexOf(',')!=-1){ params = params.split(','); for(var key in params) params[key] = doRecursive(params[key]); return params.join(','); } if(params.indexOf('(')!=-1 && params.substr(0,params.indexOf('('))=='eval') return getBetweenBrackets(params,true); if(typeof(stringPositions[params])!="undefined") return stringPositions[params]; if(params.charAt(0)=="#"){ var convertValue = hexToRgb(params); if(convertValue!=false) return convertValue; } var convertValue = nameToRgb(params); if(convertValue!=false) return convertValue; return params; } params = doRecursive(fixSpaces(params)); if(typeof(format)!='undefined') params = format.replace('(X)','('+params+')').replace('Xpx',params+'px').replace('X%',params+'%').replace('Xdeg',params+'deg').replace('Xem',params+'em'); if(isNumber(params)) return parseFloat(params); return params; } /* CREATES AND GETS CSS3 ARRAY */ isAlive.prototype.getTransitionArray = function(selector,value){ var thisObj = this; if(typeof(value)!="undefined"){ thisObj.CSS3DefaultTransitionArray[selector] = {}; if(value.indexOf('cubic-bezier')==-1) var tempArray = value.split(','); else{ var tempArray = value.split('('); for (var key in tempArray){ if(tempArray[key].indexOf(')')!=-1){ tempArray[key] = tempArray[key].split(')'); tempArray[key][0] = tempArray[key][0].replace(/,/g,'*CHAR*'); tempArray[key] = tempArray[key].join(')'); } } tempArray = tempArray.join('(').split(','); } for(key in tempArray){ var temp = tempArray[key].split(' '); var property = vP(temp[0]); if(property) thisObj.CSS3DefaultTransitionArray[selector][property] = tempArray[key].replace(temp[0],property).replace(/\*CHAR\*/g,","); } } var tempObj = {}; if(typeof(thisObj.CSS3DefaultTransitionArray[selector])!="undefined") tempObj = jQuery.extend({},tempObj,thisObj.CSS3DefaultTransitionArray[selector]); if(typeof(thisObj.CSS3TransitionArray[selector])!="undefined") tempObj = jQuery.extend({},tempObj,thisObj.CSS3TransitionArray[selector]); var rt = ""; for(var key in tempObj){ if(rt=="") rt = tempObj[key]; else rt = rt + "," + tempObj[key]; } if(rt=="") rt = "all 0s"; return rt; } /*REMAKES PAGE LAYOUT*/ isAlive.prototype.rebuildLayout = function(){ var thisObj = this; var key,selector,property,valStart,valEnd,stepStart,stepEnd,value,pos,valUnder,valAbove,stepFrom,oldValue; var changedElements = []; if(!thisObj.animating){ thisObj.params.windowWidth = jQuery(window).width(); thisObj.params.windowHeight = jQuery(window).height(); thisObj.params.documentWidth = jQuery(document).width(); thisObj.params.documentHeight = jQuery(document).height(); if(thisObj.DOMElement){ thisObj.params.elementLeft = jQuery(thisObj.mySelector).offset().left; thisObj.params.elementTop = jQuery(thisObj.mySelector).offset().top; thisObj.params.elementWidth = jQuery(thisObj.mySelector).width(); thisObj.params.elementHeight = jQuery(thisObj.mySelector).height(); } /* RESET ALL DINAMIC ELEMENTS*/ for(key in thisObj.cssDinamicElements){ if(thisObj.cssDinamicElements[key]['method']=="static"){ /*REPOSITION STATIC ELEMNTS*/ selector = thisObj.cssDinamicElements[key]['selector']; property = thisObj.cssDinamicElements[key]['property']; value = thisObj.convertParams(thisObj.cssDinamicElements[key]['value'],thisObj.cssDinamicElements[key]['format']); thisObj.setCSS(selector,property,value); } else if(thisObj.cssDinamicElements[key]['method']=="animate"){ /*REPOSITION ANIMATE*/ selector = thisObj.cssDinamicElements[key]['selector']; property = thisObj.cssDinamicElements[key]['property']; valStart = thisObj.convertParams(thisObj.cssDinamicElements[key]['value-start'],thisObj.cssDinamicElements[key]['format']); valEnd = thisObj.convertParams(thisObj.cssDinamicElements[key]['value-end'],thisObj.cssDinamicElements[key]['format']); if(thisObj.cssDinamicElements[key]['scrollbar']==true){ thisObj.settings.elements[thisObj.cssDinamicElements[key]['key']]['value-start']=valStart; thisObj.settings.elements[thisObj.cssDinamicElements[key]['key']]['value-end']=valEnd; } stepStart = thisObj.cssDinamicElements[key]['step-start'] stepEnd = thisObj.cssDinamicElements[key]['step-end'] for(pos=stepStart;pos<=stepEnd;pos++){ value = getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd); thisObj.animPositions[pos][selector][property]=value; } if(typeof(changedElements[selector])=="undefined") changedElements[selector] = []; if(indexOf(changedElements[selector],property)==-1) changedElements[selector].push(property); } else if(thisObj.cssDinamicElements[key]['method']=="set"){ /*REPOSITION SET*/ selector = thisObj.cssDinamicElements[key]['selector']; property = thisObj.cssDinamicElements[key]['property']; stepFrom = thisObj.cssDinamicElements[key]['step-from']; valAbove = thisObj.cssDinamicElements[key]['value-above']; if(isDinamic(valAbove)){ valAbove = thisObj.convertParams(valAbove,thisObj.cssDinamicElements[key]['format']); thisObj.setArray['forward'][stepFrom][selector][property] = valAbove; } valUnder = thisObj.cssDinamicElements[key]['value-under']; if(isDinamic(valUnder)){ valUnder = thisObj.convertParams(valUnder,thisObj.cssDinamicElements[key]['format']); thisObj.setArray['backward'][stepFrom][selector][property] = valUnder; } if(typeof(changedElements[selector])=="undefined") changedElements[selector] = []; if(indexOf(changedElements[selector],property)==-1) changedElements[selector].push(property); } else if(thisObj.cssDinamicElements[key]['method']=="animate-set"){ /*REPOSITION ANIMATE-SET*/ selector = thisObj.cssDinamicElements[key]['selector']; property = thisObj.cssDinamicElements[key]['property']; valStart = thisObj.convertParams(thisObj.cssDinamicElements[key]['value-start'],thisObj.cssDinamicElements[key]['format']); valEnd = thisObj.convertParams(thisObj.cssDinamicElements[key]['value-end'],thisObj.cssDinamicElements[key]['format']); stepStart = thisObj.cssDinamicElements[key]['step-start']; stepEnd = thisObj.cssDinamicElements[key]['step-end']; moveOn = thisObj.cssDinamicElements[key]['move-on']; for(pos=stepStart;pos<=stepEnd;pos++){ if((pos-stepStart)%moveOn==0){ value = getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd); if(pos>stepStart){ thisObj.setArray['forward'][pos][selector][property] = value; thisObj.setArray['backward'][pos][selector][property] = oldValue; } oldValue = value; } } if(typeof(changedElements[selector])=="undefined") changedElements[selector] = []; if(indexOf(changedElements[selector],property)==-1) changedElements[selector].push(property); } } /* REMAKE THE PAGE LAYOUT */ for(selector in changedElements){ for(key in changedElements[selector]){ property = changedElements[selector][key]; value = null; for(pos=thisObj.getPos(Math.round(thisObj.lastStep));pos>=0;pos--){ if(typeof(thisObj.setArray['forward'][pos])!="undefined" && typeof(thisObj.setArray['forward'][pos][selector])!="undefined" && typeof(thisObj.setArray['forward'][pos][selector][property])!="undefined") value = thisObj.setArray['forward'][pos][selector][property]; else if(typeof(thisObj.animPositions[pos])!="undefined" && typeof(thisObj.animPositions[pos][selector])!="undefined" && typeof(thisObj.animPositions[pos][selector][changedElements[selector][key]])!="undefined") value = thisObj.animPositions[pos][selector][changedElements[selector][key]]; if(value!=null){ thisObj.setCSS(selector,changedElements[selector][key],value); delete changedElements[selector][key]; break; } } } } for(selector in changedElements){ for(key in changedElements[selector]){ property = changedElements[selector][key]; value = null; for(pos=thisObj.getPos(Math.round(thisObj.lastStep))+1;pos<=thisObj.getPos(thisObj.settings.max-1);pos++){ if(typeof(thisObj.setArray['backward'][pos])!="undefined" && typeof(thisObj.setArray['backward'][pos][selector])!="undefined" && typeof(thisObj.setArray['backward'][pos][selector][property])!="undefined") value = thisObj.setArray['backward'][pos][selector][property]; else if(typeof(thisObj.animPositions[pos])!="undefined" && typeof(thisObj.animPositions[pos][selector])!="undefined" && typeof(thisObj.animPositions[pos][selector][changedElements[selector][key]])!="undefined") value = thisObj.animPositions[pos][selector][changedElements[selector][key]]; if(value!=null){ thisObj.setCSS(selector,changedElements[selector][key],value); break; } } } } /*CALLS THE ONREBUILD EVENT*/ if(thisObj.settings.onRebuild!=null) thisObj.settings.onRebuild(thisObj.params,thisObj.getPos(thisObj.step),Math.floor(thisObj.step/(thisObj.settings.max+1))); } else thisObj.rebuildOnStop = true; } /*GETS START VALUES*/ isAlive.prototype.getStartCssValue = function(index){ var key,pos,posFrom; var thisObj = this; if(thisObj.settings.elements[index]['method']=='animate' || thisObj.settings.elements[index]['method']=='animate-set') posFrom = parseInt(thisObj.settings.elements[index]['step-start']); else if(thisObj.settings.elements[index]['method']=='set') posFrom = parseInt(thisObj.settings.elements[index]['step-from']); for(pos=posFrom;pos>=0;pos--){ for(key in thisObj.settings.elements){ if(key!=index && thisObj.settings.elements[key]['selector']==thisObj.settings.elements[index]['selector'] && thisObj.settings.elements[key]['property']==thisObj.settings.elements[index]['property'] && thisObj.settings.elements[key]['method']=="set" && thisObj.settings.elements[key]['step-from']==pos) return thisObj.settings.elements[key]['value-above']; else if(key!=index && thisObj.settings.elements[key]['selector']==thisObj.settings.elements[index]['selector'] && thisObj.settings.elements[key]['property']==thisObj.settings.elements[index]['property'] && (thisObj.settings.elements[key]['method']=="animate" || thisObj.settings.elements[key]['method']=="animate-set") && thisObj.settings.elements[key]['step-end']==pos) return thisObj.settings.elements[key]['value-end']; else if(key!=index && thisObj.settings.elements[key]['selector']==thisObj.settings.elements[index]['selector'] && thisObj.settings.elements[key]['property']==thisObj.settings.elements[index]['property'] && thisObj.settings.elements[key]['method']=="set@start" && pos==thisObj.settings.start) return thisObj.settings.elements[key]['value']; } } if(thisObj.settings.elements[index]['property']=="scrollTop") return jQuery(thisObj.settings.elements[index]['selector']).scrollTop(); if(thisObj.settings.elements[index]['property']=="scrollLeft") return jQuery(thisObj.settings.elements[index]['selector']).scrollLeft(); if(thisObj.settings.elements[index]['property'].indexOf('F:')==0) return 0; return jQuery(thisObj.settings.elements[index]['selector']).css(thisObj.settings.elements[index]['property']); } /*FUNCTION FOR BIND MOUSE AND SCROLL EVENTS*/ isAlive.prototype.bindScrollTouchEvents = function(){ var thisObj = this; /* BIND SCROLL EVENTS */ if(thisObj.settings.enableWheel){ jQuery(thisObj.mySelector).bind(WheelEvent+'.isAlive',function(e){ var wheelValue; (e.type=='wheel') ? wheelValue = (e.originalEvent.deltaY > 0) : ((e.type=='mousewheel') ? wheelValue = (e.originalEvent.wheelDelta < 0) : wheelValue = (e.originalEvent.detail > 0)); (thisObj.settings.wheelType=="scroll") ? ((wheelValue) ? thisObj.doScroll(thisObj.settings.wheelActions.down) : thisObj.doScroll(thisObj.settings.wheelActions.up)) : ((wheelValue) ? thisObj.doJump(thisObj.settings.wheelActions.down) : thisObj.doJump(thisObj.settings.wheelActions.up)); if(thisObj.settings.preventWheel) return false; }); } /* BIND TOUCH EVENTS */ if(thisObj.settings.enableTouch){ var startX; var startY; var isMoving = false; var dragHorizontal = null; var pointerType = null; function onTouchStart(e){ if(!MSPointerEnabled){ if(e.originalEvent.touches.length != 1) return; startX = e.originalEvent.touches[0].clientX; startY = e.originalEvent.touches[0].clientY; isMoving = true; this.addEventListener('touchmove', onTouchMove, false); this.addEventListener('touchend', cancelTouch, false); } else{ if(e.originalEvent.pointerType != (e.originalEvent.MSPOINTER_TYPE_TOUCH || 'touch')) return; pointerType = e.originalEvent.pointerType; startX = e.originalEvent.clientX; startY = e.originalEvent.clientY; isMoving = true; document.addEventListener(MSPointerMove, onTouchMove, false); document.addEventListener(MSPointerUp, cancelTouch, false); } } function cancelTouch(e){ if(!MSPointerEnabled){ this.removeEventListener('touchmove', onTouchMove); this.removeEventListener('touchend', cancelTouch); } else{ if(typeof(e)!="undefined" && e.pointerType != pointerType) return; pointerType = null; document.removeEventListener(MSPointerMove, onTouchMove); document.removeEventListener(MSPointerUp, cancelTouch); } isMoving = false; dragHorizontal = null; } if(thisObj.settings.touchType=='wipe'){ var onTouchMove = function(e){ if(MSPointerEnabled && e.pointerType != pointerType) return; if(!MSPointerEnabled && thisObj.settings.preventTouch) e.preventDefault(); if(isMoving){ if(!MSPointerEnabled){ var x = e.touches[0].clientX; var y = e.touches[0].clientY; } else{ var x = e.clientX; var y = e.clientY; } var dx = startX - x; var dy = startY - y; if(Math.abs(dx)>=thisObj.settings.touchXFrom){ if(thisObj.settings.touchActions.left!=0 && dx>0){ cancelTouch(); thisObj.doWipe(thisObj.settings.touchActions.left); return; } else if(thisObj.settings.touchActions.right!=0 && dx<0){ cancelTouch(); thisObj.doWipe(thisObj.settings.touchActions.right); return; } } if(Math.abs(dy)>=thisObj.settings.touchYFrom){ if(thisObj.settings.touchActions.up!=0 && dy>0){ cancelTouch(); thisObj.doWipe(thisObj.settings.touchActions.up); return; } else if(thisObj.settings.touchActions.down!=0 && dy<0 ){ cancelTouch(); thisObj.doWipe(thisObj.settings.touchActions.down); return; } } } } } else{ var onTouchMove = function (e){ if(MSPointerEnabled && e.pointerType != pointerType) return; if(!MSPointerEnabled && thisObj.settings.preventTouch) e.preventDefault(); if(isMoving){ if(!MSPointerEnabled){ var x = e.touches[0].clientX; var y = e.touches[0].clientY; } else{ var x = e.clientX; var y = e.clientY; } var dx = startX - x; var dy = startY - y; if(Math.abs(dx)>=thisObj.settings.touchXFrom){ if(thisObj.settings.touchActions.left!=0 && dx>0 && (dragHorizontal==null || dragHorizontal==true)){ dragHorizontal = true; thisObj.doDrag(thisObj.settings.touchActions.left); startX = x; } else if(thisObj.settings.touchActions.right!=0 && dx<0 && (dragHorizontal==null || dragHorizontal==true)){ dragHorizontal = true; thisObj.doDrag(thisObj.settings.touchActions.right); startX = x; } } if(Math.abs(dy)>=thisObj.settings.touchYFrom){ if(thisObj.settings.touchActions.up!=0 && dy>0 && (dragHorizontal==null || dragHorizontal==false)){ dragHorizontal = false; thisObj.doDrag(thisObj.settings.touchActions.up); startY = y; } else if(thisObj.settings.touchActions.down!=0 && dy<0 && (dragHorizontal==null || dragHorizontal==false)){ dragHorizontal = false; thisObj.doDrag(thisObj.settings.touchActions.down); startY = y; } } } } } if(MSPointerEnabled && MSMaxTouchPoints){ jQuery(thisObj.mySelector).bind(MSPointerDown+'.isAlive',onTouchStart); /*PREVENT TOUCH EVENTS*/ if(thisObj.settings.preventTouch) jQuery(thisObj.mySelector).addClass('isalive-notouchaction'); } if('ontouchstart' in document.documentElement) jQuery(thisObj.mySelector).bind('touchstart.isAlive',onTouchStart); } } /*THIS FUNCTION CREATES ANIMATION, SET AND CLASS ARRAYS*/ isAlive.prototype.createElementsArray = function(){ var thisObj = this; var pos,key,selector,property,className,valStart,valEnd,stepStart,stepEnd,value; var oldValue = {}; thisObj.setArray['forward'] = {}; thisObj.setArray['backward'] = {}; thisObj.onOffClassArray['forward'] = {}; thisObj.onOffClassArray['backward'] = {}; /*CREATES ARRAYS FOR ADDCLASS, REMOVECLASS, SET, ANIMATION PROPERTY*/ for(pos=0;pos<=thisObj.settings.max;pos++){ for(key in thisObj.settings.elements){ if(thisObj.settings.elements[key]['method']=='animate'){ if(pos>=thisObj.settings.elements[key]['step-start'] && pos<=thisObj.settings.elements[key]['step-end']){ selector = thisObj.settings.elements[key]['selector']; property = thisObj.settings.elements[key]['property']; valStart = thisObj.settings.elements[key]['value-start']; valEnd = thisObj.settings.elements[key]['value-end']; stepStart = thisObj.settings.elements[key]['step-start']; stepEnd = thisObj.settings.elements[key]['step-end']; value = getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd); if(typeof(thisObj.animPositions[pos])=="undefined") thisObj.animPositions[pos]=[]; if(typeof(thisObj.animPositions[pos][selector])=="undefined") thisObj.animPositions[pos][selector]=[]; thisObj.animPositions[pos][selector][property]=value; } } else if(thisObj.settings.elements[key]['method']=="animate-set"){ if(pos>=thisObj.settings.elements[key]['step-start'] && pos<=thisObj.settings.elements[key]['step-end'] && (pos-thisObj.settings.elements[key]['step-start'])%thisObj.settings.elements[key]['move-on']==0){ selector = thisObj.settings.elements[key]['selector']; property = thisObj.settings.elements[key]['property']; valStart = thisObj.settings.elements[key]['value-start']; valEnd = thisObj.settings.elements[key]['value-end']; stepStart = thisObj.settings.elements[key]['step-start']; stepEnd = thisObj.settings.elements[key]['step-end']; value = getAtPosValue(pos,valStart,valEnd,stepStart,stepEnd); if(pos>stepStart){ if(typeof(thisObj.setArray['forward'][pos])=="undefined") thisObj.setArray['forward'][pos] = {}; if(typeof(thisObj.setArray['forward'][pos][selector])=="undefined") thisObj.setArray['forward'][pos][selector] = {}; thisObj.setArray['forward'][pos][selector][property] = value; if(typeof(thisObj.setArray['backward'][pos])=="undefined") thisObj.setArray['backward'][pos] = {}; if(typeof(thisObj.setArray['backward'][pos][selector])=="undefined") thisObj.setArray['backward'][pos][selector] = {}; thisObj.setArray['backward'][pos][selector][property] = oldValue[selector+'-'+property]; } oldValue[selector+'-'+property] = value; } } else if(thisObj.settings.elements[key]['method']=="set"){ if(pos==thisObj.settings.elements[key]['step-from']){ selector = thisObj.settings.elements[key]['selector']; property = thisObj.settings.elements[key]['property']; if(typeof(thisObj.setArray['forward'][pos])=="undefined") thisObj.setArray['forward'][pos] = {}; if(typeof(thisObj.setArray['forward'][pos][selector])=="undefined") thisObj.setArray['forward'][pos][selector] = {}; thisObj.setArray['forward'][pos][selector][property] = thisObj.settings.elements[key]['value-above']; if(typeof(thisObj.setArray['backward'][pos])=="undefined") thisObj.setArray['backward'][pos] = {}; if(typeof(thisObj.setArray['backward'][pos][selector])=="undefined") thisObj.setArray['backward'][pos][selector] = {}; thisObj.setArray['backward'][pos][selector][property] = thisObj.settings.elements[key]['value-under']; } }else if(thisObj.settings.elements[key]['method']=="add-class"){ if(pos==thisObj.settings.elements[key]['step-from']){ selector = thisObj.settings.elements[key]['selector']; className = thisObj.settings.elements[key]['class-name']; if(typeof(thisObj.onOffClassArray['forward'][pos])=="undefined") thisObj.onOffClassArray['forward'][pos] = {}; if(typeof(thisObj.onOffClassArray['forward'][pos][selector])=="undefined") thisObj.onOffClassArray['forward'][pos][selector] = {}; thisObj.onOffClassArray['forward'][pos][selector][className] = true; if(typeof(thisObj.onOffClassArray['backward'][pos])=="undefined") thisObj.onOffClassArray['backward'][pos] = {}; if(typeof(thisObj.onOffClassArray['backward'][pos][selector])=="undefined") thisObj.onOffClassArray['backward'][pos][selector] = {}; thisObj.onOffClassArray['backward'][pos][selector][className] = false; } }else if(thisObj.settings.elements[key]['method']=="remove-class"){ if(pos==thisObj.settings.elements[key]['step-from']){ selector = thisObj.settings.elements[key]['selector']; className = thisObj.settings.elements[key]['class-name']; if(typeof(thisObj.onOffClassArray['forward'][pos])=="undefined") thisObj.onOffClassArray['forward'][pos] = {}; if(typeof(thisObj.onOffClassArray['forward'][pos][selector])=="undefined") thisObj.onOffClassArray['forward'][pos][selector] = {}; thisObj.onOffClassArray['forward'][pos][selector][className] = false; if(typeof(thisObj.onOffClassArray['backward'][pos])=="undefined") thisObj.onOffClassArray['backward'][pos] = {}; if(typeof(thisObj.onOffClassArray['backward'][pos][selector])=="undefined") thisObj.onOffClassArray['backward'][pos][selector] = {}; thisObj.onOffClassArray['backward'][pos][selector][className] = true; } } } } } /*INITS THE STARTING POINTS*/ isAlive.prototype.initCSS = function(){ var thisObj = this; var CSSArray = {}; var classesArray = {}; var pos,selector,property,className; var pointFoundSelector = -1; for(pos=thisObj.settings.start;pos>=0;pos--){ if(thisObj.haveNavPoints && pointFoundSelector==-1) pointFoundSelector=indexOf(thisObj.settings.navPoints,pos); if(typeof(thisObj.setArray['forward'][pos])!="undefined"){ for(selector in thisObj.setArray['forward'][pos]){ if(typeof(CSSArray[selector])=="undefined") CSSArray[selector] = {}; for(property in thisObj.setArray['forward'][pos][selector]){ if(typeof(CSSArray[selector][property])=="undefined") CSSArray[selector][property] = thisObj.setArray['forward'][pos][selector][property]; } } } if(typeof(thisObj.onOffClassArray['forward'][pos])!="undefined"){ for(selector in thisObj.onOffClassArray['forward'][pos]){ if(typeof(classesArray[selector])=="undefined") classesArray[selector] = {}; for(className in thisObj.onOffClassArray['forward'][pos][selector]){ if(typeof(classesArray[selector][className])=="undefined") classesArray[selector][className] = thisObj.onOffClassArray['forward'][pos][selector][className]; } } } if(typeof(thisObj.animPositions[pos])!="undefined"){ for(selector in thisObj.animPositions[pos]){ if(typeof(CSSArray[selector])=="undefined") CSSArray[selector] = {}; for(property in thisObj.animPositions[pos][selector]) if(typeof(CSSArray[selector][property]) == "undefined") CSSArray[selector][property] = thisObj.animPositions[pos][selector][property]; } } } for(pos=thisObj.settings.start+1;pos<=thisObj.settings.max-1;pos++){ if(typeof(thisObj.setArray['backward'][pos])!="undefined"){ for(selector in thisObj.setArray['backward'][pos]){ if(typeof(CSSArray[selector])=="undefined") CSSArray[selector] = {}; for(property in thisObj.setArray['backward'][pos][selector]){ if(typeof(CSSArray[selector][property])=="undefined") CSSArray[selector][property] = thisObj.setArray['backward'][pos][selector][property]; } } } if(typeof(thisObj.onOffClassArray['backward'][pos])!="undefined"){ for(selector in thisObj.onOffClassArray['backward'][pos]){ if(typeof(classesArray[selector])=="undefined") classesArray[selector] = {}; for(className in thisObj.onOffClassArray['backward'][pos][selector]){ if(typeof(classesArray[selector][className])=="undefined") classesArray[selector][className] = thisObj.onOffClassArray['backward'][pos][selector][className]; } } } if(typeof(thisObj.animPositions[pos])!="undefined"){ for(selector in thisObj.animPositions[pos]){ if(typeof(CSSArray[selector])=="undefined") CSSArray[selector] = {}; for(property in thisObj.animPositions[pos][selector]) if(typeof(CSSArray[selector][property]) == "undefined") CSSArray[selector][property] = thisObj.animPositions[pos][selector][property]; } } } for(selector in CSSArray) for(property in CSSArray[selector]) thisObj.setCSS(selector,property,CSSArray[selector][property]); for(selector in classesArray){ for(className in classesArray[selector]){ if(classesArray[selector][className]==true) jQuery(selector).addClass(className); else jQuery(selector).removeClass(className); } } if(pointFoundSelector!=-1){ jQuery(thisObj.settings.navPointsSelector).removeClass(thisObj.settings.navPointsActiveClass); jQuery(thisObj.settings.navPointsSelector).eq(pointFoundSelector).addClass(thisObj.settings.navPointsActiveClass); } for(pos=0;pos<=thisObj.settings.start;pos++) if(thisObj.settings.onStep!=null) thisObj.settings.onStep(pos,0,'init'); }; /*THIS FUNCTION MAKES ALL THE INITIALIZATIONS FOR ANIMATIONS*/ isAlive.prototype.initAnimations = function(){ var thisObj = this; var pos,key,key2; /*GET IE VERSION AND BROWSER VARS*/ if(!incIndex){ browserObj = getBrowser(); /* ARRAY SEARCH FOR IE7&IE8 FIX*/ if(!Array.prototype.indexOf){ indexOf = function (myArray,myValue){ for(var key in myArray) if(myArray[key]==myValue) return parseInt(key); return -1; } }else{ indexOf = function (myArray,myValue){ return myArray.indexOf(myValue); } } /*ADDED VALUE FOR CSS BUG FIXED*/ _fix['opacity'] = (browserObj.opera) ? 0.004 : 0.001; _fix['px'] = (browserObj.opera || (browserObj.safari && !browserObj.mobile && ifVersion(browserObj.version,'<','6.0.0'))) ? 1 : 0.01; _fix['%'] = 0.01; _fix['deg'] = 0.01; _fix['em'] = (browserObj.opera || (browserObj.safari && !browserObj.mobile && ifVersion(browserObj.version,'<','6.0.0'))) ? 0.1 : 0.01; /*CHECK IF RGBA IS SUPPORTED*/ canRGBA = supportsRGBA(); /*GET MS POINTER EVENTS*/ MSPointerEnabled = Boolean(window.navigator.msPointerEnabled || window.navigator.pointerEnabled); MSPointerDown = (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) ? ((window.navigator.pointerEnabled) ? "pointerdown" : "MSPointerDown") : false; MSPointerMove = (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) ? ((window.navigator.pointerEnabled) ? "pointermove" : "MSPointerMove") : false; MSPointerUp = (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) ? ((window.navigator.pointerEnabled) ? "pointerup" : "MSPointerUp") : false; MSMaxTouchPoints = (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) ? (window.navigator.maxTouchPoints || window.navigator.msMaxTouchPoints) : false; /*GET WHEEL EVENT*/ WheelEvent = "onwheel" in document.createElement("div") ? "wheel" : ((typeof(document.onmousewheel) !== "undefined") ? "mousewheel" : ((browserObj.mozilla) ? "MozMousePixelScroll" : "DOMMouseScroll")); } /*BINDS RESIZE EVENT*/ if(!resizeOn){ resizeOn = true; windowWidth = jQuery(window).width(); windowHeight = jQuery(window).height(); jQuery(window).bind('resize.general',onResizeAction); /*CREATE STYLES*/ if(vP('user-select')) jQuery('head').append('<style class="isalive-style"> .isalive-nouserselect{'+vP('user-select')+':none;} </style>'); if(vP('touch-action')) jQuery('head').append('<style class="isalive-style"> .isalive-notouchaction{'+vP('touch-action')+':none;} </style>'); if (vP('backface-visibility') && vP('perspective')) jQuery('head').append('<style class="isalive-style"> .isalive-enablegpu{'+vP('backface-visibility')+':hidden;'+vP('perspective')+':1000px;} </style>'); } /*INCREMENT INDEX*/ incIndex++; /*CHECK IF ELEMENT IS FROM DOM*/ thisObj.DOMElement = (jQuery(thisObj.mySelector).length!=0); /*TIMELINE WRAPPER*/ thisObj.TimeLine = document.createElement('foo'); /*SHOW SCROLL POSITION*/ if(thisObj.settings.debug) thisObj.DOMElement ? jQuery(thisObj.mySelector).append('<div style="position:absolute;padding:5px;border:1px solid gray; color: red; top:10px;left:10px;display:inline-block;background:white;z-index:9999;" id="isalive-'+thisObj.uniqId+'-debuger" class="isalive-debuger"><span>'+thisObj.settings.start+'</span></div>') : jQuery('body').append('<div style="position:absolute;padding:5px;border:1px solid gray; color: red; top:10px;left:10px;display:inline-block;background:white;z-index:9999;" id="isalive-'+thisObj.uniqId+'-debuger" class="isalive-debuger"><span>'+thisObj.settings.start+'</span></div>'); /*GET WIDTH AND HEIGHT OF THE PARENT ELEMENT*/ thisObj.params.windowWidth = jQuery(window).width(); thisObj.params.windowHeight = jQuery(window).height(); thisObj.params.documentWidth = jQuery(document).width(); thisObj.params.documentHeight = jQuery(document).height(); if(thisObj.DOMElement){ thisObj.params.elementLeft = jQuery(thisObj.mySelector).offset().left; thisObj.params.elementTop = jQuery(thisObj.mySelector).offset().top; thisObj.params.elementWidth = jQuery(thisObj.mySelector).width(); thisObj.params.elementHeight = jQuery(thisObj.mySelector).height(); } else{ thisObj.params.elementLeft = thisObj.settings.elementTweaks['left']; thisObj.params.elementTop = thisObj.settings.elementTweaks['top']; thisObj.params.elementWidth = thisObj.settings.elementTweaks['width']; thisObj.params.elementHeight = thisObj.settings.elementTweaks['height']; } /*FIX JQUERY/CSS3 EASING*/ if(thisObj.settings.JSEasing==null) thisObj.settings.JSEasing = thisObj.settings.easing; if(thisObj.settings.CSS3Easing==null) thisObj.settings.CSS3Easing = thisObj.settings.easing; /*MAKE SURE THAT MAXSCROLL AND MAXTOUCH IS NO BIGGER THEN SCROLLJUMP AND TOUCHJUMP*/ if(thisObj.settings.maxScroll<thisObj.settings.stepsOnScroll) thisObj.settings.maxScroll = thisObj.settings.stepsOnScroll; if(thisObj.settings.maxDrag<thisObj.settings.stepsOnDrag) thisObj.settings.maxDrag = thisObj.settings.stepsOnDrag; /*CHECK FOR TOUCH*/ if(!thisObj.DOMElement || (thisObj.settings.enableTouch && thisObj.settings.touchType=="wipe" && thisObj.settings.wipePoints.length<=1)) thisObj.settings.enableTouch = false; /*CHECK FOR SCROLL*/ if(!thisObj.DOMElement || (thisObj.settings.enableWheel && thisObj.settings.wheelType=="jump" && thisObj.settings.jumpPoints.length<=1)) thisObj.settings.enableWheel = false; /*CHECK IF SCROLLBARPOINTS EXIST*/ if(thisObj.settings.scrollbarType=="jump" && thisObj.settings.scrollbarPoints.length<=1) thisObj.settings.scrollbarType = "scroll"; /*SORT AND INIT STEP POINTS*/ thisObj.haveNavPoints = (thisObj.settings.navPointsSelector!=null && thisObj.settings.navPointsActiveClass!=null && thisObj.settings.navPoints.length>0); /*SORT POINTS ARRAYS*/ thisObj.settings.wipePoints.sort(function(a,b){return a-b}); thisObj.settings.jumpPoints.sort(function(a,b){return a-b}); thisObj.settings.playPoints.sort(function(a,b){return a-b}); thisObj.settings.scrollbarPoints.sort(function(a,b){return a-b}); thisObj.settings.navPoints.sort(function(a,b){return a-b}); /*SETS THE DURATION TWEAKS*/ if(typeof(thisObj.settings.durationTweaks['wheel'])=="undefined") thisObj.settings.durationTweaks['wheel'] = {}; if(typeof(thisObj.settings.durationTweaks['touch'])=="undefined") thisObj.settings.durationTweaks['touch'] = {}; if(typeof(thisObj.settings.durationTweaks['scrollbar'])=="undefined") thisObj.settings.durationTweaks['scrollbar'] = {}; if(typeof(thisObj.settings.durationTweaks['nav'])=="undefined") thisObj.settings.durationTweaks['nav'] = {}; thisObj.settings.durationTweaks['wheel'] = jQuery.extend({duration:thisObj.settings.duration,durationType:"default",minStepDuration:thisObj.settings.minStepDuration},thisObj.settings.durationTweaks['wheel']); thisObj.settings.durationTweaks['touch'] = jQuery.extend({duration:thisObj.settings.duration,durationType:"default",minStepDuration:thisObj.settings.minStepDuration},thisObj.settings.durationTweaks['touch']); thisObj.settings.durationTweaks['scrollbar'] = jQuery.extend({duration:thisObj.settings.duration,durationType:"default",minStepDuration:thisObj.settings.minStepDuration},thisObj.settings.durationTweaks['scrollbar']); thisObj.settings.durationTweaks['nav'] = jQuery.extend({duration:thisObj.settings.duration,durationType:"default",minStepDuration:thisObj.settings.minStepDuration},thisObj.settings.durationTweaks['nav']); /*SET SCROLL & TOUCH ACTIONS*/ thisObj.settings.wheelActions = jQuery.extend({up:-1,down:1},thisObj.settings.wheelActions); if(thisObj.settings.touchXFrom==null) (thisObj.settings.touchType=="drag") ? thisObj.settings.touchXFrom = 10 : thisObj.settings.touchXFrom = 20; if(thisObj.settings.touchYFrom==null) (thisObj.settings.touchType=="drag") ? thisObj.settings.touchYFrom = 10 : thisObj.settings.touchYFrom = 20; thisObj.settings.touchActions = jQuery.extend({up:1,down:-1,right:0,left:0},thisObj.settings.touchActions); /* CONVERT FROM TREE TO LINEAR STRUCTURE */ if(thisObj.settings.elementsType=="tree"){ var tempObj = {}; var i = 0; for(key in thisObj.settings.elements){ for(key2 in thisObj.settings.elements[key]){ tempObj[i] = {}; tempObj[i] = jQuery.extend({"selector":key},thisObj.settings.elements[key][key2]); i++; } delete thisObj.settings.elements[key]; } thisObj.settings.elements = jQuery.extend({},tempObj); } var new_elements = []; var idIndex = 0; var keyIndex = 0; var tempArray = []; for(key in thisObj.settings.elements){ /*IF NO SELECTOR IS FOUND*/ if(typeof(thisObj.settings.elements[key]['selector'])=="undefined"){ delete thisObj.settings.elements[key]; continue; } /*DELETE ELEMENTS FOR OTHER BROWSERS THEN MINE*/ if(typeof(thisObj.settings.elements[key]['+browsers'])!="undefined"){ if(!validateBrowsers(thisObj.settings.elements[key]['+browsers'])){ delete thisObj.settings.elements[key]; continue; } } if(typeof(thisObj.settings.elements[key]['-browsers'])!="undefined"){ if(validateBrowsers(thisObj.settings.elements[key]['-browsers'])){ delete thisObj.settings.elements[key]; continue; } } /*DELETE NON EXISTING DOM ELEMENTS*/ if(indexOf(tempArray,thisObj.settings.elements[key]['selector'])==-1){ if(jQuery(thisObj.settings.elements[key]['selector']).length==0){ delete thisObj.settings.elements[key]; continue; } tempArray.push(thisObj.settings.elements[key]['selector']); } /*UNPACK SHORT ELEMENTS*/ if(typeof(thisObj.settings.elements[key]['do'])!="undefined"){ if(thisObj.settings.elements[key]['do'].indexOf('(')!=-1){ thisObj.settings.elements[key]['property'] = thisObj.settings.elements[key]['do'].substr(0,thisObj.settings.elements[key]['do'].indexOf('(')); var temp = getBetweenBrackets(thisObj.settings.elements[key]['do']); var values = []; var s = 0; var k = 0; for(var i=0;i<=temp.length-1;i++){ if(temp.charAt(i) == '(') s++; else if(temp.charAt(i) == ')') s--; if(temp.charAt(i)==',' && s==0) k++; else{ if(typeof(values[k])=="undefined") values[k] = ""; values[k] = values[k] + temp.charAt(i); } } if(values.length==1) thisObj.settings.elements[key]['value-end'] = values[0]; else if(values.length==2){ thisObj.settings.elements[key]['value-start'] = values[0]; thisObj.settings.elements[key]['value-end'] = values[1]; } else{ delete thisObj.settings.elements[key]; continue; } } else if(thisObj.settings.elements[key]['do']=="fadeOut"){ thisObj.settings.elements[key]['property'] = "opacity"; thisObj.settings.elements[key]['value-end'] = 0; } else if(thisObj.settings.elements[key]['do']=="fadeIn"){ thisObj.settings.elements[key]['property'] = "opacity"; thisObj.settings.elements[key]['value-end'] = 1; } else{ delete thisObj.settings.elements[key]; continue; } thisObj.settings.elements[key]['method'] = "animate"; delete thisObj.settings.elements[key]['do']; } /*ADD IF USEIDATTRIBUTE IS SET TO TRUE*/ if((thisObj.settings.useIdAttribute && (typeof(thisObj.settings.elements[key]['use-id-attribute'])=="undefined" || thisObj.settings.elements[key]['use-id-attribute']==true)) || (!thisObj.settings.useIdAttribute && thisObj.settings.elements[key]['use-id-attribute']==true)){ if(typeof(thisObj.settings.elements[key]['use-id-attribute'])!="undefined") delete thisObj.settings.elements[key]['use-id-attribute']; if(jQuery(thisObj.settings.elements[key]['selector']).length==1){ var id = jQuery(thisObj.settings.elements[key]['selector']).attr('id'); if(typeof(id)=='undefined'){ id = 'isalive-'+thisObj.uniqId+'-element-' + idIndex; idIndex++; jQuery(thisObj.settings.elements[key]['selector']).attr('id', id); thisObj.settings.elements[key]['selector'] = '#'+id; } else thisObj.settings.elements[key]['selector'] = '#'+id; } else{ jQuery(thisObj.settings.elements[key]['selector']).each(function(k, child){ if(typeof(jQuery(child).attr('id')) == "undefined"){ var id = 'isalive-'+thisObj.uniqId+'-element-' + idIndex; jQuery(child).attr('id', id); idIndex++; } else var id = jQuery(child).attr('id'); var newElement = jQuery.extend({},thisObj.settings.elements[key]); newElement['selector'] = "#"+id; new_elements.push(newElement); }); delete thisObj.settings.elements[key]; } } } for(key in new_elements){ thisObj.settings.elements["ISALIVE_OBJECT_"+keyIndex] = jQuery.extend({},new_elements[key]); keyIndex++; } /*DELETES UNVALID ELEMENTS AND ADDS ISALIVE CLASS / PREPARES CSS3*/ var tempArray = []; var jQueryCanAnimate = ('borderWidth,borderBottomWidth,borderLeftWidth,borderRightWidth,borderTopWidth,borderSpacing,margin,marginBottom,marginLeft,marginRight,marginTop,outlineWidth,padding,paddingBottom,paddingLeft,paddingRight,paddingTop,height,width,maxHeight,maxWidth,minHeight,minWidth,fontSize,bottom,left,right,top,letterSpacing,wordSpacing,lineHeight,textIndent,opacity,scrollLeft,scrollTop').split(','); for(key in thisObj.settings.elements){ if(typeof(thisObj.settings.elements[key]['property'])!="undefined"){ /*BUILD FUNCTIONS ARRAY && TRIMS PROPERTY*/ if(typeof(thisObj.settings.elements[key]['property'])=='function'){ var fTemp = 'F:'+toString(thisObj.settings.elements[key]['property']); if(typeof(thisObj.functionsArray[fTemp])=="undefined") thisObj.functionsArray[fTemp] = thisObj.settings.elements[key]['property']; thisObj.settings.elements[key]['property'] = fTemp; } else if(thisObj.settings.elements[key]['property']!='scrollTop' && thisObj.settings.elements[key]['property']!='scrollLeft'){ /*PUTS PREFIX FOR CSS3*/ thisObj.settings.elements[key]['property'] = vP(thisObj.settings.elements[key]['property']); if(!thisObj.settings.elements[key]['property']){ delete thisObj.settings.elements[key]; continue; } } /* SET@START IS NOT USED WHEN INITCSS IS TRUE*/ if(thisObj.settings.elements[key]["method"]=="set@start" && thisObj.settings.initCSS){ delete thisObj.settings.elements[key]; continue; } /*PUTS MOVE-ON VALUE TO THE ANIMATE-SET ELEMENTS*/ if(thisObj.settings.elements[key]["method"]=="animate-set" && typeof(thisObj.settings.elements[key]['move-on'])=='undefined') thisObj.settings.elements[key]['move-on'] = 1; /*SET CSS3 VARS*/ if(thisObj.settings.elements[key]["method"]=="animate"){ if(!vP('transition') || thisObj.settings.elements[key]['property']=='scrollTop' || thisObj.settings.elements[key]['property']=='scrollLeft' || thisObj.settings.elements[key]["property"].indexOf('F:')==0 || (!thisObj.settings.useCSS3 && typeof(thisObj.settings.elements[key]['useCSS3'])=="undefined") || thisObj.settings.elements[key]['useCSS3']==false){ /*BUILD JS ARRAY*/ if(indexOf(jQueryCanAnimate,propertyToStyle(thisObj.settings.elements[key]["property"]))!=-1) thisObj.settings.elements[key]['animType'] = 1; else{ thisObj.settings.elements[key]['animType'] = 2; if(typeof(thisObj.JSValuesArray[thisObj.settings.elements[key]["selector"]])=="undefined") thisObj.JSValuesArray[thisObj.settings.elements[key]["selector"]] = {}; } /*SET EASING*/ if(typeof(thisObj.settings.elements[key]["easing"])=="undefined"){ if(typeof(thisObj.settings.elements[key]["JSEasing"])=="undefined") thisObj.settings.elements[key]["easing"] = thisObj.settings.JSEasing; else thisObj.settings.elements[key]["easing"] = thisObj.settings.elements[key]["JSEasing"]; } if(typeof(jQuery.easing[thisObj.settings.elements[key]["easing"]])=='undefined') thisObj.settings.elements[key]["easing"] = "linear"; if(typeof(thisObj.settings.elements[key]["JSEasing"])!="undefined") delete thisObj.settings.elements[key]['JSEasing']; if(typeof(thisObj.settings.elements[key]["CSS3Easing"])!="undefined") delete thisObj.settings.elements[key]['CSS3Easing']; } else { /*BUILD CSS3 ARRAYS*/ thisObj.settings.elements[key]['animType'] = 3; if(typeof(thisObj.CSS3TransitionArray[thisObj.settings.elements[key]["selector"]])=="undefined"){ thisObj.CSS3TransitionArray[thisObj.settings.elements[key]["selector"]] = {}; thisObj.CSS3ValuesArray[thisObj.settings.elements[key]["selector"]] = {}; } /*SET EASING*/ if(typeof(thisObj.settings.elements[key]["easing"])=="undefined"){ if(typeof(thisObj.settings.elements[key]["CSS3Easing"])=="undefined") thisObj.settings.elements[key]["easing"] = thisObj.settings.CSS3Easing; else thisObj.settings.elements[key]["easing"] = thisObj.settings.elements[key]["CSS3Easing"]; } thisObj.settings.elements[key]["easing"] = convertEasing(thisObj.settings.elements[key]["easing"]); if(indexOf(['linear','ease','ease-in','ease-out','ease-in-out'],thisObj.settings.elements[key]["easing"])==-1 && thisObj.settings.elements[key]["easing"].indexOf('cubic-bezier')==-1) thisObj.settings.elements[key]["easing"] = "linear"; if(typeof(thisObj.settings.elements[key]["JSEasing"])!="undefined") delete thisObj.settings.elements[key]['JSEasing']; if(typeof(thisObj.settings.elements[key]["CSS3Easing"])!="undefined") delete thisObj.settings.elements[key]['CSS3Easing']; } if(typeof(thisObj.settings.elements[key]['useCSS3'])!="undefined") delete thisObj.settings.elements[key]['useCSS3']; } /*PUT ANIMATE CLASS FOR ANIMATIONS*/ if(thisObj.settings.elements[key]['method']=="animate" && indexOf(tempArray,thisObj.settings.elements[key]['selector'])==-1){ jQuery(thisObj.settings.elements[key]['selector']).addClass(thisObj.settings.animateClass); tempArray.push(thisObj.settings.elements[key]['selector']); } } } /*CHECKS IF ENABLE GPU IS VALID AND ADD SPECIAL CSS*/ if(thisObj.settings.enableGPU==true || (thisObj.settings.enableGPU!=false && validateBrowsers(thisObj.settings.enableGPU))) if(vP('backface-visibility') && vP('perspective')) jQuery('.'+thisObj.settings.animateClass).addClass('isalive-enablegpu'); var tempArray = []; for(key in thisObj.settings.elements){ /* CREATES ARRAY WITH TRANSITIONS CSS VALUES*/ if(thisObj.settings.elements[key]['animType']==3 && vP('transition')) if(typeof(thisObj.CSS3DefaultTransitionArray[thisObj.settings.elements[key]['selector']])=="undefined"){ var propTempArray = []; var pTemp1 = jQuery(thisObj.settings.elements[key]['selector']).css(vP('transition-property')); var pTemp2 = jQuery(thisObj.settings.elements[key]['selector']).css(vP('transition-duration')); if(typeof(pTemp1)!="undefined" && typeof(pTemp2)!="undefined" && (pTemp1!="all" || pTemp2!="0s")){ propTempArray.push(pTemp1); propTempArray.push(pTemp2); propTempArray.push(jQuery(thisObj.settings.elements[key]['selector']).css(vP('transition-timing-function'))); propTempArray.push(jQuery(thisObj.settings.elements[key]['selector']).css(vP('transition-delay'))); thisObj.CSS3DefaultTransitionArray[thisObj.settings.elements[key]['selector']] = propTempArray; } else thisObj.CSS3DefaultTransitionArray[thisObj.settings.elements[key]['selector']] = null; } /*FIXES IE OPACITY BUG*/ if(browserObj.msie && parseInt(browserObj.version)<9 && thisObj.settings.elements[key]['property']=='opacity' && indexOf(tempArray,thisObj.settings.elements[key]['selector'])==-1){ var cssValue=parseFloat(jQuery(thisObj.settings.elements[key]['selector']).css('opacity')); jQuery(thisObj.settings.elements[key]['selector']).css('opacity',cssValue); tempArray.push(thisObj.settings.elements[key]['selector']); } } /* DELETES UNWANTED ELEMENTS FROM TRANSITION ARRAY AND MAKES DEFAULT TRANSITION ARRAY*/ for(key in thisObj.CSS3DefaultTransitionArray){ if(thisObj.CSS3DefaultTransitionArray[key]==null){ delete thisObj.CSS3DefaultTransitionArray[key]; continue; } var tempArray = []; for(key2 in thisObj.CSS3DefaultTransitionArray[key]){ if(thisObj.CSS3DefaultTransitionArray[key][key2].indexOf('cubic-bezier')==-1) tempArray.push(thisObj.CSS3DefaultTransitionArray[key][key2].split(',')); else{ var aTemp = thisObj.CSS3DefaultTransitionArray[key][key2].split('('); for (var keyA in aTemp){ if(aTemp[keyA].indexOf(')')!=-1){ aTemp[keyA] = aTemp[keyA].split(')'); aTemp[keyA][0] = aTemp[keyA][0].replace(/,/g,'*CHAR*'); aTemp[keyA] = aTemp[keyA].join(')'); } } tempArray.push(aTemp.join('(').split(',')); } delete(thisObj.CSS3DefaultTransitionArray[key][key2]); } for(key2 in tempArray[0]){ var transVal = []; transVal.push(jQuery.trim(tempArray[0][key2])); transVal.push(jQuery.trim(tempArray[1][key2])); transVal.push(jQuery.trim(tempArray[2][key2])); transVal.push(jQuery.trim(tempArray[3][key2])); thisObj.CSS3DefaultTransitionArray[key][jQuery.trim(tempArray[0][key2])] = transVal.join(" ").replace(/\*CHAR\*/g,','); } } /*GETS MAX*/ if(thisObj.settings.max==null){ thisObj.settings.max = 0; for(key in thisObj.settings.elements){ if(thisObj.settings.elements[key]['method']=='animate' || thisObj.settings.elements[key]['method']=='animate-set'){ if(typeof(thisObj.settings.elements[key]['step-end'])!='undefined') thisObj.settings.max = Math.max(thisObj.settings.max,thisObj.settings.elements[key]['step-end']); } else if(thisObj.settings.elements[key]['method']=='set' || thisObj.settings.elements[key]['method']=='add-class' || thisObj.settings.elements[key]['method']=='remove-class'){ if(typeof(thisObj.settings.elements[key]['step-from'])!='undefined') thisObj.settings.max = Math.max(thisObj.settings.max,thisObj.settings.elements[key]['step-from']); } } } /*INCREMENT MAX*/ thisObj.settings.max++; /*INIT STARTING POINT*/ thisObj.step=thisObj.settings.start; thisObj.lastStep=thisObj.settings.start; /*GETS STARING VALUES*/ for(key in thisObj.settings.elements){ if(thisObj.settings.elements[key]['scrollbar'] && thisObj.settings.elements[key]['method']=="animate" && (thisObj.settings.elements[key]['property']=="top" || thisObj.settings.elements[key]['property']=="left")){ if(typeof(thisObj.settings.elements[key]['step-start'])=="undefined") thisObj.settings.elements[key]['step-start'] = thisObj.settings.min; if(typeof(thisObj.settings.elements[key]['step-end'])=="undefined") thisObj.settings.elements[key]['step-end'] = thisObj.settings.max-1; } if((thisObj.settings.elements[key]['method']=='animate' || thisObj.settings.elements[key]['method']=='animate-set') && typeof(thisObj.settings.elements[key]['value-start'])=="undefined") thisObj.settings.elements[key]['value-start'] = thisObj.getStartCssValue(key); else if(thisObj.settings.elements[key]['method']=='set' && typeof(thisObj.settings.elements[key]['value-under'])=="undefined") thisObj.settings.elements[key]['value-under'] = thisObj.getStartCssValue(key); } /* GET VALUES FOR CUSTOM PARAMS */ for(key in thisObj.settings.elements){ if(thisObj.settings.elements[key]["method"]=="animate" || thisObj.settings.elements[key]["method"]=="animate-set"){ if(isDinamic(thisObj.settings.elements[key]['value-start']) || isDinamic(thisObj.settings.elements[key]['value-end'])){ var tempObj = (thisObj.settings.elements[key]['scrollbar']) ? jQuery.extend({key:parseInt(key)},thisObj.settings.elements[key]) : jQuery.extend({},thisObj.settings.elements[key]); thisObj.cssDinamicElements.push(tempObj); } thisObj.settings.elements[key]['value-start'] = thisObj.convertParams(thisObj.settings.elements[key]['value-start'],thisObj.settings.elements[key]['format']); thisObj.settings.elements[key]['value-end'] = thisObj.convertParams(thisObj.settings.elements[key]['value-end'],thisObj.settings.elements[key]['format']); } else if(thisObj.settings.elements[key]["method"]=="set"){ if(isDinamic(thisObj.settings.elements[key]['value-under']) || isDinamic(thisObj.settings.elements[key]['value-above'])){ var tempObj = jQuery.extend({},thisObj.settings.elements[key]); thisObj.cssDinamicElements.push(tempObj); } thisObj.settings.elements[key]['value-under'] = thisObj.convertParams(thisObj.settings.elements[key]['value-under'],thisObj.settings.elements[key]['format']); thisObj.settings.elements[key]['value-above'] = thisObj.convertParams(thisObj.settings.elements[key]['value-above'],thisObj.settings.elements[key]['format']); } else if(thisObj.settings.elements[key]["method"]=="static"){ if(isDinamic(thisObj.settings.elements[key]['value'])){ var tempObj = jQuery.extend({},thisObj.settings.elements[key]); thisObj.cssDinamicElements.push(tempObj); } convertValue = thisObj.convertParams(thisObj.settings.elements[key]['value'],thisObj.settings.elements[key]['format']); thisObj.setCSS(thisObj.settings.elements[key]['selector'],thisObj.settings.elements[key]['property'],convertValue); delete thisObj.settings.elements[key]; } else if(thisObj.settings.elements[key]["method"]=="set@start"){ var convertValue = thisObj.convertParams(thisObj.settings.elements[key]["value"],thisObj.settings.elements[key]['format']); thisObj.setCSS(thisObj.settings.elements[key]["selector"],thisObj.settings.elements[key]["property"],convertValue); delete thisObj.settings.elements[key]; } } /*THIS FUNCTION CREATES ANIMATION, SET AND CLASS ARRAYS*/ thisObj.createElementsArray(); /*SCROLLBAR EVENTS*/ var addScrollbarEvents = function(selector,scrollbarKey){ var mousedownFunction = function(e){ var myObj = this; var eType = e.originalEvent.type; var pointerType = null; if(thisObj.animating && thisObj.animationType!="scrollbar") return; if(eType==MSPointerDown){ if(e.originalEvent.pointerType==(e.originalEvent.MSPOINTER_TYPE_PEN || 'pen') || (e.originalEvent.pointerType==(e.originalEvent.MSPOINTER_TYPE_TOUCH || 'touch') && !thisObj.settings.enableScrollbarTouch)) return; pointerType = e.originalEvent.pointerType; } else if(eType=='touchstart') if(e.originalEvent.touches.length!=1) return; var parentTopLeft,clickPos,position,positionTo,positionValid; var valStart = parseFloat(getFloat(thisObj.settings.elements[scrollbarKey]['value-start'].toString())); var valEnd = parseFloat(getFloat(thisObj.settings.elements[scrollbarKey]['value-end'].toString())); thisObj.scrollbarActive = scrollbarKey; if('onselectstart' in document.documentElement){ jQuery('body').bind("selectstart.myEventSelectStart",function(e){ e.preventDefault(); }); } if(thisObj.settings.scrollbarActiveClass!=null) jQuery(myObj).addClass(thisObj.settings.scrollbarActiveClass); if(eType=="mousedown"){ if(thisObj.settings.elements[scrollbarKey]['property']=="top"){ parentTopLeft = jQuery(myObj).parent().offset().top; clickPos = e.pageY - jQuery(myObj).offset().top; }else{ parentTopLeft = jQuery(myObj).parent().offset().left; clickPos = e.pageX - jQuery(myObj).offset().left; } } else if(eType==MSPointerDown){ if(thisObj.settings.elements[scrollbarKey]['property']=="top"){ parentTopLeft = jQuery(myObj).parent().offset().top; clickPos = e.originalEvent.pageY - jQuery(myObj).offset().top; }else{ parentTopLeft = jQuery(myObj).parent().offset().left; clickPos = e.originalEvent.pageX - jQuery(myObj).offset().left; } } else{ if(thisObj.settings.elements[scrollbarKey]['property']=="top"){ parentTopLeft = jQuery(myObj).parent().offset().top; clickPos = e.originalEvent.touches[0].pageY - jQuery(myObj).offset().top; }else{ parentTopLeft = jQuery(myObj).parent().offset().left; clickPos = e.originalEvent.touches[0].pageX - jQuery(myObj).offset().left; } } if(!thisObj.animating) thisObj.scrollBarPosition = thisObj.getPos(thisObj.step); var mousemoveFunction = function(e){ var eType = e.originalEvent.type; if(eType=="mousemove"){ if(thisObj.settings.elements[scrollbarKey]['property']=="top") var mouseNow = (e.pageY - parentTopLeft)-clickPos; else var mouseNow = (e.pageX - parentTopLeft)-clickPos; } else if(eType==MSPointerMove){ if(e.originalEvent.pointerType!=pointerType) return; if(thisObj.settings.elements[scrollbarKey]['property']=="top") var mouseNow = (e.originalEvent.pageY - parentTopLeft)-clickPos; else var mouseNow = (e.originalEvent.pageX - parentTopLeft)-clickPos; } else{ if(thisObj.settings.elements[scrollbarKey]['property']=="top") var mouseNow = (e.originalEvent.touches[0].pageY - parentTopLeft)-clickPos; else var mouseNow = (e.originalEvent.touches[0].pageX - parentTopLeft)-clickPos; } if(mouseNow>=valStart && mouseNow<=valEnd) jQuery(myObj).css(thisObj.settings.elements[scrollbarKey]['property'],mouseNow); else if(mouseNow<valStart){ jQuery(myObj).css(thisObj.settings.elements[scrollbarKey]['property'],valStart); mouseNow = valStart; } else if(mouseNow>valEnd){ jQuery(myObj).css(thisObj.settings.elements[scrollbarKey]['property'],valEnd); mouseNow = valEnd; } positionValid = false; position = thisObj.settings.elements[scrollbarKey]['step-start']+Math.round(Math.abs(thisObj.settings.elements[scrollbarKey]['step-end']-thisObj.settings.elements[scrollbarKey]['step-start'])*((mouseNow-valStart)/Math.abs(valEnd-valStart))); if(thisObj.settings.scrollbarType=="scroll"){ positionTo = thisObj.settings.elements[scrollbarKey]['step-start']+(Math.round((position-thisObj.settings.elements[scrollbarKey]['step-start'])/thisObj.settings.stepsOnScrollbar)*thisObj.settings.stepsOnScrollbar); if(positionTo!=thisObj.scrollBarPosition) if(positionTo>=thisObj.settings.elements[scrollbarKey]['step-start'] && positionTo<=thisObj.settings.elements[scrollbarKey]['step-end']) positionValid = true; }else{ if(thisObj.scrollBarPosition<position){ for(var i=position;i>=thisObj.scrollBarPosition+1;i--){ if(indexOf(thisObj.settings.scrollbarPoints,i)!=-1){ positionValid = true; positionTo = i; break; } } }else if(thisObj.scrollBarPosition>position){ for(var i=position;i<=thisObj.scrollBarPosition-1;i++){ if(indexOf(thisObj.settings.scrollbarPoints,i)!=-1){ positionValid = true; positionTo = i; break; } } } } if(positionValid){ thisObj.scrollBarPosition=positionTo; thisObj.goTo({to:positionTo,animationType:'scrollbar',duration:thisObj.settings.durationTweaks['scrollbar']['duration'],durationType:thisObj.settings.durationTweaks['scrollbar']['durationType'],minStepDuration:thisObj.settings.durationTweaks['scrollbar']['minStepDuration']}); } e.preventDefault(); e.stopPropagation(); } if(eType=="mousedown"){ jQuery(document).bind('mousemove.myEventMouseMove',mousemoveFunction); jQuery(document).bind('mouseup.myEventMouseUp',function(e){ jQuery(document).unbind('mousemove.myEventMouseMove'); jQuery(document).unbind('mouseup.myEventMouseUp'); jQuery('body').unbind("selectstart.myEventSelectStart"); if(thisObj.settings.scrollbarActiveClass!=null) jQuery(myObj).removeClass(thisObj.settings.scrollbarActiveClass); }); } else if(eType==MSPointerDown){ jQuery(document).bind(MSPointerMove+'.myEventPointerMove',mousemoveFunction); jQuery(document).bind(MSPointerUp+'.myEventPointerUp',function(e){ if(e.originalEvent.pointerType!=pointerType) return; jQuery(document).unbind(MSPointerMove+'.myEventPointerMove'); jQuery(document).unbind(MSPointerUp+'.myEventPointerUp'); jQuery('body').unbind("selectstart.myEventSelectStart"); if(thisObj.settings.scrollbarActiveClass!=null) jQuery(myObj).removeClass(thisObj.settings.scrollbarActiveClass); }); } else{ jQuery(myObj).bind('touchmove.myEventTouchMove',mousemoveFunction); jQuery(myObj).bind('touchend.myEventTouchEnd',function(e){ jQuery(myObj).unbind('touchmove.myEventTouchMove'); jQuery(myObj).unbind('touchend.myEventTouchEnd'); jQuery('body').unbind("selectstart.myEventSelectStart"); if(thisObj.settings.scrollbarActiveClass!=null) jQuery(myObj).removeClass(thisObj.settings.scrollbarActiveClass); }); } e.preventDefault(); e.stopPropagation(); } jQuery(selector).addClass('isalive-nouserselect'); jQuery(selector).attr('unselectable', 'on'); if(MSPointerEnabled){ jQuery(selector).bind(MSPointerDown+'.scrollbar',mousedownFunction); /*PREVENT TOUCH EVENTS*/ if(thisObj.settings.enableScrollbarTouch) jQuery(selector).addClass('isalive-notouchaction'); } else if('onmousedown' in document.documentElement) jQuery(selector).bind('mousedown.scrollbar',mousedownFunction); if(('ontouchstart' in document.documentElement) && thisObj.settings.enableScrollbarTouch) jQuery(selector).bind('touchstart.scrollbar',mousedownFunction); } for(key in thisObj.settings.elements){ /*DELETES ALL NON ANIMATED ELEMENTS*/ if(thisObj.settings.elements[key]['method']!='animate'){ delete thisObj.settings.elements[key]; continue; } /*DELETES THE METHOD*/ delete thisObj.settings.elements[key]['method']; /*DELETES UNUSED ELEMENTS AND FINDS SCROLLBAR*/ if(thisObj.settings.elements[key]['scrollbar']){ if(thisObj.settings.elements[key]['property']=="top" || thisObj.settings.elements[key]['property']=="left"){ /*BINDS MOUSEEVENTS TO SCROLLBAR*/ jQuery(thisObj.settings.elements[key]['selector']).each(function(){ addScrollbarEvents(thisObj.settings.elements[key]['selector'],key); }); } else{ delete thisObj.settings.elements[key]['scrollbar']; delete thisObj.settings.elements[key]['value-start']; delete thisObj.settings.elements[key]['value-end']; } } else { delete thisObj.settings.elements[key]['value-start']; delete thisObj.settings.elements[key]['value-end']; } } /*BIND CLICK ON STEP POINTS*/ if(thisObj.settings.navPointsSelector!=null && thisObj.settings.navPoints.length>0 && thisObj.settings.navPointsClickEvent) jQuery(thisObj.settings.navPointsSelector).each(function(index){ jQuery(this).bind('click',function(){ thisObj.goTo({to:thisObj.settings.navPoints[index],animationType:'nav',duration:thisObj.settings.durationTweaks['nav']['duration'],durationType:thisObj.settings.durationTweaks['nav']['durationType'],minStepDuration:thisObj.settings.durationTweaks['nav']['minStepDuration']}); }) }); /*CALLS FUNCTION TO BIND MOUSE AND SCROLL EVENTS*/ thisObj.bindScrollTouchEvents(); /*THIS WILL SET THE CSS VALUES ON LOAD*/ if(thisObj.settings.initCSS) thisObj.initCSS(); } /*ANIMATING MAIN FUNCTION!!!*/ isAlive.prototype.animateSite = function(){ var thisObj = this; //console.log('lastScroll:'+thisObj.lastStep+'|Scroll:'+thisObj.step+'|Duration:'+thisObj.animateDuration); if(thisObj.animating){ jQuery(thisObj.TimeLine).stop(); jQuery('.'+thisObj.settings.animateClass).stop(); } thisObj.animating=true; var key; var animations = {}; var start; var end; var timing; var loopFix; var directionForward; var loop,loopStart,loopEnd; loopStart = thisObj.getLoop(thisObj.lastStep); loopEnd = thisObj.getLoop(thisObj.step); if(thisObj.step>thisObj.lastStep){ /*SCROLL DOWN*/ directionForward = true; for(loop=loopStart;loop<=loopEnd;loop++){ loopFix = loop * thisObj.settings.max; for(key in thisObj.settings.elements){ if(thisObj.animationType=='scrollbar' && key==thisObj.scrollbarActive) continue; if(thisObj.settings.elements[key]['step-start']+loopFix<thisObj.step && thisObj.settings.elements[key]['step-end']+loopFix>thisObj.lastStep){ start = Math.max((thisObj.settings.elements[key]['step-start']+loopFix),thisObj.lastStep); (thisObj.settings.elements[key]['step-end']+loopFix>=thisObj.step) ? end = thisObj.getPos(thisObj.step) : end = thisObj.settings.elements[key]['step-end']; timing = Math.floor((thisObj.animateDuration/(thisObj.step-thisObj.lastStep))*((end+loopFix)-start)); if(typeof(animations[start])=="undefined") animations[start] = {}; if(typeof(animations[start][thisObj.settings.elements[key]['selector']])=="undefined") animations[start][thisObj.settings.elements[key]['selector']] = {}; animations[start][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']] = { 'animType':thisObj.settings.elements[key]['animType'], 'duration':timing, 'end':end, 'to':thisObj.animPositions[end][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']], 'easing':thisObj.settings.elements[key]['easing'] }; //console.log('Id:'+thisObj.settings.elements[key]['selector']+'|Lastscroll:'+thisObj.lastStep+'|Scroll:'+thisObj.step+'|Css:'+thisObj.settings.elements[key]['property']+'|Start:'+start+'|End:'+end+'|Duration:'+timing+'|Css Value:'+thisObj.animPositions[end][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']]+'|Css Real:'+jQuery(thisObj.settings.elements[key]['selector']).css(thisObj.settings.elements[key]['property'])); } } } }else{ /*SCROLL UP*/ directionForward = false; for(loop=loopStart;loop>=loopEnd;loop--){ loopFix = loop * thisObj.settings.max; for(key in thisObj.settings.elements){ if(thisObj.animationType=='scrollbar' && key==thisObj.scrollbarActive) continue; if(thisObj.settings.elements[key]['step-start']+loopFix<thisObj.lastStep && thisObj.settings.elements[key]['step-end']+loopFix>thisObj.step){ start = Math.min((thisObj.settings.elements[key]['step-end']+loopFix),thisObj.lastStep); (thisObj.settings.elements[key]['step-start']+loopFix<=thisObj.step) ? end = thisObj.getPos(thisObj.step) : end = thisObj.settings.elements[key]['step-start']; timing = Math.floor((thisObj.animateDuration/(thisObj.lastStep-thisObj.step))*(start-(end+loopFix))); if(typeof(animations[start])=="undefined") animations[start] = {}; if(typeof(animations[start][thisObj.settings.elements[key]['selector']])=="undefined") animations[start][thisObj.settings.elements[key]['selector']] = {}; animations[start][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']] = { 'animType':thisObj.settings.elements[key]['animType'], 'duration':timing, 'end':end, 'to':thisObj.animPositions[end][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']], 'easing':thisObj.settings.elements[key]['easing'] }; //console.log('Id:'+thisObj.settings.elements[key]['selector']+'|Lastscroll:'+thisObj.lastStep+'|Scroll:'+thisObj.step+'|Css:'+thisObj.settings.elements[key]['property']+'|Start:'+start+'|End:'+end+'|Duration:'+timing+'|Css Value:'+thisObj.animPositions[end][thisObj.settings.elements[key]['selector']][thisObj.settings.elements[key]['property']]+'|Css Real:'+jQuery(thisObj.settings.elements[key]['selector']).css(thisObj.settings.elements[key]['property'])); } } } } var stepStart = thisObj.lastStep; var stepEnd = thisObj.step; var firstTime = true; var lastStep = thisObj.lastStep; /* STARTS ANIMATION */ jQuery(thisObj.TimeLine).animate({"timer":"+=100"},{duration:thisObj.animateDuration,easing:'linear',queue:false, complete : function(){ var selector,property; thisObj.animating = false; thisObj.animationType = 'none'; thisObj.forceAnimation = false; for(selector in thisObj.CSS3TransitionArray){ thisObj.CSS3TransitionArray[selector] = {}; thisObj.CSS3ValuesArray[selector] = {}; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); } if(thisObj.rebuildOnStop){ thisObj.rebuildLayout(); thisObj.rebuildOnStop = false; if(thisObj.onComplete!==null){ setTimeout(function(){ var onComplete = thisObj.onComplete; thisObj.onComplete = null; onComplete(); },25); } } else{ if(thisObj.onComplete!==null){ var onComplete = thisObj.onComplete; thisObj.onComplete = null; onComplete(); } } }, step: function(now, fx) { var pos,step,selector,property,className,direction,duration; var value = Math.round((stepStart+(((stepEnd-stepStart)/100)*(now-fx.start)))*100)/100; thisObj.lastStep = value; var valid = false; if(firstTime){ valid = true; pos = value; } else if(directionForward && Math.floor(value)>lastStep){ valid = true; pos = Math.floor(value); } else if(!directionForward && Math.ceil(value)<lastStep){ valid = true; pos = Math.ceil(value); } if(valid){ if(firstTime){ step = lastStep; firstTime = false; } else { if(directionForward) step = lastStep+1; else step = lastStep-1; } while((directionForward && step<=pos) || (!directionForward && step>=pos)){ /*ANIMATE-SET && SET && ADD && REMOVE CLASS*/ if(step==parseInt(step)){ (directionForward)?((step!=stepStart)?direction = 'forward':direction = null):((step!=stepEnd)?direction = 'backward':direction = null); if(direction!=null){ if(typeof(thisObj.setArray[direction][thisObj.getPos(step)])!="undefined"){ for(selector in thisObj.setArray[direction][thisObj.getPos(step)]){ for(property in thisObj.setArray[direction][thisObj.getPos(step)][selector]) thisObj.setCSS(selector,property,thisObj.setArray[direction][thisObj.getPos(step)][selector][property]); } } if(typeof(thisObj.onOffClassArray[direction][thisObj.getPos(step)])!="undefined"){ for(selector in thisObj.onOffClassArray[direction][thisObj.getPos(step)]){ for(className in thisObj.onOffClassArray[direction][thisObj.getPos(step)][selector]){ if(thisObj.onOffClassArray[direction][thisObj.getPos(step)][selector][className]==true) jQuery(selector).addClass(className); else jQuery(selector).removeClass(className); } } } } } /*ANIMATE*/ if(step!=stepEnd && typeof(animations[step])!="undefined"){ for(selector in animations[step]){ for(property in animations[step][selector]){ duration = 0; if ((directionForward && (animations[step][selector][property]['end']-thisObj.getPos(value))>0) || (!directionForward && (thisObj.getPos(value)-animations[step][selector][property]['end'])>0)) duration = Math.floor(animations[step][selector][property]['duration']*(Math.abs(animations[step][selector][property]['end']-thisObj.getPos(value))/Math.abs(animations[step][selector][property]['end']-thisObj.getPos(step)))); thisObj.animate(animations[step][selector][property]['animType'],selector,property,animations[step][selector][property]['to'],duration,animations[step][selector][property]['easing'],step); } } } /*STEP-POINTS AND ON-STEP EVENT*/ if(step!=stepStart){ if(thisObj.haveNavPoints){ var pointFound=indexOf(thisObj.settings.navPoints,thisObj.getPos(step)); if(pointFound!=-1){ jQuery(thisObj.settings.navPointsSelector).removeClass(thisObj.settings.navPointsActiveClass); jQuery(thisObj.settings.navPointsSelector).eq(pointFound).addClass(thisObj.settings.navPointsActiveClass); } } if(thisObj.settings.onStep!=null) thisObj.settings.onStep(thisObj.getPos(step),thisObj.getLoop(step),thisObj.animationType); } if(directionForward){ lastStep = Math.floor(step); step = Math.floor(step)+1; } else { lastStep = Math.ceil(step); step = Math.ceil(step)-1; } } } } }); } /* FUNCTION FOR JUMP */ isAlive.prototype.doJump = function(value){ var thisObj = this; var directionForward,stepPos,currentPosition,nextPosition,notAllowed; if(!value || !thisObj.allowWheel || thisObj.forceAnimation) return false; if(thisObj.settings.wheelDelay!==false){ clearTimeout(thisObj.wheelTimer); thisObj.wheelTimer = setTimeout(function(){ thisObj.waitWheellEnd = false; },thisObj.settings.wheelDelay); } (thisObj.animating)?((thisObj.lastStep<thisObj.step)?directionForward=true:directionForward=false):directionForward=null; if(thisObj.settings.wheelDelay===false && thisObj.animating && thisObj.animationType=='jump' && ((directionForward && value==1)||(!directionForward && value==-1))) return false; if(thisObj.settings.wheelDelay!==false && thisObj.waitWheellEnd && thisObj.animating && thisObj.animationType=='jump' && ((directionForward && value==1)||(!directionForward && value==-1))) return false; if(thisObj.settings.wheelDelay!==false) thisObj.waitWheellEnd = true; stepPos = thisObj.getPos(thisObj.lastStep); currentPosition = indexOf(thisObj.settings.jumpPoints,stepPos); if(currentPosition==-1){ currentPosition = null; if(stepPos<=thisObj.settings.jumpPoints[0]) currentPosition=-0.5; else{ for(var i=0;i<=thisObj.settings.jumpPoints.length-2;i++){ if(stepPos>thisObj.settings.jumpPoints[i] && stepPos<thisObj.settings.jumpPoints[i+1]){ currentPosition = i + 0.5; break; } } if(currentPosition==null) currentPosition=(thisObj.settings.jumpPoints.length-1)+0.5; } } if(!thisObj.animating || (thisObj.animating && thisObj.animationType!='jump') || (thisObj.animating && thisObj.animationType=='jump' && ((directionForward && value==-1)||(!directionForward && value==1)))){ notAllowed = null; nextPosition = currentPosition; }else{ if(value==1){ if(currentPosition<thisObj.settings.jumpPoints.length-1) notAllowed = Math.ceil(currentPosition); else notAllowed = 0; } else{ if(currentPosition>0) notAllowed = Math.floor(currentPosition); else notAllowed = thisObj.settings.jumpPoints.length-1; } nextPosition = thisObj.jumpPosition; } if(value==1){ if(nextPosition<(thisObj.settings.jumpPoints.length-1)) nextPosition = Math.floor(nextPosition+1); else if(thisObj.settings.loop) nextPosition=0; else return; } else{ if(nextPosition>0) nextPosition = Math.ceil(nextPosition-1); else if(thisObj.settings.loop) nextPosition=thisObj.settings.jumpPoints.length-1 else return; } if(value==1){ if(nextPosition === notAllowed) return false; thisObj.jumpPosition = nextPosition; thisObj.goTo({to:thisObj.settings.jumpPoints[thisObj.jumpPosition],orientation:'next',animationType:'jump',duration:thisObj.settings.durationTweaks['wheel']['duration'],durationType:thisObj.settings.durationTweaks['wheel']['durationType'],minStepDuration:thisObj.settings.durationTweaks['wheel']['minStepDuration']}); }else{ if(nextPosition === notAllowed) return false; thisObj.jumpPosition = nextPosition; thisObj.goTo({to:thisObj.settings.jumpPoints[thisObj.jumpPosition],orientation:'prev',animationType:'jump',duration:thisObj.settings.durationTweaks['wheel']['duration'],durationType:thisObj.settings.durationTweaks['wheel']['durationType'],minStepDuration:thisObj.settings.durationTweaks['wheel']['minStepDuration']}); } } /* FUNCTION FOR SCROLL */ isAlive.prototype.doScroll = function(value){ var thisObj = this; if(!value || !thisObj.allowWheel || thisObj.forceAnimation) return false; if(thisObj.animating && thisObj.animationType!='scroll'){ thisObj.step=Math.round(thisObj.lastStep); thisObj.onComplete=null; } else if(thisObj.animating && thisObj.animationType=='scroll' && ((thisObj.lastStep<thisObj.step && value==-1)||(thisObj.lastStep>thisObj.step && value==1))) thisObj.step=Math.round(thisObj.lastStep); if(value==1){ if((thisObj.step+thisObj.settings.stepsOnScroll<=thisObj.settings.max-1 || thisObj.settings.loop) && (thisObj.step+thisObj.settings.stepsOnScroll)-thisObj.lastStep<=thisObj.settings.maxScroll) thisObj.step = thisObj.step+thisObj.settings.stepsOnScroll; else if(thisObj.step<thisObj.settings.max-1 && thisObj.step+thisObj.settings.stepsOnScroll>thisObj.settings.max-1 && !thisObj.settings.loop && (thisObj.settings.max-1)-thisObj.lastStep<=thisObj.settings.maxScroll){ thisObj.step = thisObj.settings.max-1; }else return; }else{ if((thisObj.step-thisObj.settings.stepsOnScroll>=thisObj.settings.min || thisObj.settings.loop) && thisObj.lastStep-(thisObj.step-thisObj.settings.stepsOnScroll)<=thisObj.settings.maxScroll) thisObj.step = thisObj.step-thisObj.settings.stepsOnScroll; else if(thisObj.step>thisObj.settings.min && thisObj.step-thisObj.settings.stepsOnScroll<thisObj.settings.min && !thisObj.settings.loop && thisObj.lastStep-thisObj.settings.min<=thisObj.settings.maxScroll) thisObj.step = thisObj.settings.min; else return; } if(thisObj.settings.debug) jQuery('#isalive-'+thisObj.uniqId+'-debuger span:first').html(thisObj.step); clearTimeout(thisObj.wheelTimer); if(!thisObj.animating || (thisObj.animating && thisObj.animationType!='scroll')){ thisObj.animationType='scroll'; thisObj.animateDuration = thisObj.settings.durationTweaks.wheel.duration; thisObj.animateSite(); } else{ thisObj.wheelTimer = setTimeout(function(){ thisObj.animationType='scroll'; thisObj.animateDuration = thisObj.settings.durationTweaks.wheel.duration; thisObj.animateSite(); },20); } } /*DO TOUCH WIPE*/ isAlive.prototype.doWipe = function(value){ var thisObj = this; var directionForward,stepPos,currentPosition,nextPosition,notAllowed; if(!thisObj.allowTouch || thisObj.forceAnimation) return false; (thisObj.animating)?((thisObj.lastStep<thisObj.step)?directionForward=true:directionForward=false):directionForward=null; stepPos = thisObj.getPos(thisObj.lastStep); currentPosition = indexOf(thisObj.settings.wipePoints,stepPos); if(currentPosition==-1){ currentPosition = null; if(stepPos<=thisObj.settings.wipePoints[0]) currentPosition=-0.5; else{ for(var i=0;i<=thisObj.settings.wipePoints.length-2;i++){ if(stepPos>thisObj.settings.wipePoints[i] && stepPos<thisObj.settings.wipePoints[i+1]){ currentPosition = i + 0.5; break; } } if(currentPosition==null) currentPosition=(thisObj.settings.wipePoints.length-1)+0.5; } } if(!thisObj.animating || (thisObj.animating && thisObj.animationType!='wipe') || (thisObj.animating && thisObj.animationType=='wipe' && ((directionForward && value==-1)||(!directionForward && value==1)))){ notAllowed = null; nextPosition = currentPosition; }else{ if(value==1){ if(currentPosition<thisObj.settings.wipePoints.length-1) notAllowed = Math.ceil(currentPosition); else notAllowed = 0; } else{ if(currentPosition>0) notAllowed = Math.floor(currentPosition); else notAllowed = thisObj.settings.wipePoints.length-1; } nextPosition = thisObj.wipePosition; } if(value==1){ if(nextPosition<(thisObj.settings.wipePoints.length-1)) nextPosition = Math.floor(nextPosition+1); else if(thisObj.settings.loop) nextPosition=0; else return; } else{ if(nextPosition>0) nextPosition = Math.ceil(nextPosition-1); else if(thisObj.settings.loop) nextPosition=thisObj.settings.wipePoints.length-1 else return; } if(value==1){ if(nextPosition===notAllowed) return false; thisObj.wipePosition = nextPosition; thisObj.goTo({to:thisObj.settings.wipePoints[thisObj.wipePosition],orientation:'next',animationType:'wipe',duration:thisObj.settings.durationTweaks['touch']['duration'],durationType:thisObj.settings.durationTweaks['touch']['durationType'],minStepDuration:thisObj.settings.durationTweaks['touch']['minStepDuration']}); }else{ if(nextPosition===notAllowed) return false; thisObj.wipePosition = nextPosition; thisObj.goTo({to:thisObj.settings.wipePoints[thisObj.wipePosition],orientation:'prev',animationType:'wipe',duration:thisObj.settings.durationTweaks['touch']['duration'],durationType:thisObj.settings.durationTweaks['touch']['durationType'],minStepDuration:thisObj.settings.durationTweaks['touch']['minStepDuration']}); } } /*DO TOUCH DRAG*/ isAlive.prototype.doDrag = function(value){ var thisObj = this; if(!thisObj.allowTouch || thisObj.forceAnimation) return false; if(thisObj.animating && thisObj.animationType!='drag'){ thisObj.step=Math.round(thisObj.lastStep); thisObj.onComplete=null; } else if(thisObj.animating && thisObj.animationType=='drag' && ((thisObj.lastStep<thisObj.step && value==-1)||(thisObj.lastStep>thisObj.step && value==1))) thisObj.step=Math.round(thisObj.lastStep); if(value==1){ if((thisObj.step+thisObj.settings.stepsOnDrag<=thisObj.settings.max-1 || thisObj.settings.loop) && (thisObj.step+thisObj.settings.stepsOnDrag)-thisObj.lastStep<=thisObj.settings.maxDrag) thisObj.step = thisObj.step+thisObj.settings.stepsOnDrag; else if(thisObj.step<thisObj.settings.max-1 && thisObj.step+thisObj.settings.stepsOnDrag>thisObj.settings.max-1 && !thisObj.settings.loop && (thisObj.settings.max-1)-thisObj.lastStep<=thisObj.settings.maxDrag) thisObj.step = thisObj.settings.max-1; else return; }else{ if((thisObj.step-thisObj.settings.stepsOnDrag>=thisObj.settings.min || thisObj.settings.loop) && thisObj.lastStep-(thisObj.step-thisObj.settings.stepsOnDrag)<=thisObj.settings.maxDrag) thisObj.step = thisObj.step-thisObj.settings.stepsOnDrag; else if(thisObj.step>thisObj.settings.min && thisObj.step-thisObj.settings.stepsOnDrag<thisObj.settings.min && !thisObj.settings.loop && thisObj.lastStep-thisObj.settings.min<=thisObj.settings.maxDrag) thisObj.step = thisObj.settings.min; else return; } if(thisObj.settings.debug) jQuery('#isalive-'+thisObj.uniqId+'-debuger span:first').html(thisObj.step); thisObj.animationType='drag'; thisObj.animateDuration = thisObj.settings.durationTweaks.touch.duration; thisObj.animateSite(); } /*GO TO FUNCTION*/ isAlive.prototype.goTo = function(options){ settings = jQuery.extend({ to:null, duration: null, durationType: 'default', /*default|step*/ orientation:'default', /*default|loop|next|prev*/ animationType:'goTo', onComplete:null, minStepDuration:null, force:false },options); var thisObj = this; var pos,posNext,posPrev; if(thisObj.forceAnimation) return false; pos = settings.to + (thisObj.getLoop(thisObj.lastStep)*thisObj.settings.max); if(thisObj.settings.loop){ if(settings.orientation=='loop'){ if(thisObj.lastStep<=pos) posNext = pos; else posNext = settings.to + ((thisObj.getLoop(thisObj.lastStep)+1)*thisObj.settings.max); if(thisObj.lastStep>=pos) posPrev = pos; else posPrev = settings.to + ((thisObj.getLoop(thisObj.lastStep)-1)*thisObj.settings.max); if(Math.abs(thisObj.lastStep-posNext)>Math.abs(thisObj.lastStep-posPrev)) pos = posPrev; else pos = posNext; } else if(settings.orientation == 'next'){ if(thisObj.lastStep>=pos) pos = settings.to + ((thisObj.getLoop(thisObj.lastStep)+1)*thisObj.settings.max); } else if(settings.orientation == 'prev'){ if(thisObj.lastStep<=pos) pos = settings.to + ((thisObj.getLoop(thisObj.lastStep)-1)*thisObj.settings.max); } } if(!thisObj.animating && pos==thisObj.lastStep) return; thisObj.step = pos; thisObj.animationType = settings.animationType; thisObj.forceAnimation = settings.force; (settings.onComplete!==null)?thisObj.onComplete=settings.onComplete:thisObj.onComplete=null; /*MIN VALUE FOR DURATION*/ if(settings.minStepDuration==null) var minStep = thisObj.settings.minStepDuration; else var minStep = settings.minStepDuration; if(settings.durationType=='step' && settings.duration!=null){ if(settings.duration<minStep) thisObj.animateDuration=Math.abs(thisObj.lastStep-thisObj.step)*minStep; else thisObj.animateDuration=Math.abs(thisObj.lastStep-thisObj.step)*settings.duration; } else{ if(settings.duration==null){ if(thisObj.settings.duration/Math.abs(thisObj.lastStep-thisObj.step)<minStep) thisObj.animateDuration = Math.abs(thisObj.lastStep-thisObj.step)*minStep; else thisObj.animateDuration = thisObj.settings.duration; }else{ if(settings.duration/Math.abs(thisObj.lastStep-thisObj.step)<minStep) thisObj.animateDuration = Math.abs(thisObj.lastStep-thisObj.step)*minStep; else thisObj.animateDuration = settings.duration; } } thisObj.animateSite(); } /*SKIPS TO A POSITION*/ isAlive.prototype.skip = function(step){ var thisObj = this; if(thisObj.forceAnimation) return false; var doSkip = function(step){ var pos,pointFound,pointFoundSelector,direction; var valuesCSS = {}; var valuesClasses = {}; var selector,property,className; pos = thisObj.getPos(thisObj.step); pointFoundSelector = -1; pointFound = -1; while((pos<=step && thisObj.getPos(thisObj.step)<step) || (pos>=step && thisObj.getPos(thisObj.step)>step) || (pos==step && thisObj.getPos(thisObj.step)==step)){ (step>thisObj.step)?direction = 'forward':((pos!=step)?direction = 'backward':direction = 'forward'); if(typeof(thisObj.setArray[direction][pos])!="undefined"){ for(selector in thisObj.setArray[direction][pos]){ if(typeof(valuesCSS[selector]) == "undefined") valuesCSS[selector] = {}; for(property in thisObj.setArray[direction][pos][selector]) valuesCSS[selector][property] = thisObj.setArray[direction][pos][selector][property]; } } if(typeof(thisObj.onOffClassArray[direction][pos])!="undefined"){ for(selector in thisObj.onOffClassArray[direction][pos]){ if(typeof(valuesClasses[selector]) == "undefined") valuesClasses[selector] = {} for(className in thisObj.onOffClassArray[direction][pos][selector]) valuesClasses[selector][className] = thisObj.onOffClassArray[direction][pos][selector][className]; } } if(typeof(thisObj.animPositions[pos])!="undefined"){ for(selector in thisObj.animPositions[pos]){ if(typeof(valuesCSS[selector]) == "undefined") valuesCSS[selector] = {}; for(property in thisObj.animPositions[pos][selector]) valuesCSS[selector][property] = thisObj.animPositions[pos][selector][property]; } } if(thisObj.haveNavPoints){ pointFound=indexOf(thisObj.settings.navPoints,pos); if(pointFound!=-1) pointFoundSelector = pointFound; } if(thisObj.settings.onStep!=null) thisObj.settings.onStep(pos,thisObj.getLoop(thisObj.step),'skip'); (thisObj.getPos(thisObj.step)<step)?pos = pos + 1:pos = pos - 1; } for(selector in valuesCSS) for(property in valuesCSS[selector]) thisObj.setCSS(selector,property,valuesCSS[selector][property]); for(selector in valuesClasses){ for(className in valuesClasses[selector]){ if(valuesClasses[selector][className]==true) jQuery(selector).addClass(className); else jQuery(selector).removeClass(className); } } if(pointFoundSelector!=-1 ){ jQuery(thisObj.settings.navPointsSelector).removeClass(thisObj.settings.navPointsActiveClass); jQuery(thisObj.settings.navPointsSelector).eq(pointFoundSelector).addClass(thisObj.settings.navPointsActiveClass); } step = step + (thisObj.getLoop(thisObj.step)*thisObj.settings.max); thisObj.step = step; thisObj.lastStep = step; } if(thisObj.animating){ thisObj.stop(); setTimeout(function(){ doSkip(step); },25); } else doSkip(step); } /*STOPS ANIMATIONS*/ isAlive.prototype.stopTransitions = function(){ var thisObj = this; for(var selector in thisObj.CSS3TransitionArray){ var CSSValues = {}; for(var property in thisObj.CSS3TransitionArray[selector]) CSSValues[property] = jQuery(selector).css(property); thisObj.CSS3TransitionArray[selector] = {}; thisObj.CSS3ValuesArray[selector] = {}; jQuery(selector).css(vP('transition'),thisObj.getTransitionArray(selector)); jQuery(selector).css(CSSValues); } } /*STOPS ANIMATIONS*/ isAlive.prototype.stop = function(){ var thisObj = this; if(!thisObj.animating) return true; jQuery(thisObj.TimeLine).stop(); jQuery('.'+thisObj.settings.animateClass).stop(); thisObj.stopTransitions(); thisObj.animating = false; thisObj.animationType='none'; thisObj.forceAnimation = false; thisObj.onComplete = null; thisObj.step = Math.round(thisObj.lastStep); if(thisObj.rebuildOnStop){ thisObj.rebuildLayout(); thisObj.rebuildOnStop = false; } } /*PLAYS ANIMATIONS TO THE NEXT PLAY POINT*/ isAlive.prototype.play = function(options){ var thisObj = this; if(thisObj.forceAnimation || thisObj.settings.playPoints.length<=1) return false; options = jQuery.extend({},options); var pos = Math.floor(thisObj.getPos(thisObj.lastStep)); var max = thisObj.settings.max-1; var found = null; for(var i=pos+1;i<=max;i++) if(indexOf(thisObj.settings.playPoints,i)!=-1){ found = i; break } if(found==null && thisObj.settings.loop) found = thisObj.settings.playPoints[0]; if(found==null) return false; options['to'] = found; options['orientation'] = 'next'; options['animationType'] = 'play'; thisObj.goTo(options); } /*PLAYS BACK ANIMATIONS TO THE PREV PLAY POINT*/ isAlive.prototype.rewind = function(options){ var thisObj = this; if(thisObj.forceAnimation || thisObj.settings.playPoints.length<=1) return false; options = jQuery.extend({},options); var pos = Math.ceil(thisObj.getPos(thisObj.lastStep)); var found = null; for(var i=pos-1;i>=0;i--) if(indexOf(thisObj.settings.playPoints,i)!=-1){ found = i; break } if(found==null && thisObj.settings.loop) found = thisObj.settings.playPoints[thisObj.settings.playPoints.length-1]; if(found==null) return false; options['to'] = found; options['orientation'] = 'prev'; options['animationType'] = 'rewind'; thisObj.goTo(options); } /*AUTOPLAY ANIMATION IN LOOPS*/ isAlive.prototype.autoplay = function(options){ var thisObj = this; if(thisObj.forceAnimation || !thisObj.settings.loop) return false; options = jQuery.extend({},options); var count = false; var loop = 0; if(typeof(options['count'])!="undefined"){ count = options['count']; delete options['count']; } var onLoop = null; if(typeof(options['onLoop'])!="undefined"){ onLoop = options['onLoop']; delete options['onLoop']; } options['animationType'] = 'autoplay'; options['to'] = 0; if(typeof(options['orientation'])=="undefined" || (options['orientation']!="next" && options['orientation']!="prev")) options['orientation'] = "next"; options['onComplete'] = function(){ doAutoplay(); }; var doAutoplay = function(){ if(count===false || count>0){ if(onLoop!=null){ loop++; onLoop(loop); } thisObj.goTo(options); if(count!==false) count--; } }; doAutoplay(); } /*TOGGLE ANIMATION*/ isAlive.prototype.toggle = function(options){ var thisObj = this; if(thisObj.forceAnimation) return false; options = jQuery.extend({},options); options['animationType'] = 'toggle'; if((!thisObj.animating || (thisObj.animating && thisObj.animationType!='toggle') || (thisObj.animating && thisObj.animationType=='toggle' && thisObj.toggleState==-1)) && (thisObj.getPos(thisObj.lastStep)<thisObj.settings.max-1)){ thisObj.toggleState = 1; options['to'] = thisObj.settings.max-1; } else{ thisObj.toggleState = -1; options['to'] = thisObj.settings.min; } thisObj.goTo(options); } /*UNBIND EVENTS*/ isAlive.prototype.destroy = function(){ var thisObj = this; /*UNBIND EVENTS*/ if(thisObj.DOMElement) jQuery(thisObj.mySelector).unbind('.isAlive'); for(var key in thisObj.settings.elements){ if(thisObj.settings.elements[key]['scrollbar']){ jQuery(thisObj.settings.elements[key]['selector']).unbind('.scrollbar'); jQuery(thisObj.settings.elements[key]['selector']).removeAttr('unselectable'); jQuery(thisObj.settings.elements[key]['selector']).removeClass('isalive-nouserselect'); jQuery(thisObj.settings.elements[key]['selector']).removeClass('isalive-notouchaction'); } } /*REMOVE DEBUGER*/ jQuery('#isalive-'+this.uniqId+'-debuger').remove(); /*REMOVE ADDED ID ATTRIBUTES*/ jQuery('[id^="isalive-'+this.uniqId+'-element"]').removeAttr('id'); /*REMOVE ENABLE GPU CLASS*/ jQuery('.'+thisObj.settings.animateClass).removeClass('isalive-enablegpu'); /*REMOVE ADDED CLASSES*/ jQuery('.'+thisObj.settings.animateClass).removeClass(thisObj.settings.animateClass); } /*ISALIVE MAIN OBJECT:END*/ /*JQUERY PLUGIN PART:BEGIN*/ var methods = { create : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])!="undefined") return false; if(typeof(options) == "undefined") options = {}; isAliveObjects[selector] = new isAlive(selector,options); return thisObj; }, destroy : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].destroy(); delete isAliveObjects[selector]; return thisObj; }, goTo : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; if(typeof(options) == "undefined" || typeof(options['to']) == "undefined" || options['to']<0 || options['to']>isAliveObjects[selector].settings.max-1) return false; options['to'] = Math.round(options['to']); isAliveObjects[selector].goTo(options); return thisObj; }, skip : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; if(typeof(options) == "undefined" || typeof(options['to']) == "undefined" || options['to']<0 || options['to']>isAliveObjects[selector].settings.max-1) return false; options['to'] = Math.round(options['to']); isAliveObjects[selector].skip(options['to']); return thisObj; }, play : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].play(options); return thisObj; }, rewind : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].rewind(options); return thisObj; }, autoplay : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].autoplay(options); return thisObj; }, toggle : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].toggle(options); return thisObj; }, stop : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].stop(); return thisObj; }, rebuild : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].rebuildLayout(); return thisObj; }, enableWheel : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].allowWheel = options; return thisObj; }, enableTouch : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; isAliveObjects[selector].allowTouch = options; return thisObj; }, addOnComplete : function(thisObj,options){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined" || !isAliveObjects[selector].animating) return false; isAliveObjects[selector].onComplete = options; return thisObj; }, getCurrentPosition : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; return isAliveObjects[selector].getPos(isAliveObjects[selector].lastStep); }, getStepPosition : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; return isAliveObjects[selector].getPos(isAliveObjects[selector].step); }, getMaxStep : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; return (isAliveObjects[selector].settings.max-1); }, getAnimationState : function(thisObj){ var selector = thisObj.selector; if(typeof(isAliveObjects[selector])=="undefined") return false; return (isAliveObjects[selector].animating); }, destroyAll : function(){ for(var selector in isAliveObjects){ isAliveObjects[selector].destroy(); delete isAliveObjects[selector]; } jQuery('style.isalive-style').remove() jQuery(window).unbind('resize.general'); resizeOn = false; return true; }, getBrowser : function(){ return getBrowser(); }, getVersion : function(){ return "1.10.0"; } }; jQuery.fn.isAlive = function(method,options) { if(methods[method]){ var mFunc = methods[method]; return mFunc(this,options); } else return (typeof(method)=='undefined') ? (typeof(isAliveObjects[this.selector])!='undefined') : false; }; /*JQUERY PLUGIN PART:END*/ })(jQuery);
Update jquery.isAlive.js
src/jquery.isAlive.js
Update jquery.isAlive.js
<ide><path>rc/jquery.isAlive.js <ide> Licensed under the MIT (https://github.com/georgecheteles/jQuery.isAlive/blob/master/MIT-LICENSE.txt) license. <ide> Please attribute the author if you use it. <ide> Find me at: <del> [email protected] <add> [email protected] <ide> https://github.com/georgecheteles <ide> Last modification on this file: 03 June 2014 <ide> */
Java
apache-2.0
c11667b716ebef85c2153cd3f3113f30d91d4b22
0
apache/airavata,gouravshenoy/airavata,apache/airavata,machristie/airavata,machristie/airavata,gouravshenoy/airavata,apache/airavata,machristie/airavata,anujbhan/airavata,anujbhan/airavata,apache/airavata,apache/airavata,gouravshenoy/airavata,gouravshenoy/airavata,anujbhan/airavata,gouravshenoy/airavata,machristie/airavata,anujbhan/airavata,apache/airavata,gouravshenoy/airavata,gouravshenoy/airavata,anujbhan/airavata,apache/airavata,apache/airavata,machristie/airavata,machristie/airavata,machristie/airavata,anujbhan/airavata,anujbhan/airavata
/* * * 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.airavata.gfac.impl; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.UserInfo; import org.apache.airavata.common.exception.AiravataException; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.utils.ServerSettings; import org.apache.airavata.credential.store.credential.Credential; import org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential; import org.apache.airavata.credential.store.store.CredentialReader; import org.apache.airavata.credential.store.store.CredentialStoreException; import org.apache.airavata.gfac.core.GFacEngine; import org.apache.airavata.gfac.core.GFacException; import org.apache.airavata.gfac.core.GFacUtils; import org.apache.airavata.gfac.core.JobManagerConfiguration; import org.apache.airavata.gfac.core.authentication.AuthenticationInfo; import org.apache.airavata.gfac.core.authentication.SSHKeyAuthentication; import org.apache.airavata.gfac.core.cluster.OutputParser; import org.apache.airavata.gfac.core.cluster.RemoteCluster; import org.apache.airavata.gfac.core.cluster.ServerInfo; import org.apache.airavata.gfac.core.config.DataTransferTaskConfig; import org.apache.airavata.gfac.core.config.GFacYamlConfigruation; import org.apache.airavata.gfac.core.config.JobSubmitterTaskConfig; import org.apache.airavata.gfac.core.config.ResourceConfig; import org.apache.airavata.gfac.core.context.GFacContext; import org.apache.airavata.gfac.core.context.ProcessContext; import org.apache.airavata.gfac.core.monitor.JobMonitor; import org.apache.airavata.gfac.core.scheduler.HostScheduler; import org.apache.airavata.gfac.core.task.JobSubmissionTask; import org.apache.airavata.gfac.core.task.Task; import org.apache.airavata.gfac.core.watcher.CancelRequestWatcher; import org.apache.airavata.gfac.core.watcher.RedeliveryRequestWatcher; import org.apache.airavata.gfac.impl.job.*; import org.apache.airavata.gfac.impl.task.ArchiveTask; import org.apache.airavata.gfac.impl.watcher.CancelRequestWatcherImpl; import org.apache.airavata.gfac.impl.watcher.RedeliveryRequestWatcherImpl; import org.apache.airavata.gfac.monitor.email.EmailBasedMonitor; import org.apache.airavata.messaging.core.Publisher; import org.apache.airavata.messaging.core.impl.RabbitMQProcessLaunchConsumer; import org.apache.airavata.messaging.core.impl.RabbitMQStatusPublisher; import org.apache.airavata.model.appcatalog.computeresource.*; import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference; import org.apache.airavata.model.appcatalog.gatewayprofile.StoragePreference; import org.apache.airavata.model.commons.ErrorModel; import org.apache.airavata.model.data.movement.DataMovementProtocol; import org.apache.airavata.model.status.TaskState; import org.apache.airavata.registry.core.experiment.catalog.impl.RegistryFactory; import org.apache.airavata.registry.cpi.AppCatalog; import org.apache.airavata.registry.cpi.AppCatalogException; import org.apache.airavata.registry.cpi.ExperimentCatalog; import org.apache.airavata.registry.cpi.RegistryException; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; import java.util.UUID; public abstract class Factory { private static final Logger log = LoggerFactory.getLogger(Factory.class); /* static{ try { loadConfiguration(); } catch (GFacException e) { log.error("Error while loading configurations"); } }*/ private static GFacEngine engine; private static GFacContext gfacContext; private static Publisher statusPublisher; private static CuratorFramework curatorClient; private static EmailBasedMonitor emailBasedMonitor; private static Map<String, RemoteCluster> remoteClusterMap = new HashMap<>(); private static Map<JobSubmissionProtocol, JobSubmissionTask> jobSubmissionTask = new HashMap<>(); private static Map<DataMovementProtocol, Task> dataMovementTask = new HashMap<>(); private static Map<ResourceJobManagerType, ResourceConfig> resources = new HashMap<>(); private static Map<MonitorMode, JobMonitor> jobMonitorServices = new HashMap<>(); private static RabbitMQProcessLaunchConsumer processLaunchConsumer; private static Map<String, Session> sessionMap = new HashMap<>(); public static GFacEngine getGFacEngine() throws GFacException { if (engine == null) { synchronized (GFacEngineImpl.class) { if (engine == null) { engine = new GFacEngineImpl(); } } } return engine; } public static GFacContext getGfacContext() { if (gfacContext == null) { gfacContext = GFacContext.getInstance(); } return gfacContext; } public static ExperimentCatalog getDefaultExpCatalog() throws RegistryException { return RegistryFactory.getDefaultExpCatalog(); } public static AppCatalog getDefaultAppCatalog() throws AppCatalogException { return RegistryFactory.getAppCatalog(); } public static Publisher getStatusPublisher() throws AiravataException { if (statusPublisher == null) { synchronized (RabbitMQStatusPublisher.class) { if (statusPublisher == null) { statusPublisher = new RabbitMQStatusPublisher(); } } } return statusPublisher; } public static CuratorFramework getCuratorClient() throws ApplicationSettingsException { if (curatorClient == null) { synchronized (Factory.class) { if (curatorClient == null) { String connectionSting = ServerSettings.getZookeeperConnection(); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5); curatorClient = CuratorFrameworkFactory.newClient(connectionSting, retryPolicy); } } } return curatorClient; } public static RabbitMQProcessLaunchConsumer getProcessLaunchConsumer() throws AiravataException { if (processLaunchConsumer == null) { processLaunchConsumer = new RabbitMQProcessLaunchConsumer(); } return processLaunchConsumer; } public static JobManagerConfiguration getJobManagerConfiguration(ResourceJobManager resourceJobManager) throws GFacException { ResourceConfig resourceConfig = Factory.getResourceConfig(resourceJobManager.getResourceJobManagerType()); OutputParser outputParser; try { Class<? extends OutputParser> aClass = Class.forName(resourceConfig.getCommandOutputParser()).asSubclass (OutputParser.class); outputParser = aClass.getConstructor().newInstance(); } catch (Exception e) { throw new GFacException("Error while instantiating output parser for " + resourceJobManager .getResourceJobManagerType().name()); } switch (resourceJobManager.getResourceJobManagerType()) { case PBS: return new PBSJobConfiguration("PBSTemplate.xslt", ".pbs", resourceJobManager.getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); case SLURM: return new SlurmJobConfiguration("SLURMTemplate.xslt", ".slurm", resourceJobManager .getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); case LSF: return new LSFJobConfiguration("LSFTemplate.xslt", ".lsf", resourceJobManager.getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); case UGE: return new UGEJobConfiguration("UGETemplate.xslt", ".pbs", resourceJobManager.getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); case FORK: return new ForkJobConfiguration("ForkTemplate.xslt", ".sh", resourceJobManager.getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); default: return null; } } public static HostScheduler getHostScheduler() { return new DefaultHostScheduler(); } /** * Factory class manage reomete cluster map, this will solve too many connections/ sessions issues with cluster * communications. * @param processContext * @return * @throws GFacException * @throws AppCatalogException * @throws AiravataException */ public static RemoteCluster getJobSubmissionRemoteCluster(ProcessContext processContext) throws GFacException, AppCatalogException, AiravataException { String computeResourceId = processContext.getComputeResourceId(); JobSubmissionProtocol jobSubmissionProtocol = processContext.getJobSubmissionProtocol(); String key = jobSubmissionProtocol.name() + ":" + computeResourceId; RemoteCluster remoteCluster = remoteClusterMap.get(key); if (remoteCluster == null) { JobManagerConfiguration jobManagerConfiguration = getJobManagerConfiguration(processContext.getResourceJobManager()); if (jobSubmissionProtocol == JobSubmissionProtocol.LOCAL || jobSubmissionProtocol == JobSubmissionProtocol.LOCAL_FORK) { remoteCluster = new LocalRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, null); } else if (jobSubmissionProtocol == JobSubmissionProtocol.SSH || jobSubmissionProtocol == JobSubmissionProtocol.SSH_FORK) { remoteCluster = new HPCRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, processContext.getSshKeyAuthentication()); } remoteClusterMap.put(key, remoteCluster); }else { AuthenticationInfo authentication = remoteCluster.getAuthentication(); if (authentication instanceof SSHKeyAuthentication){ SSHKeyAuthentication sshKeyAuthentication = (SSHKeyAuthentication)authentication; if (!sshKeyAuthentication.getUserName().equals(processContext.getComputeResourcePreference().getLoginUserName())){ JobManagerConfiguration jobManagerConfiguration = getJobManagerConfiguration(processContext.getResourceJobManager()); if (jobSubmissionProtocol == JobSubmissionProtocol.SSH || jobSubmissionProtocol == JobSubmissionProtocol.SSH_FORK) { remoteCluster = new HPCRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, processContext.getSshKeyAuthentication()); } } } } return remoteCluster; } public static RemoteCluster getDataMovementRemoteCluster(ProcessContext processContext) throws GFacException, AiravataException { String computeResourceId = processContext.getComputeResourceId(); DataMovementProtocol dataMovementProtocol = processContext.getDataMovementProtocol(); String key = dataMovementProtocol.name() + ":" + computeResourceId; RemoteCluster remoteCluster = remoteClusterMap.get(key); if (remoteCluster == null) { JobManagerConfiguration jobManagerConfiguration = getJobManagerConfiguration(processContext.getResourceJobManager()); if (dataMovementProtocol == DataMovementProtocol.LOCAL) { remoteCluster = new LocalRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, null); } else if (dataMovementProtocol == DataMovementProtocol.SCP) { remoteCluster = new HPCRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, processContext.getSshKeyAuthentication()); } remoteClusterMap.put(key, remoteCluster); }else { AuthenticationInfo authentication = remoteCluster.getAuthentication(); if (authentication instanceof SSHKeyAuthentication){ SSHKeyAuthentication sshKeyAuthentication = (SSHKeyAuthentication)authentication; if (!sshKeyAuthentication.getUserName().equals(processContext.getComputeResourcePreference().getLoginUserName())){ JobManagerConfiguration jobManagerConfiguration = getJobManagerConfiguration(processContext.getResourceJobManager()); dataMovementProtocol = processContext.getDataMovementProtocol(); if (dataMovementProtocol == DataMovementProtocol.SCP) { remoteCluster = new HPCRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, processContext.getSshKeyAuthentication()); } } } } return remoteCluster; } public static SSHKeyAuthentication getComputerResourceSSHKeyAuthentication(ProcessContext pc) throws GFacException { try { ComputeResourcePreference computeResourcePreference = pc.getComputeResourcePreference(); String loginUserName = computeResourcePreference.getLoginUserName(); String credentialStoreToken = computeResourcePreference.getResourceSpecificCredentialStoreToken(); if (credentialStoreToken == null || credentialStoreToken.isEmpty()) { credentialStoreToken = pc.getGatewayResourceProfile().getCredentialStoreToken(); } return getSshKeyAuthentication(pc.getGatewayId(),loginUserName, credentialStoreToken); } catch (ApplicationSettingsException | IllegalAccessException | InstantiationException | CredentialStoreException e) { throw new GFacException("Couldn't build ssh authentication object", e); } } public static SSHKeyAuthentication getStorageSSHKeyAuthentication(ProcessContext pc) throws GFacException { try { StoragePreference storagePreference = pc.getStoragePreference(); String loginUserName = storagePreference.getLoginUserName(); String credentialStoreToken = storagePreference.getResourceSpecificCredentialStoreToken(); if (credentialStoreToken == null || credentialStoreToken.isEmpty()) { credentialStoreToken = pc.getGatewayResourceProfile().getCredentialStoreToken(); } return getSshKeyAuthentication(pc.getGatewayId(), loginUserName, credentialStoreToken); } catch (ApplicationSettingsException | IllegalAccessException | InstantiationException | CredentialStoreException e) { throw new GFacException("Couldn't build ssh authentication object", e); } } private static SSHKeyAuthentication getSshKeyAuthentication(String gatewayId, String loginUserName, String credentialStoreToken) throws ApplicationSettingsException, IllegalAccessException, InstantiationException, CredentialStoreException, GFacException { SSHKeyAuthentication sshKA;CredentialReader credentialReader = GFacUtils.getCredentialReader(); Credential credential = credentialReader.getCredential(gatewayId, credentialStoreToken); if (credential instanceof SSHCredential) { sshKA = new SSHKeyAuthentication(); sshKA.setUserName(loginUserName); SSHCredential sshCredential = (SSHCredential) credential; sshKA.setPublicKey(sshCredential.getPublicKey()); sshKA.setPrivateKey(sshCredential.getPrivateKey()); sshKA.setPassphrase(sshCredential.getPassphrase()); sshKA.setStrictHostKeyChecking("no"); /* sshKA.setStrictHostKeyChecking(ServerSettings.getSetting("ssh.strict.hostKey.checking", "no")); sshKA.setKnownHostsFilePath(ServerSettings.getSetting("ssh.known.hosts.file", null)); if (sshKA.getStrictHostKeyChecking().equals("yes") && sshKA.getKnownHostsFilePath() == null) { throw new ApplicationSettingsException("If ssh strict hostkey checking property is set to yes, you must " + "provide known host file path"); }*/ return sshKA; } else { String msg = "Provided credential store token is not valid. Please provide the correct credential store token"; log.error(msg); throw new GFacException("Invalid credential store token:" + credentialStoreToken); } } public static JobSubmissionTask getJobSubmissionTask(JobSubmissionProtocol jobSubmissionProtocol) { return jobSubmissionTask.get(jobSubmissionProtocol); } public static Task getDataMovementTask(DataMovementProtocol dataMovementProtocol){ return dataMovementTask.get(dataMovementProtocol); } public static ResourceConfig getResourceConfig(ResourceJobManagerType resourceJobManagerType) { return resources.get(resourceJobManagerType); } public static Map<ResourceJobManagerType, ResourceConfig> getResourceConfig() { return resources; } public static void loadConfiguration() throws GFacException { GFacYamlConfigruation config = new GFacYamlConfigruation(); try { for (JobSubmitterTaskConfig jobSubmitterTaskConfig : config.getJobSbumitters()) { String taskClass = jobSubmitterTaskConfig.getTaskClass(); Class<?> aClass = Class.forName(taskClass); Constructor<?> constructor = aClass.getConstructor(); JobSubmissionTask task = (JobSubmissionTask) constructor.newInstance(); task.init(jobSubmitterTaskConfig.getProperties()); jobSubmissionTask.put(jobSubmitterTaskConfig.getSubmissionProtocol(), task); } for (DataTransferTaskConfig dataTransferTaskConfig : config.getFileTransferTasks()) { String taskClass = dataTransferTaskConfig.getTaskClass(); Class<?> aClass = Class.forName(taskClass); Constructor<?> constructor = aClass.getConstructor(); Task task = (Task) constructor.newInstance(); task.init(dataTransferTaskConfig.getProperties()); dataMovementTask.put(dataTransferTaskConfig.getTransferProtocol(), task); } for (ResourceConfig resourceConfig : config.getResourceConfiguration()) { resources.put(resourceConfig.getJobManagerType(), resourceConfig); } } catch (Exception e) { throw new GFacException("Gfac config issue", e); } } public static JobMonitor getMonitorService(MonitorMode monitorMode) throws AiravataException { JobMonitor jobMonitor = jobMonitorServices.get(monitorMode); if (jobMonitor == null) { synchronized (JobMonitor.class) { jobMonitor = jobMonitorServices.get(monitorMode); if (jobMonitor == null) { switch (monitorMode) { case JOB_EMAIL_NOTIFICATION_MONITOR: EmailBasedMonitor emailBasedMonitor = new EmailBasedMonitor(Factory.getResourceConfig()); jobMonitorServices.put(MonitorMode.JOB_EMAIL_NOTIFICATION_MONITOR, emailBasedMonitor); jobMonitor = ((JobMonitor) emailBasedMonitor); new Thread(emailBasedMonitor).start(); } } } } return jobMonitor; } public static JobMonitor getDefaultMonitorService() throws AiravataException { return getMonitorService(MonitorMode.JOB_EMAIL_NOTIFICATION_MONITOR); } public static RedeliveryRequestWatcher getRedeliveryReqeustWatcher(String experimentId, String processId) { return new RedeliveryRequestWatcherImpl(experimentId, processId); } public static CancelRequestWatcher getCancelRequestWatcher(String experimentId, String processId) { return new CancelRequestWatcherImpl(experimentId, processId); } public static Session getSSHSession(AuthenticationInfo authenticationInfo, ServerInfo serverInfo) throws AiravataException { SSHKeyAuthentication authentication = null; String key = serverInfo.getUserName() + "_" + serverInfo.getHost() + "_" + serverInfo.getPort(); Session session = sessionMap.get(key); if (session == null || !session.isConnected()) { try { if (authenticationInfo instanceof SSHKeyAuthentication) { authentication = (SSHKeyAuthentication) authenticationInfo; } else { throw new AiravataException("Support ssh key authentication only"); } JSch jSch = new JSch(); jSch.addIdentity(UUID.randomUUID().toString(), authentication.getPrivateKey(), authentication.getPublicKey(), authentication.getPassphrase().getBytes()); session = jSch.getSession(serverInfo.getUserName(), serverInfo.getHost(), serverInfo.getPort()); session.setUserInfo(new DefaultUserInfo(serverInfo.getUserName(), null, authentication.getPassphrase())); if (authentication.getStrictHostKeyChecking().equals("yes")) { jSch.setKnownHosts(authentication.getKnownHostsFilePath()); } else { session.setConfig("StrictHostKeyChecking","no"); } session.connect(); // 0 connection timeout sessionMap.put(key, session); } catch (JSchException e) { throw new AiravataException("JSch initialization error ", e); } } return sessionMap.get(key); } public static Task getArchiveTask() { return new ArchiveTask(); } private static class DefaultUserInfo implements UserInfo { private String userName; private String password; private String passphrase; public DefaultUserInfo(String userName, String password, String passphrase) { this.userName = userName; this.password = password; this.passphrase = passphrase; } @Override public String getPassphrase() { return null; } @Override public String getPassword() { return null; } @Override public boolean promptPassword(String s) { return false; } @Override public boolean promptPassphrase(String s) { return false; } @Override public boolean promptYesNo(String s) { return false; } @Override public void showMessage(String s) { } } }
modules/gfac/gfac-impl/src/main/java/org/apache/airavata/gfac/impl/Factory.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.airavata.gfac.impl; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.UserInfo; import org.apache.airavata.common.exception.AiravataException; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.utils.ServerSettings; import org.apache.airavata.credential.store.credential.Credential; import org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential; import org.apache.airavata.credential.store.store.CredentialReader; import org.apache.airavata.credential.store.store.CredentialStoreException; import org.apache.airavata.gfac.core.GFacEngine; import org.apache.airavata.gfac.core.GFacException; import org.apache.airavata.gfac.core.GFacUtils; import org.apache.airavata.gfac.core.JobManagerConfiguration; import org.apache.airavata.gfac.core.authentication.AuthenticationInfo; import org.apache.airavata.gfac.core.authentication.SSHKeyAuthentication; import org.apache.airavata.gfac.core.cluster.OutputParser; import org.apache.airavata.gfac.core.cluster.RemoteCluster; import org.apache.airavata.gfac.core.cluster.ServerInfo; import org.apache.airavata.gfac.core.config.DataTransferTaskConfig; import org.apache.airavata.gfac.core.config.GFacYamlConfigruation; import org.apache.airavata.gfac.core.config.JobSubmitterTaskConfig; import org.apache.airavata.gfac.core.config.ResourceConfig; import org.apache.airavata.gfac.core.context.GFacContext; import org.apache.airavata.gfac.core.context.ProcessContext; import org.apache.airavata.gfac.core.monitor.JobMonitor; import org.apache.airavata.gfac.core.scheduler.HostScheduler; import org.apache.airavata.gfac.core.task.JobSubmissionTask; import org.apache.airavata.gfac.core.task.Task; import org.apache.airavata.gfac.core.watcher.CancelRequestWatcher; import org.apache.airavata.gfac.core.watcher.RedeliveryRequestWatcher; import org.apache.airavata.gfac.impl.job.*; import org.apache.airavata.gfac.impl.task.ArchiveTask; import org.apache.airavata.gfac.impl.watcher.CancelRequestWatcherImpl; import org.apache.airavata.gfac.impl.watcher.RedeliveryRequestWatcherImpl; import org.apache.airavata.gfac.monitor.email.EmailBasedMonitor; import org.apache.airavata.messaging.core.Publisher; import org.apache.airavata.messaging.core.impl.RabbitMQProcessLaunchConsumer; import org.apache.airavata.messaging.core.impl.RabbitMQStatusPublisher; import org.apache.airavata.model.appcatalog.computeresource.*; import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference; import org.apache.airavata.model.appcatalog.gatewayprofile.StoragePreference; import org.apache.airavata.model.commons.ErrorModel; import org.apache.airavata.model.data.movement.DataMovementProtocol; import org.apache.airavata.model.status.TaskState; import org.apache.airavata.registry.core.experiment.catalog.impl.RegistryFactory; import org.apache.airavata.registry.cpi.AppCatalog; import org.apache.airavata.registry.cpi.AppCatalogException; import org.apache.airavata.registry.cpi.ExperimentCatalog; import org.apache.airavata.registry.cpi.RegistryException; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; import java.util.UUID; public abstract class Factory { private static final Logger log = LoggerFactory.getLogger(Factory.class); /* static{ try { loadConfiguration(); } catch (GFacException e) { log.error("Error while loading configurations"); } }*/ private static GFacEngine engine; private static GFacContext gfacContext; private static Publisher statusPublisher; private static CuratorFramework curatorClient; private static EmailBasedMonitor emailBasedMonitor; private static Map<String, RemoteCluster> remoteClusterMap = new HashMap<>(); private static Map<JobSubmissionProtocol, JobSubmissionTask> jobSubmissionTask = new HashMap<>(); private static Map<DataMovementProtocol, Task> dataMovementTask = new HashMap<>(); private static Map<ResourceJobManagerType, ResourceConfig> resources = new HashMap<>(); private static Map<MonitorMode, JobMonitor> jobMonitorServices = new HashMap<>(); private static RabbitMQProcessLaunchConsumer processLaunchConsumer; private static Map<String, Session> sessionMap = new HashMap<>(); public static GFacEngine getGFacEngine() throws GFacException { if (engine == null) { synchronized (GFacEngineImpl.class) { if (engine == null) { engine = new GFacEngineImpl(); } } } return engine; } public static GFacContext getGfacContext() { if (gfacContext == null) { gfacContext = GFacContext.getInstance(); } return gfacContext; } public static ExperimentCatalog getDefaultExpCatalog() throws RegistryException { return RegistryFactory.getDefaultExpCatalog(); } public static AppCatalog getDefaultAppCatalog() throws AppCatalogException { return RegistryFactory.getAppCatalog(); } public static Publisher getStatusPublisher() throws AiravataException { if (statusPublisher == null) { synchronized (RabbitMQStatusPublisher.class) { if (statusPublisher == null) { statusPublisher = new RabbitMQStatusPublisher(); } } } return statusPublisher; } public static CuratorFramework getCuratorClient() throws ApplicationSettingsException { if (curatorClient == null) { synchronized (Factory.class) { if (curatorClient == null) { String connectionSting = ServerSettings.getZookeeperConnection(); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5); curatorClient = CuratorFrameworkFactory.newClient(connectionSting, retryPolicy); } } } return curatorClient; } public static RabbitMQProcessLaunchConsumer getProcessLaunchConsumer() throws AiravataException { if (processLaunchConsumer == null) { processLaunchConsumer = new RabbitMQProcessLaunchConsumer(); } return processLaunchConsumer; } public static JobManagerConfiguration getJobManagerConfiguration(ResourceJobManager resourceJobManager) throws GFacException { ResourceConfig resourceConfig = Factory.getResourceConfig(resourceJobManager.getResourceJobManagerType()); OutputParser outputParser; try { Class<? extends OutputParser> aClass = Class.forName(resourceConfig.getCommandOutputParser()).asSubclass (OutputParser.class); outputParser = aClass.getConstructor().newInstance(); } catch (Exception e) { throw new GFacException("Error while instantiating output parser for " + resourceJobManager .getResourceJobManagerType().name()); } switch (resourceJobManager.getResourceJobManagerType()) { case PBS: return new PBSJobConfiguration("PBSTemplate.xslt", ".pbs", resourceJobManager.getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); case SLURM: return new SlurmJobConfiguration("SLURMTemplate.xslt", ".slurm", resourceJobManager .getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); case LSF: return new LSFJobConfiguration("LSFTemplate.xslt", ".lsf", resourceJobManager.getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); case UGE: return new UGEJobConfiguration("UGETemplate.xslt", ".pbs", resourceJobManager.getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); case FORK: return new ForkJobConfiguration("ForkTemplate.xslt", ".sh", resourceJobManager.getJobManagerBinPath(), resourceJobManager.getJobManagerCommands(), outputParser); default: return null; } } public static HostScheduler getHostScheduler() { return new DefaultHostScheduler(); } /** * Factory class manage reomete cluster map, this will solve too many connections/ sessions issues with cluster * communications. * @param processContext * @return * @throws GFacException * @throws AppCatalogException * @throws AiravataException */ public static RemoteCluster getJobSubmissionRemoteCluster(ProcessContext processContext) throws GFacException, AppCatalogException, AiravataException { String computeResourceId = processContext.getComputeResourceId(); JobSubmissionProtocol jobSubmissionProtocol = processContext.getJobSubmissionProtocol(); String key = jobSubmissionProtocol.name() + ":" + computeResourceId; RemoteCluster remoteCluster = remoteClusterMap.get(key); if (remoteCluster == null) { JobManagerConfiguration jobManagerConfiguration = getJobManagerConfiguration(processContext.getResourceJobManager()); if (jobSubmissionProtocol == JobSubmissionProtocol.LOCAL || jobSubmissionProtocol == JobSubmissionProtocol.LOCAL_FORK) { remoteCluster = new LocalRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, null); } else if (jobSubmissionProtocol == JobSubmissionProtocol.SSH || jobSubmissionProtocol == JobSubmissionProtocol.SSH_FORK) { remoteCluster = new HPCRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, processContext.getSshKeyAuthentication()); } remoteClusterMap.put(key, remoteCluster); }else { AuthenticationInfo authentication = remoteCluster.getAuthentication(); if (authentication instanceof SSHKeyAuthentication){ SSHKeyAuthentication sshKeyAuthentication = (SSHKeyAuthentication)authentication; if (!sshKeyAuthentication.getUserName().equals(processContext.getComputeResourcePreference().getLoginUserName())){ JobManagerConfiguration jobManagerConfiguration = getJobManagerConfiguration(processContext.getResourceJobManager()); if (jobSubmissionProtocol == JobSubmissionProtocol.SSH || jobSubmissionProtocol == JobSubmissionProtocol.SSH_FORK) { remoteCluster = new HPCRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, processContext.getSshKeyAuthentication()); } } } } return remoteCluster; } public static RemoteCluster getDataMovementRemoteCluster(ProcessContext processContext) throws GFacException, AiravataException { String computeResourceId = processContext.getComputeResourceId(); DataMovementProtocol dataMovementProtocol = processContext.getDataMovementProtocol(); String key = dataMovementProtocol.name() + ":" + computeResourceId; RemoteCluster remoteCluster = remoteClusterMap.get(key); if (remoteCluster == null) { JobManagerConfiguration jobManagerConfiguration = getJobManagerConfiguration(processContext.getResourceJobManager()); if (dataMovementProtocol == DataMovementProtocol.LOCAL) { remoteCluster = new LocalRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, null); } else if (dataMovementProtocol == DataMovementProtocol.SCP) { remoteCluster = new HPCRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, processContext.getSshKeyAuthentication()); } remoteClusterMap.put(key, remoteCluster); }else { AuthenticationInfo authentication = remoteCluster.getAuthentication(); if (authentication instanceof SSHKeyAuthentication){ SSHKeyAuthentication sshKeyAuthentication = (SSHKeyAuthentication)authentication; if (!sshKeyAuthentication.getUserName().equals(processContext.getComputeResourcePreference().getLoginUserName())){ JobManagerConfiguration jobManagerConfiguration = getJobManagerConfiguration(processContext.getResourceJobManager()); dataMovementProtocol = processContext.getDataMovementProtocol(); if (dataMovementProtocol == DataMovementProtocol.SCP) { remoteCluster = new HPCRemoteCluster(processContext.getServerInfo(), jobManagerConfiguration, processContext.getSshKeyAuthentication()); } } } } return remoteCluster; } public static SSHKeyAuthentication getComputerResourceSSHKeyAuthentication(ProcessContext pc) throws GFacException { try { ComputeResourcePreference computeResourcePreference = pc.getComputeResourcePreference(); String loginUserName = computeResourcePreference.getLoginUserName(); String credentialStoreToken = computeResourcePreference.getResourceSpecificCredentialStoreToken(); if (credentialStoreToken == null || credentialStoreToken.isEmpty()) { credentialStoreToken = pc.getGatewayResourceProfile().getCredentialStoreToken(); } return getSshKeyAuthentication(pc.getGatewayId(),loginUserName, credentialStoreToken); } catch (ApplicationSettingsException | IllegalAccessException | InstantiationException | CredentialStoreException e) { throw new GFacException("Couldn't build ssh authentication object", e); } } public static SSHKeyAuthentication getStorageSSHKeyAuthentication(ProcessContext pc) throws GFacException { try { StoragePreference storagePreference = pc.getStoragePreference(); String loginUserName = storagePreference.getLoginUserName(); String credentialStoreToken = storagePreference.getResourceSpecificCredentialStoreToken(); if (credentialStoreToken == null || credentialStoreToken.isEmpty()) { credentialStoreToken = pc.getGatewayResourceProfile().getCredentialStoreToken(); } return getSshKeyAuthentication(pc.getGatewayId(), loginUserName, credentialStoreToken); } catch (ApplicationSettingsException | IllegalAccessException | InstantiationException | CredentialStoreException e) { throw new GFacException("Couldn't build ssh authentication object", e); } } private static SSHKeyAuthentication getSshKeyAuthentication(String gatewayId, String loginUserName, String credentialStoreToken) throws ApplicationSettingsException, IllegalAccessException, InstantiationException, CredentialStoreException, GFacException { SSHKeyAuthentication sshKA;CredentialReader credentialReader = GFacUtils.getCredentialReader(); Credential credential = credentialReader.getCredential(gatewayId, credentialStoreToken); if (credential instanceof SSHCredential) { sshKA = new SSHKeyAuthentication(); sshKA.setUserName(loginUserName); SSHCredential sshCredential = (SSHCredential) credential; sshKA.setPublicKey(sshCredential.getPublicKey()); sshKA.setPrivateKey(sshCredential.getPrivateKey()); sshKA.setPassphrase(sshCredential.getPassphrase()); sshKA.setStrictHostKeyChecking("no"); /* sshKA.setStrictHostKeyChecking(ServerSettings.getSetting("ssh.strict.hostKey.checking", "no")); sshKA.setKnownHostsFilePath(ServerSettings.getSetting("ssh.known.hosts.file", null)); if (sshKA.getStrictHostKeyChecking().equals("yes") && sshKA.getKnownHostsFilePath() == null) { throw new ApplicationSettingsException("If ssh strict hostkey checking property is set to yes, you must " + "provide known host file path"); }*/ return sshKA; } else { String msg = "Provided credential store token is not valid. Please provide the correct credential store token"; log.error(msg); throw new GFacException("Invalid credential store token:" + credentialStoreToken); } } public static JobSubmissionTask getJobSubmissionTask(JobSubmissionProtocol jobSubmissionProtocol) { return jobSubmissionTask.get(jobSubmissionProtocol); } public static Task getDataMovementTask(DataMovementProtocol dataMovementProtocol){ return dataMovementTask.get(dataMovementProtocol); } public static ResourceConfig getResourceConfig(ResourceJobManagerType resourceJobManagerType) { return resources.get(resourceJobManagerType); } public static Map<ResourceJobManagerType, ResourceConfig> getResourceConfig() { return resources; } public static void loadConfiguration() throws GFacException { GFacYamlConfigruation config = new GFacYamlConfigruation(); try { for (JobSubmitterTaskConfig jobSubmitterTaskConfig : config.getJobSbumitters()) { String taskClass = jobSubmitterTaskConfig.getTaskClass(); Class<?> aClass = Class.forName(taskClass); Constructor<?> constructor = aClass.getConstructor(); JobSubmissionTask task = (JobSubmissionTask) constructor.newInstance(); task.init(jobSubmitterTaskConfig.getProperties()); jobSubmissionTask.put(jobSubmitterTaskConfig.getSubmissionProtocol(), task); } for (DataTransferTaskConfig dataTransferTaskConfig : config.getFileTransferTasks()) { String taskClass = dataTransferTaskConfig.getTaskClass(); Class<?> aClass = Class.forName(taskClass); Constructor<?> constructor = aClass.getConstructor(); Task task = (Task) constructor.newInstance(); task.init(dataTransferTaskConfig.getProperties()); dataMovementTask.put(dataTransferTaskConfig.getTransferProtocol(), task); } for (ResourceConfig resourceConfig : config.getResourceConfiguration()) { resources.put(resourceConfig.getJobManagerType(), resourceConfig); } } catch (Exception e) { throw new GFacException("Gfac config issue", e); } } public static JobMonitor getMonitorService(MonitorMode monitorMode) throws AiravataException { JobMonitor jobMonitor = jobMonitorServices.get(monitorMode); if (jobMonitor == null) { synchronized (JobMonitor.class) { jobMonitor = jobMonitorServices.get(monitorMode); if (jobMonitor == null) { switch (monitorMode) { case JOB_EMAIL_NOTIFICATION_MONITOR: EmailBasedMonitor emailBasedMonitor = new EmailBasedMonitor(Factory.getResourceConfig()); jobMonitorServices.put(MonitorMode.JOB_EMAIL_NOTIFICATION_MONITOR, emailBasedMonitor); jobMonitor = ((JobMonitor) emailBasedMonitor); new Thread(emailBasedMonitor).start(); } } } } return jobMonitor; } public static JobMonitor getDefaultMonitorService() throws AiravataException { return getMonitorService(MonitorMode.JOB_EMAIL_NOTIFICATION_MONITOR); } public static RedeliveryRequestWatcher getRedeliveryReqeustWatcher(String experimentId, String processId) { return new RedeliveryRequestWatcherImpl(experimentId, processId); } public static CancelRequestWatcher getCancelRequestWatcher(String experimentId, String processId) { return new CancelRequestWatcherImpl(experimentId, processId); } public static Session getSSHSession(AuthenticationInfo authenticationInfo, ServerInfo serverInfo) throws AiravataException { SSHKeyAuthentication authentication = null; String key = serverInfo.getUserName() + "_" + serverInfo.getHost() + "_" + serverInfo.getPort(); if (sessionMap.get(key) == null) { try { if (authenticationInfo instanceof SSHKeyAuthentication) { authentication = (SSHKeyAuthentication) authenticationInfo; } else { throw new AiravataException("Support ssh key authentication only"); } JSch jSch = new JSch(); jSch.addIdentity(UUID.randomUUID().toString(), authentication.getPrivateKey(), authentication.getPublicKey(), authentication.getPassphrase().getBytes()); Session session = jSch.getSession(serverInfo.getUserName(), serverInfo.getHost(), serverInfo.getPort()); session.setUserInfo(new DefaultUserInfo(serverInfo.getUserName(), null, authentication.getPassphrase())); if (authentication.getStrictHostKeyChecking().equals("yes")) { jSch.setKnownHosts(authentication.getKnownHostsFilePath()); } else { session.setConfig("StrictHostKeyChecking","no"); } session.connect(); // 0 connection timeout sessionMap.put(key, session); } catch (JSchException e) { throw new AiravataException("JSch initialization error ", e); } } return sessionMap.get(key); } public static Task getArchiveTask() { return new ArchiveTask(); } private static class DefaultUserInfo implements UserInfo { private String userName; private String password; private String passphrase; public DefaultUserInfo(String userName, String password, String passphrase) { this.userName = userName; this.password = password; this.passphrase = passphrase; } @Override public String getPassphrase() { return null; } @Override public String getPassword() { return null; } @Override public boolean promptPassword(String s) { return false; } @Override public boolean promptPassphrase(String s) { return false; } @Override public boolean promptYesNo(String s) { return false; } @Override public void showMessage(String s) { } } }
Create new session if previous connection is closed
modules/gfac/gfac-impl/src/main/java/org/apache/airavata/gfac/impl/Factory.java
Create new session if previous connection is closed
<ide><path>odules/gfac/gfac-impl/src/main/java/org/apache/airavata/gfac/impl/Factory.java <ide> public static Session getSSHSession(AuthenticationInfo authenticationInfo, ServerInfo serverInfo) throws AiravataException { <ide> SSHKeyAuthentication authentication = null; <ide> String key = serverInfo.getUserName() + "_" + serverInfo.getHost() + "_" + serverInfo.getPort(); <del> if (sessionMap.get(key) == null) { <add> Session session = sessionMap.get(key); <add> if (session == null || !session.isConnected()) { <ide> try { <ide> if (authenticationInfo instanceof SSHKeyAuthentication) { <ide> authentication = (SSHKeyAuthentication) authenticationInfo; <ide> JSch jSch = new JSch(); <ide> jSch.addIdentity(UUID.randomUUID().toString(), authentication.getPrivateKey(), authentication.getPublicKey(), <ide> authentication.getPassphrase().getBytes()); <del> Session session = jSch.getSession(serverInfo.getUserName(), serverInfo.getHost(), <add> session = jSch.getSession(serverInfo.getUserName(), serverInfo.getHost(), <ide> serverInfo.getPort()); <ide> session.setUserInfo(new DefaultUserInfo(serverInfo.getUserName(), null, authentication.getPassphrase())); <ide> if (authentication.getStrictHostKeyChecking().equals("yes")) {
Java
apache-2.0
801fa11ab49ee39b625dfe2859ef9cefda202669
0
gamerson/liferay-blade-cli,gamerson/liferay-blade-cli,gamerson/liferay-blade-cli
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liferay.blade.cli.command; import com.liferay.blade.cli.TestUtil; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.stream.Stream; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.zeroturnaround.process.PidProcess; import org.zeroturnaround.process.ProcessUtil; import org.zeroturnaround.process.Processes; /** * @author Christopher Bryan Boyd * @author Gregory Amerson */ public class ServerStartCommandTest { @Before public void setUp() throws Exception { File testWorkspaceFile = temporaryFolder.newFolder("testWorkspaceDir"); _testWorkspacePath = testWorkspaceFile.toPath(); File extensionsFile = temporaryFolder.newFolder(".blade", "extensions"); _extensionsPath = extensionsFile.toPath(); } @Test public void testServerInitCustomEnvironment() throws Exception { _initBladeWorkspace(); _customizeProdProperties(); _initServerBundle("--environment", "prod"); Path bundleConfigPath = _getBundleConfigPath(); _validateBundleConfigFile(bundleConfigPath); } @Test public void testServerRunCommandTomcat() throws Exception { _findAndTerminateTomcat(false); _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _runServer(); _findAndTerminateTomcat(true); } @Test public void testServerRunCommandTomcatDebug() throws Exception { _findAndTerminateTomcat(false); _debugPort = _DEFAULT_DEBUG_PORT_TOMCAT; _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _runServerDebug(); _findAndTerminateTomcat(true); } @Test public void testServerRunCommandTomcatDebugCustomPort() throws Exception { _findAndTerminateTomcat(false); _debugPort = _getAvailablePort(); _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _runServerDebug(); _findAndTerminateTomcat(true); } @Test public void testServerRunCommandWildfly() throws Exception { _findAndTerminateWildfly(false); _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _runServer(); _findAndTerminateWildfly(true); } @Test public void testServerRunCommandWildflyDebug() throws Exception { _findAndTerminateWildfly(false); _debugPort = _DEFAULT_DEBUG_PORT_WILDFLY; _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _runServerDebug(); _findAndTerminateWildfly(true); } @Test public void testServerRunCommandWildflyDebugCustomPort() throws Exception { _findAndTerminateWildfly(false); _debugPort = _getAvailablePort(); _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _runServerDebug(); _findAndTerminateWildfly(true); } @Test public void testServerStartCommandExists() throws Exception { Assert.assertTrue(_commandExists("server", "start")); Assert.assertTrue(_commandExists("server start")); Assert.assertFalse(_commandExists("server", "startx")); Assert.assertFalse(_commandExists("server startx")); Assert.assertFalse(_commandExists("serverx", "start")); Assert.assertFalse(_commandExists("serverx start")); } @Test public void testServerStartCommandTomcat() throws Exception { _findAndTerminateTomcat(false); _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _startServer(); _findAndTerminateTomcat(true); } @Test public void testServerStartCommandTomcatDebug() throws Exception { _findAndTerminateTomcat(false); _debugPort = _DEFAULT_DEBUG_PORT_TOMCAT; _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _startServerDebug(); _findAndTerminateTomcat(true); } @Test public void testServerStartCommandTomcatDebugCustomPort() throws Exception { _findAndTerminateTomcat(false); _debugPort = _getAvailablePort(); _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _startServerDebug(); _findAndTerminateTomcat(true); } @Test public void testServerStartCommandWildfly() throws Exception { _findAndTerminateWildfly(false); _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _startServer(); _findAndTerminateWildfly(true); } @Test public void testServerStartCommandWildflyDebug() throws Exception { _findAndTerminateWildfly(false); _debugPort = _DEFAULT_DEBUG_PORT_WILDFLY; _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _startServerDebug(); _findAndTerminateWildfly(true); } @Test public void testServerStartCommandWildflyDebugCustomPort() throws Exception { _findAndTerminateWildfly(false); _debugPort = _getAvailablePort(); _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _startServerDebug(); _findAndTerminateWildfly(true); } @Test public void testServerStopCommandExists() throws Exception { Assert.assertTrue(_commandExists("server", "stop")); Assert.assertTrue(_commandExists("server stop")); Assert.assertFalse(_commandExists("server", "stopx")); Assert.assertFalse(_commandExists("server stopx")); Assert.assertFalse(_commandExists("serverx", "stopx")); Assert.assertFalse(_commandExists("serverx stop")); } @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private static int _getAvailablePort() { try (ServerSocket serverSocket = new ServerSocket(0)) { serverSocket.setReuseAddress(true); return serverSocket.getLocalPort(); } catch (IOException ioe) { throw new IllegalStateException("No available ports"); } } private static boolean _isDebugPortListening(int debugPort) { InetAddress loopbackAddress = InetAddress.getLoopbackAddress(); try (Socket socket = new Socket(loopbackAddress, debugPort)) { return true; } catch (IOException ioe) { return false; } } private static void _terminateProcess(PidProcess tomcatPidProcess) throws Exception { ProcessUtil.destroyForcefullyAndWait(tomcatPidProcess, 1, TimeUnit.MINUTES); String processName = tomcatPidProcess.getDescription(); Assert.assertFalse("Expected " + processName + " process to be destroyed.", tomcatPidProcess.isAlive()); } private void _addBundleToGradle(String bundleFileName) throws Exception { Path gradlePropertiesPath = _testWorkspacePath.resolve("gradle.properties"); String contents = new String(Files.readAllBytes(gradlePropertiesPath)); StringBuilder sb = new StringBuilder(); sb.append(_LIFERAY_WORKSPACE_BUNDLE_KEY); sb.append("="); sb.append(_LIFERAY_WORKSPACE_BUNDLE_URL); sb.append(bundleFileName); sb.append(System.lineSeparator()); String bundleUrl = sb.toString(); contents = bundleUrl + contents; Files.write(gradlePropertiesPath, bundleUrl.getBytes(), StandardOpenOption.TRUNCATE_EXISTING); } private void _addTomcatBundleToGradle() throws Exception { _addBundleToGradle(_LIFERAY_WORKSPACE_BUNDLE_TOMCAT); } private void _addWildflyBundleToGradle() throws Exception { _addBundleToGradle(_LIFERAY_WORKSPACE_BUNDLE_WILDFLY); } private boolean _commandExists(String... args) { try { TestUtil.runBlade(_testWorkspacePath, _extensionsPath, args); } catch (Throwable throwable) { String message = throwable.getMessage(); if (Objects.nonNull(message) && !message.contains("No such command")) { return true; } return false; } return false; } private void _customizeProdProperties() throws FileNotFoundException, IOException { Path prodConfigPath = _testWorkspacePath.resolve(Paths.get("configs", "prod", "portal-ext.properties")); Properties portalExtProperties = new Properties(); try (InputStream inputStream = Files.newInputStream(prodConfigPath)) { portalExtProperties.load(inputStream); } portalExtProperties.put("foo.bar", "foobar"); try (OutputStream outputStream = Files.newOutputStream(prodConfigPath)) { portalExtProperties.store(outputStream, ""); } } private void _findAndTerminateServer(Predicate<JavaProcess> processFilter, boolean assertFound) throws Exception { Optional<PidProcess> serverProcess = _findServerProcess(processFilter, assertFound); if (!serverProcess.isPresent()) { return; } boolean debugPortListening = false; if (_useDebug) { debugPortListening = _isDebugPortListening(_debugPort); Assert.assertEquals("Debug port not in a correct state", _useDebug, debugPortListening); } _terminateProcess(serverProcess.get()); if (_useDebug) { debugPortListening = _isDebugPortListening(_debugPort); Assert.assertFalse("Debug port should no longer be listening", debugPortListening); } } private void _findAndTerminateTomcat(boolean assertFound) throws Exception { _findAndTerminateServer( process -> { String displayName = process.getDisplayName(); return displayName.contains("org.apache.catalina.startup.Bootstrap"); }, assertFound); } private void _findAndTerminateWildfly(boolean assertFound) throws Exception { _findAndTerminateServer( process -> { String displayName = process.getDisplayName(); return displayName.contains("jboss-modules"); }, assertFound); } private Optional<JavaProcess> _findProcess( Collection<JavaProcess> javaProcesses, Predicate<JavaProcess> processFilter) { Stream<JavaProcess> stream = javaProcesses.stream(); return stream.filter( processFilter ).findFirst(); } private Optional<PidProcess> _findServerProcess(Predicate<JavaProcess> processFilter, boolean assertFound) throws InterruptedException, IOException { Collection<JavaProcess> javaProcesses = JavaProcesses.list(); Optional<JavaProcess> optionalProcess = _findProcess(javaProcesses, processFilter); if (assertFound) { Assert.assertTrue( "Expected to find server process:\n" + _printDisplayNames(javaProcesses), optionalProcess.isPresent()); } else { return Optional.ofNullable(null); } JavaProcess javaProcess = optionalProcess.get(); String processName = javaProcess.getDisplayName(); PidProcess pidProcess = Processes.newPidProcess(javaProcess.getId()); Assert.assertTrue("Expected " + processName + " process to be alive", pidProcess.isAlive()); return Optional.of(pidProcess); } private Path _getBundleConfigPath() { Path bundlesFolderPath = _testWorkspacePath.resolve("bundles"); boolean bundlesFolderExists = Files.exists(bundlesFolderPath); Assert.assertTrue(bundlesFolderExists); Path bundleConfigPath = bundlesFolderPath.resolve("portal-ext.properties"); boolean bundleConfigFileExists = Files.exists(bundleConfigPath); Assert.assertTrue(bundleConfigFileExists); return bundleConfigPath; } private String[] _getDebugArgs(String[] serverStartArgs) { Collection<String> serverStartArgsCollection = Arrays.asList(serverStartArgs); serverStartArgsCollection = new ArrayList<>(serverStartArgsCollection); serverStartArgsCollection.add("--debug"); serverStartArgsCollection.add("--port"); serverStartArgsCollection.add(String.valueOf(_debugPort)); serverStartArgs = serverStartArgsCollection.toArray(new String[0]); return serverStartArgs; } private void _initBladeWorkspace() throws Exception { String[] initArgs = {"--base", _testWorkspacePath.toString(), "init", "-v", "7.1"}; TestUtil.runBlade(_testWorkspacePath, _extensionsPath, initArgs); } private void _initServerBundle(String... additionalArgs) throws Exception { String[] serverInitArgs = {"--base", _testWorkspacePath.toString(), "server", "init"}; if ((additionalArgs != null) && (additionalArgs.length > 0)) { Collection<String> serverInitArgsCollection = Arrays.asList(serverInitArgs); Collection<String> additionalArgsCollection = Arrays.asList(additionalArgs); serverInitArgsCollection = new ArrayList<>(serverInitArgsCollection); serverInitArgsCollection.addAll(additionalArgsCollection); serverInitArgs = serverInitArgsCollection.toArray(new String[0]); } TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverInitArgs); } private String _printDisplayNames(Collection<JavaProcess> javaProcesses) { StringBuilder sb = new StringBuilder(); for (JavaProcess javaProcess : javaProcesses) { sb.append(javaProcess.getDisplayName() + System.lineSeparator()); } return sb.toString(); } private void _runServer() throws Exception, InterruptedException { String[] serverRunArgs = {"--base", _testWorkspacePath.toString(), "server", "run"}; int maxProcessId = JavaProcesses.maxProcessId(); CountDownLatch latch = new CountDownLatch(1); CompletableFuture.runAsync( () -> { latch.countDown(); TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverRunArgs); }, _executorService); latch.await(); int newMaxProcessId = JavaProcesses.maxProcessId(); int retries = 0; while ((newMaxProcessId == maxProcessId) && (retries < 12)) { Thread.sleep(5000); newMaxProcessId = JavaProcesses.maxProcessId(); retries++; } Assert.assertTrue("Expected a new process", newMaxProcessId > maxProcessId); } private void _runServerDebug() throws Exception, InterruptedException { _useDebug = true; String[] serverRunArgs = {"--base", _testWorkspacePath.toString(), "server", "run"}; int maxProcessId = JavaProcesses.maxProcessId(); final String[] serverRunDebugArgs = _getDebugArgs(serverRunArgs); CountDownLatch latch = new CountDownLatch(1); CompletableFuture.runAsync( () -> { latch.countDown(); TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverRunDebugArgs); }, _executorService); latch.await(); int newMaxProcessId = JavaProcesses.maxProcessId(); int retries = 0; while ((newMaxProcessId == maxProcessId) && (retries < 12)) { Thread.sleep(5000); newMaxProcessId = JavaProcesses.maxProcessId(); retries++; } Assert.assertTrue("Expected a new process", newMaxProcessId > maxProcessId); } private void _startServer() throws Exception, InterruptedException { String[] serverStartArgs = {"--base", _testWorkspacePath.toString(), "server", "start"}; int maxProcessId = JavaProcesses.maxProcessId(); CountDownLatch latch = new CountDownLatch(1); CompletableFuture.runAsync( () -> { latch.countDown(); TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverStartArgs); }, _executorService); latch.await(); int newMaxProcessId = JavaProcesses.maxProcessId(); int retries = 0; while ((newMaxProcessId == maxProcessId) && (retries < 12)) { Thread.sleep(5000); newMaxProcessId = JavaProcesses.maxProcessId(); retries++; } Assert.assertTrue("Expected a new process", newMaxProcessId > maxProcessId); } private void _startServerDebug() throws Exception, InterruptedException { _useDebug = true; String[] serverStartArgs = {"--base", _testWorkspacePath.toString(), "server", "start"}; int maxProcessId = JavaProcesses.maxProcessId(); final String[] serverStartArgsFinal = _getDebugArgs(serverStartArgs); CountDownLatch latch = new CountDownLatch(1); CompletableFuture.runAsync( () -> { latch.countDown(); TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverStartArgsFinal); }, _executorService); latch.await(); int newMaxProcessId = JavaProcesses.maxProcessId(); int retries = 0; while ((newMaxProcessId == maxProcessId) && (retries < 12)) { Thread.sleep(5000); newMaxProcessId = JavaProcesses.maxProcessId(); retries++; } Assert.assertTrue("Expected a new process", newMaxProcessId > maxProcessId); } private void _validateBundleConfigFile(Path bundleConfigPath) throws FileNotFoundException, IOException { Properties runtimePortalExtProperties = new Properties(); try (InputStream inputStream = Files.newInputStream(bundleConfigPath)) { runtimePortalExtProperties.load(inputStream); } String fooBarProperty = runtimePortalExtProperties.getProperty("foo.bar"); Assert.assertEquals("foobar", fooBarProperty); } private void _verifyBundlePath(String folderName) { Path bundlesPath = _testWorkspacePath.resolve(Paths.get("bundles", folderName)); boolean bundlesPathExists = Files.exists(bundlesPath); Assert.assertTrue("Bundles folder " + bundlesPath + " must exist", bundlesPathExists); } private void _verifyTomcatBundlePath() { _verifyBundlePath(_BUNDLE_FOLDER_NAME_TOMCAT); } private void _verifyWildflyBundlePath() { _verifyBundlePath(_BUNDLE_FOLDER_NAME_WILDFLY); } private static final String _BUNDLE_FOLDER_NAME_TOMCAT = "tomcat-9.0.10"; private static final String _BUNDLE_FOLDER_NAME_WILDFLY = "wildfly-11.0.0"; private static final int _DEFAULT_DEBUG_PORT_TOMCAT = 8000; private static final int _DEFAULT_DEBUG_PORT_WILDFLY = 8787; private static final String _LIFERAY_WORKSPACE_BUNDLE_KEY = "liferay.workspace.bundle.url"; private static final String _LIFERAY_WORKSPACE_BUNDLE_TOMCAT = "liferay-ce-portal-tomcat-7.1.1-ga2-20181112144637000.tar.gz"; private static final String _LIFERAY_WORKSPACE_BUNDLE_URL = "https://releases-cdn.liferay.com/portal/7.1.1-ga2/"; private static final String _LIFERAY_WORKSPACE_BUNDLE_WILDFLY = "liferay-ce-portal-wildfly-7.1.1-ga2-20181112144637000.tar.gz"; private int _debugPort = -1; private ExecutorService _executorService = Executors.newSingleThreadExecutor(); private Path _extensionsPath = null; private Path _testWorkspacePath = null; private boolean _useDebug = false; }
cli/src/test/java/com/liferay/blade/cli/command/ServerStartCommandTest.java
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liferay.blade.cli.command; import com.liferay.blade.cli.TestUtil; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.stream.Stream; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.zeroturnaround.process.PidProcess; import org.zeroturnaround.process.Processes; /** * @author Christopher Bryan Boyd * @author Gregory Amerson */ public class ServerStartCommandTest { @Before public void setUp() throws Exception { File testWorkspaceFile = temporaryFolder.newFolder("testWorkspaceDir"); _testWorkspacePath = testWorkspaceFile.toPath(); File extensionsFile = temporaryFolder.newFolder(".blade", "extensions"); _extensionsPath = extensionsFile.toPath(); } @Test public void testServerInitCustomEnvironment() throws Exception { _initBladeWorkspace(); _customizeProdProperties(); _initServerBundle("--environment", "prod"); Path bundleConfigPath = _getBundleConfigPath(); _validateBundleConfigFile(bundleConfigPath); } @Test public void testServerRunCommandTomcat() throws Exception { _findAndTerminateTomcat(false); _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _runServer(); _findAndTerminateTomcat(true); } @Test public void testServerRunCommandTomcatDebug() throws Exception { _findAndTerminateTomcat(false); _debugPort = _DEFAULT_DEBUG_PORT_TOMCAT; _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _runServerDebug(); _findAndTerminateTomcat(true); } @Test public void testServerRunCommandTomcatDebugCustomPort() throws Exception { _findAndTerminateTomcat(false); _debugPort = _getAvailablePort(); _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _runServerDebug(); _findAndTerminateTomcat(true); } @Test public void testServerRunCommandWildfly() throws Exception { _findAndTerminateWildfly(false); _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _runServer(); _findAndTerminateWildfly(true); } @Test public void testServerRunCommandWildflyDebug() throws Exception { _findAndTerminateWildfly(false); _debugPort = _DEFAULT_DEBUG_PORT_WILDFLY; _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _runServerDebug(); _findAndTerminateWildfly(true); } @Test public void testServerRunCommandWildflyDebugCustomPort() throws Exception { _findAndTerminateWildfly(false); _debugPort = _getAvailablePort(); _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _runServerDebug(); _findAndTerminateWildfly(true); } @Test public void testServerStartCommandExists() throws Exception { Assert.assertTrue(_commandExists("server", "start")); Assert.assertTrue(_commandExists("server start")); Assert.assertFalse(_commandExists("server", "startx")); Assert.assertFalse(_commandExists("server startx")); Assert.assertFalse(_commandExists("serverx", "start")); Assert.assertFalse(_commandExists("serverx start")); } @Test public void testServerStartCommandTomcat() throws Exception { _findAndTerminateTomcat(false); _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _startServer(); _findAndTerminateTomcat(true); } @Test public void testServerStartCommandTomcatDebug() throws Exception { _findAndTerminateTomcat(false); _debugPort = _DEFAULT_DEBUG_PORT_TOMCAT; _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _startServerDebug(); _findAndTerminateTomcat(true); } @Test public void testServerStartCommandTomcatDebugCustomPort() throws Exception { _findAndTerminateTomcat(false); _debugPort = _getAvailablePort(); _initBladeWorkspace(); _addTomcatBundleToGradle(); _initServerBundle(); _verifyTomcatBundlePath(); _startServerDebug(); _findAndTerminateTomcat(true); } @Test public void testServerStartCommandWildfly() throws Exception { _findAndTerminateWildfly(false); _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _startServer(); _findAndTerminateWildfly(true); } @Test public void testServerStartCommandWildflyDebug() throws Exception { _findAndTerminateWildfly(false); _debugPort = _DEFAULT_DEBUG_PORT_WILDFLY; _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _startServerDebug(); _findAndTerminateWildfly(true); } @Test public void testServerStartCommandWildflyDebugCustomPort() throws Exception { _findAndTerminateWildfly(false); _debugPort = _getAvailablePort(); _initBladeWorkspace(); _addWildflyBundleToGradle(); _initServerBundle(); _verifyWildflyBundlePath(); _startServerDebug(); _findAndTerminateWildfly(true); } @Test public void testServerStopCommandExists() throws Exception { Assert.assertTrue(_commandExists("server", "stop")); Assert.assertTrue(_commandExists("server stop")); Assert.assertFalse(_commandExists("server", "stopx")); Assert.assertFalse(_commandExists("server stopx")); Assert.assertFalse(_commandExists("serverx", "stopx")); Assert.assertFalse(_commandExists("serverx stop")); } @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private static int _getAvailablePort() { try (ServerSocket serverSocket = new ServerSocket(0)) { serverSocket.setReuseAddress(true); return serverSocket.getLocalPort(); } catch (IOException ioe) { throw new IllegalStateException("No available ports"); } } private static boolean _isDebugPortListening(int debugPort) { InetAddress loopbackAddress = InetAddress.getLoopbackAddress(); try (Socket socket = new Socket(loopbackAddress, debugPort)) { return true; } catch (IOException ioe) { return false; } } private static void _terminateProcess(PidProcess tomcatPidProcess) throws InterruptedException, IOException { tomcatPidProcess.destroyForcefully(); tomcatPidProcess.waitFor(1, TimeUnit.MINUTES); String processName = tomcatPidProcess.getDescription(); Assert.assertFalse("Expected " + processName + " process to be destroyed.", tomcatPidProcess.isAlive()); } private void _addBundleToGradle(String bundleFileName) throws Exception { Path gradlePropertiesPath = _testWorkspacePath.resolve("gradle.properties"); String contents = new String(Files.readAllBytes(gradlePropertiesPath)); StringBuilder sb = new StringBuilder(); sb.append(_LIFERAY_WORKSPACE_BUNDLE_KEY); sb.append("="); sb.append(_LIFERAY_WORKSPACE_BUNDLE_URL); sb.append(bundleFileName); sb.append(System.lineSeparator()); String bundleUrl = sb.toString(); contents = bundleUrl + contents; Files.write(gradlePropertiesPath, bundleUrl.getBytes(), StandardOpenOption.TRUNCATE_EXISTING); } private void _addTomcatBundleToGradle() throws Exception { _addBundleToGradle(_LIFERAY_WORKSPACE_BUNDLE_TOMCAT); } private void _addWildflyBundleToGradle() throws Exception { _addBundleToGradle(_LIFERAY_WORKSPACE_BUNDLE_WILDFLY); } private boolean _commandExists(String... args) { try { TestUtil.runBlade(_testWorkspacePath, _extensionsPath, args); } catch (Throwable throwable) { String message = throwable.getMessage(); if (Objects.nonNull(message) && !message.contains("No such command")) { return true; } return false; } return false; } private void _customizeProdProperties() throws FileNotFoundException, IOException { Path prodConfigPath = _testWorkspacePath.resolve(Paths.get("configs", "prod", "portal-ext.properties")); Properties portalExtProperties = new Properties(); try (InputStream inputStream = Files.newInputStream(prodConfigPath)) { portalExtProperties.load(inputStream); } portalExtProperties.put("foo.bar", "foobar"); try (OutputStream outputStream = Files.newOutputStream(prodConfigPath)) { portalExtProperties.store(outputStream, ""); } } private void _findAndTerminateServer(Predicate<JavaProcess> processFilter, boolean assertFound) throws Exception { Optional<PidProcess> serverProcess = _findServerProcess(processFilter, assertFound); if (!serverProcess.isPresent()) { return; } boolean debugPortListening = false; if (_useDebug) { debugPortListening = _isDebugPortListening(_debugPort); Assert.assertEquals("Debug port not in a correct state", _useDebug, debugPortListening); } _terminateProcess(serverProcess.get()); if (_useDebug) { debugPortListening = _isDebugPortListening(_debugPort); Assert.assertFalse("Debug port should no longer be listening", debugPortListening); } } private void _findAndTerminateTomcat(boolean assertFound) throws Exception { _findAndTerminateServer( process -> { String displayName = process.getDisplayName(); return displayName.contains("org.apache.catalina.startup.Bootstrap"); }, assertFound); } private void _findAndTerminateWildfly(boolean assertFound) throws Exception { _findAndTerminateServer( process -> { String displayName = process.getDisplayName(); return displayName.contains("jboss-modules"); }, assertFound); } private Optional<JavaProcess> _findProcess( Collection<JavaProcess> javaProcesses, Predicate<JavaProcess> processFilter) { Stream<JavaProcess> stream = javaProcesses.stream(); return stream.filter( processFilter ).findFirst(); } private Optional<PidProcess> _findServerProcess(Predicate<JavaProcess> processFilter, boolean assertFound) throws InterruptedException, IOException { Collection<JavaProcess> javaProcesses = JavaProcesses.list(); Optional<JavaProcess> optionalProcess = _findProcess(javaProcesses, processFilter); if (assertFound) { Assert.assertTrue( "Expected to find server process:\n" + _printDisplayNames(javaProcesses), optionalProcess.isPresent()); } else { return Optional.ofNullable(null); } JavaProcess javaProcess = optionalProcess.get(); String processName = javaProcess.getDisplayName(); PidProcess pidProcess = Processes.newPidProcess(javaProcess.getId()); Assert.assertTrue("Expected " + processName + " process to be alive", pidProcess.isAlive()); return Optional.of(pidProcess); } private Path _getBundleConfigPath() { Path bundlesFolderPath = _testWorkspacePath.resolve("bundles"); boolean bundlesFolderExists = Files.exists(bundlesFolderPath); Assert.assertTrue(bundlesFolderExists); Path bundleConfigPath = bundlesFolderPath.resolve("portal-ext.properties"); boolean bundleConfigFileExists = Files.exists(bundleConfigPath); Assert.assertTrue(bundleConfigFileExists); return bundleConfigPath; } private String[] _getDebugArgs(String[] serverStartArgs) { Collection<String> serverStartArgsCollection = Arrays.asList(serverStartArgs); serverStartArgsCollection = new ArrayList<>(serverStartArgsCollection); serverStartArgsCollection.add("--debug"); serverStartArgsCollection.add("--port"); serverStartArgsCollection.add(String.valueOf(_debugPort)); serverStartArgs = serverStartArgsCollection.toArray(new String[0]); return serverStartArgs; } private void _initBladeWorkspace() throws Exception { String[] initArgs = {"--base", _testWorkspacePath.toString(), "init", "-v", "7.1"}; TestUtil.runBlade(_testWorkspacePath, _extensionsPath, initArgs); } private void _initServerBundle(String... additionalArgs) throws Exception { String[] serverInitArgs = {"--base", _testWorkspacePath.toString(), "server", "init"}; if ((additionalArgs != null) && (additionalArgs.length > 0)) { Collection<String> serverInitArgsCollection = Arrays.asList(serverInitArgs); Collection<String> additionalArgsCollection = Arrays.asList(additionalArgs); serverInitArgsCollection = new ArrayList<>(serverInitArgsCollection); serverInitArgsCollection.addAll(additionalArgsCollection); serverInitArgs = serverInitArgsCollection.toArray(new String[0]); } TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverInitArgs); } private String _printDisplayNames(Collection<JavaProcess> javaProcesses) { StringBuilder sb = new StringBuilder(); for (JavaProcess javaProcess : javaProcesses) { sb.append(javaProcess.getDisplayName() + System.lineSeparator()); } return sb.toString(); } private void _runServer() throws Exception, InterruptedException { String[] serverRunArgs = {"--base", _testWorkspacePath.toString(), "server", "run"}; int maxProcessId = JavaProcesses.maxProcessId(); CountDownLatch latch = new CountDownLatch(1); CompletableFuture.runAsync( () -> { latch.countDown(); TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverRunArgs); }, _executorService); latch.await(); int newMaxProcessId = JavaProcesses.maxProcessId(); int retries = 0; while ((newMaxProcessId == maxProcessId) && (retries < 12)) { Thread.sleep(5000); newMaxProcessId = JavaProcesses.maxProcessId(); retries++; } Assert.assertTrue("Expected a new process", newMaxProcessId > maxProcessId); } private void _runServerDebug() throws Exception, InterruptedException { _useDebug = true; String[] serverRunArgs = {"--base", _testWorkspacePath.toString(), "server", "run"}; int maxProcessId = JavaProcesses.maxProcessId(); final String[] serverRunDebugArgs = _getDebugArgs(serverRunArgs); CountDownLatch latch = new CountDownLatch(1); CompletableFuture.runAsync( () -> { latch.countDown(); TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverRunDebugArgs); }, _executorService); latch.await(); int newMaxProcessId = JavaProcesses.maxProcessId(); int retries = 0; while ((newMaxProcessId == maxProcessId) && (retries < 12)) { Thread.sleep(5000); newMaxProcessId = JavaProcesses.maxProcessId(); retries++; } Assert.assertTrue("Expected a new process", newMaxProcessId > maxProcessId); } private void _startServer() throws Exception, InterruptedException { String[] serverStartArgs = {"--base", _testWorkspacePath.toString(), "server", "start"}; int maxProcessId = JavaProcesses.maxProcessId(); CountDownLatch latch = new CountDownLatch(1); CompletableFuture.runAsync( () -> { latch.countDown(); TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverStartArgs); }, _executorService); latch.await(); int newMaxProcessId = JavaProcesses.maxProcessId(); int retries = 0; while ((newMaxProcessId == maxProcessId) && (retries < 12)) { Thread.sleep(5000); newMaxProcessId = JavaProcesses.maxProcessId(); retries++; } Assert.assertTrue("Expected a new process", newMaxProcessId > maxProcessId); } private void _startServerDebug() throws Exception, InterruptedException { _useDebug = true; String[] serverStartArgs = {"--base", _testWorkspacePath.toString(), "server", "start"}; int maxProcessId = JavaProcesses.maxProcessId(); final String[] serverStartArgsFinal = _getDebugArgs(serverStartArgs); CountDownLatch latch = new CountDownLatch(1); CompletableFuture.runAsync( () -> { latch.countDown(); TestUtil.runBlade(_testWorkspacePath, _extensionsPath, serverStartArgsFinal); }, _executorService); latch.await(); int newMaxProcessId = JavaProcesses.maxProcessId(); int retries = 0; while ((newMaxProcessId == maxProcessId) && (retries < 12)) { Thread.sleep(5000); newMaxProcessId = JavaProcesses.maxProcessId(); retries++; } Assert.assertTrue("Expected a new process", newMaxProcessId > maxProcessId); } private void _validateBundleConfigFile(Path bundleConfigPath) throws FileNotFoundException, IOException { Properties runtimePortalExtProperties = new Properties(); try (InputStream inputStream = Files.newInputStream(bundleConfigPath)) { runtimePortalExtProperties.load(inputStream); } String fooBarProperty = runtimePortalExtProperties.getProperty("foo.bar"); Assert.assertEquals("foobar", fooBarProperty); } private void _verifyBundlePath(String folderName) { Path bundlesPath = _testWorkspacePath.resolve(Paths.get("bundles", folderName)); boolean bundlesPathExists = Files.exists(bundlesPath); Assert.assertTrue("Bundles folder " + bundlesPath + " must exist", bundlesPathExists); } private void _verifyTomcatBundlePath() { _verifyBundlePath(_BUNDLE_FOLDER_NAME_TOMCAT); } private void _verifyWildflyBundlePath() { _verifyBundlePath(_BUNDLE_FOLDER_NAME_WILDFLY); } private static final String _BUNDLE_FOLDER_NAME_TOMCAT = "tomcat-9.0.10"; private static final String _BUNDLE_FOLDER_NAME_WILDFLY = "wildfly-11.0.0"; private static final int _DEFAULT_DEBUG_PORT_TOMCAT = 8000; private static final int _DEFAULT_DEBUG_PORT_WILDFLY = 8787; private static final String _LIFERAY_WORKSPACE_BUNDLE_KEY = "liferay.workspace.bundle.url"; private static final String _LIFERAY_WORKSPACE_BUNDLE_TOMCAT = "liferay-ce-portal-tomcat-7.1.1-ga2-20181112144637000.tar.gz"; private static final String _LIFERAY_WORKSPACE_BUNDLE_URL = "https://releases-cdn.liferay.com/portal/7.1.1-ga2/"; private static final String _LIFERAY_WORKSPACE_BUNDLE_WILDFLY = "liferay-ce-portal-wildfly-7.1.1-ga2-20181112144637000.tar.gz"; private int _debugPort = -1; private ExecutorService _executorService = Executors.newSingleThreadExecutor(); private Path _extensionsPath = null; private Path _testWorkspacePath = null; private boolean _useDebug = false; }
use process util method
cli/src/test/java/com/liferay/blade/cli/command/ServerStartCommandTest.java
use process util method
<ide><path>li/src/test/java/com/liferay/blade/cli/command/ServerStartCommandTest.java <ide> import org.junit.rules.TemporaryFolder; <ide> <ide> import org.zeroturnaround.process.PidProcess; <add>import org.zeroturnaround.process.ProcessUtil; <ide> import org.zeroturnaround.process.Processes; <ide> <ide> /** <ide> } <ide> } <ide> <del> private static void _terminateProcess(PidProcess tomcatPidProcess) throws InterruptedException, IOException { <del> tomcatPidProcess.destroyForcefully(); <del> <del> tomcatPidProcess.waitFor(1, TimeUnit.MINUTES); <add> private static void _terminateProcess(PidProcess tomcatPidProcess) throws Exception { <add> ProcessUtil.destroyForcefullyAndWait(tomcatPidProcess, 1, TimeUnit.MINUTES); <ide> <ide> String processName = tomcatPidProcess.getDescription(); <ide>
Java
apache-2.0
f65f4ce97c4e59efeebd1554d3dbc6b8a4a7b6c6
0
avafanasiev/groovy,adjohnson916/groovy-core,aaronzirbes/incubator-groovy,gillius/incubator-groovy,russel/groovy,i55ac/incubator-groovy,apache/incubator-groovy,rlovtangen/groovy-core,russel/groovy,apache/incubator-groovy,sagarsane/groovy-core,avafanasiev/groovy,PascalSchumacher/incubator-groovy,ebourg/incubator-groovy,paulk-asert/groovy,paulk-asert/groovy,mariogarcia/groovy-core,russel/incubator-groovy,adjohnson916/incubator-groovy,groovy/groovy-core,paplorinc/incubator-groovy,mariogarcia/groovy-core,pickypg/incubator-groovy,pledbrook/incubator-groovy,genqiang/incubator-groovy,fpavageau/groovy,paulk-asert/incubator-groovy,yukangguo/incubator-groovy,aim-for-better/incubator-groovy,pickypg/incubator-groovy,upadhyayap/incubator-groovy,antoaravinth/incubator-groovy,ebourg/incubator-groovy,jwagenleitner/groovy,graemerocher/incubator-groovy,dpolivaev/groovy,sagarsane/groovy-core,samanalysis/incubator-groovy,apache/groovy,ebourg/incubator-groovy,avafanasiev/groovy,tkruse/incubator-groovy,alien11689/incubator-groovy,aaronzirbes/incubator-groovy,alien11689/groovy-core,i55ac/incubator-groovy,shils/groovy,nobeans/incubator-groovy,rabbitcount/incubator-groovy,mariogarcia/groovy-core,nobeans/incubator-groovy,bsideup/incubator-groovy,ebourg/groovy-core,PascalSchumacher/incubator-groovy,sagarsane/groovy-core,pickypg/incubator-groovy,aim-for-better/incubator-groovy,EPadronU/incubator-groovy,adjohnson916/groovy-core,ChanJLee/incubator-groovy,rlovtangen/groovy-core,rlovtangen/groovy-core,gillius/incubator-groovy,antoaravinth/incubator-groovy,alien11689/groovy-core,ebourg/groovy-core,traneHead/groovy-core,EPadronU/incubator-groovy,ebourg/groovy-core,aim-for-better/incubator-groovy,samanalysis/incubator-groovy,nkhuyu/incubator-groovy,upadhyayap/incubator-groovy,fpavageau/groovy,genqiang/incubator-groovy,alien11689/incubator-groovy,yukangguo/incubator-groovy,bsideup/groovy-core,christoph-frick/groovy-core,upadhyayap/incubator-groovy,jwagenleitner/incubator-groovy,russel/incubator-groovy,rabbitcount/incubator-groovy,kidaa/incubator-groovy,graemerocher/incubator-groovy,paulk-asert/groovy,tkruse/incubator-groovy,fpavageau/groovy,alien11689/groovy-core,i55ac/incubator-groovy,shils/groovy,rlovtangen/groovy-core,fpavageau/groovy,guangying945/incubator-groovy,rabbitcount/incubator-groovy,genqiang/incubator-groovy,apache/incubator-groovy,paulk-asert/incubator-groovy,paulk-asert/incubator-groovy,groovy/groovy-core,nobeans/incubator-groovy,armsargis/groovy,jwagenleitner/incubator-groovy,groovy/groovy-core,jwagenleitner/groovy,adjohnson916/incubator-groovy,tkruse/incubator-groovy,sagarsane/incubator-groovy,apache/groovy,nkhuyu/incubator-groovy,ebourg/incubator-groovy,graemerocher/incubator-groovy,paplorinc/incubator-groovy,PascalSchumacher/incubator-groovy,avafanasiev/groovy,samanalysis/incubator-groovy,upadhyayap/incubator-groovy,bsideup/incubator-groovy,PascalSchumacher/incubator-groovy,nobeans/incubator-groovy,eginez/incubator-groovy,yukangguo/incubator-groovy,bsideup/groovy-core,ChanJLee/incubator-groovy,sagarsane/incubator-groovy,aaronzirbes/incubator-groovy,kenzanmedia/incubator-groovy,jwagenleitner/groovy,EPadronU/incubator-groovy,pledbrook/incubator-groovy,traneHead/groovy-core,groovy/groovy-core,kidaa/incubator-groovy,eginez/incubator-groovy,ChanJLee/incubator-groovy,adjohnson916/incubator-groovy,dpolivaev/groovy,ebourg/groovy-core,jwagenleitner/incubator-groovy,shils/incubator-groovy,guangying945/incubator-groovy,shils/incubator-groovy,shils/groovy,aim-for-better/incubator-groovy,bsideup/incubator-groovy,taoguan/incubator-groovy,paulk-asert/incubator-groovy,mariogarcia/groovy-core,i55ac/incubator-groovy,apache/groovy,sagarsane/groovy-core,christoph-frick/groovy-core,alien11689/incubator-groovy,bsideup/groovy-core,pledbrook/incubator-groovy,bsideup/groovy-core,guangying945/incubator-groovy,taoguan/incubator-groovy,paplorinc/incubator-groovy,armsargis/groovy,armsargis/groovy,shils/incubator-groovy,traneHead/groovy-core,gillius/incubator-groovy,russel/groovy,adjohnson916/incubator-groovy,jwagenleitner/incubator-groovy,traneHead/groovy-core,eginez/incubator-groovy,genqiang/incubator-groovy,rlovtangen/groovy-core,groovy/groovy-core,dpolivaev/groovy,apache/groovy,nkhuyu/incubator-groovy,PascalSchumacher/incubator-groovy,shils/incubator-groovy,taoguan/incubator-groovy,eginez/incubator-groovy,shils/groovy,rabbitcount/incubator-groovy,dpolivaev/groovy,kenzanmedia/incubator-groovy,mariogarcia/groovy-core,armsargis/groovy,paulk-asert/incubator-groovy,antoaravinth/incubator-groovy,kidaa/incubator-groovy,nkhuyu/incubator-groovy,christoph-frick/groovy-core,alien11689/incubator-groovy,adjohnson916/groovy-core,tkruse/incubator-groovy,sagarsane/incubator-groovy,alien11689/groovy-core,christoph-frick/groovy-core,christoph-frick/groovy-core,antoaravinth/incubator-groovy,paulk-asert/groovy,guangying945/incubator-groovy,graemerocher/incubator-groovy,adjohnson916/groovy-core,ebourg/groovy-core,aaronzirbes/incubator-groovy,sagarsane/incubator-groovy,pickypg/incubator-groovy,kidaa/incubator-groovy,taoguan/incubator-groovy,bsideup/incubator-groovy,yukangguo/incubator-groovy,adjohnson916/groovy-core,EPadronU/incubator-groovy,pledbrook/incubator-groovy,apache/incubator-groovy,gillius/incubator-groovy,jwagenleitner/groovy,kenzanmedia/incubator-groovy,sagarsane/groovy-core,samanalysis/incubator-groovy,russel/groovy,russel/incubator-groovy,alien11689/groovy-core,russel/incubator-groovy,kenzanmedia/incubator-groovy,paplorinc/incubator-groovy,ChanJLee/incubator-groovy
/* * Copyright 2005 John G. Wilson * * 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 groovy.util.slurpersupport; import groovy.lang.Buildable; import groovy.lang.Closure; import groovy.lang.DelegatingMetaClass; import groovy.lang.GroovyObjectSupport; import groovy.lang.MetaClass; import groovy.lang.Writable; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; /** * @author John Wilson * */ public abstract class GPathResult extends GroovyObjectSupport implements Writable, Buildable { protected final GPathResult parent; protected final String name; protected final String namespacePrefix; protected final Map namespaceMap = new HashMap(); protected final Map namespaceTagHints; /** * @param parent * @param name */ public GPathResult(final GPathResult parent, final String name, final String namespacePrefix, final Map namespaceTagHints) { if (parent == null) { // we are the top of the tree this.parent = this; this.namespaceMap.put("xml", "http://www.w3.org/XML/1998/namespace"); // The XML namespace is always defined } else { this.parent = parent; this.namespaceMap.putAll(parent.namespaceMap); } this.name = name; this.namespacePrefix = namespacePrefix; this.namespaceTagHints = namespaceTagHints; setMetaClass(getMetaClass()); // wrap the standard MetaClass with the delegate } /* (non-Javadoc) * @see groovy.lang.GroovyObjectSupport#setMetaClass(groovy.lang.MetaClass) */ public void setMetaClass(final MetaClass metaClass) { final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) { /* (non-Javadoc) * @see groovy.lang.DelegatingMetaClass#getAttribute(java.lang.Object, java.lang.String) */ public Object getAttribute(Object object, String attribute) { return GPathResult.this.getProperty("@" + attribute); } }; super.setMetaClass(newMetaClass); } public Object getProperty(final String property) { if ("..".equals(property)) { return parent(); } else if ("*".equals(property)){ return children(); } else if ("**".equals(property)){ return depthFirst(); } else if (property.startsWith("@")) { if (property.indexOf(":") != -1) { final int i = property.indexOf(":"); return new Attributes(this, "@" + property.substring(i + 1), property.substring(1, i), this.namespaceTagHints); } else { return new Attributes(this, property, this.namespaceTagHints); } } else { if (property.indexOf(":") != -1) { final int i = property.indexOf(":"); return new NodeChildren(this, property.substring(i + 1), property.substring(0, i), this.namespaceTagHints); } else { return new NodeChildren(this, property, this.namespaceTagHints); } } } public String name() { return this.name; } public GPathResult parent() { return this.parent; } public GPathResult children() { return new NodeChildren(this, this.namespaceTagHints); } public String toString() { return text(); } public GPathResult declareNamespace(final Map newNamespaceMapping) { this.namespaceMap.putAll(newNamespaceMapping); return this; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return text().equals(obj.toString()); } public Object getAt(final int index) { final Iterator iter = iterator(); int count = 0; while (iter.hasNext()) { if (count++ == index) { return iter.next(); } else { iter.next(); } } throw new ArrayIndexOutOfBoundsException(index); } public Iterator depthFirst() { return new Iterator() { private final Stack stack = new Stack(); private Iterator iter = iterator(); private GPathResult next = getNextByDepth(); public boolean hasNext() { return this.next != null; } public Object next() { try { return this.next; } finally { this.next = getNextByDepth(); } } public void remove() { throw new UnsupportedOperationException(); } private GPathResult getNextByDepth() { while (this.iter.hasNext()) { final GPathResult node = (GPathResult)this.iter.next(); this.stack.push(node); this.stack.push(this.iter); this.iter = node.children().iterator(); } if (this.stack.empty()) { return null; } else { this.iter = (Iterator)this.stack.pop(); return (GPathResult)this.stack.pop(); } } }; } public List list() { final Iterator iter = nodeIterator(); final List result = new LinkedList(); while (iter.hasNext()) { result.add(iter.next()); } return result; } public abstract int size(); public abstract String text(); public abstract GPathResult parents(); public abstract Iterator childNodes(); public abstract Iterator iterator(); public abstract GPathResult find(Closure closure); public abstract GPathResult findAll(Closure closure); public abstract Iterator nodeIterator(); }
src/main/groovy/util/slurpersupport/GPathResult.java
/* * Copyright 2005 John G. Wilson * * 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 groovy.util.slurpersupport; import groovy.lang.Buildable; import groovy.lang.Closure; import groovy.lang.DelegatingMetaClass; import groovy.lang.GroovyObjectSupport; import groovy.lang.MetaClass; import groovy.lang.Writable; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * @author John Wilson * */ public abstract class GPathResult extends GroovyObjectSupport implements Writable, Buildable { protected final GPathResult parent; protected final String name; protected final String namespacePrefix; protected final Map namespaceMap = new HashMap(); protected final Map namespaceTagHints; /** * @param parent * @param name */ public GPathResult(final GPathResult parent, final String name, final String namespacePrefix, final Map namespaceTagHints) { if (parent == null) { // we are the top of the tree this.parent = this; this.namespaceMap.put("xml", "http://www.w3.org/XML/1998/namespace"); // The XML namespace is always defined } else { this.parent = parent; this.namespaceMap.putAll(parent.namespaceMap); } this.name = name; this.namespacePrefix = namespacePrefix; this.namespaceTagHints = namespaceTagHints; setMetaClass(getMetaClass()); // wrap the standard MetaClass with the delegate } /* (non-Javadoc) * @see groovy.lang.GroovyObjectSupport#setMetaClass(groovy.lang.MetaClass) */ public void setMetaClass(final MetaClass metaClass) { final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) { /* (non-Javadoc) * @see groovy.lang.DelegatingMetaClass#getAttribute(java.lang.Object, java.lang.String) */ public Object getAttribute(Object object, String attribute) { return GPathResult.this.getProperty("@" + attribute); } }; super.setMetaClass(newMetaClass); } public Object getProperty(final String property) { if ("..".equals(property)) { return parent(); } else if ("*".equals(property)){ return children(); } else if (property.startsWith("@")) { if (property.indexOf(":") != -1) { final int i = property.indexOf(":"); return new Attributes(this, "@" + property.substring(i + 1), property.substring(1, i), this.namespaceTagHints); } else { return new Attributes(this, property, this.namespaceTagHints); } } else { if (property.indexOf(":") != -1) { final int i = property.indexOf(":"); return new NodeChildren(this, property.substring(i + 1), property.substring(0, i), this.namespaceTagHints); } else { return new NodeChildren(this, property, this.namespaceTagHints); } } } public String name() { return this.name; } public GPathResult parent() { return this.parent; } public GPathResult children() { return new NodeChildren(this, this.namespaceTagHints); } public String toString() { return text(); } public GPathResult declareNamespace(final Map newNamespaceMapping) { this.namespaceMap.putAll(newNamespaceMapping); return this; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return text().equals(obj.toString()); } public Object getAt(final int index) { final Iterator iter = iterator(); int count = 0; while (iter.hasNext()) { if (count++ == index) { return iter.next(); } else { iter.next(); } } throw new ArrayIndexOutOfBoundsException(index); } public List list() { final Iterator iter = nodeIterator(); final List result = new LinkedList(); while (iter.hasNext()) { result.add(iter.next()); } return result; } public abstract int size(); public abstract String text(); public abstract GPathResult parents(); public abstract Iterator childNodes(); public abstract Iterator iterator(); public abstract GPathResult find(Closure closure); public abstract GPathResult findAll(Closure closure); public abstract Iterator nodeIterator(); }
Add depthFirst() whic returns an iteratore over all the nodes in the tree. The iteration is lsft to right starting with the deepest node. f."**" is equivalent to f.depthfirst() git-svn-id: aa43ce4553b005588bb3cc6c16966320b011facb@3210 a5544e8c-8a19-0410-ba12-f9af4593a198
src/main/groovy/util/slurpersupport/GPathResult.java
Add depthFirst() whic returns an iteratore over all the nodes in the tree. The iteration is lsft to right starting with the deepest node.
<ide><path>rc/main/groovy/util/slurpersupport/GPathResult.java <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.Stack; <ide> <ide> <ide> /** <ide> if ("..".equals(property)) { <ide> return parent(); <ide> } else if ("*".equals(property)){ <del> return children(); <add> return children(); <add> } else if ("**".equals(property)){ <add> return depthFirst(); <ide> } else if (property.startsWith("@")) { <ide> if (property.indexOf(":") != -1) { <ide> final int i = property.indexOf(":"); <ide> throw new ArrayIndexOutOfBoundsException(index); <ide> } <ide> <add> public Iterator depthFirst() { <add> return new Iterator() { <add> private final Stack stack = new Stack(); <add> private Iterator iter = iterator(); <add> private GPathResult next = getNextByDepth(); <add> <add> public boolean hasNext() { <add> return this.next != null; <add> } <add> <add> public Object next() { <add> try { <add> return this.next; <add> } finally { <add> this.next = getNextByDepth(); <add> } <add> } <add> <add> public void remove() { <add> throw new UnsupportedOperationException(); <add> } <add> <add> private GPathResult getNextByDepth() { <add> while (this.iter.hasNext()) { <add> final GPathResult node = (GPathResult)this.iter.next(); <add> <add> this.stack.push(node); <add> this.stack.push(this.iter); <add> this.iter = node.children().iterator(); <add> } <add> <add> if (this.stack.empty()) { <add> return null; <add> } else { <add> this.iter = (Iterator)this.stack.pop(); <add> return (GPathResult)this.stack.pop(); <add> } <add> } <add> }; <add> } <add> <ide> public List list() { <ide> final Iterator iter = nodeIterator(); <ide> final List result = new LinkedList();
Java
apache-2.0
83e1a028e5881e0a47728a64299b0be1b2bdf860
0
diffplug/spotless,diffplug/spotless,diffplug/spotless,diffplug/spotless,diffplug/spotless,diffplug/spotless
/* * Copyright 2016-2020 DiffPlug * * 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.diffplug.gradle.spotless; import static java.util.Objects.requireNonNull; import java.lang.reflect.Constructor; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.Nullable; import org.gradle.api.Action; import org.gradle.api.GradleException; import org.gradle.api.Project; import com.diffplug.common.base.Errors; import com.diffplug.spotless.LineEnding; public abstract class SpotlessExtensionBase { final Project project; protected static final String TASK_GROUP = "Verification"; protected static final String CHECK_DESCRIPTION = "Checks that sourcecode satisfies formatting steps."; protected static final String APPLY_DESCRIPTION = "Applies code formatting steps to sourcecode in-place."; static final String EXTENSION = "spotless"; static final String CHECK = "Check"; static final String APPLY = "Apply"; static final String DIAGNOSE = "Diagnose"; public SpotlessExtensionBase(Project project) { this.project = requireNonNull(project); } abstract RegisterDependenciesTask getRegisterDependenciesTask(); /** Line endings (if any). */ LineEnding lineEndings = LineEnding.GIT_ATTRIBUTES; public LineEnding getLineEndings() { return lineEndings; } public void setLineEndings(LineEnding lineEndings) { this.lineEndings = requireNonNull(lineEndings); } Charset encoding = StandardCharsets.UTF_8; /** Returns the encoding to use. */ public Charset getEncoding() { return encoding; } /** Sets encoding to use (defaults to UTF_8). */ public void setEncoding(String name) { requireNonNull(name); setEncoding(Charset.forName(name)); } /** Sets encoding to use (defaults to UTF_8). */ public void setEncoding(Charset charset) { encoding = requireNonNull(charset); } /** Sets encoding to use (defaults to UTF_8). */ public void encoding(String charset) { setEncoding(charset); } private @Nullable String ratchetFrom; /** * Limits the target to only the files which have changed since the given git reference, * which is resolved according to [this](https://javadoc.io/static/org.eclipse.jgit/org.eclipse.jgit/5.6.1.202002131546-r/org/eclipse/jgit/lib/Repository.html#resolve-java.lang.String-) */ public void setRatchetFrom(String ratchetFrom) { this.ratchetFrom = ratchetFrom; } /** @see #setRatchetFrom(String) */ public @Nullable String getRatchetFrom() { return ratchetFrom; } /** @see #setRatchetFrom(String) */ public void ratchetFrom(String ratchetFrom) { setRatchetFrom(ratchetFrom); } final Map<String, FormatExtension> formats = new LinkedHashMap<>(); /** Configures the special java-specific extension. */ public void java(Action<JavaExtension> closure) { requireNonNull(closure); format(JavaExtension.NAME, JavaExtension.class, closure); } /** Configures the special scala-specific extension. */ public void scala(Action<ScalaExtension> closure) { requireNonNull(closure); format(ScalaExtension.NAME, ScalaExtension.class, closure); } /** Configures the special kotlin-specific extension. */ public void kotlin(Action<KotlinExtension> closure) { requireNonNull(closure); format(KotlinExtension.NAME, KotlinExtension.class, closure); } /** Configures the special Gradle Kotlin DSL specific extension. */ public void kotlinGradle(Action<KotlinGradleExtension> closure) { requireNonNull(closure); format(KotlinGradleExtension.NAME, KotlinGradleExtension.class, closure); } /** Configures the special freshmark-specific extension. */ public void freshmark(Action<FreshMarkExtension> closure) { requireNonNull(closure); format(FreshMarkExtension.NAME, FreshMarkExtension.class, closure); } /** Configures the special groovy-specific extension. */ public void groovy(Action<GroovyExtension> closure) { format(GroovyExtension.NAME, GroovyExtension.class, closure); } /** Configures the special groovy-specific extension for Gradle files. */ public void groovyGradle(Action<GroovyGradleExtension> closure) { format(GroovyGradleExtension.NAME, GroovyGradleExtension.class, closure); } /** Configures the special sql-specific extension for SQL files. */ public void sql(Action<SqlExtension> closure) { format(SqlExtension.NAME, SqlExtension.class, closure); } /** Configures the special C/C++-specific extension. */ public void cpp(Action<CppExtension> closure) { format(CppExtension.NAME, CppExtension.class, closure); } /** Configures the special typescript-specific extension for typescript files. */ public void typescript(Action<TypescriptExtension> closure) { format(TypescriptExtension.NAME, TypescriptExtension.class, closure); } /** Configures the special antlr4-specific extension for antlr4 files. */ public void antlr4(Action<Antlr4Extension> closure) { format(Antlr4Extension.NAME, Antlr4Extension.class, closure); } /** Configures a custom extension. */ public void format(String name, Action<FormatExtension> closure) { requireNonNull(name, "name"); requireNonNull(closure, "closure"); format(name, FormatExtension.class, closure); } /** Makes it possible to remove a format which was created earlier. */ public void removeFormat(String name) { requireNonNull(name); FormatExtension toRemove = formats.remove(name); if (toRemove == null) { project.getLogger().warn("Called removeFormat('" + name + "') but there was no such format."); } } boolean enforceCheck = true; /** Returns `true` if Gradle's `check` task should run `spotlessCheck`; `false` otherwise. */ public boolean isEnforceCheck() { return enforceCheck; } /** * Configures Gradle's `check` task to run `spotlessCheck` if `true`, * but to not do so if `false`. * * `true` by default. */ public void setEnforceCheck(boolean enforceCheck) { this.enforceCheck = enforceCheck; } public <T extends FormatExtension> void format(String name, Class<T> clazz, Action<T> configure) { T format = maybeCreate(name, clazz); configure.execute(format); } @SuppressWarnings("unchecked") protected final <T extends FormatExtension> T maybeCreate(String name, Class<T> clazz) { FormatExtension existing = formats.get(name); if (existing != null) { if (!existing.getClass().equals(clazz)) { throw new GradleException("Tried to add format named '" + name + "'" + " of type " + clazz + " but one has already been created of type " + existing.getClass()); } else { return (T) existing; } } else { try { Constructor<T> constructor = clazz.getConstructor(SpotlessExtensionBase.class); T formatExtension = constructor.newInstance(this); formats.put(name, formatExtension); createFormatTasks(name, formatExtension); return formatExtension; } catch (NoSuchMethodException e) { throw new GradleException("Must have a constructor " + clazz.getSimpleName() + "(SpotlessExtension root)", e); } catch (Exception e) { throw Errors.asRuntime(e); } } } protected abstract void createFormatTasks(String name, FormatExtension formatExtension); }
plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionBase.java
/* * Copyright 2016-2020 DiffPlug * * 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.diffplug.gradle.spotless; import static java.util.Objects.requireNonNull; import java.lang.reflect.Constructor; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.Nullable; import org.gradle.api.Action; import org.gradle.api.GradleException; import org.gradle.api.Project; import com.diffplug.common.base.Errors; import com.diffplug.spotless.LineEnding; public abstract class SpotlessExtensionBase { final Project project; protected static final String TASK_GROUP = "Verification"; protected static final String CHECK_DESCRIPTION = "Checks that sourcecode satisfies formatting steps."; protected static final String APPLY_DESCRIPTION = "Applies code formatting steps to sourcecode in-place."; static final String EXTENSION = "spotless"; static final String CHECK = "Check"; static final String APPLY = "Apply"; static final String DIAGNOSE = "Diagnose"; public SpotlessExtensionBase(Project project) { this.project = requireNonNull(project); } abstract RegisterDependenciesTask getRegisterDependenciesTask(); /** Line endings (if any). */ LineEnding lineEndings = LineEnding.GIT_ATTRIBUTES; public LineEnding getLineEndings() { return lineEndings; } public void setLineEndings(LineEnding lineEndings) { this.lineEndings = requireNonNull(lineEndings); } Charset encoding = StandardCharsets.UTF_8; /** Returns the encoding to use. */ public Charset getEncoding() { return encoding; } /** Sets encoding to use (defaults to UTF_8). */ public void setEncoding(String name) { requireNonNull(name); setEncoding(Charset.forName(name)); } /** Sets encoding to use (defaults to UTF_8). */ public void setEncoding(Charset charset) { encoding = requireNonNull(charset); } /** Sets encoding to use (defaults to UTF_8). */ public void encoding(String charset) { setEncoding(charset); } private @Nullable String ratchetFrom; /** * Limits the target to only the files which have changed since the given git reference, * which is resolved according to [this](https://javadoc.io/static/org.eclipse.jgit/org.eclipse.jgit/5.6.1.202002131546-r/org/eclipse/jgit/lib/Repository.html#resolve-java.lang.String-) */ public void setRatchetFrom(String ratchetFrom) { this.ratchetFrom = ratchetFrom; } /** @see #setRatchetFrom(String) */ public @Nullable String getRatchetFrom() { return ratchetFrom; } /** @see #setRatchetFrom(String) */ public void ratchetFrom(String ratchetFrom) { setRatchetFrom(ratchetFrom); } final Map<String, FormatExtension> formats = new LinkedHashMap<>(); /** Configures the special java-specific extension. */ public void java(Action<JavaExtension> closure) { requireNonNull(closure); format(JavaExtension.NAME, JavaExtension.class, closure); } /** Configures the special scala-specific extension. */ public void scala(Action<ScalaExtension> closure) { requireNonNull(closure); format(ScalaExtension.NAME, ScalaExtension.class, closure); } /** Configures the special kotlin-specific extension. */ public void kotlin(Action<KotlinExtension> closure) { requireNonNull(closure); format(KotlinExtension.NAME, KotlinExtension.class, closure); } /** Configures the special Gradle Kotlin DSL specific extension. */ public void kotlinGradle(Action<KotlinGradleExtension> closure) { requireNonNull(closure); format(KotlinGradleExtension.NAME, KotlinGradleExtension.class, closure); } /** Configures the special freshmark-specific extension. */ public void freshmark(Action<FreshMarkExtension> closure) { requireNonNull(closure); format(FreshMarkExtension.NAME, FreshMarkExtension.class, closure); } /** Configures the special groovy-specific extension. */ public void groovy(Action<GroovyExtension> closure) { format(GroovyExtension.NAME, GroovyExtension.class, closure); } /** Configures the special groovy-specific extension for Gradle files. */ public void groovyGradle(Action<GroovyGradleExtension> closure) { format(GroovyGradleExtension.NAME, GroovyGradleExtension.class, closure); } /** Configures the special sql-specific extension for SQL files. */ public void sql(Action<SqlExtension> closure) { format(SqlExtension.NAME, SqlExtension.class, closure); } /** Configures the special C/C++-specific extension. */ public void cpp(Action<CppExtension> closure) { format(CppExtension.NAME, CppExtension.class, closure); } /** Configures the special typescript-specific extension for typescript files. */ public void typescript(Action<TypescriptExtension> closure) { format(TypescriptExtension.NAME, TypescriptExtension.class, closure); } /** Configures a custom extension. */ public void format(String name, Action<FormatExtension> closure) { requireNonNull(name, "name"); requireNonNull(closure, "closure"); format(name, FormatExtension.class, closure); } /** Makes it possible to remove a format which was created earlier. */ public void removeFormat(String name) { requireNonNull(name); FormatExtension toRemove = formats.remove(name); if (toRemove == null) { project.getLogger().warn("Called removeFormat('" + name + "') but there was no such format."); } } boolean enforceCheck = true; /** Returns `true` if Gradle's `check` task should run `spotlessCheck`; `false` otherwise. */ public boolean isEnforceCheck() { return enforceCheck; } /** * Configures Gradle's `check` task to run `spotlessCheck` if `true`, * but to not do so if `false`. * * `true` by default. */ public void setEnforceCheck(boolean enforceCheck) { this.enforceCheck = enforceCheck; } public <T extends FormatExtension> void format(String name, Class<T> clazz, Action<T> configure) { T format = maybeCreate(name, clazz); configure.execute(format); } @SuppressWarnings("unchecked") protected final <T extends FormatExtension> T maybeCreate(String name, Class<T> clazz) { FormatExtension existing = formats.get(name); if (existing != null) { if (!existing.getClass().equals(clazz)) { throw new GradleException("Tried to add format named '" + name + "'" + " of type " + clazz + " but one has already been created of type " + existing.getClass()); } else { return (T) existing; } } else { try { Constructor<T> constructor = clazz.getConstructor(SpotlessExtensionBase.class); T formatExtension = constructor.newInstance(this); formats.put(name, formatExtension); createFormatTasks(name, formatExtension); return formatExtension; } catch (NoSuchMethodException e) { throw new GradleException("Must have a constructor " + clazz.getSimpleName() + "(SpotlessExtension root)", e); } catch (Exception e) { throw Errors.asRuntime(e); } } } protected abstract void createFormatTasks(String name, FormatExtension formatExtension); }
Add the `antlr4` extension to SpotlessExtensionBase.
plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionBase.java
Add the `antlr4` extension to SpotlessExtensionBase.
<ide><path>lugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionBase.java <ide> /** Configures the special typescript-specific extension for typescript files. */ <ide> public void typescript(Action<TypescriptExtension> closure) { <ide> format(TypescriptExtension.NAME, TypescriptExtension.class, closure); <add> } <add> <add> /** Configures the special antlr4-specific extension for antlr4 files. */ <add> public void antlr4(Action<Antlr4Extension> closure) { <add> format(Antlr4Extension.NAME, Antlr4Extension.class, closure); <ide> } <ide> <ide> /** Configures a custom extension. */
JavaScript
mit
9ac1547bc938f03947d9a644893242135c2dade8
0
raypulver/jsh,raypulver/jsh,raypulver/jsh
var child_process = require('child_process'), inherits = require('util').inherits, fs = require('fs'), path = require('path'), emitter = require('events').EventEmitter; var history = require('./history')(process.env.JSH_HISTORY || '.jsh_history'), input = require('./input')(), times = require('./util/string-multiply'); var PS1 = 'jsh>> ', buffer = '', cursor = 0, cmds = {}, aliases = {}; (function loadBuiltInCmds (commands) { var commandPath = path.join(__dirname, 'commands'), fileRe = /(.*)\.js/; fs.readdirSync(commandPath).forEach(function (v) { var fn = v.match(fileRe)[1]; commands[fn] = require(path.join(commandPath, fn)); }); })(cmds); inherits(Shell, emitter); module.exports = Shell; function Shell (config) { var self = this; if (!(self instanceof Shell)) return new Shell(config); emitter.call(self); self.aliases = aliases; self.history = history; self.runInternal = runInternal; input.on('keypress', function (ch, key) { if (key && (key.name === 'enter' || key.name === 'return')) { execBuffer(); } else if (key && key.name === 'up') up(); else if (key && key.name === 'down') down(); else if (key && key.name === 'right') { if (cursor !== buffer.length) { cursor++; write(key.sequence); } } else if (key && key.name === 'left') { if (cursor !== 0) { cursor--; write(key.sequence); } } else if (key && key.name === 'c' && key.ctrl) { write('\n'); cursor = 0; nextLine(); } else if (key && key.name === 'backspace') backspace(); else { buffer = buffer.substr(0, cursor) + ch + buffer.substr(cursor); cursor++; deleteLine(); write(buffer + times('\u001b[D', buffer.length - cursor)); } }); nextLine(); resetTitle(); } function nextLine() { buffer = ''; write(PS1); resume(); } function error (msg) { process.stderr.write(msg); } function write (msg) { process.stdout.write(msg); } function deleteLine () { process.stdout.clearLine(); process.stdout.cursorTo(0); process.stdout.write(PS1); } function backspace () { if (cursor !== 0) { buffer = buffer.substr(0, cursor - 1) + buffer.substr(cursor); cursor--; deleteLine(); process.stdout.write(buffer); write(times('\u001b[D', buffer.length - cursor)); } } function spawn (cmd) { var inherit = { stdio: 'inherit', env: process.env }, args = cmd.split(/\s+/); cmd = args.splice(0, 1)[0]; if (cmd && executableExists(cmd)) { process.title = cmd; if (args.length > 0) return child_process.spawn(cmd, args, inherit); else return child_process.spawn(cmd, inherit); } } function executableExists (exe) { return process.env.PATH.split(':').reduce(function (r, v) { if (r) return true; return fs.existsSync(path.join(v, exe)); }, false); } function resume () { process.stdin.resume(); } function pause () { process.stdin.pause(); } function up () { if (history.atEnd()) history.write(buffer); deleteLine(); buffer = history.prev(); cursor = buffer.length; write(buffer); } function down () { deleteLine(); buffer = history.next(); cursor = buffer.length; write(buffer); } function execBuffer(aliased) { if (!aliased) { history.write(buffer); write('\n'); } pause(); if (aliases[buffer]) { buffer = aliases[buffer]; execBuffer(true); } else { if (runInternal(buffer)) { nextLine(); } else { var subprocess = spawn(buffer); if (subprocess) { subprocess.on('exit', function () { resetTitle(); nextLine(); }); } else { nextLine(); } } } } function runInternal(cmd) { var commands = Object.keys(cmds), currentCmd, args, re; for (var i = 0; i < commands.length; i++) { re = RegExp('^' + commands[i] + '(.*)$'); if (re.test(cmd)) { currentCmd = commands[i]; var argStr = cmd.match(re)[1]; if (argStr) args = argStr.split(' ').slice(1).map(function (v) { return v.trim() }); break; } } if (currentCmd) { cmds[currentCmd].apply(this, args); return true; } else return false; } function resetTitle () { process.title = path.basename(process.argv[1]); }
lib/shell.js
var child_process = require('child_process'), inherits = require('util').inherits, fs = require('fs'), path = require('path'), emitter = require('events').EventEmitter; var history = require('./history')(process.env.JSH_HISTORY || '.jsh_history'); var PS1 = 'jsh>> ', buffer = '', cursor = 0, cmds = {}, aliases = {}; (function loadBuiltInCmds (commands) { var commandPath = path.join(__dirname, 'commands'), fileRe = /(.*)\.js/; fs.readdirSync(commandPath).forEach(function (v) { var fn = v.match(fileRe)[1]; commands[fn] = require(path.join(commandPath, fn)); }); })(cmds); inherits(Shell, emitter); module.exports = Shell; function Shell (config) { var self = this; if (!(self instanceof Shell)) return new Shell(config); emitter.call(self); process.stdin.setRawMode(true); process.stdin.setEncoding('utf8'); self.aliases = aliases; self.history = history; self.runInternal = runInternal; process.stdin.on('data', function (key) { if (key === '\r' || key === '\n') { execBuffer(); } else if (key === '\u001b[A') up(); else if (key === '\u001b[B') down(); else if (key === '\u0003') { write('\n'); nextLine(); } else if (key === '\b' || key === '\x7f') backspace(); else { buffer += key; write(key); } }); nextLine(); resetTitle(); } function nextLine() { buffer = ''; write(PS1); resume(); } function error (msg) { process.stderr.write(msg); } function write (msg) { process.stdout.write(msg); } function deleteLine () { process.stdout.clearLine(); process.stdout.cursorTo(0); process.stdout.write(PS1); } function backspace () { buffer = buffer.substr(0, buffer.length - 1); deleteLine(); process.stdout.write(buffer); } function spawn (cmd) { var inherit = { stdio: 'inherit', env: process.env }, args = cmd.split(/\s+/); cmd = args.splice(0, 1)[0]; if (cmd && executableExists(cmd)) { process.title = cmd; if (args.length > 0) return child_process.spawn(cmd, args, inherit); else return child_process.spawn(cmd, inherit); } } function executableExists (exe) { return process.env.PATH.split(':').reduce(function (r, v) { if (r) return true; return fs.existsSync(path.join(v, exe)); }, false); } function resume () { process.stdin.resume(); } function pause () { process.stdin.pause(); } function up () { if (history.atEnd()) history.write(buffer); deleteLine(); buffer = history.prev(); write(buffer); } function down () { deleteLine(); buffer = history.next(); write(buffer); } function execBuffer(aliased) { if (!aliased) { history.write(buffer); write('\n'); } pause(); if (aliases[buffer]) { buffer = aliases[buffer]; execBuffer(true); } else { if (runInternal(buffer)) { nextLine(); } else { var subprocess = spawn(buffer); if (subprocess) { subprocess.on('exit', function () { resetTitle(); nextLine(); }); } else { nextLine(); } } } } function runInternal(cmd) { var commands = Object.keys(cmds), currentCmd, args, re; for (var i = 0; i < commands.length; i++) { re = RegExp('^' + commands[i] + '(.*)$'); if (re.test(cmd)) { currentCmd = commands[i]; var argStr = cmd.match(re)[1]; if (argStr) args = argStr.split(' ').slice(1).map(function (v) { return v.trim() }); break; } } if (currentCmd) { cmds[currentCmd].apply(this, args); return true; } else return false; } function resetTitle () { process.title = path.basename(process.argv[1]); }
keypress ported to a standalone input module, cursor unbreakable
lib/shell.js
keypress ported to a standalone input module, cursor unbreakable
<ide><path>ib/shell.js <ide> path = require('path'), <ide> emitter = require('events').EventEmitter; <ide> <del>var history = require('./history')(process.env.JSH_HISTORY || '.jsh_history'); <add>var history = require('./history')(process.env.JSH_HISTORY || '.jsh_history'), <add> input = require('./input')(), <add> times = require('./util/string-multiply'); <ide> <ide> var PS1 = 'jsh>> ', <ide> buffer = '', <ide> var self = this; <ide> if (!(self instanceof Shell)) return new Shell(config); <ide> emitter.call(self); <del> process.stdin.setRawMode(true); <del> process.stdin.setEncoding('utf8'); <ide> self.aliases = aliases; <ide> self.history = history; <ide> self.runInternal = runInternal; <del> process.stdin.on('data', function (key) { <del> if (key === '\r' || key === '\n') { <add> input.on('keypress', function (ch, key) { <add> if (key && (key.name === 'enter' || key.name === 'return')) { <ide> execBuffer(); <ide> } <del> else if (key === '\u001b[A') up(); <del> else if (key === '\u001b[B') down(); <del> else if (key === '\u0003') { <add> else if (key && key.name === 'up') up(); <add> else if (key && key.name === 'down') down(); <add> else if (key && key.name === 'right') { <add> if (cursor !== buffer.length) { <add> cursor++; <add> write(key.sequence); <add> } <add> } else if (key && key.name === 'left') { <add> if (cursor !== 0) { <add> cursor--; <add> write(key.sequence); <add> } <add> } <add> else if (key && key.name === 'c' && key.ctrl) { <ide> write('\n'); <add> cursor = 0; <ide> nextLine(); <ide> } <del> else if (key === '\b' || key === '\x7f') backspace(); <add> else if (key && key.name === 'backspace') backspace(); <ide> else { <del> buffer += key; <del> write(key); <add> buffer = buffer.substr(0, cursor) + ch + buffer.substr(cursor); <add> cursor++; <add> deleteLine(); <add> write(buffer + times('\u001b[D', buffer.length - cursor)); <ide> } <ide> }); <ide> nextLine(); <ide> process.stdout.write(PS1); <ide> } <ide> function backspace () { <del> buffer = buffer.substr(0, buffer.length - 1); <del> deleteLine(); <del> process.stdout.write(buffer); <add> if (cursor !== 0) { <add> buffer = buffer.substr(0, cursor - 1) + buffer.substr(cursor); <add> cursor--; <add> deleteLine(); <add> process.stdout.write(buffer); <add> write(times('\u001b[D', buffer.length - cursor)); <add> } <ide> } <ide> function spawn (cmd) { <ide> var inherit = { stdio: 'inherit', env: process.env }, <ide> history.write(buffer); <ide> deleteLine(); <ide> buffer = history.prev(); <add> cursor = buffer.length; <ide> write(buffer); <ide> } <ide> function down () { <ide> deleteLine(); <ide> buffer = history.next(); <add> cursor = buffer.length; <ide> write(buffer); <ide> } <ide> function execBuffer(aliased) {
Java
bsd-3-clause
509ca8f3e4ce498a9c125fccfc7dabb3f548d4e7
0
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
/* * Copyright (c) 2011, 2011, 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.nodes.calc; import com.oracle.graal.api.meta.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.spi.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; @NodeInfo(shortName = "==") public final class ObjectEqualsNode extends CompareNode implements Virtualizable { /** * Constructs a new object equality comparison node. * * @param x the instruction producing the first input to the instruction * @param y the instruction that produces the second input to this instruction */ public ObjectEqualsNode(ValueNode x, ValueNode y) { super(x, y); assert x.kind() == Kind.Object; assert y.kind() == Kind.Object; } @Override public Condition condition() { return Condition.EQ; } @Override public boolean unorderedIsTrue() { return false; } @Override public Node canonical(CanonicalizerTool tool) { if (x() == y()) { return LogicConstantNode.tautology(graph()); } if (ObjectStamp.isObjectAlwaysNull(x())) { return graph().unique(new IsNullNode(y())); } else if (ObjectStamp.isObjectAlwaysNull(y())) { return graph().unique(new IsNullNode(x())); } if (x().stamp().alwaysDistinct(y().stamp())) { return LogicConstantNode.contradiction(graph()); } return super.canonical(tool); } private void virtualizeNonVirtualComparison(State state, ValueNode other, VirtualizerTool tool) { if (!state.getVirtualObject().hasIdentity() && state.getVirtualObject().entryKind(0) == Kind.Boolean) { if (other.isConstant()) { Object otherValue = other.asConstant().asObject(); if (otherValue == Boolean.TRUE || otherValue == Boolean.FALSE) { int expectedValue = (otherValue == Boolean.TRUE) ? 1 : 0; IntegerEqualsNode equals = new IntegerEqualsNode(state.getEntry(0), ConstantNode.forInt(expectedValue, graph())); tool.addNode(equals); tool.replaceWithValue(equals); } else { tool.replaceWithValue(LogicConstantNode.contradiction(graph())); } } } else { // one of them is virtual: they can never be the same objects tool.replaceWithValue(LogicConstantNode.contradiction(graph())); } } @Override public void virtualize(VirtualizerTool tool) { State stateX = tool.getObjectState(x()); State stateY = tool.getObjectState(y()); boolean xVirtual = stateX != null && stateX.getState() == EscapeState.Virtual; boolean yVirtual = stateY != null && stateY.getState() == EscapeState.Virtual; if (xVirtual && !yVirtual) { virtualizeNonVirtualComparison(stateX, stateY != null ? stateY.getMaterializedValue() : y(), tool); } else if (!xVirtual && yVirtual) { virtualizeNonVirtualComparison(stateY, stateX != null ? stateX.getMaterializedValue() : x(), tool); } else if (xVirtual && yVirtual) { boolean xIdentity = stateX.getVirtualObject().hasIdentity(); boolean yIdentity = stateY.getVirtualObject().hasIdentity(); if (xIdentity ^ yIdentity) { /* * One of the two objects has identity, the other doesn't. In code, this looks like * "Integer.valueOf(a) == new Integer(b)", which is always false. * * In other words: an object created via valueOf can never be equal to one created * by new in the same compilation unit. */ tool.replaceWithValue(LogicConstantNode.contradiction(graph())); } else if (!xIdentity && !yIdentity) { // both are virtual without identity: check contents assert stateX.getVirtualObject().entryCount() == 1 && stateY.getVirtualObject().entryCount() == 1; assert stateX.getVirtualObject().type() == stateY.getVirtualObject().type(); assert stateX.getVirtualObject().entryKind(0).getStackKind() == Kind.Int || stateX.getVirtualObject().entryKind(0) == Kind.Long; IntegerEqualsNode equals = new IntegerEqualsNode(stateX.getEntry(0), stateY.getEntry(0)); tool.addNode(equals); tool.replaceWithValue(equals); } else { // both are virtual with identity: check if they refer to the same object tool.replaceWithValue(LogicConstantNode.forBoolean(stateX == stateY, graph())); } } } }
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/calc/ObjectEqualsNode.java
/* * Copyright (c) 2011, 2011, 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.nodes.calc; import com.oracle.graal.api.meta.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.spi.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; @NodeInfo(shortName = "==") public final class ObjectEqualsNode extends CompareNode implements Virtualizable { /** * Constructs a new object equality comparison node. * * @param x the instruction producing the first input to the instruction * @param y the instruction that produces the second input to this instruction */ public ObjectEqualsNode(ValueNode x, ValueNode y) { super(x, y); assert x.kind() == Kind.Object; assert y.kind() == Kind.Object; } @Override public Condition condition() { return Condition.EQ; } @Override public boolean unorderedIsTrue() { return false; } @Override public Node canonical(CanonicalizerTool tool) { if (x() == y()) { return LogicConstantNode.tautology(graph()); } if (ObjectStamp.isObjectAlwaysNull(x())) { return graph().unique(new IsNullNode(y())); } else if (ObjectStamp.isObjectAlwaysNull(y())) { return graph().unique(new IsNullNode(x())); } if (x().stamp().alwaysDistinct(y().stamp())) { return LogicConstantNode.contradiction(graph()); } return super.canonical(tool); } private void virtualizeNonVirtualComparison(State state, ValueNode other, VirtualizerTool tool) { if (!state.getVirtualObject().hasIdentity() && state.getVirtualObject().entryKind(0) == Kind.Boolean) { if (other.isConstant()) { Object otherValue = other.asConstant().asObject(); if (otherValue == Boolean.TRUE || otherValue == Boolean.FALSE) { int expectedValue = (otherValue == Boolean.TRUE) ? 1 : 0; IntegerEqualsNode equals = new IntegerEqualsNode(state.getEntry(0), ConstantNode.forInt(expectedValue, graph())); tool.addNode(equals); tool.replaceWithValue(equals); } else { tool.replaceWithValue(LogicConstantNode.contradiction(graph())); } } } else { // one of them is virtual: they can never be the same objects tool.replaceWithValue(LogicConstantNode.contradiction(graph())); } } @Override public void virtualize(VirtualizerTool tool) { State stateX = tool.getObjectState(x()); State stateY = tool.getObjectState(y()); boolean xVirtual = stateX != null && stateX.getState() == EscapeState.Virtual; boolean yVirtual = stateY != null && stateY.getState() == EscapeState.Virtual; if (xVirtual && !yVirtual) { virtualizeNonVirtualComparison(stateX, stateY != null ? stateY.getMaterializedValue() : y(), tool); } else if (!xVirtual && yVirtual) { virtualizeNonVirtualComparison(stateY, stateX != null ? stateX.getMaterializedValue() : x(), tool); } else if (xVirtual && yVirtual) { boolean xIdentity = stateX.getVirtualObject().hasIdentity(); boolean yIdentity = stateY.getVirtualObject().hasIdentity(); if (xIdentity ^ yIdentity) { /* * One of the two objects has identity, the other doesn't. In code, this looks like * "Integer.valueOf(a) == new Integer(b)", which is always false. * * In other words: an object created via valueOf can never be equal to one created * by new in the same compilation unit. */ tool.replaceWithValue(LogicConstantNode.contradiction(graph())); } else if (!xIdentity && !yIdentity) { // both are virtual without identity: check contents assert stateX.getVirtualObject().entryCount() == 1 && stateY.getVirtualObject().entryCount() == 1; assert stateX.getVirtualObject().type() == stateY.getVirtualObject().type(); assert stateX.getVirtualObject().entryKind(0) == Kind.Int || stateX.getVirtualObject().entryKind(0) == Kind.Long; IntegerEqualsNode equals = new IntegerEqualsNode(stateX.getEntry(0), stateY.getEntry(0)); tool.addNode(equals); tool.replaceWithValue(equals); } else { // both are virtual with identity: check if they refer to the same object tool.replaceWithValue(LogicConstantNode.forBoolean(stateX == stateY, graph())); } } } }
Check for stackKind
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/calc/ObjectEqualsNode.java
Check for stackKind
<ide><path>raal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/calc/ObjectEqualsNode.java <ide> // both are virtual without identity: check contents <ide> assert stateX.getVirtualObject().entryCount() == 1 && stateY.getVirtualObject().entryCount() == 1; <ide> assert stateX.getVirtualObject().type() == stateY.getVirtualObject().type(); <del> assert stateX.getVirtualObject().entryKind(0) == Kind.Int || stateX.getVirtualObject().entryKind(0) == Kind.Long; <add> assert stateX.getVirtualObject().entryKind(0).getStackKind() == Kind.Int || stateX.getVirtualObject().entryKind(0) == Kind.Long; <ide> IntegerEqualsNode equals = new IntegerEqualsNode(stateX.getEntry(0), stateY.getEntry(0)); <ide> tool.addNode(equals); <ide> tool.replaceWithValue(equals);
Java
mit
0129ba03de196425c060ea50ea86af52c1e501f8
0
adbms-benchmark/storage,adbms-benchmark/storage,adbms-benchmark/storage
package benchmark; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.BenchmarkUtil; import util.IO; /** * Runs a benchmark, considering all the given ingredients (context, ADBMS * system, query generator). * * @author George Merticariu * @author Dimitar Misev */ public class BenchmarkExecutor { private static final Logger log = LoggerFactory.getLogger(BenchmarkExecutor.class); public static final int MAX_RETRY = 3; private final QueryGenerator queryGenerator; private final QueryExecutor queryExecutor; private final AdbmsSystem systemController; private final BenchmarkContext benchmarkContext; private final DataManager dataManager; public BenchmarkExecutor(BenchmarkContext benchmarkContext, QueryGenerator queryGenerator, QueryExecutor queryExecutor, DataManager dataManager, AdbmsSystem systemController) { this.queryGenerator = queryGenerator; this.queryExecutor = queryExecutor; this.systemController = systemController; this.benchmarkContext = benchmarkContext; this.dataManager = dataManager; } public void runBenchmark() throws Exception { log.info("Executing " + benchmarkContext.getBenchmarkType() + " benchmark on " + systemController.getSystemName() + ", " + benchmarkContext.getArrayDimensionality() + "D data of size " + benchmarkContext.getArraySizeShort() + " (" + benchmarkContext.getArraySize() + "B)"); boolean alreadyDropped = false; File resultsDir = IO.getResultsDir(); File resultsFile = new File(resultsDir.getAbsolutePath(), systemController.getSystemName() + "_benchmark_results.csv"); try (PrintWriter pr = new PrintWriter(new FileWriter(resultsFile, true))) { loadData(pr); runBenchmark(pr); alreadyDropped = dropData(pr); } finally { if (!alreadyDropped) { dropData(null); } } } private boolean runBenchmark(PrintWriter pr) throws Exception { if (benchmarkContext.isDisableBenchmark()) { return false; } pr.println("----------------------------------------------------------------------------"); pr.println("# Starting benchmark"); pr.println(""); Benchmark benchmark = queryGenerator.getBenchmark(); Double msElapsed = 0.0; for (BenchmarkSession session : benchmark.getBenchmarkSessions()) { msElapsed += runBenchmarkSession(session, pr); } pr.println("----------------------------------------------------------------------------"); pr.println("# Total benchmark execution time (ms): " + msElapsed); return true; } private Double runBenchmarkSession(BenchmarkSession session, PrintWriter pr) throws Exception { pr.println("----------------------------------------------------------------------------"); pr.println("# Benchmark session: " + session.getDescription()); pr.println("System, " + benchmarkContext.getBenchmarkSpecificHeader() + "Mean execution time (ms)"); systemController.restartSystem(); BenchmarkUtil.dropSystemCaches(); Double msElapsed = 0.0; for (BenchmarkQuery query : session.getBenchmarkQueries()) { msElapsed += runBenchmarkQuery(query, pr); } pr.println("# Benchmark session '" + session.getDescription() + "' execution time (ms): " + msElapsed); pr.flush(); return msElapsed; } private Double runBenchmarkQuery(BenchmarkQuery query, PrintWriter pr) { log.info("Executing benchmark query: " + query.getQueryString()); List<Long> queryExecutionTimes = new ArrayList<>(); int repeatNumber = benchmarkContext.getRepeatNumber(); for (int repeatIndex = 0; repeatIndex < repeatNumber; ++repeatIndex) { boolean failed = true; long time = -1; for (int retryIndex = 0; retryIndex < MAX_RETRY && failed; ++retryIndex) { try { time = queryExecutor.executeTimedQuery(query.getQueryString()); log.debug(" -> " + time + "ms"); failed = false; } catch (Exception ex) { log.warn(" query \"" + query.getQueryString() + "\" failed on try " + (retryIndex + 1) + ". Retrying."); } } queryExecutionTimes.add(time); } StringBuilder resultLine = new StringBuilder(); resultLine.append(String.format("%s, %s", systemController.getSystemName(), benchmarkContext.getBenchmarkResultLine(query))); for (Long queryExecutionTime : queryExecutionTimes) { resultLine.append(queryExecutionTime); resultLine.append(", "); } Double ret = BenchmarkUtil.getBenchmarkMean(queryExecutionTimes); resultLine.append(ret); pr.println(resultLine.toString()); pr.flush(); return ret; } private boolean loadData(PrintWriter pr) throws Exception { if (benchmarkContext.isLoadData()) { systemController.restartSystem(); if (benchmarkContext.isGenerateData()) { log.debug("Generating data..."); dataManager.generateData(); } long msElapsed = dataManager.loadData(); if (pr != null) { pr.println("Loaded benchmark data in (ms): " + msElapsed); } else { log.info("Loaded benchmark data in (ms): " + msElapsed); } return true; } else { return false; } } private boolean dropData(PrintWriter pr) throws Exception { if (benchmarkContext.isDropData()) { systemController.restartSystem(); long msElapsed = dataManager.dropData(); if (pr != null) { pr.println("Dropped benchmark data in (ms): " + msElapsed); } return true; } else { return false; } } }
src/benchmark/BenchmarkExecutor.java
package benchmark; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.BenchmarkUtil; import util.IO; /** * Runs a benchmark, considering all the given ingredients (context, ADBMS * system, query generator). * * @author George Merticariu * @author Dimitar Misev */ public class BenchmarkExecutor { private static final Logger log = LoggerFactory.getLogger(BenchmarkExecutor.class); public static final int MAX_RETRY = 3; private final QueryGenerator queryGenerator; private final QueryExecutor queryExecutor; private final AdbmsSystem systemController; private final BenchmarkContext benchmarkContext; private final DataManager dataManager; public BenchmarkExecutor(BenchmarkContext benchmarkContext, QueryGenerator queryGenerator, QueryExecutor queryExecutor, DataManager dataManager, AdbmsSystem systemController) { this.queryGenerator = queryGenerator; this.queryExecutor = queryExecutor; this.systemController = systemController; this.benchmarkContext = benchmarkContext; this.dataManager = dataManager; } public void runBenchmark() throws Exception { log.info("Executing " + benchmarkContext.getBenchmarkType() + " benchmark on " + systemController.getSystemName() + ", " + benchmarkContext.getArrayDimensionality() + "D data of size " + benchmarkContext.getArraySizeShort() + " (" + benchmarkContext.getArraySize() + "B)"); boolean alreadyDropped = false; File resultsDir = IO.getResultsDir(); File resultsFile = new File(resultsDir.getAbsolutePath(), systemController.getSystemName() + "_benchmark_results.csv"); try (PrintWriter pr = new PrintWriter(new FileWriter(resultsFile, true))) { loadData(pr); runBenchmark(pr); alreadyDropped = dropData(pr); } finally { if (!alreadyDropped) { dropData(null); } } } private boolean runBenchmark(PrintWriter pr) throws Exception { if (benchmarkContext.isDisableBenchmark()) { return false; } pr.println("----------------------------------------------------------------------------"); pr.println("# Starting benchmark"); pr.println(""); Benchmark benchmark = queryGenerator.getBenchmark(); Double msElapsed = 0.0; for (BenchmarkSession session : benchmark.getBenchmarkSessions()) { msElapsed += runBenchmarkSession(session, pr); } pr.println("----------------------------------------------------------------------------"); pr.println("# Total benchmark execution time (ms): " + msElapsed); return true; } private Double runBenchmarkSession(BenchmarkSession session, PrintWriter pr) throws Exception { pr.println("----------------------------------------------------------------------------"); pr.println("# Benchmark session: " + session.getDescription()); pr.println("System, " + benchmarkContext.getBenchmarkSpecificHeader() + "Mean execution time (ms)"); systemController.restartSystem(); BenchmarkUtil.dropSystemCaches(); Double msElapsed = 0.0; for (BenchmarkQuery query : session.getBenchmarkQueries()) { msElapsed += runBenchmarkQuery(query, pr); } pr.println("# Benchmark session '" + session.getDescription() + "' execution time (ms): " + msElapsed); pr.flush(); return msElapsed; } private Double runBenchmarkQuery(BenchmarkQuery query, PrintWriter pr) { log.info("Executing benchmark query: " + query.getQueryString()); List<Long> queryExecutionTimes = new ArrayList<>(); int repeatNumber = benchmarkContext.getRepeatNumber(); for (int repeatIndex = 0; repeatIndex < repeatNumber; ++repeatIndex) { boolean failed = true; long time = -1; for (int retryIndex = 0; retryIndex < MAX_RETRY && failed; ++retryIndex) { try { time = queryExecutor.executeTimedQuery(query.getQueryString()); log.debug(" -> " + time + "ms"); failed = false; } catch (Exception ex) { log.warn(" query \"" + query.getQueryString() + "\" failed on try " + (retryIndex + 1) + ". Retrying."); } } queryExecutionTimes.add(time); } StringBuilder resultLine = new StringBuilder(); resultLine.append(String.format("%s, %s", systemController.getSystemName(), benchmarkContext.getBenchmarkResultLine(query))); for (Long queryExecutionTime : queryExecutionTimes) { resultLine.append(queryExecutionTime); resultLine.append(", "); } Double ret = BenchmarkUtil.getBenchmarkMean(queryExecutionTimes); resultLine.append(ret); pr.println(resultLine.toString()); pr.flush(); return ret; } private boolean loadData(PrintWriter pr) throws Exception { if (benchmarkContext.isLoadData()) { systemController.restartSystem(); long msElapsed = dataManager.loadData(); if (pr != null) { pr.println("Loaded benchmark data in (ms): " + msElapsed); } else { log.info("Loaded benchmark data in (ms): " + msElapsed); } return true; } else { return false; } } private boolean dropData(PrintWriter pr) throws Exception { if (benchmarkContext.isDropData()) { systemController.restartSystem(); long msElapsed = dataManager.dropData(); if (pr != null) { pr.println("Dropped benchmark data in (ms): " + msElapsed); } return true; } else { return false; } } }
generate data
src/benchmark/BenchmarkExecutor.java
generate data
<ide><path>rc/benchmark/BenchmarkExecutor.java <ide> private boolean loadData(PrintWriter pr) throws Exception { <ide> if (benchmarkContext.isLoadData()) { <ide> systemController.restartSystem(); <add> if (benchmarkContext.isGenerateData()) { <add> log.debug("Generating data..."); <add> dataManager.generateData(); <add> } <ide> long msElapsed = dataManager.loadData(); <ide> if (pr != null) { <ide> pr.println("Loaded benchmark data in (ms): " + msElapsed);
Java
lgpl-2.1
e5406af2fd71b2caa47950a6ea1fbce945206bcd
0
luiz158/yougi-javaee7,luiz158/yougi-javaee7,cejug/yougi,luiz158/yougi-javaee7,luiz158/yougi-javaee7,cejug/yougi
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.cejug.knowledge.business; import com.sun.mail.imap.IMAPBodyPart; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.LocalBean; import javax.ejb.Schedule; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeMultipart; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import org.cejug.business.ApplicationPropertyBsn; import org.cejug.entity.ApplicationProperty; import org.cejug.entity.Properties; import org.cejug.knowledge.entity.MailingList; import org.cejug.knowledge.entity.MailingListMessage; import org.cejug.knowledge.entity.MailingListSubscription; import org.cejug.util.EntitySupport; /** * * @author Hildeberto Mendonca */ @Stateless @LocalBean public class MailingListBsn { @Resource(name = "mail/jug") private Session mailSession; @PersistenceContext private EntityManager em; @EJB private ApplicationPropertyBsn applicationPropertyBsn; static final Logger logger = Logger.getLogger("org.cejug.knowledge.business.MailingListBsn"); public MailingList findMailingListByEmail(String email) { try { return (MailingList) em.createQuery("select ml from MailingList ml where ml.email = :email") .setParameter("email", email) .getSingleResult(); } catch(NoResultException nre) { return null; } } public MailingListSubscription findMailingListSubscription(String emailAddress) { try { return (MailingListSubscription) em.createQuery("select mls from MailingListSubscription mls where mls.emailAddress = :email") .setParameter("email", emailAddress) .getSingleResult(); } catch(NoResultException nre) { return null; } } @Schedule(minute="*/2", hour="*") public void retrieveMailingListMessages() { try { logger.log(Level.INFO, "Start retrieving of emails..."); ApplicationProperty appProp = applicationPropertyBsn.findApplicationProperty(Properties.EMAIL_SERVER_TYPE); Store store = mailSession.getStore(appProp.getPropertyValue()); store.connect(); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); Message[] message = folder.getMessages(); List<MailingListMessage> mailingListMessages = new ArrayList<MailingListMessage>(); MailingListMessage mailingListMessage; MailingListSubscription mailingListSubscription; String address; List<MailingList> mailingLists; for (int i = 0, n = message.length; i < n; i++) { mailingListMessage = new MailingListMessage(); mailingListMessage.setId(EntitySupport.generateEntityId()); mailingListMessage.setSubject(message[i].getSubject()); /* Get the email address of the 'from' field, search the address * in the subscription table and set the sender of the message. * Only those who are registered in the subscription table have * their message considered. */ address = message[i].getFrom()[0].toString(); if(address.indexOf("<") >= 0) address = address.substring(address.indexOf("<") + 1, address.indexOf(">")); address = address.toLowerCase(); mailingListSubscription = findMailingListSubscription(address); logger.log(Level.INFO, "Sender: {0}", new Object[]{address.toString()}); if(mailingListSubscription == null) continue; else mailingListMessage.setSender(mailingListSubscription); /* This part tries to get the full content of the message to * store in the database. For that, a simple OutputStream * implementation writes the whole content of the message in a * string, which defines the attribute body of the * mailingListMessage object. */ OutputStream output = new OutputStream() { private StringBuilder string = new StringBuilder(); @Override public void write(int b) throws IOException { this.string.append((char) b ); } @Override public String toString() { return this.string.toString(); } }; message[i].writeTo(output); mailingListMessage.setBody(output.toString()); // if(message[i].getContent() instanceof MimeMultipart) { // MimeMultipart mm = (MimeMultipart)message[i].getContent(); // logger.log(Level.INFO, "Parts: {0}", mm.getCount()); // StringBuilder body = new StringBuilder(); // for(int j = 0;j < mm.getCount();j++) { // if(mm.getBodyPart(j) instanceof IMAPBodyPart) { // IMAPBodyPart ibp = (IMAPBodyPart)mm.getBodyPart(j); // body.append(ibp.getDescription()); // } // } // mailingListMessage.setBody(body.toString()); // } // else // mailingListMessage.setBody(message[i].getContent().toString()); mailingListMessage.setWhenReceived(message[i].getReceivedDate()); /* Stores in the database only those messages that were sent to * a registered mailing list. */ mailingLists = figureOutMailingLists(message[i].getAllRecipients()); if(mailingLists == null || mailingLists.isEmpty()) continue; else { mailingListMessage.setMailingList(mailingLists.get(0)); em.persist(mailingListMessage); message[i].setFlag(Flags.Flag.DELETED, true); } for(int j = 1;j < mailingLists.size();j++) { mailingListMessage = (MailingListMessage)mailingListMessage.clone(); mailingListMessage.setMailingList(mailingLists.get(j)); em.persist(mailingListMessage); } } folder.close(true); store.close(); logger.log(Level.INFO, "Email retrieval ended."); } catch (IOException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } } /** Check the recipients to detect for which mailing lists the message was sent. */ private List<MailingList> figureOutMailingLists(Address[] extendedListAddresses) { String listAddress; List<MailingList> mailingLists = new ArrayList<MailingList>(); MailingList mailingList; for(int i = 0;i < extendedListAddresses.length;i++) { // Extracts emails from the listAddress = extendedListAddresses[i].toString(); if(listAddress.indexOf("<") >= 0) listAddress = listAddress.substring(listAddress.indexOf("<") + 1, listAddress.indexOf(">")); listAddress = listAddress.toLowerCase(); logger.log(Level.INFO, "List address: {0}", new Object[]{listAddress}); mailingList = findMailingListByEmail(listAddress); if(mailingList != null) mailingLists.add(mailingList); } return mailingLists; } }
jug-ejb/src/java/org/cejug/knowledge/business/MailingListBsn.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.cejug.knowledge.business; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.LocalBean; import javax.ejb.Schedule; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeMessage; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import org.cejug.business.ApplicationPropertyBsn; import org.cejug.entity.ApplicationProperty; import org.cejug.entity.Properties; import org.cejug.knowledge.entity.MailingList; import org.cejug.knowledge.entity.MailingListMessage; import org.cejug.knowledge.entity.MailingListSubscription; import org.cejug.util.EntitySupport; /** * * @author Hildeberto Mendonca */ @Stateless @LocalBean public class MailingListBsn { @Resource(name = "mail/jug") private Session mailSession; @PersistenceContext private EntityManager em; @EJB private ApplicationPropertyBsn applicationPropertyBsn; static final Logger logger = Logger.getLogger("org.cejug.knowledge.business.MailingListBsn"); public MailingList findMailingListByEmail(String email) { try { return (MailingList) em.createQuery("select ml from MailingList ml where ml.email = :email") .setParameter("email", email) .getSingleResult(); } catch(NoResultException nre) { return null; } } public MailingListSubscription findMailingListSubscription(String emailAddress) { try { return (MailingListSubscription) em.createQuery("select mls from MailingListSubscription mls where mls.emailAddress = :email") .setParameter("email", emailAddress) .getSingleResult(); } catch(NoResultException nre) { return null; } } @Schedule(minute="*/2", hour="*") public void retrieveMailingListMessages() { try { logger.log(Level.INFO, "Start retrieving of emails..."); ApplicationProperty appProp = applicationPropertyBsn.findApplicationProperty(Properties.EMAIL_SERVER_TYPE); Store store = mailSession.getStore(appProp.getPropertyValue()); store.connect(); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); Message[] message = folder.getMessages(); List<MailingListMessage> mailingListMessages = new ArrayList<MailingListMessage>(); MailingListMessage mailingListMessage; MailingListSubscription mailingListSubscription; String address; List<MailingList> mailingLists; for (int i = 0, n = message.length; i < n; i++) { mailingListMessage = new MailingListMessage(); mailingListMessage.setId(EntitySupport.generateEntityId()); mailingListMessage.setSubject(message[i].getSubject()); /* Get the email address of the 'from' field, search the address * in the subscription table and set the sender of the message. * Only those who are registered in the subscription table have * their message considered. */ address = message[i].getFrom()[0].toString(); if(address.indexOf("<") >= 0) address = address.substring(address.indexOf("<") + 1, address.indexOf(">")); address = address.toLowerCase(); mailingListSubscription = findMailingListSubscription(address); logger.log(Level.INFO, "Sender: {0}", new Object[]{address.toString()}); if(mailingListSubscription == null) continue; else mailingListMessage.setSender(mailingListSubscription); /* This part tries to get the full content of the message to * store in the database. For that, a simple OutputStream * implementation writes the whole content of the message in a * string, which defines the attribute body of the * mailingListMessage object. */ OutputStream output = new OutputStream() { private StringBuilder string = new StringBuilder(); @Override public void write(int b) throws IOException { this.string.append((char) b ); } @Override public String toString() { return this.string.toString(); } }; message[i].writeTo(output); mailingListMessage.setBody(output.toString()); mailingListMessage.setWhenReceived(message[i].getReceivedDate()); /* Stores in the database only those messages that were sent to * a registered mailing list. */ mailingLists = figureOutMailingLists(message[i].getAllRecipients()); if(mailingLists == null || mailingLists.isEmpty()) continue; else { mailingListMessage.setMailingList(mailingLists.get(0)); em.persist(mailingListMessage); } for(int j = 1;j < mailingLists.size();j++) { mailingListMessage = (MailingListMessage)mailingListMessage.clone(); mailingListMessage.setMailingList(mailingLists.get(j)); em.persist(mailingListMessage); } message[i].setFlag(Flags.Flag.DELETED, true); } folder.close(false); store.close(); logger.log(Level.INFO, "Email retrieval ended."); } catch (IOException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } } /** Check the recipients to detect for which mailing lists the message was sent. */ private List<MailingList> figureOutMailingLists(Address[] extendedListAddresses) { String listAddress; List<MailingList> mailingLists = new ArrayList<MailingList>(); MailingList mailingList; for(int i = 0;i < extendedListAddresses.length;i++) { // Extracts emails from the listAddress = extendedListAddresses[i].toString(); if(listAddress.indexOf("<") >= 0) listAddress = listAddress.substring(listAddress.indexOf("<") + 1, listAddress.indexOf(">")); listAddress = listAddress.toLowerCase(); logger.log(Level.INFO, "List address: {0}", new Object[]{listAddress}); mailingList = findMailingListByEmail(listAddress); if(mailingList != null) mailingLists.add(mailingList); } return mailingLists; } }
Download messages and set those messages to be deleted from the server
jug-ejb/src/java/org/cejug/knowledge/business/MailingListBsn.java
Download messages and set those messages to be deleted from the server
<ide><path>ug-ejb/src/java/org/cejug/knowledge/business/MailingListBsn.java <ide> <ide> package org.cejug.knowledge.business; <ide> <add>import com.sun.mail.imap.IMAPBodyPart; <ide> import java.io.IOException; <ide> import java.io.OutputStream; <ide> import java.util.ArrayList; <ide> import javax.mail.MessagingException; <ide> import javax.mail.Session; <ide> import javax.mail.Store; <del>import javax.mail.internet.MimeMessage; <add>import javax.mail.internet.MimeMultipart; <ide> import javax.persistence.EntityManager; <ide> import javax.persistence.NoResultException; <ide> import javax.persistence.PersistenceContext; <ide> * mailingListMessage object. */ <ide> OutputStream output = new OutputStream() { <ide> private StringBuilder string = new StringBuilder(); <del> <add> <ide> @Override <ide> public void write(int b) throws IOException { <ide> this.string.append((char) b ); <ide> }; <ide> message[i].writeTo(output); <ide> mailingListMessage.setBody(output.toString()); <add>// if(message[i].getContent() instanceof MimeMultipart) { <add>// MimeMultipart mm = (MimeMultipart)message[i].getContent(); <add>// logger.log(Level.INFO, "Parts: {0}", mm.getCount()); <add>// StringBuilder body = new StringBuilder(); <add>// for(int j = 0;j < mm.getCount();j++) { <add>// if(mm.getBodyPart(j) instanceof IMAPBodyPart) { <add>// IMAPBodyPart ibp = (IMAPBodyPart)mm.getBodyPart(j); <add>// body.append(ibp.getDescription()); <add>// } <add>// } <add>// mailingListMessage.setBody(body.toString()); <add>// } <add>// else <add>// mailingListMessage.setBody(message[i].getContent().toString()); <ide> <ide> mailingListMessage.setWhenReceived(message[i].getReceivedDate()); <ide> <ide> else { <ide> mailingListMessage.setMailingList(mailingLists.get(0)); <ide> em.persist(mailingListMessage); <add> message[i].setFlag(Flags.Flag.DELETED, true); <ide> } <ide> <ide> for(int j = 1;j < mailingLists.size();j++) { <ide> mailingListMessage.setMailingList(mailingLists.get(j)); <ide> em.persist(mailingListMessage); <ide> } <del> message[i].setFlag(Flags.Flag.DELETED, true); <ide> } <del> folder.close(false); <add> folder.close(true); <ide> store.close(); <ide> logger.log(Level.INFO, "Email retrieval ended."); <ide> } catch (IOException ex) {
JavaScript
mit
d0e50c572415c3839aebb597f0bb182052a6470f
0
wonknu/abecms,abecms/abecms,wonknu/abecms,wonknu/abecms,AdFabConnect/abejs,abecms/abecms,AdFabConnect/abejs,abecms/abecms,AdFabConnect/abejs
var nodemon = require('nodemon') var clc = require('cli-color') // NODE_ENV=development nodemon --exec npm run babel-app src/server/app.js --kill-others // ROOT=/path/to/my/abesite node src/tasks/nodemon.js nodemon({ script: __dirname + '/../../src/server/app.js', options: { exec: __dirname + '/../../node_modules/.bin/babel-node --presets es2015' }, nodeArgs: ['--debug'], restartable: 'rs', colours: true, execMap: { js: __dirname + '/../../node_modules/.bin/babel-node --presets es2015' }, env: { 'NODE_ENV': 'development' }, ignore: [ 'docs/*' ], watch: [ 'src/cli/*', 'src/hooks/*', 'src/server/routes/*', 'src/server/helpers/*', 'src/server/middlewares/*', 'src/server/controllers/*', 'src/server/app.js', 'src/server/index.js', process.env.ROOT + '/scripts/**/**/*.js', process.env.ROOT + '/abe.json', process.env.ROOT + '/locales/*', process.env.ROOT + '/hooks/**/*.js', process.env.ROOT + '/reference/**/*.json' ], stdin: true, runOnChangeOnly: false, verbose: true, // 'stdout' refers to the default behaviour of a required nodemon's child, // but also includes stderr. If this is false, data is still dispatched via // nodemon.on('stdout/stderr') stdout: true }) nodemon.on('start', function () { }).on('quit', function () { console.log(clc.green('Kill process nodemon')) process.exit() }).on('restart', function (files) { console.log('------------------------------------------------------------') console.log(clc.green('App restarted due to: '), files[0]) })
src/tasks/nodemon.js
var nodemon = require('nodemon') var clc = require('cli-color') // NODE_ENV=development nodemon --exec npm run babel-app src/server/app.js --kill-others // ROOT=/path/to/my/abesite node src/tasks/nodemon.js nodemon({ script: __dirname + '/../../src/server/app.js', options: { exec: __dirname + '/../../node_modules/.bin/babel-node --presets es2015' }, nodeArgs: ['--debug'], restartable: 'rs', colours: true, execMap: { js: __dirname + '/../../node_modules/.bin/babel-node --presets es2015' }, env: { 'NODE_ENV': 'development' }, ignore: [ // 'docs/*' ], watch: [ 'src/cli/*', 'src/hooks/*', 'src/server/routes/*', 'src/server/helpers/*', 'src/server/middlewares/*', 'src/server/controllers/*', 'src/server/app.js', 'src/server/index.js', process.env.ROOT + '/scripts/**/**/*.js', process.env.ROOT + '/abe.json', process.env.ROOT + '/locales/*', process.env.ROOT + '/hooks/**/*.js', process.env.ROOT + '/reference/**/*.json' ], stdin: true, runOnChangeOnly: false, verbose: true, // 'stdout' refers to the default behaviour of a required nodemon's child, // but also includes stderr. If this is false, data is still dispatched via // nodemon.on('stdout/stderr') stdout: true }) nodemon.on('start', function () { }).on('quit', function () { console.log(clc.green('Kill process nodemon')) process.exit() }).on('restart', function (files) { console.log('------------------------------------------------------------') console.log(clc.green('App restarted due to: '), files[0]) })
uncomment docs
src/tasks/nodemon.js
uncomment docs
<ide><path>rc/tasks/nodemon.js <ide> 'NODE_ENV': 'development' <ide> }, <ide> ignore: [ <del> // 'docs/*' <add> 'docs/*' <ide> ], <ide> watch: [ <ide> 'src/cli/*',
Java
agpl-3.0
17599a797ac78e4dfab3aa45c53878f20e6916ea
0
Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge
/* Copyright (C) 2016-2019 Andreas Shimokawa, Carsten Pfeiffer, Daniele Gobbetti This file is part of Gadgetbridge. Gadgetbridge 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. Gadgetbridge 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/>. */ package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.operations; import android.net.Uri; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiService; import nodomain.freeyourgadget.gadgetbridge.service.btle.BLETypeConversions; import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceBusyAction; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareInfo; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiSupport; public class UpdateFirmwareOperationNew extends UpdateFirmwareOperation { private static final Logger LOG = LoggerFactory.getLogger(UpdateFirmwareOperationNew.class); public UpdateFirmwareOperationNew(Uri uri, HuamiSupport support) { super(uri, support); } public boolean sendFwInfo() { try { TransactionBuilder builder = performInitialized("send firmware info"); builder.add(new SetDeviceBusyAction(getDevice(), getContext().getString(R.string.updating_firmware), getContext())); int fwSize = getFirmwareInfo().getSize(); byte[] sizeBytes = BLETypeConversions.fromUint24(fwSize); byte[] bytes = new byte[10]; int i = 0; bytes[i++] = HuamiService.COMMAND_FIRMWARE_INIT; bytes[i++] = getFirmwareInfo().getFirmwareType().getValue(); bytes[i++] = sizeBytes[0]; bytes[i++] = sizeBytes[1]; bytes[i++] = sizeBytes[2]; bytes[i++] = 0; // TODO: what is that? int crc32 = firmwareInfo.getCrc32(); byte[] crcBytes = BLETypeConversions.fromUint32(crc32); bytes[i++] = crcBytes[0]; bytes[i++] = crcBytes[1]; bytes[i++] = crcBytes[2]; bytes[i] = crcBytes[3]; builder.write(fwCControlChar, bytes); builder.queue(getQueue()); return true; } catch (IOException e) { LOG.error("Error sending firmware info: " + e.getLocalizedMessage(), e); return false; } } @Override protected void sendChecksum(HuamiFirmwareInfo firmwareInfo) throws IOException { TransactionBuilder builder = performInitialized("send firmware upload finished"); builder.write(fwCControlChar, new byte[]{HuamiService.COMMAND_FIRMWARE_CHECKSUM}); builder.queue(getQueue()); } @Override protected byte[] getFirmwareStartCommand() { return new byte[]{HuamiService.COMMAND_FIRMWARE_START_DATA, 1}; } }
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/operations/UpdateFirmwareOperationNew.java
/* Copyright (C) 2016-2019 Andreas Shimokawa, Carsten Pfeiffer, Daniele Gobbetti This file is part of Gadgetbridge. Gadgetbridge 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. Gadgetbridge 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/>. */ package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.operations; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.content.Context; import android.net.Uri; import android.widget.Toast; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.UUID; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventDisplayMessage; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiFWHelper; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiService; import nodomain.freeyourgadget.gadgetbridge.model.DeviceType; import nodomain.freeyourgadget.gadgetbridge.service.btle.BLETypeConversions; import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceBusyAction; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetProgressAction; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.AbstractHuamiOperation; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareInfo; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareType; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiSupport; import nodomain.freeyourgadget.gadgetbridge.util.GB; import nodomain.freeyourgadget.gadgetbridge.util.Prefs; public class UpdateFirmwareOperationNew extends UpdateFirmwareOperation { private static final Logger LOG = LoggerFactory.getLogger(UpdateFirmwareOperationNew.class); public UpdateFirmwareOperationNew(Uri uri, HuamiSupport support) { super(uri, support); } public boolean sendFwInfo() { try { TransactionBuilder builder = performInitialized("send firmware info"); builder.add(new SetDeviceBusyAction(getDevice(), getContext().getString(R.string.updating_firmware), getContext())); int fwSize = getFirmwareInfo().getSize(); byte[] sizeBytes = BLETypeConversions.fromUint24(fwSize); byte[] bytes = new byte[10]; int i = 0; bytes[i++] = HuamiService.COMMAND_FIRMWARE_INIT; bytes[i++] = getFirmwareInfo().getFirmwareType().getValue(); bytes[i++] = sizeBytes[0]; bytes[i++] = sizeBytes[1]; bytes[i++] = sizeBytes[2]; bytes[i++] = 0; // TODO: what is that? int crc32 = firmwareInfo.getCrc32(); byte[] crcBytes = BLETypeConversions.fromUint32(crc32); bytes[i++] = crcBytes[0]; bytes[i++] = crcBytes[1]; bytes[i++] = crcBytes[2]; bytes[i] = crcBytes[3]; builder.write(fwCControlChar, bytes); builder.queue(getQueue()); return true; } catch (IOException e) { LOG.error("Error sending firmware info: " + e.getLocalizedMessage(), e); return false; } } @Override protected void sendChecksum(HuamiFirmwareInfo firmwareInfo) throws IOException { TransactionBuilder builder = performInitialized("send firmware upload finished"); builder.write(fwCControlChar, new byte[]{HuamiService.COMMAND_FIRMWARE_CHECKSUM}); builder.queue(getQueue()); } @Override protected byte[] getFirmwareStartCommand() { return new byte[]{HuamiService.COMMAND_FIRMWARE_START_DATA, 1}; } }
remove unused imports
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/operations/UpdateFirmwareOperationNew.java
remove unused imports
<ide><path>pp/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/operations/UpdateFirmwareOperationNew.java <ide> along with this program. If not, see <http://www.gnu.org/licenses/>. */ <ide> package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.operations; <ide> <del>import android.bluetooth.BluetoothGatt; <del>import android.bluetooth.BluetoothGattCharacteristic; <del>import android.content.Context; <ide> import android.net.Uri; <del>import android.widget.Toast; <ide> <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <ide> import java.io.IOException; <del>import java.util.Arrays; <del>import java.util.UUID; <ide> <del>import nodomain.freeyourgadget.gadgetbridge.GBApplication; <ide> import nodomain.freeyourgadget.gadgetbridge.R; <del>import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventDisplayMessage; <del>import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiFWHelper; <ide> import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiService; <del>import nodomain.freeyourgadget.gadgetbridge.model.DeviceType; <ide> import nodomain.freeyourgadget.gadgetbridge.service.btle.BLETypeConversions; <ide> import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder; <ide> import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceBusyAction; <del>import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetProgressAction; <del>import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.AbstractHuamiOperation; <ide> import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareInfo; <del>import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareType; <ide> import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiSupport; <del>import nodomain.freeyourgadget.gadgetbridge.util.GB; <del>import nodomain.freeyourgadget.gadgetbridge.util.Prefs; <ide> <ide> public class UpdateFirmwareOperationNew extends UpdateFirmwareOperation { <ide> private static final Logger LOG = LoggerFactory.getLogger(UpdateFirmwareOperationNew.class);
JavaScript
agpl-3.0
bffd2a7ea9a9744c1d81e610de1b7dab9e34f1f1
0
Brennon11/cgm-remote-monitor,rachellynnae/cgm-remote-monitor,rdobb/cgm-remote-monitor,aaroecker/cgm-remote-monitor,JosiahNS/cgm-remote-monitor,jerryfuselier/cgm-remote-monitor,yleniadm/cgm-remote-monitor,dshier/cgm-remote-monitor,ryanfire12/cgm-remote-monitor,asidorovich/cgm-remote-monitor,NSDreamsicle/cgm-remote-monitor,ejensen719/cgm-remote-monitor,dia1234/cgm-remote-monitor,lotharmartinez/cgm-remote-monitor,albertodalcero/cgm-remote-monitor,sinweb/cgm-remote-monitor,johansvdb/cgm-remote-monitor,davinche07/cgm-remote-monitor,skafandrami/cgm-remote-monitor,cooperlushell/cgm-remote-monitor,porkupan/cgm-remote-monitor,Rmaw02/cgm-remote-monitor,brownkkeb/cgm-remote-monitor,ejdemers/cgm-remote-monitor,jiaa6908/cgm-remote-monitor,Larsjon/cgm-remote-monitor,dexinfo/cgm-remote-monitor,mrfoley/cgm-remote-monitor,AllyCat09/cgm-remote-monitor,natsera/cgm-remote-monitor,ancameron/cgm-remote-monitor,lewispope/cgm-remote-monitor,AJStinson/cgm-remote-monitor,snicastro/cgm-remote-monitor,faromatilde/cgm-remote-monitor,dadadmin/cgm-remote-monitor,ccarrigan/cgm-remote-monitor,samihusseingit/cgm-remote-monitor,nsmegi/cgm-remote-monitor,brendanroche/cgm-remote-monitor,lilislifesavers/cgm-remote-monitor,Ashcgm/cgm-remote-monitor,sebastianlorant/cgm-remote-monitor,kdauenbaugh/cgm-remote-monitor,manaolana/cgm-remote-monitor,jennifercnightscout/cgm-remote-monitor,kdauenbaugh/cgm-remote-monitor,xdripab/cgm-remote-monitor,ak8418/cgm-remote-monitor,codakean/cgm-remote-monitor,linascout/cgm-remote-monitor,Aslush23/cgm-remote-monitor,mikestebbins/cgm-remote-monitor,miglesia/cgm-remote-monitor,JakubkoDIA/cgm-remote-monitor,martinek10/cgm-remote-monitor,gregwaehner/cgm-remote-monitor,XanderNels/cgm-remote-monitor,tommy06/cgm-remote-monitor,donnamichelle/cgm-remote-monitor,editdata7/cgm-remote-monitor,jcdrapp/cgm-remote-monitor,laurenvan7/cgm-remote-monitor,dbeasy/cgm-remote-monitor,rmcfar09/cgm-remote-monitor,ajbrugnano/cgm-remote-monitor,stampertk/cgm-remote-monitor,libby4label/cgm-remote-monitor,drcameron/cgm-remote-monitor,jweismann/cgm-remote-monitor,thomcost/cgm-remote-monitor,kgilles2000/cgm-remote-monitor,Grahnarna/cgm-remote-monitor,Grahnarna/cgm-remote-monitor,vnaslund/cgm-remote-monitor,runebrostrom/cgm-remote-monitor,dan170278/cgm-remote-monitor,camns/cgm-remote-monitor,pedrojparedes/cgm-remote-monitor,JakubkoDIA/cgm-remote-monitor,runebrostrom/cgm-remote-monitor,moylan/cgm-remote-monitor,cowboylogic13/cgm-remote-monitor,jrogers2199/cgm-remote-monitor,ns-nathan/cgm-remote-monitor,seelynat/cgm-remote-monitor,rogerhaugerud/cgm-remote-monitor,kaelyncgm/cgm-remote-monitor,lincolnprice/cgm-remote-monitor,chelesawilds/cgm-remote-monitor,urmc-costik/cgm-remote-monitor,Martata83/cgm-remote-monitor,nightscoutjdp/cgm-remote-monitor,raresdexcom/cgm-remote-monitor,alive5050/cgm-remote-monitor,asg8146/cgm-remote-monitor,baembel08/cgm-remote-monitor,mwmoore12/cgm-remote-monitor,janetlizconroy/cgm-remote-monitor,tomas69/cgm-remote-monitor,sherri29/cgm-remote-monitor,Artorias360/cgm-remote-monitor,Fredensvold/cgm-remote-monitor,josephnightscout/cgm-remote-monitor,adriwelborn/cgm-remote-monitor,ejensen719/cgm-remote-monitor,forte687/cgm-remote-monitor,jiaa6908/cgm-remote-monitor,mhersco/cgm-remote-monitor,albertotrg/cgm-remote-monitor,llehtio/cgm-remote-monitor,TylerMathews/cgm-remote-monitor,brmccollum/Test,monkeymankjb/cgm-remote-monitor,Aes02/cgm-remote-monitor,cowboylogic13/cgm-remote-monitor,dadadmin/cgm-remote-monitor,nsmegi/cgm-remote-monitor,GarthDB/cgm-remote-monitor,CassidyAccount/cgm-remote-monitor,JockeOrn/cgm-remote-monitor,britishguy4/cgm-remote-monitor,UphwbKpqSm47z3qewH9x/cgm-remote-monitor,metzlernsdb/cgm-remote-monitor,AshleyZeigler/cgm-remote-monitor,diab1234/cgm-remote-monitor,lexa140978/cgm-remote-monitor,snicastro/cgm-remote-monitor,jenlamoureux/cgm-remote-monitor,stampertk/cgm-remote-monitor,ahalyacarter/cgm-remote-monitor,XbridgeBuri94/cgm-remote-monitor,Wanitta/cgm-remote-monitor,Candyhearts/cgm-remote-monitor,dexcom2014/cgm-remote-monitor,nippe71/cgm-remote-monitor,AddisonMKNS/cgm-remote-monitor,RebekahLindsay/cgm-remote-monitor,editdata14/cgm-remote-monitor,nsnwells/cgm-remote-monitor,chriscin/cgm-remote-monitor,Thebassefamily/cgm-remote-monitor,Elysespump/cgm-remote-monitor,fboegard/cgm-remote-monitor,fuddster/cgm-remote-monitor,shaunaT/cgm-remote-monitor,gth001/cgm-remote-monitor,bklinker/cgm-remote-monitor,thecaseyjames/cgm-remote-monitor,diegodexcom/cgm-remote-monitor,NightDrip/cgm-remote-monitor,iris4acure/cgm-remote-monitor,hel1fire/cgm-remote-monitor,annbennett/cgm-remote-monitor,Kraey/cgm-remote-monitor,baembel08/cgm-remote-monitor,ericmetzlerns/cgm-remote-monitor,utefan/cgm-remote-monitor,NightScoutErin/cgm-remote-monitor,yeahbaby/cgm-remote-monitor,leonimo2/cgm-remote-monitor,scottleibrand/cgm-remote-monitor,DanielFilipov/cgm-remote-monitor-1,PoludaMargo/cgm-remote-monitor,bogdangorescu/cgm-remote-monitor,riley1216/cgm-remote-monitor,mddub/cgm-remote-monitor,emilybsessions/cgm-remote-monitor,delaney726/cgm-remote-monitor,Della330/cgm-remote-monitor,mattlevine22/cgm-remote-monitor,ericscgm/cgm-remote-monitor,ilasuper1/cgm-remote-monitor,XbridgeBuri94/cgm-remote-monitor,averydex/cgm-remote-monitor,bricgm/cgm-remote-monitor,Makenna2004/cgm-remote-monitor,tyrahustedt/cgm-remote-monitor,maxsdmom/cgm-remote-monitor,antalois/cgm-remote-monitor,DylansCGM/cgm-remote-monitor,ahalyacarter/cgm-remote-monitor,Trivera04/cgm-remote-monitor,lewispope/cgm-remote-monitor,alapiscd/cgm-remote-monitor,mwmoore12/cgm-remote-monitor,dia1234/cgm-remote-monitor,davinche07/cgm-remote-monitor,tripstoner/cgm-remote-monitor,serena12/cgm-remote-monitor,vicmarc/cgm-remote-monitor,aphelps5/cgm-remote-monitor,sugabetic/cgm-remote-monitor,AndreaAzzarello/cgm-remote-monitor-1,morganmott/cgm-remote-monitor,baskak/cgm-remote-monitor,ethanstr/cgm-remote-monitor,LTatu/cgm-remote-monitor,pavel1981/cgm-remote-monitor,superbravemillsy/cgm-remote-monitor,serena12/cgm-remote-monitor,pepecb/cgm-remote-monitor,audiefile/cgm-remote-monitor,viljanightscout/cgm-remote-monitor,geoff004/cgm-remote-monitor,fiberfan/cgm-remote-monitor,WholeEnchilada/cgm-remote-monitor,Tsokonut/cgm-remote-monitor,rafaelomartin/cgm-remote-monitor,aphelps5/cgm-remote-monitor,nightscoutjdp/cgm-remote-monitor,livingston93/cgm-remote-monitor,tanja3981/cgm-remote-monitor,slipgate/cgm-remote-monitor,maesey/cgm-remote-monitor,jessdex2/cgm-remote-monitor,gregwaehner/cgm-remote-monitor,jonahtaxt/cgm-remote-monitor,miglesia/cgm-remote-monitor,natsera/cgm-remote-monitor,Marc78400/cgm-remote-monitor,ljusername/cgm-remote-monitor,bogdangorescu/cgm-remote-monitor,dylanalba/cgm-remote-monitor,chris4295/cgm-remote-monitor,jschoeps/cgm-remote-monitor,lbscoutgh/cgm-remote-monitor,ashbyakgm/cgm-remote-monitor,tjkns/cgm-remote-monitor,jerryfuselier/cgm-remote-monitor,gina1beana/cgm-remote-monitor,mzst123/cgm-remote-monitor,MidgeysMom/cgm-remote-monitor,tripstoner/cgm-remote-monitor,ilasuper1/cgm-remote-monitor,sethkennedy01/cgm-remote-monitor,levinightscout/cgm-remote-monitor,Fokko/cgm-remote-monitor,Aslush23/cgm-remote-monitor,HowardLook/cgm-remote-monitor,isaaccgm/cgm-remote-monitor,patric82/cgm-remote-monitor,patric82/cgm-remote-monitor,lazzeb/cgm-remote-monitor,Wanitta/cgm-remote-monitor,Jemmamc1985/cgm-remote-monitor,jaysheree/cgm-remote-monitor,baskak/cgm-remote-monitor,urmc-costik/cgm-remote-monitor,CassidyAccount/cgm-remote-monitor,albertodc/cgm-remote-monitor,jcdrapp/cgm-remote-monitor,julieraines/cgm-remote-monitor,ccarrigan/cgm-remote-monitor,lexiergeson/cgm-remote-monitor,dexinfo/cgm-remote-monitor,kcnygaard/cgm-remote-monitor,ccarrigan/cgm-remote-monitor,telma2006/cgm-remote-monitor,jaghitop/cgm-remote-monitor,gws1/cgm-remote-monitor,ThomasEmge/cgm-remote-monitor,albertodc/cgm-remote-monitor,Katerina01/cgm-remote-monitor,ellabellakaramella/cgm-remote-monitor,codakean/cgm-remote-monitor,githubns/cgm-remote-monitor,camns/cgm-remote-monitor,leonimo/cgm-remote-monitor,rnewby/cgm-remote-monitor,marcips/cgm-remote-monitor,mattlevine22/cgm-remote-monitor,ceben80/cgm-remote-monitor,inform880/cgm-remote-monitor,diab1234/cgm-remote-monitor,EmilyCGM/cgm-remote-monitor,juliatakeuti/cgm-remote-monitor,titusfaber/cgm-remote-monitor,Ayaz2014/cgm-remote-monitor-1,iwalktheline86/cgm-remote-monitor,Kainicus/cgm-remote-monitor,Mihaeladex/cgm-remote-monitor,michaelpears/cgm-remote-monitor,lisafolkestad/cgm-remote-monitor,bianca2015/cgm-remote-monitor,kgilles2000/cgm-remote-monitor,casey21/cgm-remote-monitor,dlmgit/cgm-remote-monitor,lionheartman/cgm-remote-monitor,Larsjon/cgm-remote-monitor,sarah4hand/cgm-remote-monitor,UphwbKpqSm47z3qewH9x/cgm-remote-monitor,MitchDex/cgm-remote-monitor,mhersco/cgm-remote-monitor,jpirronecgm/cgm-remote-monitor,morganmott/cgm-remote-monitor,nightscout963/cgm-remote-monitor,Landbchecker/cgm-remote-monitor,beckerfamily2/cgm-remote-monitor,ThomasEmge/cgm-remote-monitor,ryandexcom/cgm-remote-monitor,baskak/cgm-remote-monitor,Rmaw02/cgm-remote-monitor,KatyTanet/cgm-remote-monitor,jenzamom/cgm-remote-monitor,cgmmiles/cgm-remote-monitor,AlexanderP01/cgm-remote-monitor,jadendexcom/cgm-remote-monitor,BrentNS/cgm-remote-monitor,pugarts/cgm-remote-monitor,DavMedek/cgm-remote-monitor,Landbchecker/cgm-remote-monitor,robertanye/cgm-remote-monitor,sbessolina81/cgm-remote-monitor,barry45/cgm-remote-monitor,cblove73/cgm-remote-monitor,JakubkoDIA/cgm-remote-monitor,edencgm/cgm-remote-monitor,mimes/cgm-remote-monitor,Karahbevin/cgm-remote-monitor,jonahtaxt/cgm-remote-monitor,shannonhaywood/cgm-remote-monitor,live4sw/cgm-remote-monitor,Tribunesix/cgm-remote-monitor,bscutero/cgm-remote-monitor,stevenrgriffin/cgm-remote-monitor,PTGScout/cgm-remote-monitor,babyannascgm/cgm-remote-monitor,HugoKollegger/cgm-remote-monitor,pjweiss/cgm-remote-monitor,foxlazza/cgm-remote-monitor,lucyrm/cgm-remote-monitor,madisonmen123/cgm-remote-monitor,Bellagh1/cgm-remote-monitor,jonvarner/cgm-remote-monitor,Slawek1981/cgm-remote-monitor,jonvarner/cgm-remote-monitor,zkjohnson/cgm-remote-monitor,katiestone808/cgm-remote-monitor,beavisandgirl/cgm-remote-monitor,mushetal/cgm-remote-monitor,morganmott/cgm-remote-monitor,Jake1114/cgm-remote-monitor,scottmark/cgm-remote-monitor,HoskinsNSGithub2179/cgm-remote-monitor,shannonhaywood/cgm-remote-monitor,claytonfrost/cgm-remote-monitor,meandahlia/cgm-remote-monitor,Diabetiger/cgm-remote-monitor,mvieau/cgm-remote-monitor,abcschooldr/cgm-remote-monitor,goranssons/cgm-remote-monitor,tylee2009/cgm-remote-monitor,maddiemom/cgm-remote-monitor,HowardLook/cgm-remote-monitor,forte687/cgm-remote-monitor,drummer35/cgm-remote-monitor,slipgate/cgm-remote-monitor,annbennett/cgm-remote-monitor,kiserman/cgm-remote-monitor,pauljlucas/cgm-remote-monitor,jwedding/cgm-remote-monitor,lilyraine/cgm-remote-monitor,ajwyckoff/cgm-remote-monitor,Smith78/cgm-remote-monitor,gitanO0/cgm-remote-monitor,ashlynnsorenson/cgm-remote-monitor,AJS2008/cgm-remote-monitor,hansonfamilyfive/cgm-remote-monitor,AlexDesjardins/cgm-remote-monitor,srimes/cgm-remote-monitor,melaniesugarsonline/cgm-remote-monitor,jflores1948/cgm-remote-monitor,bobocmtj14/cgm-remote-monitor,dayiiijh/cgm-remote-monitor,CeciliaAlicia/cgm-remote-monitor,fuddster/cgm-remote-monitor,Artorias360/cgm-remote-monitor,star37NS/cgm-remote-monitor,vandyjt/cgm-remote-monitor,rogerhaugerud/cgm-remote-monitor,jennymattyste83/cgm-remote-monitor,dshier/cgm-remote-monitor,NightscoutSasha/cgm-remote-monitor,DanielFilipov/cgm-remote-monitor-1,ThesSpawn826/cgm-remote-monitor,jenlamoureux/cgm-remote-monitor,marcusjonsson76/cgm-remote-monitor,thomascostello/cgm-remote-monitor,melaniesugarsonline/cgm-remote-monitor,ldknoch/cgm-remote-monitor,hyeokseo/cgm-remote-monitor,juliehageman/cgm-remote-monitor,marcusjonsson76/cgm-remote-monitor,lennydog/cgm-remote-monitor,jrogers2199/cgm-remote-monitor,KatyTanet/cgm-remote-monitor,ajwyckoff/cgm-remote-monitor,jen92225/cgm-remote-monitor,mhersco/cgm-remote-monitor,mzst123/cgm-remote-monitor,bldalbey/cgm-remote-monitor,LiamMagnus/cgm-remote-monitor,seelynat/cgm-remote-monitor,ethanstr/cgm-remote-monitor,livingston93/cgm-remote-monitor,FraserRoethel/cgm-remote-monitor,nightscout963/cgm-remote-monitor,brmccollum/Test,rsuvalle/cgm-remote-monitor,cooperlushell/cgm-remote-monitor,lilagw/cgm-remote-monitor,kkileyhub/cgm-remote-monitor,noelle1211/cgm-remote-monitor,IsaacBGallaher/cgm-remote-monitor,feraridurango/cgm-remote-monitor,casey21/cgm-remote-monitor,mrfoley/cgm-remote-monitor,jenlamoureux/cgm-remote-monitor,linascout/cgm-remote-monitor,skythegreat/cgm-remote-monitor,OpossumGit/cgm-remote-monitor,brbaldwin1970/cgm-remote-monitor,momof10/cgm-remote-monitor,aabramowicz/cgm-remote-monitor,demonicpagan/cgm-remote-monitor,ldpcloud/cgm-remote-monitor,Thebassefamily/cgm-remote-monitor,grevsjonightscout/cgm-remote-monitor,mkruiswyk/cgm-remote-monitor,paleoCoder/cgm-remote-monitor,simigit/cgm-remote-monitor,tommy06/cgm-remote-monitor,brmccollum/Test,ktomy/cgm-remote-monitor,Fokko/cgm-remote-monitor,oamyoamy/cgm-remote-monitor,tycho40/cgm-remote-monitor,levinightscout/cgm-remote-monitor,PieterGit/cgm-remote-monitor,ldkbyj/cgm-remote-monitor,ethanstr/cgm-remote-monitor,brookeshelley/cgm-remote-monitor,d-liza/cgm-remote-monitor,nvmybug01/cgm-remote-monitor,gregwaehner/cgm-remote-monitor,marincgm/cgm-remote-monitor,cindythornburgh/cgm-remote-monitor,drcameron/cgm-remote-monitor,martinrq/cgm-remote-monitor,westoncgm/cgm-remote-monitor,telma2006/cgm-remote-monitor,sobrecht/cgm-remote-monitor,marincgm/cgm-remote-monitor,phisparks/cgm-remote-monitor,ericscgm/cgm-remote-monitor,albertotrg/cgm-remote-monitor,Audrawebb/cgm-remote-monitor,Choens/cgm-remote-monitor,Silvia1972/cgm-remote-monitor,serena12/cgm-remote-monitor,Choens/cgm-remote-monitor,emppuli/cgm-remote-monitor,shaynejmt/cgm-remote-monitor,shaynejmt/cgm-remote-monitor,skafandrami/cgm-remote-monitor,AnnabelleT1D/cgm-remote-monitor,astrocam/cgm-remote-monitor,drex304/cgm-remote-monitor,GrechCGM4/cgm-remote-monitor,johansvdb/cgm-remote-monitor,gina1beana/cgm-remote-monitor,raresdexcom/cgm-remote-monitor,mzst123/cgm-remote-monitor,nomareel/cgm-remote-monitor,Jemmamc1985/cgm-remote-monitor,Treshots/cgm-remote-monitor,dseekert/cgm-remote-monitor,brookeshelley/cgm-remote-monitor,BlackDogsRule/cgm-remote-monitor,Sammydickenson/cgm-remote-monitor,ThesSpawn826/cgm-remote-monitor,lisafolkestad/cgm-remote-monitor,skafandrami/cgm-remote-monitor,nsmariette/cgm-remote-monitor,kdaNOTdka/cgm-remote-monitor,goldendel/cgm-remote-monitor,michealjj/cgm-remote-monitor,ak8418/cgm-remote-monitor,telma2006/cgm-remote-monitor,cindythornburgh/cgm-remote-monitor,nsmom/cgm-remote-monitor,jschoeps/cgm-remote-monitor,ramstrand/cgm-remote-monitor,garath77/cgm-remote-monitor,Viktoriartem/cgm-remote-monitor,leonimo/cgm-remote-monitor,vittetoe/cgm-remote-monitor,tomasboudr/cgm-remote-monitor,DiggerboyDylan/cgm-remote-monitor,wagnerpe/cgm-remote-monitor,pauljlucas/cgm-remote-monitor,rubinstein/cgm-remote-monitor,TylerCGM/cgm-remote-monitor,rhianna10/cgm-remote-monitor,k1960/cgm-remote-monitor,noelle1211/cgm-remote-monitor,lucikf/cgm-remote-monitor,AndreaAzzarello/cgm-remote-monitor-1,dastanton/cgm-remote-monitor,howxdrip/cgm-remote-monitor,jessica7990td/cgm-remote-monitor,Bonnar/cgm-remote-monitor,nsmegi/cgm-remote-monitor,ejdemers/cgm-remote-monitor,fichtenweg/cgm-remote-monitor,czahner/cgm-remote-monitor,ericscgm/cgm-remote-monitor,asidorovich/cgm-remote-monitor,thecaseyjames/cgm-remote-monitor,fiberfan/cgm-remote-monitor,mavster/cgm-remote-monitor,AbbysArmy/cgm-remote-monitor,jcurlander/cgm-remote-monitor,ProjectSafety/cgm-remote-monitor,kmasseygh/cgm-remote-monitor-1,tomstclair/cgm-remote-monitor,PoludaMargo/cgm-remote-monitor,lovezg/cgm-remote-monitor,VivianKnueppel/cgm-remote-monitor,Fredensvold/cgm-remote-monitor,spamis/cgm-remote-monitor,emppuli/cgm-remote-monitor,dexcom2014/cgm-remote-monitor,JosiahNS/cgm-remote-monitor,kbensing/cgm-remote-monitor,E2013/cgm-remote-monitor,Artorias360/cgm-remote-monitor,mvieau/cgm-remote-monitor,ryandexcom/cgm-remote-monitor,feraridurango/cgm-remote-monitor,scottswitz/cgm-remote-monitor,alex2007/cgm-remote-monitor,nseto475ghun/cgm-remote-monitor,cblove73/cgm-remote-monitor,vicmarc/cgm-remote-monitor,hannahggdb/cgm-remote-monitor,JeffJinSD/cgm-remote-monitor,spamis/cgm-remote-monitor,humphrey4526/cgm-remote-monitor,Diabetiger/cgm-remote-monitor,Maddie1222/cgm-remote-monitor,blakeflu/cgm-remote-monitor,CloudPL/cgm-remote-monitor,jonhunterbui/cgm-remote-monitor,dylanalba/cgm-remote-monitor,ariellecgm/cgm-remote-monitor,tylee2009/cgm-remote-monitor,LilyAD/cgm-remote-monitor,lukedfeus/cgm-remote-monitor,githubns/cgm-remote-monitor,hannahggdb/cgm-remote-monitor,pedrojparedes/cgm-remote-monitor,jadendexcom/cgm-remote-monitor,JeffJinSD/cgm-remote-monitor,dayiiijh/cgm-remote-monitor,DebbieMM/cgm-remote-monitor,nletrheim/cgm-remote-monitor,SweetRooks/cgm-remote-monitor,skjelland/cgm-remote-monitor,nightscoutjdp/cgm-remote-monitor,drex304/cgm-remote-monitor,JasperCGM/cgm-remote-monitor,mde1300/cgm-remote-monitor,forte687/cgm-remote-monitor,ethanscout/cgm-remote-monitor,josephnightscout/cgm-remote-monitor,blessedwhitney/cgm-remote-monitor,jojoyue200/cgm-remote-monitor,Elysespump/cgm-remote-monitor,fredivar1/cgm-remote-monitor,AnnabelleT1D/cgm-remote-monitor,ldpcloud/cgm-remote-monitor,AJStinson/cgm-remote-monitor,slburnett/cgm-remote-monitor,NSGabi/cgm-remote-monitor,dseekert/cgm-remote-monitor,crobinuk/cgm-remote-monitor,skrislov/cgm-remote-monitor,jgobat/cgm-remote-monitor,jenzamom/cgm-remote-monitor,tomas69/cgm-remote-monitor,thegoodnews/cgm-remote-monitor,kaelyncgm/cgm-remote-monitor,LilyAD/cgm-remote-monitor,tzweti/cgm-remote-monitor,Katerina01/cgm-remote-monitor,AbbysArmy/cgm-remote-monitor,abcschooldr/cgm-remote-monitor,mazzekp/cgm-remote-monitor,JockeOrn/cgm-remote-monitor,bromaco/cgm-remote-monitor,playingbball20/cgm-remote-monitor,livingston93/cgm-remote-monitor,loriwells8/cgm-remote-monitor,Brennon11/cgm-remote-monitor,jrmorrison/cgm-remote-monitor,skubigolf/cgm-remote-monitor,andrewbs/cgm-remote-monitor,ruiannie/cgm-remote-monitor,viljanightscout/cgm-remote-monitor,jleodaniel/cgm-remote-monitor,mjyrala/cgm-remote-monitor,jpirronecgm/cgm-remote-monitor,fichtenweg/cgm-remote-monitor,grossga/cgm-remote-monitor,sarahgit/cgm-remote-monitor,jjkrebs/cgm-remote-monitor,porkupan/cgm-remote-monitor,ryder08/cgm-remote-monitor,gleipert/cgm-remote-monitor,andyhandy/cgm-remote-monitor,xdripab/cgm-remote-monitor,thender11/cgm-remote-monitor,josephnightscout/cgm-remote-monitor,erikafromamerica/cgm-remote-monitor,corrdara/cgm-remote-monitor,VSCDR/cgm-remote-monitor,stjack1/cgm-remote-monitor,mel2095/cgm-remote-monitor,stevenrgriffin/cgm-remote-monitor,swissalpine/cgm-remote-monitor,jungsomyeonggithub/cgm-remote-monitor,skubesch/Nightscout-V8,Layni/cgm-remote-monitor,smilloy519/cgm-remote-monitor,rreed454/cgm-remote-monitor,kirks/cgm-remote-monitor,moylan/cgm-remote-monitor,lotharmartinez/cgm-remote-monitor,timomer/cgm-remote-monitor,logichammer/cgm-remote-monitor,javierdexcom/cgm-remote-monitor,galiapolia/cgm-remote-monitor,fgentzel/cgm-remote-monitor,DrSeattle/cgm-remote-monitor,Della330/cgm-remote-monitor,rsuvalle/cgm-remote-monitor,Aslush23/cgm-remote-monitor,ericmetzlerns/cgm-remote-monitor,donnamichelle/cgm-remote-monitor,sarahgit/cgm-remote-monitor,joshcorwin/cgm-remote-monitor,leyton2ns/cgm-remote-monitor,thegoodnews/cgm-remote-monitor,peanut1/cgm-remote-monitor,alexandrutomi/cgm-remote-monitor,XbridgeBuri94/cgm-remote-monitor,ccspiess/cgm-remote-monitor,martinek10/cgm-remote-monitor,loriwells8/cgm-remote-monitor,jessica7990td/cgm-remote-monitor,jonvarner/cgm-remote-monitor,michaelpears/cgm-remote-monitor,runebrostrom/cgm-remote-monitor,TylerCGM/cgm-remote-monitor,pablomariocgm/cgm-remote-monitor,EllieGitHub/cgm-remote-monitor,nvmybug01/cgm-remote-monitor,rebeccaorto/cgm-remote-monitor,BrentNS/cgm-remote-monitor,kritterfoster86/cgm-remote-monitor,thender11/cgm-remote-monitor,silvalized/cgm-remote-monitor,sbolshakov/cgm-remote-monitor,lucikf/cgm-remote-monitor,MackenzieT1D/cgm-remote-monitor,Mikael600/cgm-remote-monitor,HidroRaul/cgm-remote-monitor,pugarts/cgm-remote-monitor,githubns/cgm-remote-monitor,thender11/cgm-remote-monitor,shenkel74/cgm-remote-monitor,blakeflu/cgm-remote-monitor,mimes/cgm-remote-monitor,Gallooggi/cgm-remote-monitor,jonahtaxt/cgm-remote-monitor,IsaacEastridge/cgm-remote-monitor,AlexDesjardins/cgm-remote-monitor,eliz4142/cgm-remote-monitor,JamesCaw/cgm-remote-monitor,avielf/cgm-remote-monitor,AllyCat09/cgm-remote-monitor,tchancey/cgm-remote-monitor,Fedechicco2/cgm-remote-monitor,olivia08/cgm-remote-monitor,dexterbooty/cgm-remote-monitor,Wanitta/cgm-remote-monitor,yoda226/cgm-remote-monitor,geoff004/cgm-remote-monitor,hel1fire/cgm-remote-monitor,stefanakerblom/cgm-remote-monitor,scottleibrand/cgm-remote-monitor,mavster/cgm-remote-monitor,imnanjl/cgm-remote-monitor,dbogardaustin/cgm-remote-monitor,rafaelomartin/cgm-remote-monitor,nsmariette/cgm-remote-monitor,gempickfordwaugh/cgm-remote-monitor,Fedechicco2/cgm-remote-monitor,tyrahustedt/cgm-remote-monitor,diasigvard/cgm-remote-monitor,jasoncalabrese/cgm-remote-monitor,Hamby1214/cgm-remote-monitor,bw396704/cgm-remote-monitor,ruiannie/cgm-remote-monitor,barry45/cgm-remote-monitor,jordan-berger/cgm-remote-monitor,aaykayg/cgm-remote-monitor,lewispope/cgm-remote-monitor,T1Dcooper/cgm-remote-monitor,diasigvard/cgm-remote-monitor,melaniesugarsonline/cgm-remote-monitor,racechick3/cgm-remote-monitor,bdr1177/cgm-remote-monitor,lucyrm/cgm-remote-monitor,twinmomdb/cgm-remote-monitor,skirby99/cgm-remote-monitor,TerriV/cgm-remote-monitor,ps2/cgm-remote-monitor,Mikael600/cgm-remote-monitor,peanut1/cgm-remote-monitor,riley1216/cgm-remote-monitor,Trivera04/cgm-remote-monitor,nsnwells/cgm-remote-monitor,shanusmagnus/cgm-remote-monitor,ewanm/cgm-remote-monitor,butterfly6890/cgm-remote-monitor,nippe71/cgm-remote-monitor,mjyrala/cgm-remote-monitor,acanderson10/cgm-remote-monitor,msharpy/cgm-remote-monitor,rmiclescu/cgm-remote-monitor,Supersawyer/cgm-remote-monitor,Shane33/cgm-remote-monitor,bkdollar/cgm-remote-monitor,CaerwynRoberts/cgm-remote-monitor,bklinker/cgm-remote-monitor,betacellblues/cgm-remote-monitor,h20ford/cgm-remote-monitor,rachellynnae/cgm-remote-monitor,beckerfamily/cgm-remote-monitor,acanderson10/cgm-remote-monitor,dchesher/cgm-remote-monitor,leonimo2/cgm-remote-monitor,caoimhecgmitc/cgm-remote-monitor,chriscin/cgm-remote-monitor,sbolshakov/cgm-remote-monitor,dylanbdawe/cgm-remote-monitor,bscutero/cgm-remote-monitor,rdobb/cgm-remote-monitor,Ayaz2014/cgm-remote-monitor-1,elodaille01/cgm-remote-monitor,Maddie1222/cgm-remote-monitor,EllieGitHub/cgm-remote-monitor,galiapolia/cgm-remote-monitor,rubinstein/cgm-remote-monitor,SidneyH128/cgm-remote-monitor,MackenzieT1D/cgm-remote-monitor,brocm/cgm-remote-monitor,jleodaniel/cgm-remote-monitor,yleniadm/cgm-remote-monitor,fichtenweg/cgm-remote-monitor,cdmccook/cgm-remote-monitor,AbbysArmy/cgm-remote-monitor,Katerina01/cgm-remote-monitor,robertanye/cgm-remote-monitor,lennydog/cgm-remote-monitor,delaney726/cgm-remote-monitor,bjack17/cgm-remote-monitor,crossfamily888/cgm-remote-monitor,tjkns/cgm-remote-monitor,ccmorris1/cgm-remote-monitor,LiamCGM/cgm-remote-monitor,substars/cgm-remote-monitor,Layni/cgm-remote-monitor,audiefile/cgm-remote-monitor,mbmcquil/cgm-remote-monitor,alive5050/cgm-remote-monitor,shenkel74/cgm-remote-monitor,ktomy/cgm-remote-monitor,demonicpagan/cgm-remote-monitor,AJStinson/cgm-remote-monitor,welshgirl/cgm-remote-monitor,nsmom/cgm-remote-monitor,perkins19/cgm-remote-monitor,vnaslund/cgm-remote-monitor,asidorovich/cgm-remote-monitor-liliya,katiestone808/cgm-remote-monitor,slburnett/cgm-remote-monitor,siegel1230/cgm-remote-monitor,editdata14/cgm-remote-monitor,aujerome/cgm-remote-monitor,t1crazy/cgm-remote-monitor,Audrawebb/cgm-remote-monitor,taltsu/cgm-remote-monitor,AdrianLxM/cgm-remote-monitor,NatBrUser/cgm-remote-monitor,ToineT1/cgm-remote-monitor,rosengrenswe/cgm-remote-monitor,crystalc72/cgm-remote-monitor,ThomasEmge/cgm-remote-monitor,denvergail/cgm-remote-monitor,tchancey/cgm-remote-monitor,diasigvard/cgm-remote-monitor,JBBerglund/cgm-remote-monitor,LilyAD/cgm-remote-monitor,gleski/cgm-remote-monitor,davinche07/cgm-remote-monitor,EdenSophie/cgm-remote-monitor,maddiemom/cgm-remote-monitor,czcottage/cgm-remote-monitor,valphilmus/cgm-remote-monitor,tynbendad/cgm-remote-monitor,rmiclescu/cgm-remote-monitor,rnewby/cgm-remote-monitor,abdulhadicgm/cgm-remote-monitor,46egemert/cgm-remote-monitor,Jacque471/cgm-remote-monitor,olivercgm/cgm-remote-monitor,malloryns/cgm-remote-monitor,mazzekp/cgm-remote-monitor,Jimwedel/cgm-remote-monitor,mommyandloganarecrazy/cgm-remote-monitor,Viktoriartem/cgm-remote-monitor,isabell12/cgm-remote-monitor,jjkrebs/cgm-remote-monitor,star37NS/cgm-remote-monitor,NoahT72/cgm-remote-monitor,timomer/cgm-remote-monitor,lotharmartinez/cgm-remote-monitor,pepecb/cgm-remote-monitor,VivianKnueppel/cgm-remote-monitor,skrislov/cgm-remote-monitor,lukedolezal/cgm-remote-monitor,BrentNS/cgm-remote-monitor,PODVESNAV/cgm-remote-monitor,t1dcheyanne/cgm-remote-monitor,babyannascgm/cgm-remote-monitor,rhianna10/cgm-remote-monitor,stellagw10/cgm-remote-monitor,gleski/cgm-remote-monitor,ashbyakgm/cgm-remote-monitor,dwestall63/cgm-remote-monitor,jojoyue200/cgm-remote-monitor,steve6158/cgm-remote-monitor,mde1300/cgm-remote-monitor,swissalpine/cgm-remote-monitor,Aes02/cgm-remote-monitor,tomstclair/cgm-remote-monitor,oliver2011/cgm-remote-monitor,destea1/cgm-remote-monitor,plfcgm/cgm-remote-monitor,star37NS/cgm-remote-monitor,northanger/cgm-remote-monitor,williamwimberly/cgm-remote-monitor,LiamMagnus/cgm-remote-monitor,faromatilde/cgm-remote-monitor,westoncgm/cgm-remote-monitor,sugabetic/cgm-remote-monitor,daffodilfriend/cgm-remote-monitor,galiapolia/cgm-remote-monitor,jessdex2/cgm-remote-monitor,bettecgm/cgm-remote-monitor-1,cjo20/cgm-remote-monitor,julieraines/cgm-remote-monitor,TylerMathews/cgm-remote-monitor,taltsu/cgm-remote-monitor,Della330/cgm-remote-monitor,meandahlia/cgm-remote-monitor,nsmom/cgm-remote-monitor,gitnea/cgm-remote-monitor,JacknSundrop/cgm-remote-monitor,dswagg13/cgm-remote-monitor,siegel1230/cgm-remote-monitor,Max3ntius/cgm-remote-monitor,rpeanut77/cgm-remote-monitor,nseto475ghun/cgm-remote-monitor,humphrey4526/cgm-remote-monitor,seelynat/cgm-remote-monitor,drummer35/cgm-remote-monitor,ajwyckoff/cgm-remote-monitor,bldalbey/cgm-remote-monitor,JBBerglund/cgm-remote-monitor,pablomariocgm/cgm-remote-monitor,gavmoir/cgm-remote-monitor,rsuvalle/cgm-remote-monitor,audiefile/cgm-remote-monitor,dswagg13/cgm-remote-monitor,Silvia1972/cgm-remote-monitor,jgobat/cgm-remote-monitor,melsmith/cgm-remote-monitor,rubinstein/cgm-remote-monitor,caydongood/cgm-remote-monitor,iorghi/cgm-remote-monitor,ccspiess/cgm-remote-monitor,nsmariette/cgm-remote-monitor,AllyCat09/cgm-remote-monitor,riverjones2007/cgm-remote-monitor,samihusseingit/cgm-remote-monitor,jwedding/cgm-remote-monitor,capitanpato/cgm-remote-monitor,lilagw/cgm-remote-monitor,juliatakeuti/cgm-remote-monitor,HoskinsNSGithub2179/cgm-remote-monitor,kylecloud/cgm-remote-monitor,HidroRaul/cgm-remote-monitor,asidorovich/cgm-remote-monitor-liliya,aabramowicz/cgm-remote-monitor,lincolnprice/cgm-remote-monitor,vanderjagt/cgm-remote-monitor,kgilles2000/cgm-remote-monitor,mdbottego74/cgm-remote-monitor,rosengrenswe/cgm-remote-monitor,pedrojparedes/cgm-remote-monitor,mkruiswyk/cgm-remote-monitor,scotown/cgm-remote-monitor,iorghi/cgm-remote-monitor,williamwimberly/cgm-remote-monitor,IsaacBGallaher/cgm-remote-monitor,skubesch/cgm-remote-monitor,joshcorwin/cgm-remote-monitor,cowboylogic13/cgm-remote-monitor,brownkkeb/cgm-remote-monitor,dseekert/cgm-remote-monitor,liamthomascgm/cgm-remote-monitor,sugars208/cgm-remote-monitor,ldkbyj/cgm-remote-monitor,GHaynesww/cgm-remote-monitor,beavisandgirl/cgm-remote-monitor,efrewin/cgm-remote-monitor,baembel08/cgm-remote-monitor,Silvermynt82/cgm-remote-monitor-v,Elysespump/cgm-remote-monitor,dotbreadcrumb/cgm-remote-monitor,oskaricciu/cgm-remote-monitor,rebecacirre/cgm-remote-monitor,Ashcgm/cgm-remote-monitor,dexcom/cgm-remote-monitor,kritterfoster86/cgm-remote-monitor,hansonfamilyfive/cgm-remote-monitor,samihusseingit/cgm-remote-monitor,jpbecker/cgm-remote-monitor,Emmikos/cgm-remote-monitor,NSDreamsicle/cgm-remote-monitor,NSGabi/cgm-remote-monitor,blessedwhitney/cgm-remote-monitor,jwedding/cgm-remote-monitor,PODVESNAV/cgm-remote-monitor,dexinfo/cgm-remote-monitor,Trees2001/cgm-remote-monitor,gavmoir/cgm-remote-monitor,willpower04/cgm-remote-monitor,hedgens/cgm-remote-monitor,djmacias2/cgm-remote-monitor,clchrisman/cgm-remote-monitor,beckerfamily/cgm-remote-monitor,MartinDexcom/cgm-remote-monitor,jpbecker/cgm-remote-monitor,HugoKollegger/cgm-remote-monitor,Tsokonut/cgm-remote-monitor,PrincessHaley/cgm-remote-monitor,logichammer/cgm-remote-monitor,LTatu/cgm-remote-monitor,NightscoutSasha/cgm-remote-monitor,skubesch/cgm-remote-monitor,namme59/cgm-remote-monitor,karlork/cgm-remote-monitor,kakoni/cgm-remote-monitor,Mihaeladex/cgm-remote-monitor,ariellecgm/cgm-remote-monitor,mvetter/cgm-remote-monitor,gleipert/cgm-remote-monitor,dbogardaustin/cgm-remote-monitor,hedgens/cgm-remote-monitor,Landbchecker/cgm-remote-monitor,zoeystoes/cgm-remote-monitor,JDBM1/cgm-remote-monitor,marcips/cgm-remote-monitor,moodiendb/cgm-remote-monitor,Jake1114/cgm-remote-monitor,rajatgupta431/cgm-remote-monitor,garath77/cgm-remote-monitor,grhulz/cgm-remote-monitor,lincolnprice/cgm-remote-monitor,kdaNOTdka/cgm-remote-monitor,vittetoe/cgm-remote-monitor,LucaGerrard/cgm-remote-monitor,CeciliaAlicia/cgm-remote-monitor,gavmoir/cgm-remote-monitor,olivercgm/cgm-remote-monitor,SveaW/cgm-remote-monitor,HugoKollegger/cgm-remote-monitor,rebeccaorto/cgm-remote-monitor,Trivera04/cgm-remote-monitor,clchrisman/cgm-remote-monitor,mushetal/cgm-remote-monitor,MartinDexcom/cgm-remote-monitor,melsmith/cgm-remote-monitor,destea1/cgm-remote-monitor,NightScoutErin/cgm-remote-monitor,julieraines/cgm-remote-monitor,leyton2ns/cgm-remote-monitor,feraridurango/cgm-remote-monitor,giorgiagentile/cgm-remote-monitor,willsimpson1997/cgm-remote-monitor,briant1d/cgm-remote-monitor,substars/cgm-remote-monitor,vanderjagt/cgm-remote-monitor,willpower04/cgm-remote-monitor,spencerto/cgm-remote-monitor,ashlynnsorenson/cgm-remote-monitor,komby/cgm-remote-monitor,lionheartman/cgm-remote-monitor,gitanO0/cgm-remote-monitor,OpossumGit/cgm-remote-monitor,liamthomascgm/cgm-remote-monitor,drcameron/cgm-remote-monitor,grantinthecloud/cgm-remote-monitor,jojoyue200/cgm-remote-monitor,ThesSpawn826/cgm-remote-monitor,lbscoutgh/cgm-remote-monitor,dchesher/cgm-remote-monitor,lovezg/cgm-remote-monitor,dexies14/cgm-remote-monitor,szpaku80/cgm-remote-monitor,CharlieBowyer/cgm-remote-monitor,oliver2011/cgm-remote-monitor,Supersawyer/cgm-remote-monitor,SveaW/cgm-remote-monitor,jonhunterbui/cgm-remote-monitor,Layni/cgm-remote-monitor,nomareel/cgm-remote-monitor,Grinchmob/cgm-remote-monitor,twinmomdb/cgm-remote-monitor,grantinthecloud/cgm-remote-monitor,rebeccaorto/cgm-remote-monitor,jessdex2/cgm-remote-monitor,jweismann/cgm-remote-monitor,EdenSophie/cgm-remote-monitor,beckerfamily2/cgm-remote-monitor,viljanightscout/cgm-remote-monitor,stjack1/cgm-remote-monitor,ferasnf/cgm-remote-monitor,Grinchmob/cgm-remote-monitor,jadendexcom/cgm-remote-monitor,sherri29/cgm-remote-monitor,sarahgit/cgm-remote-monitor,AlexanderP01/cgm-remote-monitor,nletrheim/cgm-remote-monitor,dawnmifsud/cgm-remote-monitor,tomas69/cgm-remote-monitor,novagannas/cgm-remote-monitor,ToineT1/cgm-remote-monitor,dbogardaustin/cgm-remote-monitor,divishinating/cgm-remote-monitor,jleodaniel/cgm-remote-monitor,thomcost/cgm-remote-monitor,nightscout/cgm-remote-monitor,ktomy/cgm-remote-monitor,shannonhaywood/cgm-remote-monitor,robynec75/cgm-remote-monitor,MosiGitHub/cgm-remote-monitor,alapiscd/cgm-remote-monitor,Kajr/cgm-remote-monitor,plfcgm/cgm-remote-monitor,PrincessHaley/cgm-remote-monitor,dbeasy/cgm-remote-monitor,LivyLoo/cgm-remote-monitor,M-Reinhardt/cgm-remote-monitor,mdbottego74/cgm-remote-monitor,GatorcubNS/cgm-remote-monitor,ccm779799/cgm-remote-monitor,tzweti/cgm-remote-monitor,madisonmen123/cgm-remote-monitor,lilislifesavers/cgm-remote-monitor,isaaccgm/cgm-remote-monitor,DunePlodder/cgm-remote-monitor,mbmcquil/cgm-remote-monitor,swainoe/cgm-remote-monitor,MidgeysMom/cgm-remote-monitor,bricgm/cgm-remote-monitor,nikealli25/cgm-remote-monitor,MitchDex/cgm-remote-monitor,fgentzel/cgm-remote-monitor,EmilyCGM/cgm-remote-monitor,marincgm/cgm-remote-monitor,gth001/cgm-remote-monitor,jpirronecgm/cgm-remote-monitor,larazucchiatti2011/cgm-remote-monitor,MosiGitHub/cgm-remote-monitor,spencerto/cgm-remote-monitor,fiberfan/cgm-remote-monitor,czcottage/cgm-remote-monitor,Yassen2008/cgm-remote-monitor,divishinating/cgm-remote-monitor,msharpy/cgm-remote-monitor,lukedfeus/cgm-remote-monitor,ToineT1/cgm-remote-monitor,mel2095/cgm-remote-monitor,albertotrg/cgm-remote-monitor,oskaricciu/cgm-remote-monitor,DylansCGM/cgm-remote-monitor,jen92225/cgm-remote-monitor,Wolfenberger/cgm-remote-monitor,Brennon11/cgm-remote-monitor,antalois/cgm-remote-monitor,imnanjl/cgm-remote-monitor,johansvdb/cgm-remote-monitor,larazeren/cgm-remote-monitor,grenntreeateam/cgm-remote-monitor,fgentzel/cgm-remote-monitor,denvergail/cgm-remote-monitor,britishguy4/cgm-remote-monitor,claytonfrost/cgm-remote-monitor,JenSteier/cgm-remote-monitor,jcurlander/cgm-remote-monitor,kakoni/cgm-remote-monitor,SophiaPed/cgm-remote-monitor,sinweb/cgm-remote-monitor,Cuiyujun/cgm-remote-monitor,ldkbyj/cgm-remote-monitor,GrechCGM4/cgm-remote-monitor,nsmatt/cgm-remote-monitor,mikestebbins/cgm-remote-monitor,goldendel/cgm-remote-monitor,pugarts/cgm-remote-monitor,paleoCoder/cgm-remote-monitor,alive5050/cgm-remote-monitor,grevsjonightscout/cgm-remote-monitor,czahner/cgm-remote-monitor,dwestall63/cgm-remote-monitor,WholeEnchilada/cgm-remote-monitor,pepecb/cgm-remote-monitor,riverjones2007/cgm-remote-monitor,paleoCoder/cgm-remote-monitor,merrickdaigneault/cgm-remote-monitor,LivyLoo/cgm-remote-monitor,Tsokonut/cgm-remote-monitor,abdulhadicgm/cgm-remote-monitor,ferasnf/cgm-remote-monitor,tchancey/cgm-remote-monitor,jaylagorio/cgm-remote-monitor,Jake1114/cgm-remote-monitor,Teodorwallberg/cgm-remote-monitor,blakeflu/cgm-remote-monitor,fuddster/cgm-remote-monitor,yoda226/cgm-remote-monitor,Alyssalinmartinez/cgm-remote-monitor,snicastro/cgm-remote-monitor,LisaHerrera/cgm-remote-monitor,mkruiswyk/cgm-remote-monitor,bobocmtj14/cgm-remote-monitor,nsmatt/cgm-remote-monitor,blessedwhitney/cgm-remote-monitor,dadadmin/cgm-remote-monitor,djmacias2/cgm-remote-monitor,lilyraine/cgm-remote-monitor,johnmales/cgm-remote-monitor,martinrq/cgm-remote-monitor,avielf/cgm-remote-monitor,Rmaw02/cgm-remote-monitor,rebecacirre/cgm-remote-monitor,chris4295/cgm-remote-monitor,Bellagh1/cgm-remote-monitor,Ashcgm/cgm-remote-monitor,Karahbevin/cgm-remote-monitor,jweismann/cgm-remote-monitor,Rjm907NSdb/cgm-remote-monitor,RebekahLindsay/cgm-remote-monitor,Wolfenberger/cgm-remote-monitor,Nadinekj/cgm-remote-monitor,lazzeb/cgm-remote-monitor,shaunaT/cgm-remote-monitor,patric82/cgm-remote-monitor,GarthDB/cgm-remote-monitor,albertodalcero/cgm-remote-monitor,ellabellakaramella/cgm-remote-monitor,simigit/cgm-remote-monitor,riverjones2007/cgm-remote-monitor,ns-nathan/cgm-remote-monitor,ellinorlian/cgm-remote-monitor,tomstclair/cgm-remote-monitor,tanja3981/cgm-remote-monitor,LiamMagnus/cgm-remote-monitor,juliehageman/cgm-remote-monitor,crystalc72/cgm-remote-monitor,asidorovich/cgm-remote-monitor,stampertk/cgm-remote-monitor,ccm779799/cgm-remote-monitor,emilybsessions/cgm-remote-monitor,sherri29/cgm-remote-monitor,xdripab/cgm-remote-monitor,maesey/cgm-remote-monitor,KatyTanet/cgm-remote-monitor,laurenvan7/cgm-remote-monitor,renoca/cgm-remote-monitor,AshleyZeigler/cgm-remote-monitor,AlexDesjardins/cgm-remote-monitor,bettecgm/cgm-remote-monitor-1,bdr1177/cgm-remote-monitor,ancameron/cgm-remote-monitor,bradleybear/cgm-remote-monitor,Silvermynt82/cgm-remote-monitor-v,juliatakeuti/cgm-remote-monitor,mvetter/cgm-remote-monitor,michellels/cgm-remote-monitor,Larsjon/cgm-remote-monitor,HidroRaul/cgm-remote-monitor,jrmorrison/cgm-remote-monitor,bromaco/cgm-remote-monitor,rjayork/cgm-remote-monitor,Kaydence/cgm-remote-monitor,demonicpagan/cgm-remote-monitor,tycho40/cgm-remote-monitor,EmilyCGM/cgm-remote-monitor,martinrq/cgm-remote-monitor,BRADENBENJAMIN/cgm-remote-monitor,Sammydickenson/cgm-remote-monitor,lilyraine/cgm-remote-monitor,MartinDexcom/cgm-remote-monitor,GrechCGM4/cgm-remote-monitor,titusfaber/cgm-remote-monitor,inform880/cgm-remote-monitor,AddisonMKNS/cgm-remote-monitor,amlynek/cgm-remote-monitor,racechick3/cgm-remote-monitor,averydex/cgm-remote-monitor,vnaslund/cgm-remote-monitor,lexa140978/cgm-remote-monitor,nightscout963/cgm-remote-monitor,Kraey/cgm-remote-monitor,grhulz/cgm-remote-monitor,michealjj/cgm-remote-monitor,DebbieMM/cgm-remote-monitor,hansonfamilyfive/cgm-remote-monitor,aidandevine/cgm-remote-monitor,shanusmagnus/cgm-remote-monitor,hyeokseo/cgm-remote-monitor,scottswitz/cgm-remote-monitor,peanut1/cgm-remote-monitor,rosengrenswe/cgm-remote-monitor,dayiiijh/cgm-remote-monitor,ryandexcom/cgm-remote-monitor,lucyrm/cgm-remote-monitor,czahner/cgm-remote-monitor,Kajr/cgm-remote-monitor,foxlazza/cgm-remote-monitor,tylaamy/cgm-remote-monitor,Fokko/cgm-remote-monitor,MidgeysMom/cgm-remote-monitor,IzzysNightscout/cgm-remote-monitor,andyhandy/cgm-remote-monitor,skythegreat/cgm-remote-monitor,dramageek/cgm-remote-monitor,rcacho/cgm-remote-monitor,LucaGerrard/cgm-remote-monitor,wagnerpe/cgm-remote-monitor,ryder08/cgm-remote-monitor,WholeEnchilada/cgm-remote-monitor,Aes02/cgm-remote-monitor,Katieh227/cgm-remote-monitor,pablomariocgm/cgm-remote-monitor,bhcamp/cgm-remote-monitor,DunePlodder/cgm-remote-monitor,chriscin/cgm-remote-monitor,johnmales/cgm-remote-monitor,mddub/cgm-remote-monitor,efrewin/cgm-remote-monitor,albertodalcero/cgm-remote-monitor,skjelland/cgm-remote-monitor,JacknSundrop/cgm-remote-monitor,scottleibrand/cgm-remote-monitor,elodaille01/cgm-remote-monitor,dexterbooty/cgm-remote-monitor,DunePlodder/cgm-remote-monitor,nuriavegal/cgm-remote-monitor,dex4jake/cgm-remote-monitor,solemia/cgm-remote-monitor,Ayaz2014/cgm-remote-monitor-1,sbessolina81/cgm-remote-monitor,Gallooggi/cgm-remote-monitor,marco-seb/cgm-remote-monitor,capitanpato/cgm-remote-monitor,mjyrala/cgm-remote-monitor,manaolana/cgm-remote-monitor,chris4295/cgm-remote-monitor,aaroecker/cgm-remote-monitor,thedob/cgm-remote-monitor,cblove73/cgm-remote-monitor,LivyLoo/cgm-remote-monitor,amlynek/cgm-remote-monitor,samsamscgm/cgm-remote-monitor,mshafa/cgm-remote-monitor,gleski/cgm-remote-monitor,abcschooldr/cgm-remote-monitor,komby/cgm-remote-monitor,thaahtel/cgm-remote-monitor,caoimhecgmitc/cgm-remote-monitor,rene4547/cgm-remote-monitor,donnamichelle/cgm-remote-monitor,thaahtel/cgm-remote-monitor,bagleytorri/cgm-remote-monitor-1,giorgiagentile/cgm-remote-monitor,ProjectSafety/cgm-remote-monitor,lukedolezal/cgm-remote-monitor,rcacho/cgm-remote-monitor,rreed454/cgm-remote-monitor,ldknoch/cgm-remote-monitor,hedgens/cgm-remote-monitor,codakean/cgm-remote-monitor,GmanType1/cgm-remote-monitor,harryrowe2010/cgm-remote-monitor,ajbrugnano/cgm-remote-monitor,FraserRoethel/cgm-remote-monitor,tornado14/cgm-remote-monitor,hurtman/cgm-remote-monitor,pilonicamilla/cgm-remote-monitor,sinweb/cgm-remote-monitor,cooperlushell/cgm-remote-monitor,libby4label/cgm-remote-monitor,jasoncalabrese/cgm-remote-monitor,cclcgm/cgm-remote-monitor,Bellagh1/cgm-remote-monitor,adrianmoli/cgm-remote-monitor,jordan-berger/cgm-remote-monitor,DavMedek/cgm-remote-monitor,Teodorwallberg/cgm-remote-monitor,sethkennedy01/cgm-remote-monitor,rcacho/cgm-remote-monitor,JeffJinSD/cgm-remote-monitor,ashlynnsorenson/cgm-remote-monitor,sbessolina81/cgm-remote-monitor,GHaynesww/cgm-remote-monitor,IsaacEastridge/cgm-remote-monitor,BRADENBENJAMIN/cgm-remote-monitor,bw396704/cgm-remote-monitor,chelesawilds/cgm-remote-monitor,FirdausJones/cgm-remote-monitor,SophiaPed/cgm-remote-monitor,DrSeattle/cgm-remote-monitor,VivianKnueppel/cgm-remote-monitor,mimes/cgm-remote-monitor,martinek10/cgm-remote-monitor,annbennett/cgm-remote-monitor,nightscout/cgm-remote-monitor,daffodilfriend/cgm-remote-monitor,nippe71/cgm-remote-monitor,tycho40/cgm-remote-monitor,live4sw/cgm-remote-monitor,NightDrip/cgm-remote-monitor,tylaamy/cgm-remote-monitor,ashleyabilamartin/cgm-remote-monitor,porkupan/cgm-remote-monitor,briant1d/cgm-remote-monitor,bldalbey/cgm-remote-monitor,mjsell/cgm-remote-monitor,jackwain/cgm-remote-monitor,mandy6770/cgm-remote-monitor,marcon2000/cgm-remote-monitor,live4sw/cgm-remote-monitor,srimes/cgm-remote-monitor,dexies14/cgm-remote-monitor,Choens/cgm-remote-monitor,JenSteier/cgm-remote-monitor,DylansCGM/cgm-remote-monitor,bianca2015/cgm-remote-monitor,T1Dcooper/cgm-remote-monitor,Martata83/cgm-remote-monitor,courtray712/cgm-remote-monitor,welshgirl/cgm-remote-monitor,bobocmtj14/cgm-remote-monitor,jjkrebs/cgm-remote-monitor,robynec75/cgm-remote-monitor,Eastondex/cgm-remote-monitor,jrogers2199/cgm-remote-monitor,marco-seb/cgm-remote-monitor,EdenSophie/cgm-remote-monitor,Shoug/cgm-remote-monitor,olivia08/cgm-remote-monitor,DrSeattle/cgm-remote-monitor,mde1300/cgm-remote-monitor,szpaku80/cgm-remote-monitor,larazucchiatti2011/cgm-remote-monitor,adriwelborn/cgm-remote-monitor,gempickfordwaugh/cgm-remote-monitor,pilonicamilla/cgm-remote-monitor,marcips/cgm-remote-monitor,lilagw/cgm-remote-monitor,dinner1985/cgm-remote-monitor,mushetal/cgm-remote-monitor,alexcgm/cgm-remote-monitor,someoneAnyone/cgm-remote-monitor,pavel1981/cgm-remote-monitor,Slawek1981/cgm-remote-monitor,racechick3/cgm-remote-monitor,Jimwedel/cgm-remote-monitor,malloryns/cgm-remote-monitor,Candyhearts/cgm-remote-monitor,Bonnar/cgm-remote-monitor,oskaricciu/cgm-remote-monitor,PrincessHaley/cgm-remote-monitor,northanger/cgm-remote-monitor,pjweiss/cgm-remote-monitor,chiaramorris/cgm-remote-monitor,lennydog/cgm-remote-monitor,abdulhadicgm/cgm-remote-monitor,sawiris/cgm-remote-monitor,ccmorris1/cgm-remote-monitor,jaysheree/cgm-remote-monitor,Treshots/cgm-remote-monitor,scottmark/cgm-remote-monitor,Slawek1981/cgm-remote-monitor,masonsbattle/cgm-remote-monitor,dchesher/cgm-remote-monitor,tylee2009/cgm-remote-monitor,RebekahLindsay/cgm-remote-monitor,someoneAnyone/cgm-remote-monitor,msharpy/cgm-remote-monitor,edencgm/cgm-remote-monitor,crystalc72/cgm-remote-monitor,llehtio/cgm-remote-monitor,briant1d/cgm-remote-monitor,Hamby1214/cgm-remote-monitor,Shoug/cgm-remote-monitor,elodaille01/cgm-remote-monitor,babyannascgm/cgm-remote-monitor,rdobb/cgm-remote-monitor,aujerome/cgm-remote-monitor,slipgate/cgm-remote-monitor,ldpcloud/cgm-remote-monitor,E2013/cgm-remote-monitor,ashbyakgm/cgm-remote-monitor,Jimwedel/cgm-remote-monitor,Silvia1972/cgm-remote-monitor,Treshots/cgm-remote-monitor,raresdexcom/cgm-remote-monitor,ruiannie/cgm-remote-monitor,JGiacalone/cgm-remote-monitor,Cuiyujun/cgm-remote-monitor,kritterfoster86/cgm-remote-monitor,t1dcheyanne/cgm-remote-monitor,bw396704/cgm-remote-monitor,bianca2015/cgm-remote-monitor,aujerome/cgm-remote-monitor,twinmomdb/cgm-remote-monitor,scotown/cgm-remote-monitor,williamwimberly/cgm-remote-monitor,ryanfire12/cgm-remote-monitor,efrewin/cgm-remote-monitor,dupoyetb/cgm-remote-monitor,ellinorlian/cgm-remote-monitor,destea1/cgm-remote-monitor,wondermom/cgm-remote-monitor,dwestall63/cgm-remote-monitor,editdata7/cgm-remote-monitor,ccspiess/cgm-remote-monitor,samsamscgm/cgm-remote-monitor,IzzysNightscout/cgm-remote-monitor,46egemert/cgm-remote-monitor,imnanjl/cgm-remote-monitor,AliMiller/cgm-remote-monitor,jaghitop/cgm-remote-monitor,momof10/cgm-remote-monitor,CassidyAccount/cgm-remote-monitor,MasonT1/cgm-remote-monitor,dexterbooty/cgm-remote-monitor,jeaninemt2003/cgm-remote-monitor,rpeanut77/cgm-remote-monitor,gws1/cgm-remote-monitor,andyhandy/cgm-remote-monitor,iris4acure/cgm-remote-monitor,Diabetiger/cgm-remote-monitor,ramstrand/cgm-remote-monitor,jtchambe/cgm-remote-monitor,renoca/cgm-remote-monitor,AidanHamlin/cgm-remote-monitor,rjayork/cgm-remote-monitor,Shane33/cgm-remote-monitor,cclcgm/cgm-remote-monitor,shenkel74/cgm-remote-monitor,edencgm/cgm-remote-monitor,leonimo/cgm-remote-monitor,vandyjt/cgm-remote-monitor,madisonmen123/cgm-remote-monitor,AJS2008/cgm-remote-monitor,sbolshakov/cgm-remote-monitor,dia1234/cgm-remote-monitor,TerriV/cgm-remote-monitor,mwmoore12/cgm-remote-monitor,bradleybear/cgm-remote-monitor,noelle1211/cgm-remote-monitor,jaidenlee/cgm-remote-monitor,lionheartman/cgm-remote-monitor,Tribunesix/cgm-remote-monitor,MasonT1/cgm-remote-monitor,thomcost/cgm-remote-monitor,d-liza/cgm-remote-monitor,NSGabi/cgm-remote-monitor,geoff004/cgm-remote-monitor,loriwells8/cgm-remote-monitor,SophiaPed/cgm-remote-monitor,lexiergeson/cgm-remote-monitor,jennymattyste83/cgm-remote-monitor,willsimpson1997/cgm-remote-monitor,larazeren/cgm-remote-monitor,swainoe/cgm-remote-monitor,valphilmus/cgm-remote-monitor,lgmsmith/cgm-remote-monitor,butterfly6890/cgm-remote-monitor,sawiris/cgm-remote-monitor,hurtman/cgm-remote-monitor,moodiendb/cgm-remote-monitor,ps2/cgm-remote-monitor,CharlieBowyer/cgm-remote-monitor,tynbendad/cgm-remote-monitor,Tribunesix/cgm-remote-monitor,DiggerboyDylan/cgm-remote-monitor,jackwain/cgm-remote-monitor,skubigolf/cgm-remote-monitor,AlexanderP01/cgm-remote-monitor,cindythornburgh/cgm-remote-monitor,lexa140978/cgm-remote-monitor,asha0613/cgm-remote-monitor,grevsjonightscout/cgm-remote-monitor,lilislifesavers/cgm-remote-monitor,BRADENBENJAMIN/cgm-remote-monitor,Yassen2008/cgm-remote-monitor,stefanakerblom/cgm-remote-monitor,michealjj/cgm-remote-monitor,ellinorlian/cgm-remote-monitor,moodiendb/cgm-remote-monitor,gth001/cgm-remote-monitor,leyton2ns/cgm-remote-monitor,cgmmiles/cgm-remote-monitor,gitnea/cgm-remote-monitor,daffodilfriend/cgm-remote-monitor,nomareel/cgm-remote-monitor,momof10/cgm-remote-monitor,Lexieloula/cgm-remote-monitor,kdauenbaugh/cgm-remote-monitor,PODVESNAV/cgm-remote-monitor,TristaS/cgm-remote-monitor,llehtio/cgm-remote-monitor,andrewbs/cgm-remote-monitor,JDBM1/cgm-remote-monitor,jennifercnightscout/cgm-remote-monitor,yeahbaby/cgm-remote-monitor,juliehageman/cgm-remote-monitor,natsera/cgm-remote-monitor,javierdexcom/cgm-remote-monitor,Nadinekj/cgm-remote-monitor,maesey/cgm-remote-monitor,Lexieloula/cgm-remote-monitor,Kajr/cgm-remote-monitor,crobinuk/cgm-remote-monitor,Smith78/cgm-remote-monitor,zkjohnson/cgm-remote-monitor,mjsell/cgm-remote-monitor,LiamCGM/cgm-remote-monitor,yleniadm/cgm-remote-monitor,IsaacEastridge/cgm-remote-monitor,FraserRoethel/cgm-remote-monitor,ericmetzlerns/cgm-remote-monitor,Kraey/cgm-remote-monitor,nuriavegal/cgm-remote-monitor,mahlon15/cgm-remote-monitor,laurenvan7/cgm-remote-monitor,EllieGitHub/cgm-remote-monitor,PoludaMargo/cgm-remote-monitor,jcurlander/cgm-remote-monitor,someoneAnyone/cgm-remote-monitor,simigit/cgm-remote-monitor,vanderjagt/cgm-remote-monitor,rmiclescu/cgm-remote-monitor,michellels/cgm-remote-monitor,t1crazy/cgm-remote-monitor,bkdollar/cgm-remote-monitor,iris4acure/cgm-remote-monitor,superbravemillsy/cgm-remote-monitor,grossga/cgm-remote-monitor,sethkennedy01/cgm-remote-monitor,howxdrip/cgm-remote-monitor,JamesCaw/cgm-remote-monitor,bklinker/cgm-remote-monitor,dylanalba/cgm-remote-monitor,Cuiyujun/cgm-remote-monitor,gleipert/cgm-remote-monitor,alex2007/cgm-remote-monitor,avielf/cgm-remote-monitor,pauljlucas/cgm-remote-monitor,samson2011/cgm-remote-monitor,NoahT72/cgm-remote-monitor,eszcloud/cgm-remote-monitor,Shoug/cgm-remote-monitor,horoshulin/cgm-remote-monitor,ethanscout/cgm-remote-monitor,crobinuk/cgm-remote-monitor,Viktoriartem/cgm-remote-monitor,bscutero/cgm-remote-monitor,skubesch/Nightscout-V8,brendanroche/cgm-remote-monitor,caydongood/cgm-remote-monitor,bogdangorescu/cgm-remote-monitor,PieterGit/cgm-remote-monitor,courtray712/cgm-remote-monitor,Nadinekj/cgm-remote-monitor,jfinlay2/cgm-remote-monitor,skirby99/cgm-remote-monitor,stellagw10/cgm-remote-monitor,yeahbaby/cgm-remote-monitor,dshier/cgm-remote-monitor,nightscout752/cgm-remote-monitor,wondermom/cgm-remote-monitor,drex304/cgm-remote-monitor,AddisonMKNS/cgm-remote-monitor,kdaNOTdka/cgm-remote-monitor,jaidenlee/cgm-remote-monitor,dmanders/cgm-remote-monitor,alapiscd/cgm-remote-monitor,welshgirl/cgm-remote-monitor,lukedolezal/cgm-remote-monitor,playingbball20/cgm-remote-monitor,monkeymankjb/cgm-remote-monitor,tornado14/cgm-remote-monitor,phisparks/cgm-remote-monitor,masonsbattle/cgm-remote-monitor,Marc78400/cgm-remote-monitor,dastanton/cgm-remote-monitor,mshafa/cgm-remote-monitor,Emmikos/cgm-remote-monitor,Jacque471/cgm-remote-monitor,rnewby/cgm-remote-monitor,substars/cgm-remote-monitor,levinightscout/cgm-remote-monitor,pajallen/cgm-remote-monitor,silvalized/cgm-remote-monitor,Katieh227/cgm-remote-monitor,sugars208/cgm-remote-monitor,dastanton/cgm-remote-monitor,miglesia/cgm-remote-monitor,liamthomascgm/cgm-remote-monitor,clchrisman/cgm-remote-monitor,plfcgm/cgm-remote-monitor,cgmmiles/cgm-remote-monitor,stjack1/cgm-remote-monitor,DianeJohnson100/cgm-remote-monitor,SveaW/cgm-remote-monitor,rpeanut77/cgm-remote-monitor,averydex/cgm-remote-monitor,johnmales/cgm-remote-monitor,giorgiagentile/cgm-remote-monitor,Grahnarna/cgm-remote-monitor,skrislov/cgm-remote-monitor,dexcom/cgm-remote-monitor,Mikael600/cgm-remote-monitor,delaney726/cgm-remote-monitor,Makenna2004/cgm-remote-monitor,VSCDR/cgm-remote-monitor,bagleytorri/cgm-remote-monitor-1,siegel1230/cgm-remote-monitor,jenzamom/cgm-remote-monitor,swissalpine/cgm-remote-monitor,dbeasy/cgm-remote-monitor,marcon2000/cgm-remote-monitor,LucaGerrard/cgm-remote-monitor,andrewbs/cgm-remote-monitor,jrmorrison/cgm-remote-monitor,samson2011/cgm-remote-monitor,nikealli25/cgm-remote-monitor,utefan/cgm-remote-monitor,Trees2001/cgm-remote-monitor,DanielFilipov/cgm-remote-monitor-1,emppuli/cgm-remote-monitor,maxsdmom/cgm-remote-monitor,GmanType1/cgm-remote-monitor,iwalktheline86/cgm-remote-monitor,jflores1948/cgm-remote-monitor,ariellecgm/cgm-remote-monitor,shaunaT/cgm-remote-monitor,solemia/cgm-remote-monitor,LisaHerrera/cgm-remote-monitor,UphwbKpqSm47z3qewH9x/cgm-remote-monitor,dinner1985/cgm-remote-monitor,JacknSundrop/cgm-remote-monitor,janetlizconroy/cgm-remote-monitor,bricgm/cgm-remote-monitor,swainoe/cgm-remote-monitor,wondermom/cgm-remote-monitor,AshleyZeigler/cgm-remote-monitor,snolte/cgm-remote-monitor,thedob/cgm-remote-monitor,lgmsmith/cgm-remote-monitor,aidandevine/cgm-remote-monitor,Hamby1214/cgm-remote-monitor,brocm/cgm-remote-monitor,XanderNels/cgm-remote-monitor,manaolana/cgm-remote-monitor,Rjm907NSdb/cgm-remote-monitor,BlackDogsRule/cgm-remote-monitor,LisaHerrera/cgm-remote-monitor,dotbreadcrumb/cgm-remote-monitor,northanger/cgm-remote-monitor,nightscout/cgm-remote-monitor,h20ford/cgm-remote-monitor,h20ford/cgm-remote-monitor,DebbieMM/cgm-remote-monitor,slburnett/cgm-remote-monitor,wagnerpe/cgm-remote-monitor,corrdara/cgm-remote-monitor,jerryfuselier/cgm-remote-monitor,Rjm907NSdb/cgm-remote-monitor,shanselman/cgm-remote-monitor,NoahT72/cgm-remote-monitor,aaroecker/cgm-remote-monitor,grenntreeateam/cgm-remote-monitor,skythegreat/cgm-remote-monitor,claytonfrost/cgm-remote-monitor,hyeokseo/cgm-remote-monitor,Marc78400/cgm-remote-monitor,spamis/cgm-remote-monitor,kirks/cgm-remote-monitor,taltsu/cgm-remote-monitor,jcdrapp/cgm-remote-monitor,connorcgmdata/cgm-remote-monitor,mwillis130/cgm-remote-monitor,ashleyabilamartin/cgm-remote-monitor,mavster/cgm-remote-monitor,masonsbattle/cgm-remote-monitor,AJM1396/cgm-remote-monitor,tjkns/cgm-remote-monitor,ns-nathan/cgm-remote-monitor,ccmorris1/cgm-remote-monitor,betacellblues/cgm-remote-monitor,oamyoamy/cgm-remote-monitor,mddub/cgm-remote-monitor,asidorovich/cgm-remote-monitor-liliya,DiggerboyDylan/cgm-remote-monitor,sarah4hand/cgm-remote-monitor,silvalized/cgm-remote-monitor,metzlernsdb/cgm-remote-monitor,jungsomyeonggithub/cgm-remote-monitor,novagannas/cgm-remote-monitor,JockeOrn/cgm-remote-monitor,perkins19/cgm-remote-monitor,rjayork/cgm-remote-monitor,jaghitop/cgm-remote-monitor,johnkaren4boys/cgm-remote-monitor,dlmgit/cgm-remote-monitor,merrickdaigneault/cgm-remote-monitor,Martata83/cgm-remote-monitor,smcscout/cgm-remote-monitor,rachellynnae/cgm-remote-monitor,dex4jake/cgm-remote-monitor,libby4label/cgm-remote-monitor,rafaelomartin/cgm-remote-monitor,ondrolexa/cgm-remote-monitor,spencerto/cgm-remote-monitor,thomascostello/cgm-remote-monitor,phisparks/cgm-remote-monitor,XanderNels/cgm-remote-monitor,Smith78/cgm-remote-monitor,editdata14/cgm-remote-monitor,PieterGit/cgm-remote-monitor,nvmybug01/cgm-remote-monitor,bagleytorri/cgm-remote-monitor-1,MasonT1/cgm-remote-monitor,lbscoutgh/cgm-remote-monitor,johnkaren4boys/cgm-remote-monitor,AJM1396/cgm-remote-monitor,jordan-berger/cgm-remote-monitor,hurtman/cgm-remote-monitor,ajbrugnano/cgm-remote-monitor,Sammydickenson/cgm-remote-monitor,diegodexcom/cgm-remote-monitor,ilasuper1/cgm-remote-monitor,ethanscout/cgm-remote-monitor,Max3ntius/cgm-remote-monitor,jtchambe/cgm-remote-monitor,sebastianlorant/cgm-remote-monitor,courtray712/cgm-remote-monitor,jiaa6908/cgm-remote-monitor,NatBrUser/cgm-remote-monitor,t1crazy/cgm-remote-monitor,shanselman/cgm-remote-monitor,alexandrutomi/cgm-remote-monitor,Audrawebb/cgm-remote-monitor,Makenna2004/cgm-remote-monitor,playingbball20/cgm-remote-monitor,utefan/cgm-remote-monitor,kkileyhub/cgm-remote-monitor,ferasnf/cgm-remote-monitor,sobrecht/cgm-remote-monitor,jaylagorio/cgm-remote-monitor,tripstoner/cgm-remote-monitor,maddiemom/cgm-remote-monitor,ondrolexa/cgm-remote-monitor,rene4547/cgm-remote-monitor,LTatu/cgm-remote-monitor,adrianmoli/cgm-remote-monitor,Grinchmob/cgm-remote-monitor,iwalktheline86/cgm-remote-monitor,bjack17/cgm-remote-monitor,metzlernsdb/cgm-remote-monitor,dylanbdawe/cgm-remote-monitor,rmcfar09/cgm-remote-monitor,mommyandloganarecrazy/cgm-remote-monitor,sarah4hand/cgm-remote-monitor,HoskinsNSGithub2179/cgm-remote-monitor,M-Reinhardt/cgm-remote-monitor,Natalie12/cgm-remote-monitor,dswagg13/cgm-remote-monitor,PTGScout/cgm-remote-monitor,ejdemers/cgm-remote-monitor,DominikStefan/cgm-remote-monitor,grantinthecloud/cgm-remote-monitor,JGiacalone/cgm-remote-monitor,titusfaber/cgm-remote-monitor,dlmgit/cgm-remote-monitor,ceben80/cgm-remote-monitor,monkeymankjb/cgm-remote-monitor,rhianna10/cgm-remote-monitor,AJM1396/cgm-remote-monitor,nsnwells/cgm-remote-monitor,kylecloud/cgm-remote-monitor,vandyjt/cgm-remote-monitor,aphelps5/cgm-remote-monitor,fredivar1/cgm-remote-monitor,lgmsmith/cgm-remote-monitor,renoca/cgm-remote-monitor,mrfoley/cgm-remote-monitor,oamyoamy/cgm-remote-monitor,mahlon15/cgm-remote-monitor,jgobat/cgm-remote-monitor,IzzysNightscout/cgm-remote-monitor,jennifercnightscout/cgm-remote-monitor,kmasseygh/cgm-remote-monitor-1,ccm779799/cgm-remote-monitor,TristaS/cgm-remote-monitor,TylerCGM/cgm-remote-monitor,jflores1948/cgm-remote-monitor,kaelyncgm/cgm-remote-monitor,larazucchiatti2011/cgm-remote-monitor,olivercgm/cgm-remote-monitor,horoshulin/cgm-remote-monitor,zkjohnson/cgm-remote-monitor,AliMiller/cgm-remote-monitor,ancameron/cgm-remote-monitor,Natalie12/cgm-remote-monitor,caoimhecgmitc/cgm-remote-monitor,GatorcubNS/cgm-remote-monitor,acanderson10/cgm-remote-monitor,smcscout/cgm-remote-monitor,mahlon15/cgm-remote-monitor,harryrowe2010/cgm-remote-monitor,inform880/cgm-remote-monitor,thaahtel/cgm-remote-monitor,jfelkins/cgm-remote-monitor,tomasboudr/cgm-remote-monitor,albertodc/cgm-remote-monitor,hel1fire/cgm-remote-monitor,AnnabelleT1D/cgm-remote-monitor,Katieh227/cgm-remote-monitor,smilloy519/cgm-remote-monitor,joshcorwin/cgm-remote-monitor,isaaccgm/cgm-remote-monitor,beckerfamily/cgm-remote-monitor,Trees2001/cgm-remote-monitor,nuriavegal/cgm-remote-monitor,Max3ntius/cgm-remote-monitor,brbaldwin1970/cgm-remote-monitor,ewanm/cgm-remote-monitor,mvetter/cgm-remote-monitor,oliver2011/cgm-remote-monitor,Kainicus/cgm-remote-monitor,komby/cgm-remote-monitor,E2013/cgm-remote-monitor,dex4jake/cgm-remote-monitor,dinner1985/cgm-remote-monitor,karlork/cgm-remote-monitor,tzweti/cgm-remote-monitor,tyannad/cgm-remote-monitor,Jacque471/cgm-remote-monitor,Gallooggi/cgm-remote-monitor,SidneyH128/cgm-remote-monitor,smcscout/cgm-remote-monitor,superbravemillsy/cgm-remote-monitor,ahalyacarter/cgm-remote-monitor,namme59/cgm-remote-monitor,goranssons/cgm-remote-monitor,mwillis130/cgm-remote-monitor,britishguy4/cgm-remote-monitor,kakoni/cgm-remote-monitor,fboegard/cgm-remote-monitor,IsaacBGallaher/cgm-remote-monitor,lisafolkestad/cgm-remote-monitor,LiamCGM/cgm-remote-monitor,cdmccook/cgm-remote-monitor,kcnygaard/cgm-remote-monitor,maxsdmom/cgm-remote-monitor,tyannad/cgm-remote-monitor,meandahlia/cgm-remote-monitor,asha0613/cgm-remote-monitor,solemia/cgm-remote-monitor,denvergail/cgm-remote-monitor,t1dcheyanne/cgm-remote-monitor,jschoeps/cgm-remote-monitor,mbmcquil/cgm-remote-monitor,k1960/cgm-remote-monitor,alexandrutomi/cgm-remote-monitor,novagannas/cgm-remote-monitor,ewanm/cgm-remote-monitor,vittetoe/cgm-remote-monitor,capitanpato/cgm-remote-monitor,ashleyabilamartin/cgm-remote-monitor,timomer/cgm-remote-monitor,tyrahustedt/cgm-remote-monitor,jpbecker/cgm-remote-monitor,shanusmagnus/cgm-remote-monitor,kcnygaard/cgm-remote-monitor,brookeshelley/cgm-remote-monitor,nletrheim/cgm-remote-monitor,sobrecht/cgm-remote-monitor,marco-seb/cgm-remote-monitor,aaykayg/cgm-remote-monitor,johnkaren4boys/cgm-remote-monitor,nightscout752/cgm-remote-monitor,cdmccook/cgm-remote-monitor,vicmarc/cgm-remote-monitor,chelesawilds/cgm-remote-monitor,tomasboudr/cgm-remote-monitor,TristaS/cgm-remote-monitor,lexiergeson/cgm-remote-monitor,nseto475ghun/cgm-remote-monitor,ejensen719/cgm-remote-monitor,jen92225/cgm-remote-monitor,tyannad/cgm-remote-monitor,nikealli25/cgm-remote-monitor,ProjectSafety/cgm-remote-monitor,HowardLook/cgm-remote-monitor,GmanType1/cgm-remote-monitor,butterfly6890/cgm-remote-monitor,smilloy519/cgm-remote-monitor,alex2007/cgm-remote-monitor,gina1beana/cgm-remote-monitor,AndreaAzzarello/cgm-remote-monitor-1,brbaldwin1970/cgm-remote-monitor,lovezg/cgm-remote-monitor,stevenrgriffin/cgm-remote-monitor,lazzeb/cgm-remote-monitor,grossga/cgm-remote-monitor,dexies14/cgm-remote-monitor,goldendel/cgm-remote-monitor,rafaena/cgm-remote-monitor,scotown/cgm-remote-monitor,beckerfamily2/cgm-remote-monitor,dawnmifsud/cgm-remote-monitor,corrdara/cgm-remote-monitor,humphrey4526/cgm-remote-monitor,tynbendad/cgm-remote-monitor,yoda226/cgm-remote-monitor,pajallen/cgm-remote-monitor,erikafromamerica/cgm-remote-monitor,dupoyetb/cgm-remote-monitor,mazzekp/cgm-remote-monitor,aaykayg/cgm-remote-monitor,mommyandloganarecrazy/cgm-remote-monitor,M-Reinhardt/cgm-remote-monitor,NightscoutSasha/cgm-remote-monitor,dupoyetb/cgm-remote-monitor,k1960/cgm-remote-monitor,ljusername/cgm-remote-monitor,jfelkins/cgm-remote-monitor,jessica7990td/cgm-remote-monitor,antalois/cgm-remote-monitor,Shane33/cgm-remote-monitor,linascout/cgm-remote-monitor,lucikf/cgm-remote-monitor,Thebassefamily/cgm-remote-monitor,skubesch/cgm-remote-monitor,skirby99/cgm-remote-monitor,bdr1177/cgm-remote-monitor,Alyssalinmartinez/cgm-remote-monitor,fboegard/cgm-remote-monitor,samson2011/cgm-remote-monitor,dmanders/cgm-remote-monitor,olivia08/cgm-remote-monitor,kbensing/cgm-remote-monitor,cjo20/cgm-remote-monitor,fredivar1/cgm-remote-monitor,Jemmamc1985/cgm-remote-monitor,spiggelina1/cgm-remote-monitor,moylan/cgm-remote-monitor,dan170278/cgm-remote-monitor,kmasseygh/cgm-remote-monitor-1,divishinating/cgm-remote-monitor,AdrianLxM/cgm-remote-monitor,steve6158/cgm-remote-monitor,dan170278/cgm-remote-monitor,T1Dcooper/cgm-remote-monitor,brendanroche/cgm-remote-monitor,Kainicus/cgm-remote-monitor,mshafa/cgm-remote-monitor,AdrianLxM/cgm-remote-monitor,gws1/cgm-remote-monitor,Silvermynt82/cgm-remote-monitor-v,GHaynesww/cgm-remote-monitor,JGiacalone/cgm-remote-monitor,gitnea/cgm-remote-monitor,rreed454/cgm-remote-monitor,ps2/cgm-remote-monitor,nsmatt/cgm-remote-monitor,mikestebbins/cgm-remote-monitor,JBBerglund/cgm-remote-monitor,CaerwynRoberts/cgm-remote-monitor,JasperCGM/cgm-remote-monitor,DianeJohnson100/cgm-remote-monitor,SidneyH128/cgm-remote-monitor,GatorcubNS/cgm-remote-monitor,perkins19/cgm-remote-monitor,mandy6770/cgm-remote-monitor,eliz4142/cgm-remote-monitor,Wolfenberger/cgm-remote-monitor,kiserman/cgm-remote-monitor,TerriV/cgm-remote-monitor,isabell12/cgm-remote-monitor,stellagw10/cgm-remote-monitor,kbensing/cgm-remote-monitor,shanselman/cgm-remote-monitor,camns/cgm-remote-monitor,dexcom2014/cgm-remote-monitor,NightDrip/cgm-remote-monitor,sugars208/cgm-remote-monitor,asg8146/cgm-remote-monitor,rmcfar09/cgm-remote-monitor,MitchDex/cgm-remote-monitor,alexcgm/cgm-remote-monitor,katiestone808/cgm-remote-monitor,rogerhaugerud/cgm-remote-monitor,willpower04/cgm-remote-monitor,karlork/cgm-remote-monitor,snolte/cgm-remote-monitor,DavMedek/cgm-remote-monitor,OpossumGit/cgm-remote-monitor,marcon2000/cgm-remote-monitor,ceben80/cgm-remote-monitor,JamesCaw/cgm-remote-monitor,westoncgm/cgm-remote-monitor,brocm/cgm-remote-monitor,skubesch/Nightscout-V8,DianeJohnson100/cgm-remote-monitor,bettecgm/cgm-remote-monitor-1,janetlizconroy/cgm-remote-monitor,ljusername/cgm-remote-monitor,gitanO0/cgm-remote-monitor,CeciliaAlicia/cgm-remote-monitor,BlackDogsRule/cgm-remote-monitor,willsimpson1997/cgm-remote-monitor,michellels/cgm-remote-monitor,tornado14/cgm-remote-monitor,howxdrip/cgm-remote-monitor,zoeystoes/cgm-remote-monitor,Kaydence/cgm-remote-monitor,kylecloud/cgm-remote-monitor,alexcgm/cgm-remote-monitor,Supersawyer/cgm-remote-monitor,faromatilde/cgm-remote-monitor,rajatgupta431/cgm-remote-monitor,horoshulin/cgm-remote-monitor,cclcgm/cgm-remote-monitor,dramageek/cgm-remote-monitor,asg8146/cgm-remote-monitor,kiserman/cgm-remote-monitor,Yassen2008/cgm-remote-monitor,ellabellakaramella/cgm-remote-monitor,beavisandgirl/cgm-remote-monitor,robynec75/cgm-remote-monitor,chiaramorris/cgm-remote-monitor,TylerMathews/cgm-remote-monitor,SweetRooks/cgm-remote-monitor,Alyssalinmartinez/cgm-remote-monitor,namme59/cgm-remote-monitor,asha0613/cgm-remote-monitor,casey21/cgm-remote-monitor,riley1216/cgm-remote-monitor,jfinlay2/cgm-remote-monitor,bjack17/cgm-remote-monitor,samsamscgm/cgm-remote-monitor,GarthDB/cgm-remote-monitor,barry45/cgm-remote-monitor,bhcamp/cgm-remote-monitor,MackenzieT1D/cgm-remote-monitor,jaylagorio/cgm-remote-monitor,JenSteier/cgm-remote-monitor,sugabetic/cgm-remote-monitor,jackwain/cgm-remote-monitor,tylaamy/cgm-remote-monitor,leonimo2/cgm-remote-monitor,rene4547/cgm-remote-monitor,jungsomyeonggithub/cgm-remote-monitor,djmacias2/cgm-remote-monitor,pjweiss/cgm-remote-monitor,ondrolexa/cgm-remote-monitor,grhulz/cgm-remote-monitor,diab1234/cgm-remote-monitor,cjo20/cgm-remote-monitor,d-liza/cgm-remote-monitor,mandy6770/cgm-remote-monitor,steve6158/cgm-remote-monitor,DominikStefan/cgm-remote-monitor,spiggelina1/cgm-remote-monitor,astrocam/cgm-remote-monitor,AJS2008/cgm-remote-monitor,CloudPL/cgm-remote-monitor,thecaseyjames/cgm-remote-monitor,NightScoutErin/cgm-remote-monitor,mel2095/cgm-remote-monitor,crossfamily888/cgm-remote-monitor,zoeystoes/cgm-remote-monitor,jennymattyste83/cgm-remote-monitor,CloudPL/cgm-remote-monitor,aabramowicz/cgm-remote-monitor,pajallen/cgm-remote-monitor,malloryns/cgm-remote-monitor,mwillis130/cgm-remote-monitor,scottmark/cgm-remote-monitor,logichammer/cgm-remote-monitor,Karahbevin/cgm-remote-monitor,NSDreamsicle/cgm-remote-monitor,Natalie12/cgm-remote-monitor,ak8418/cgm-remote-monitor,foxlazza/cgm-remote-monitor,Kaydence/cgm-remote-monitor,AidanHamlin/cgm-remote-monitor,robertanye/cgm-remote-monitor,jtchambe/cgm-remote-monitor,rebecacirre/cgm-remote-monitor,erikafromamerica/cgm-remote-monitor,brownkkeb/cgm-remote-monitor,spiggelina1/cgm-remote-monitor,AliMiller/cgm-remote-monitor,ramstrand/cgm-remote-monitor,dylanbdawe/cgm-remote-monitor,javierdexcom/cgm-remote-monitor,eszcloud/cgm-remote-monitor,thegoodnews/cgm-remote-monitor,iorghi/cgm-remote-monitor,diegodexcom/cgm-remote-monitor,skjelland/cgm-remote-monitor,VSCDR/cgm-remote-monitor,thedob/cgm-remote-monitor,CaerwynRoberts/cgm-remote-monitor,mjsell/cgm-remote-monitor,pavel1981/cgm-remote-monitor,szpaku80/cgm-remote-monitor,tommy06/cgm-remote-monitor,larazeren/cgm-remote-monitor,pilonicamilla/cgm-remote-monitor,connorcgmdata/cgm-remote-monitor,mvieau/cgm-remote-monitor,stefanakerblom/cgm-remote-monitor,eliz4142/cgm-remote-monitor,bkdollar/cgm-remote-monitor,Mihaeladex/cgm-remote-monitor,FirdausJones/cgm-remote-monitor,kirks/cgm-remote-monitor,tanja3981/cgm-remote-monitor,ldknoch/cgm-remote-monitor,thomascostello/cgm-remote-monitor,JDBM1/cgm-remote-monitor,sawiris/cgm-remote-monitor,jfelkins/cgm-remote-monitor,sebastianlorant/cgm-remote-monitor,Eastondex/cgm-remote-monitor,goranssons/cgm-remote-monitor,Candyhearts/cgm-remote-monitor,rafaena/cgm-remote-monitor,mdbottego74/cgm-remote-monitor,caydongood/cgm-remote-monitor,bradleybear/cgm-remote-monitor,valphilmus/cgm-remote-monitor,jasoncalabrese/cgm-remote-monitor,emilybsessions/cgm-remote-monitor,Teodorwallberg/cgm-remote-monitor,CharlieBowyer/cgm-remote-monitor,grenntreeateam/cgm-remote-monitor,melsmith/cgm-remote-monitor,Fredensvold/cgm-remote-monitor,AidanHamlin/cgm-remote-monitor,czcottage/cgm-remote-monitor,garath77/cgm-remote-monitor,srimes/cgm-remote-monitor,harryrowe2010/cgm-remote-monitor,crossfamily888/cgm-remote-monitor,DominikStefan/cgm-remote-monitor,46egemert/cgm-remote-monitor,kkileyhub/cgm-remote-monitor,jonhunterbui/cgm-remote-monitor,jeaninemt2003/cgm-remote-monitor,jaysheree/cgm-remote-monitor,merrickdaigneault/cgm-remote-monitor,ryder08/cgm-remote-monitor,dmanders/cgm-remote-monitor,bromaco/cgm-remote-monitor,astrocam/cgm-remote-monitor,chiaramorris/cgm-remote-monitor,skubigolf/cgm-remote-monitor,marcusjonsson76/cgm-remote-monitor,PTGScout/cgm-remote-monitor,bhcamp/cgm-remote-monitor,dotbreadcrumb/cgm-remote-monitor,hannahggdb/cgm-remote-monitor,jeaninemt2003/cgm-remote-monitor,Lexieloula/cgm-remote-monitor,shaynejmt/cgm-remote-monitor,lukedfeus/cgm-remote-monitor,snolte/cgm-remote-monitor,Eastondex/cgm-remote-monitor,urmc-costik/cgm-remote-monitor,jaidenlee/cgm-remote-monitor,dexcom/cgm-remote-monitor,ryanfire12/cgm-remote-monitor,scottswitz/cgm-remote-monitor,editdata7/cgm-remote-monitor,mattlevine22/cgm-remote-monitor,connorcgmdata/cgm-remote-monitor,MosiGitHub/cgm-remote-monitor,aidandevine/cgm-remote-monitor,gempickfordwaugh/cgm-remote-monitor,JasperCGM/cgm-remote-monitor,NatBrUser/cgm-remote-monitor,rafaena/cgm-remote-monitor,Emmikos/cgm-remote-monitor,Bonnar/cgm-remote-monitor,nightscout752/cgm-remote-monitor,adriwelborn/cgm-remote-monitor,betacellblues/cgm-remote-monitor,Maddie1222/cgm-remote-monitor,SweetRooks/cgm-remote-monitor,jfinlay2/cgm-remote-monitor,Fedechicco2/cgm-remote-monitor,JosiahNS/cgm-remote-monitor,rajatgupta431/cgm-remote-monitor,drummer35/cgm-remote-monitor,adrianmoli/cgm-remote-monitor,FirdausJones/cgm-remote-monitor,amlynek/cgm-remote-monitor,dramageek/cgm-remote-monitor,michaelpears/cgm-remote-monitor,eszcloud/cgm-remote-monitor,isabell12/cgm-remote-monitor,dawnmifsud/cgm-remote-monitor
'use strict'; var _ = require('lodash'); var levels = require('./levels'); function init ( ) { var settings = { units: 'mg/dL' , timeFormat: '12' , nightMode: false , showRawbg: 'never' , customTitle: 'Nightscout' , theme: 'default' , alarmUrgentHigh: true , alarmUrgentHighMins: [30, 60, 90, 120] , alarmHigh: true , alarmHighMins: [30, 60, 90, 120] , alarmLow: true , alarmLowMins: [15, 30, 45, 60] , alarmUrgentLow: true , alarmUrgentLowMins: [15, 30, 45] , alarmUrgentMins: [30, 60, 90, 120] , alarmWarnMins: [30, 60, 90, 120] , alarmTimeagoWarn: true , alarmTimeagoWarnMins: 15 , alarmTimeagoUrgent: true , alarmTimeagoUrgentMins: 30 , language: 'en' , showPlugins: '' , heartbeat: 60 , baseURL: '' , thresholds: { bgHigh: 260 , bgTargetTop: 180 , bgTargetBottom: 80 , bgLow: 55 } }; var valueMappers = { alarmUrgentHighMins: mapNumberArray , alarmHighMins: mapNumberArray , alarmLowMins: mapNumberArray , alarmUrgentLowMins: mapNumberArray , alarmUrgentMins: mapNumberArray , alarmWarnMins: mapNumberArray }; function mapNumberArray (value) { if (!value || _.isArray(value)) { return value; } if (isNaN(value)) { var rawValues = value && value.split(' ') || []; return _.map(rawValues, function (num) { return isNaN(num) ? null : Number(num); }); } else { return value; } } //TODO: getting sent in status.json, shouldn't be settings.DEFAULT_FEATURES = ['delta', 'direction', 'upbat', 'errorcodes']; var wasSet = []; function isSimple (value) { return _.isArray(value) || (typeof value !== 'function' && typeof value !== 'object'); } function nameFromKey (key, nameType) { return nameType === 'env' ? _.snakeCase(key).toUpperCase() : key; } function eachSettingAs (nameType) { function mapKeys (accessor, keys) { _.forIn(keys, function each (value, key) { if (isSimple(value)) { var newValue = accessor(nameFromKey(key, nameType)); if (newValue !== undefined) { var mapper = valueMappers[key]; wasSet.push(key); keys[key] = mapper ? mapper(newValue) : newValue; } } }); } return function allKeys (accessor) { mapKeys(accessor, settings); mapKeys(accessor, settings.thresholds); enableAndDisableFeatures(accessor, nameType); }; } function enableAndDisableFeatures (accessor, nameType) { function getAndPrepare (key) { var raw = accessor(nameFromKey(key, nameType)) || ''; var cleaned = decodeURIComponent(raw).toLowerCase(); return cleaned ? cleaned.split(' ') : []; } function enableIf (feature, condition) { if (condition) { enable.push(feature); } } function anyEnabled (features) { return _.findIndex(features, function (feature) { return enable.indexOf(feature) > -1; }) > -1; } function prepareAlarmTypes ( ) { var alarmTypes = _.filter(getAndPrepare('alarmTypes'), function onlyKnownTypes (type) { return type === 'predict' || type === 'simple'; }); if (alarmTypes.length === 0) { var thresholdWasSet = _.findIndex(wasSet, function (name) { return name.indexOf('bg') === 0; }) > -1; alarmTypes = thresholdWasSet ? ['simple'] : ['predict']; } return alarmTypes; } var enable = getAndPrepare('enable'); var disable = getAndPrepare('disable'); settings.alarmTypes = prepareAlarmTypes(); //don't require pushover to be enabled to preserve backwards compatibility if there are extendedSettings for it enableIf('pushover', accessor(nameFromKey('pushoverApiToken', nameType))); enableIf('treatmentnotify', anyEnabled(['careportal', 'pushover', 'maker'])); _.each(settings.DEFAULT_FEATURES, function eachDefault (feature) { enableIf(feature, enable.indexOf(feature) < 0); }); //TODO: maybe get rid of ALARM_TYPES and only use enable? enableIf('simplealarms', settings.alarmTypes.indexOf('simple') > -1); enableIf('ar2', settings.alarmTypes.indexOf('predict') > -1); if (disable.length > 0) { console.info('disabling', disable); } //all enabled feature, without any that have been disabled settings.enable = _.difference(enable, disable); var thresholds = settings.thresholds; thresholds.bgHigh = Number(thresholds.bgHigh); thresholds.bgTargetTop = Number(thresholds.bgTargetTop); thresholds.bgTargetBottom = Number(thresholds.bgTargetBottom); thresholds.bgLow = Number(thresholds.bgLow); verifyThresholds(); adjustShownPlugins(); } function verifyThresholds() { var thresholds = settings.thresholds; if (thresholds.bgTargetBottom >= thresholds.bgTargetTop) { console.warn('BG_TARGET_BOTTOM(' + thresholds.bgTargetBottom + ') was >= BG_TARGET_TOP(' + thresholds.bgTargetTop + ')'); thresholds.bgTargetBottom = thresholds.bgTargetTop - 1; console.warn('BG_TARGET_BOTTOM is now ' + thresholds.bgTargetBottom); } if (thresholds.bgTargetTop <= thresholds.bgTargetBottom) { console.warn('BG_TARGET_TOP(' + thresholds.bgTargetTop + ') was <= BG_TARGET_BOTTOM(' + thresholds.bgTargetBottom + ')'); thresholds.bgTargetTop = thresholds.bgTargetBottom + 1; console.warn('BG_TARGET_TOP is now ' + thresholds.bgTargetTop); } if (thresholds.bgLow >= thresholds.bgTargetBottom) { console.warn('BG_LOW(' + thresholds.bgLow + ') was >= BG_TARGET_BOTTOM(' + thresholds.bgTargetBottom + ')'); thresholds.bgLow = thresholds.bgTargetBottom - 1; console.warn('BG_LOW is now ' + thresholds.bgLow); } if (thresholds.bgHigh <= thresholds.bgTargetTop) { console.warn('BG_HIGH(' + thresholds.bgHigh + ') was <= BG_TARGET_TOP(' + thresholds.bgTargetTop + ')'); thresholds.bgHigh = thresholds.bgTargetTop + 1; console.warn('BG_HIGH is now ' + thresholds.bgHigh); } } function adjustShownPlugins ( ) { //TODO: figure out something for some plugins to have them shown by default if (settings.showPlugins !== '') { settings.showPlugins += ' delta direction upbat'; if (settings.showRawbg === 'always' || settings.showRawbg === 'noise') { settings.showPlugins += ' rawbg'; } } } function isEnabled (feature) { var enabled = false; if (settings.enable && typeof feature === 'object' && feature.length !== undefined) { enabled = _.find(feature, function eachFeature (f) { return settings.enable.indexOf(f) > -1; }) !== undefined; } else { enabled = settings.enable && settings.enable.indexOf(feature) > -1; } return enabled; } function isAlarmEventEnabled (notify) { var enabled = false; if ('high' !== notify.eventName && 'low' !== notify.eventName) { enabled = true; } else if (notify.eventName === 'high' && notify.level === levels.URGENT && settings.alarmUrgentHigh) { enabled = true; } else if (notify.eventName === 'high' && settings.alarmHigh) { enabled = true; } else if (notify.eventName === 'low' && notify.level === levels.URGENT && settings.alarmUrgentLow) { enabled = true; } else if (notify.eventName === 'low' && settings.alarmLow) { enabled = true; } return enabled; } function snoozeMinsForAlarmEvent (notify) { var snoozeTime; if (notify.eventName === 'high' && notify.level === levels.URGENT && settings.alarmUrgentHigh) { snoozeTime = settings.alarmUrgentHighMins; } else if (notify.eventName === 'high' && settings.alarmHigh) { snoozeTime = settings.alarmHighMins; } else if (notify.eventName === 'low' && notify.level === levels.URGENT && settings.alarmUrgentLow) { snoozeTime = settings.alarmUrgentLowMins; } else if (notify.eventName === 'low' && settings.alarmLow) { snoozeTime = settings.alarmLowMins; } else if (notify.level === levels.URGENT) { snoozeTime = settings.alarmUrgentMins; } else { snoozeTime = settings.alarmWarnMins; } return snoozeTime; } function snoozeFirstMinsForAlarmEvent (notify) { return _.first(snoozeMinsForAlarmEvent(notify)); } settings.eachSetting = eachSettingAs(); settings.eachSettingAsEnv = eachSettingAs('env'); settings.isEnabled = isEnabled; settings.isAlarmEventEnabled = isAlarmEventEnabled; settings.snoozeMinsForAlarmEvent = snoozeMinsForAlarmEvent; settings.snoozeFirstMinsForAlarmEvent = snoozeFirstMinsForAlarmEvent; return settings; } module.exports = init;
lib/settings.js
'use strict'; var _ = require('lodash'); var levels = require('./levels'); function init ( ) { var settings = { units: 'mg/dL' , timeFormat: '12' , nightMode: false , showRawbg: 'never' , customTitle: 'Nightscout' , theme: 'default' , alarmUrgentHigh: true , alarmUrgentHighMins: [30, 60, 90, 120] , alarmHigh: true , alarmHighMins: [30, 60, 90, 120] , alarmLow: true , alarmLowMins: [15, 30, 45, 60] , alarmUrgentLow: true , alarmUrgentLowMins: [15, 30, 45] , alarmUrgentMins: [30, 60, 90, 120] , alarmWarnMins: [30, 60, 90, 120] , alarmTimeagoWarn: true , alarmTimeagoWarnMins: 15 , alarmTimeagoUrgent: true , alarmTimeagoUrgentMins: 30 , language: 'en' , showPlugins: '' , heartbeat: 60 , baseURL: '' , thresholds: { bgHigh: 260 , bgTargetTop: 180 , bgTargetBottom: 80 , bgLow: 55 } }; var valueMappers = { alarmUrgentHighMins: mapNumberArray , alarmHighMins: mapNumberArray , alarmLowMins: mapNumberArray , alarmUrgentLowMins: mapNumberArray , alarmUrgentMins: mapNumberArray , alarmWarnMins: mapNumberArray }; function mapNumberArray (value) { if (!value || _.isArray(value)) { return value; } if (isNaN(value)) { var rawValues = value && value.split(' ') || []; return _.map(rawValues, function (num) { return isNaN(num) ? null : Number(num); }); } else { return value; } } //TODO: getting sent in status.json, shouldn't be settings.DEFAULT_FEATURES = ['delta', 'direction', 'upbat', 'errorcodes']; var wasSet = []; function isSimple (value) { return _.isArray(value) || (typeof value !== 'function' && typeof value !== 'object'); } function nameFromKey (key, nameType) { return nameType === 'env' ? _.snakeCase(key).toUpperCase() : key; } function eachSettingAs (nameType) { function mapKeys (accessor, keys) { _.forIn(keys, function each (value, key) { if (isSimple(value)) { var newValue = accessor(nameFromKey(key, nameType)); if (newValue !== undefined) { var mapper = valueMappers[key]; wasSet.push(key); keys[key] = mapper ? mapper(newValue) : newValue; } } }); } return function allKeys (accessor) { mapKeys(accessor, settings); mapKeys(accessor, settings.thresholds); enableAndDisableFeatures(accessor, nameType); }; } function enableAndDisableFeatures (accessor, nameType) { function getAndPrepare (key) { var raw = accessor(nameFromKey(key, nameType)) || ''; var cleaned = decodeURIComponent(raw).toLowerCase(); return cleaned ? cleaned.split(' ') : []; } function enableIf (feature, condition) { if (condition) { enable.push(feature); } } function anyEnabled (features) { return _.findIndex(features, function (feature) { return enable.indexOf(feature) > -1; }) > -1; } function prepareAlarmTypes ( ) { var alarmTypes = _.filter(getAndPrepare('alarmTypes'), function onlyKnownTypes (type) { return type === 'predict' || type === 'simple'; }); if (alarmTypes.length === 0) { var thresholdWasSet = _.findIndex(wasSet, function (name) { return name.indexOf('bg') === 0; }) > -1; alarmTypes = thresholdWasSet ? ['simple'] : ['predict']; } return alarmTypes; } var enable = getAndPrepare('enable'); var disable = getAndPrepare('disable'); settings.alarmTypes = prepareAlarmTypes(); //don't require pushover to be enabled to preserve backwards compatibility if there are extendedSettings for it enableIf('pushover', accessor(nameFromKey('pushoverApiToken', nameType))); enableIf('treatmentnotify', anyEnabled(['careportal', 'pushover', 'maker'])); _.each(settings.DEFAULT_FEATURES, function eachDefault (feature) { enableIf(feature, enable.indexOf(feature) < 0); }); //TODO: maybe get rid of ALARM_TYPES and only use enable? enableIf('simplealarms', settings.alarmTypes.indexOf('simple') > -1); enableIf('ar2', settings.alarmTypes.indexOf('predict') > -1); if (disable.length > 0) { console.info('disabling', disable); } //all enabled feature, without any that have been disabled settings.enable = _.difference(enable, disable); var thresholds = settings.thresholds; thresholds.bgHigh = Number(thresholds.bgHigh); thresholds.bgTargetTop = Number(thresholds.bgTargetTop); thresholds.bgTargetBottom = Number(thresholds.bgTargetBottom); thresholds.bgLow = Number(thresholds.bgLow); verifyThresholds(); adjustShownPlugins(); } function verifyThresholds() { var thresholds = settings.thresholds; if (thresholds.bgTargetBottom >= thresholds.bgTargetTop) { console.warn('BG_TARGET_BOTTOM(' + thresholds.bgTargetBottom + ') was >= BG_TARGET_TOP(' + thresholds.bgTargetTop + ')'); thresholds.bgTargetBottom = thresholds.bgTargetTop - 1; console.warn('BG_TARGET_BOTTOM is now ' + thresholds.bgTargetBottom); } if (thresholds.bgTargetTop <= thresholds.bgTargetBottom) { console.warn('BG_TARGET_TOP(' + thresholds.bgTargetTop + ') was <= BG_TARGET_BOTTOM(' + thresholds.bgTargetBottom + ')'); thresholds.bgTargetTop = thresholds.bgTargetBottom + 1; console.warn('BG_TARGET_TOP is now ' + thresholds.bgTargetTop); } if (thresholds.bgLow >= thresholds.bgTargetBottom) { console.warn('BG_LOW(' + thresholds.bgLow + ') was >= BG_TARGET_BOTTOM(' + thresholds.bgTargetBottom + ')'); thresholds.bgLow = thresholds.bgTargetBottom - 1; console.warn('BG_LOW is now ' + thresholds.bgLow); } if (thresholds.bgHigh <= thresholds.bgTargetTop) { console.warn('BG_HIGH(' + thresholds.bgHigh + ') was <= BG_TARGET_TOP(' + thresholds.bgTargetTop + ')'); thresholds.bgHigh = thresholds.bgTargetTop + 1; console.warn('BG_HIGH is now ' + thresholds.bgHigh); } } function adjustShownPlugins ( ) { //TODO: figure out something for some plugins to have them shown by default if (settings.showPlugins !== '') { settings.showPlugins += ' delta direction upbat'; if (settings.showRawbg === 'always' || settings.showRawbg === 'noise') { settings.showPlugins += ' rawbg'; } } } function isEnabled (feature) { var enabled = false; if (settings.enable && typeof feature === 'object' && feature.length !== undefined) { enabled = _.find(feature, function eachFeature (f) { return settings.enable.indexOf(f) > -1; }) !== undefined; } else { enabled = settings.enable && settings.enable.indexOf(feature) > -1; } return enabled; } function isAlarmEventEnabled (notify) { var enabled = false; if (!notify.eventName) { enabled = true; } else if (notify.eventName === 'high' && notify.level === levels.URGENT && settings.alarmUrgentHigh) { enabled = true; } else if (notify.eventName === 'high' && settings.alarmHigh) { enabled = true; } else if (notify.eventName === 'low' && notify.level === levels.URGENT && settings.alarmUrgentLow) { enabled = true; } else if (notify.eventName === 'low' && settings.alarmLow) { enabled = true; } return enabled; } function snoozeMinsForAlarmEvent (notify) { var snoozeTime; if (notify.eventName === 'high' && notify.level === levels.URGENT && settings.alarmUrgentHigh) { snoozeTime = settings.alarmUrgentHighMins; } else if (notify.eventName === 'high' && settings.alarmHigh) { snoozeTime = settings.alarmHighMins; } else if (notify.eventName === 'low' && notify.level === levels.URGENT && settings.alarmUrgentLow) { snoozeTime = settings.alarmUrgentLowMins; } else if (notify.eventName === 'low' && settings.alarmLow) { snoozeTime = settings.alarmLowMins; } else if (notify.level === levels.URGENT) { snoozeTime = settings.alarmUrgentMins; } else { snoozeTime = settings.alarmWarnMins; } return snoozeTime; } function snoozeFirstMinsForAlarmEvent (notify) { return _.first(snoozeMinsForAlarmEvent(notify)); } settings.eachSetting = eachSettingAs(); settings.eachSettingAsEnv = eachSettingAs('env'); settings.isEnabled = isEnabled; settings.isAlarmEventEnabled = isAlarmEventEnabled; settings.snoozeMinsForAlarmEvent = snoozeMinsForAlarmEvent; settings.snoozeFirstMinsForAlarmEvent = snoozeFirstMinsForAlarmEvent; return settings; } module.exports = init;
only check if low/high events are enabled for now
lib/settings.js
only check if low/high events are enabled for now
<ide><path>ib/settings.js <ide> function isAlarmEventEnabled (notify) { <ide> var enabled = false; <ide> <del> if (!notify.eventName) { <add> if ('high' !== notify.eventName && 'low' !== notify.eventName) { <ide> enabled = true; <ide> } else if (notify.eventName === 'high' && notify.level === levels.URGENT && settings.alarmUrgentHigh) { <ide> enabled = true;
Java
mit
683ba3bf5beddd2bd136eb943c3a391535206734
0
kuangami/LeetCode,kuangami/LeetCode,kuangami/LeetCode
package ListNode; //2. Add Two Numbers /** * You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. * * You may assume the two numbers do not contain any leading zero, except the number 0 itself. * * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 0 -> 8 * * Tags: Linked List, Math * Similar Problems: (M) Multiply Strings (E) Add Binary (E) Sum of Two Integers (E) Add Strings (M) Add Two Numbers II * * @author Xinyue Zhang * */ //ListNode class /** package ListNode; public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } ListNode(int x, ListNode node) { val = x; next = node; } }**/ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode prev = new ListNode(0); ListNode head = prev; int carry = 0, sum = 0; while (l1 != null || l2 != null || carry != 0) { sum = carry + ((l1 == null) ? 0 : l1.val) + ((l2 == null) ? 0 : l2.val); carry = sum / 10; prev.next = new ListNode(sum % 10); prev = prev.next; l1 = l1 == null ? l1 : l1.next; l2 = l2 == null ? l2 : l2.next; } return head.next; } public static void main(String[] args) { ListNode l1 = new ListNode(3), l1_1 = new ListNode(4, l1), l1_2 = new ListNode(2, l1_1); ListNode l2 = new ListNode(4), l2_1 = new ListNode(6, l2), l2_2 = new ListNode(5, l2_1); System.out.println("Sum = "); ListNode sum = new ListNode(0); Solution sol = new Solution(); sum = sol.addTwoNumbers(l1_2, l2_2); while (sum != null) { System.out.println(sum.val); sum = sum.next; } } }
java/002_Add_Two_Numbers.java
package ListNode; //2. Add Two Numbers /** * You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. * * You may assume the two numbers do not contain any leading zero, except the number 0 itself. * * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 0 -> 8 * * Tags: Linked List, Math * Similar Problems: (M) Multiply Strings (E) Add Binary (E) Sum of Two Integers (E) Add Strings (M) Add Two Numbers II * * @author Xinyue Zhang * */ //ListNode class /** package ListNode; public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } public static void insertList(int val, ListNode head) { ListNode node = new ListNode(0); node.val = val; while (head.next != null) head = head.next; head.next = node; } }**/ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode prev = new ListNode(0); ListNode head = prev; int carry = 0, sum = 0; while (l1 != null || l2 != null || carry != 0) { sum = carry + ((l1 == null) ? 0 : l1.val) + ((l2 == null) ? 0 : l2.val); carry = sum / 10; prev.next = new ListNode(sum % 10); prev = prev.next; l1 = l1 == null ? l1 : l1.next; l2 = l2 == null ? l2 : l2.next; } return head.next; } public static void main(String[] args) { ListNode l1 = new ListNode(2); ListNode.insertList(4, l1); ListNode.insertList(3, l1); ListNode l2 = new ListNode(5); ListNode.insertList(6, l2); ListNode.insertList(4, l2); System.out.println("Sum = "); ListNode sum = new ListNode(0); Solution sol = new Solution(); sum = sol.addTwoNumbers(l1, l2); while (sum != null) { System.out.println(sum.val); sum = sum.next; } } }
Update 002_Add_Two_Numbers.java Use another constructor instead of a insertList function. Change the test code.
java/002_Add_Two_Numbers.java
Update 002_Add_Two_Numbers.java
<ide><path>ava/002_Add_Two_Numbers.java <ide> int val; <ide> ListNode next; <ide> ListNode(int x) { val = x; } <add> ListNode(int x, ListNode node) { val = x; next = node; } <ide> <del> public static void insertList(int val, ListNode head) { <del> ListNode node = new ListNode(0); <del> node.val = val; <del> while (head.next != null) <del> head = head.next; <del> head.next = node; <del> } <ide> }**/ <ide> <ide> public class Solution { <ide> } <ide> <ide> public static void main(String[] args) { <del> ListNode l1 = new ListNode(2); <del> ListNode.insertList(4, l1); <del> ListNode.insertList(3, l1); <add> ListNode l1 = new ListNode(3), l1_1 = new ListNode(4, l1), l1_2 = new ListNode(2, l1_1); <ide> <del> ListNode l2 = new ListNode(5); <del> ListNode.insertList(6, l2); <del> ListNode.insertList(4, l2); <add> ListNode l2 = new ListNode(4), l2_1 = new ListNode(6, l2), l2_2 = new ListNode(5, l2_1); <ide> <ide> System.out.println("Sum = "); <ide> ListNode sum = new ListNode(0); <ide> Solution sol = new Solution(); <del> sum = sol.addTwoNumbers(l1, l2); <add> sum = sol.addTwoNumbers(l1_2, l2_2); <ide> while (sum != null) { <ide> System.out.println(sum.val); <ide> sum = sum.next;
Java
mpl-2.0
aa29754b3c530fd1907e24becf177170c2a31031
0
msteinhoff/hello-world
7f63947d-cb8e-11e5-a2ef-00264a111016
src/main/java/HelloWorld.java
7f57d4b8-cb8e-11e5-b892-00264a111016
My Backup
src/main/java/HelloWorld.java
My Backup
<ide><path>rc/main/java/HelloWorld.java <del>7f57d4b8-cb8e-11e5-b892-00264a111016 <add>7f63947d-cb8e-11e5-a2ef-00264a111016
Java
apache-2.0
7382581d463d830721fda2e04dde14926d48fa41
0
wro4j/wro4j,UAK-35/wro4j,dacofr/wro4j,wro4j/wro4j,dacofr/wro4j,dacofr/wro4j,dacofr/wro4j,wro4j/wro4j,UAK-35/wro4j,UAK-35/wro4j,UAK-35/wro4j
package ro.isdc.wro.model.resource.locator.support; import java.util.HashMap; import java.util.Map; import ro.isdc.wro.model.resource.locator.ClasspathUriLocator; import ro.isdc.wro.model.resource.locator.ServletContextUriLocator; import ro.isdc.wro.model.resource.locator.ServletContextUriLocator.LocatorStrategy; import ro.isdc.wro.model.resource.locator.UriLocator; import ro.isdc.wro.model.resource.locator.UrlUriLocator; import ro.isdc.wro.util.provider.ProviderPriorityAware; import ro.isdc.wro.util.provider.ProviderPriority; /** * Default implementation of {@link LocatorProvider} providing all {@link UriLocator} implementations from core module. * * @author Alex Objelean * @created 16 Jun 2012 * @since 1.4.7 */ public class DefaultLocatorProvider implements LocatorProvider, ProviderPriorityAware { /** * {@inheritDoc} */ public Map<String, UriLocator> provideLocators() { final Map<String, UriLocator> map = new HashMap<String, UriLocator>(); map.put(ClasspathUriLocator.ALIAS, new ClasspathUriLocator()); map.put(ServletContextUriLocator.ALIAS, new ServletContextUriLocator()); map.put(ServletContextUriLocator.ALIAS_DISPATCHER_FIRST, new ServletContextUriLocator().setLocatorStrategy(LocatorStrategy.DISPATCHER_FIRST)); map.put(ServletContextUriLocator.ALIAS_SERVLET_CONTEXT_FIRST, new ServletContextUriLocator().setLocatorStrategy(LocatorStrategy.SERVLET_CONTEXT_FIRST)); map.put(UrlUriLocator.ALIAS, new UrlUriLocator()); return map; } public ProviderPriority getPriority() { return ProviderPriority.LOW; } }
wro4j-core/src/main/java/ro/isdc/wro/model/resource/locator/support/DefaultLocatorProvider.java
package ro.isdc.wro.model.resource.locator.support; import java.util.HashMap; import java.util.Map; import ro.isdc.wro.model.resource.locator.ClasspathUriLocator; import ro.isdc.wro.model.resource.locator.ServletContextUriLocator; import ro.isdc.wro.model.resource.locator.ServletContextUriLocator.LocatorStrategy; import ro.isdc.wro.model.resource.locator.UriLocator; import ro.isdc.wro.model.resource.locator.UrlUriLocator; /** * Default implementation of {@link LocatorProvider} providing all {@link UriLocator} implementations from core module. * * @author Alex Objelean * @created 16 Jun 2012 * @since 1.4.7 */ public class DefaultLocatorProvider implements LocatorProvider { /** * {@inheritDoc} */ public Map<String, UriLocator> provideLocators() { final Map<String, UriLocator> map = new HashMap<String, UriLocator>(); map.put(ClasspathUriLocator.ALIAS, new ClasspathUriLocator()); map.put(ServletContextUriLocator.ALIAS, new ServletContextUriLocator()); map.put(ServletContextUriLocator.ALIAS_DISPATCHER_FIRST, new ServletContextUriLocator().setLocatorStrategy(LocatorStrategy.DISPATCHER_FIRST)); map.put(ServletContextUriLocator.ALIAS_SERVLET_CONTEXT_FIRST, new ServletContextUriLocator().setLocatorStrategy(LocatorStrategy.SERVLET_CONTEXT_FIRST)); map.put(UrlUriLocator.ALIAS, new UrlUriLocator()); return map; } }
DefaultLocatorProvider implements ProviderPriorityAware
wro4j-core/src/main/java/ro/isdc/wro/model/resource/locator/support/DefaultLocatorProvider.java
DefaultLocatorProvider implements ProviderPriorityAware
<ide><path>ro4j-core/src/main/java/ro/isdc/wro/model/resource/locator/support/DefaultLocatorProvider.java <ide> import ro.isdc.wro.model.resource.locator.ServletContextUriLocator.LocatorStrategy; <ide> import ro.isdc.wro.model.resource.locator.UriLocator; <ide> import ro.isdc.wro.model.resource.locator.UrlUriLocator; <add>import ro.isdc.wro.util.provider.ProviderPriorityAware; <add>import ro.isdc.wro.util.provider.ProviderPriority; <ide> <ide> <ide> /** <ide> * @since 1.4.7 <ide> */ <ide> public class DefaultLocatorProvider <del> implements LocatorProvider { <add> implements LocatorProvider, ProviderPriorityAware { <ide> /** <ide> * {@inheritDoc} <ide> */ <ide> map.put(UrlUriLocator.ALIAS, new UrlUriLocator()); <ide> return map; <ide> } <add> <add> public ProviderPriority getPriority() { <add> return ProviderPriority.LOW; <add> } <ide> }